richfitz / storr

:package: Object cacher for R
http://richfitz.github.io/storr
Other
116 stars 10 forks source link

Avoid calling exists on key lookup for drivers that can throw reliably #17

Closed richfitz closed 8 years ago

richfitz commented 8 years ago

Drivers should declare if they will promise to throw an error on nonexistant key retrieval.

    get=function(key, namespace=self$default_namespace, use_cache=TRUE) {
      self$get_value(self$get_hash(key, namespace), use_cache)
    },

    get_hash=function(key, namespace=self$default_namespace) {
      if (self$exists(key, namespace)) {
        self$driver$get_hash(key, namespace)
      } else {
        stop(KeyError(key, namespace))
      }
    },

    get_value=function(hash, use_cache=TRUE) {
      envir <- self$envir
      if (use_cache && exists0(hash, envir)) {
        value <- envir[[hash]]
      } else {
        if (!self$driver$exists_hash(hash)) {
          stop(HashError(hash))
        }
        value <- self$driver$get_object(hash)
        if (use_cache) {
          envir[[hash]] <- value
        }
      }
      value
    },

If driver$get_hash(key, namespace) throws an error if the key is not there (or alternatively simply return NULL would be OK) then we can avoid the self$exists(key, namespace) call. That can be tested for in the inst/spec tests too.

Then the second exists_hash could be removed if the driver promises to throw an error (through some sort of capability reporting thing).

if (self$driver$capabilities$get_object_throws) {
  value <- tryCatch(self$driver$get_object(hash), error=function(e) stop(HashError(hash)))
} else if (self$driver$exists_hash(hash)) {
  value <- self$driver$get_object(hash)
} else {
 stop(HashError(hash)
}
richfitz commented 8 years ago

done via dc7d4ad8266518f89b4e6b27b37d1af566787f98