services/cloudsync/CloudSyncBookmarksFolderCache.jsm
author Julian Seward <jseward@acm.org>
Tue, 24 Jan 2017 17:10:01 +0100
changeset 361633 a9f258d042482099bbbd9bfd235efbf742959df0
parent 360242 4a4bd6ca18c3860d74f5a3b63ce316b6e142ce94
permissions -rw-r--r--
Bug 1232696 - Remove NS_DECL_AND_IMPL_ZEROING_OPERATOR_NEW as it causes segfaulting for GCC 6 builds (1 of 5, fixes for view/). r=tnikkel.

/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

"use strict";

this.EXPORTED_SYMBOLS = ["FolderCache"];

// Cache for bookmarks folder heirarchy.
var FolderCache = function() {
  this.cache = new Map();
}

FolderCache.prototype = {
  has(id) {
    return this.cache.has(id);
  },

  insert(id, parentId) {
    if (this.cache.has(id)) {
      return;
    }

    if (parentId && !(this.cache.has(parentId))) {
      throw new Error("insert :: parentId not found in cache: " + parentId);
    }

    this.cache.set(id, {
      parent: parentId || null,
      children: new Set(),
    });

    if (parentId) {
      this.cache.get(parentId).children.add(id);
    }
  },

  remove(id) {
    if (!(this.cache.has(id))) {
      throw new Error("remote :: id not found in cache: " + id);
    }

    let parentId = this.cache.get(id).parent;
    if (parentId) {
      this.cache.get(parentId).children.delete(id);
    }

    for (let child of this.cache.get(id).children) {
      this.cache.get(child).parent = null;
    }

    this.cache.delete(id);
  },

  setParent(id, parentId) {
    if (!(this.cache.has(id))) {
      throw new Error("setParent :: id not found in cache: " + id);
    }

    if (parentId && !(this.cache.has(parentId))) {
      throw new Error("setParent :: parentId not found in cache: " + parentId);
    }

    let oldParent = this.cache.get(id).parent;
    if (oldParent) {
      this.cache.get(oldParent).children.delete(id);
    }
    this.cache.get(id).parent = parentId;
    this.cache.get(parentId).children.add(id);

    return true;
  },

  getParent(id) {
    if (this.cache.has(id)) {
      return this.cache.get(id).parent;
    }

    throw new Error("getParent :: id not found in cache: " + id);
  },

  getChildren(id) {
    if (this.cache.has(id)) {
      return this.cache.get(id).children;
    }

    throw new Error("getChildren :: id not found in cache: " + id);
  },

  setChildren(id, children) {
    for (let child of children) {
      if (!this.cache.has(child)) {
        this.insert(child, id);
      } else {
        this.setParent(child, id);
      }
    }
  },

  dump() {
    dump("FolderCache: " + JSON.stringify(this.cache) + "\n");
  },
};

this.FolderCache = FolderCache;