 
 ;; Filesystem storage:
 
+(defvar elfeed-ref-archive nil
+  "Index of archived/packed content.")
+
+(defvar elfeed-ref-cache nil
+  "Temporary storage of the full archive content.")
+
 (defstruct elfeed-ref
   id)
 

                        when (null (cddr (directory-files dir)))
                        do (delete-directory dir)))))

(defun elfeed-db-gc-safe ()
  "Run `elfeed-db-gc' without triggering any errors, for use as a safe hook."
  (ignore-errors (elfeed-db-gc)))

         (subdir (expand-file-name (substring id 0 2) root)))
    (expand-file-name id subdir)))

(defun* elfeed-ref-archive-filename (&optional (suffix ""))
  "Return the base filename of the archive files."
  (concat (expand-file-name "data/archive" elfeed-db-directory) suffix))

(defun elfeed-ref-archive-load ()
  "Load the archived ref index."
  (let ((archive-index (elfeed-ref-archive-filename ".index")))
    (if (file-exists-p archive-index)
      (with-temp-buffer
        (insert-file-contents archive-index)
        (setf elfeed-ref-archive (read (current-buffer))))
      (setf elfeed-ref-archive :empty))))

(defun elfeed-ref-archive-ensure ()
  "Ensure that the archive index is loaded."
  (when (null elfeed-ref-archive) (elfeed-ref-archive-load)))

(defun elfeed-ref-exists-p (ref)
  "Return true if REF can be dereferenced."
  (elfeed-ref-archive-ensure)
  (or (and (hash-table-p elfeed-ref-archive)
           (not (null (gethash (elfeed-ref-id ref) elfeed-ref-archive))))
      (file-exists-p (elfeed-ref--file ref))))

(defun elfeed-deref (ref)
  "Fetch the content behind the reference, or nil if non-existent."
  (elfeed-ref-archive-ensure)
  (if (not (elfeed-ref-p ref))
      ref
    (let ((index (and (hash-table-p elfeed-ref-archive)
                      (gethash (elfeed-ref-id ref) elfeed-ref-archive)))
          (archive-file (elfeed-ref-archive-filename ".gz")))
      (if (and index (file-exists-p archive-file))
          (progn
            (when (null elfeed-ref-cache)
              (with-temp-buffer
                (insert-file-contents archive-file)
                (setf elfeed-ref-cache (buffer-string)))
              ;; Clear cache on next turn.
              (run-at-time 0 nil (lambda () (setf elfeed-ref-cache nil))))
            (substring elfeed-ref-cache (car index) (cdr index)))
        (let ((file (elfeed-ref--file ref)))
          (when (file-exists-p file)
            (with-temp-buffer
              (insert-file-contents file)
              (buffer-string))))))))

(defun elfeed-ref (content)
  "Create a reference to CONTENT, to be persistently stored."
