R/memory-cache.R

MemoryCache <- R6Class(
  classname = "MemoryCache",
  inherit = Cache,

  public = list(
    initialize = function() {
      private$meta <-data.frame()
      private$values <- list()
    },

    # TODO: refactor the table update logic
    get = function(key, default = NULL) {
      key_hash <- private$hash(key)
      val <- private$values[[key_hash]]

      if (is.null(val)) {
        return(default)
      }

      row_index <- private$meta$key_hash == key_hash
      row <- private$meta[row_index, ]

      if (private$is_expired(row)) {
        self$delete(key)
        return(default)
      }

      row[["access_time"]] <- time_now()
      row[["access_count"]] <- row[["access_count"]] + 1
      private$meta[row_index, ] <- row

      val
    },

    set = function(key, value, expire_in = NULL) {
      private$meta <- rbind(private$meta, private$make_row(key, value, expire_in))
      private$values[[private$hash(key)]] <- value
    },

    delete = function(key) {
      key_hash <- private$hash(key)

      private$meta <- private$meta[private$meta$key_hash != key_hash, ]
      private$values[[key_hash]] <- NULL
    },

    exists = function(key) {
      !is.null(private$values[[private$hash(key)]])
    },

    trim = function() {
      # TODO
    },

    print_meta = function() {
      private$meta
    },

    destroy = function() {}
  ),

  private = list(
    meta = NULL,
    values = NULL,

    make_row = function(key, value, expire_in) {
      time_now <- time_now()

      data.frame(
        key_hash = private$hash(key),
        store_time = time_now,
        access_time = time_now,
        expire_time = ifelse(is.null(expire_in), NA, time_now + expire_in),
        access_count = 0
      )
    }
  )
)
skubicius/cashmere documentation built on May 22, 2019, 2:46 p.m.