'''
Cache interscanners for sagator, version 1.0

(c) 2005-2006 Jan ONDREJ (SAL) <ondrejj(at)salstar.sk>

 This program is free software; you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation; either version 2 of the License, or
 (at your option) any later version.
                                                                                
'''
                                                                                
from avlib import *
from match import match_any
                                                                                
__all__=['cache','store','restore']

class cache(match_any):
  '''
  Cache return value of a scanner.

  First call of this scanner caches return value for a scanner included into
  and return it's value. Next calls returns stored values.
  
  Usage: cache('VAR',scanners...)
  
  Where: 'VAR' is a string, which defines variable name to cache return value

  Example: cache('var1', scanner1()) # to store and return scanner1()'s value
           cache('var1') # to only return previously stored value
  
  New in version 0.7.0.
  '''
  name='cache()'
  VARA={}
  def __init__(self,var,*scanners):
      self.var=var
      match_any.__init__(self,scanners)
  def reinit(self):
      if cache.VARA.has_key(self.var):
        del cache.VARA[self.var]
  def scanbuffer(self,buffer,args={}):
      if cache.VARA.has_key(self.var):
        return cache.VARA[self.var]
      else:
        level,detected,virlist=match_any.scanbuffer(self,buffer,args)
        cache.VARA[self.var]=level,detected,virlist
      return level,detected,virlist

class store(match_any):
  '''
  Store scanner return value. [obsolete]
  
  This scanner return's return value for a scanner included into
  and stores it's value into a variable.
  
  Usage: store('VAR',scanners...)
  
  Where: 'VAR' is a string, which defines variable name to store return value

  Example: store('var1', scanner1())

  Obsolete since 0.7.0, use cache() instead.
  '''
  name='store()'
  VARA={}
  def __init__(self,var,*scanners):
      self.var=var
      match_any.__init__(self,scanners)
  def scanbuffer(self,buffer,args={}):
      level,detected,virlist=match_any.scanbuffer(self,buffer,args)
      store.VARA[self.var]=level,detected,virlist
      return level,detected,virlist

class restore(match_any):
  '''
  Restore scanner return value. [obsolete]
  
  This scanner return's return value for previously stored variable.

  Usage: restore('VAR')
  
  Where: 'VAR' is a string, which defines variable name to store
           scanner's return value.

  Example: store('var1')
  
  Obsolete since 0.7.0, use cache() instead.
  '''
  name='restore()'
  def __init__(self,var):
      self.var=var
  def scanbuffer(self,buffer,args={}):
      return store.VARA[self.var]
