diff --git a/src/Buffer.mo b/src/Buffer.mo index 4608fa59..ad341a2c 100644 --- a/src/Buffer.mo +++ b/src/Buffer.mo @@ -32,6 +32,23 @@ public class Buffer (initCapacity : Nat) { var count : Nat = 0; var elems : [var X] = [var]; // initially empty; allocated upon first `add` + /// Get purely-functional representation + public func share() : [X] { + Prim.Array_tabulate(count, func i = elems[i]) + }; + + /// Put purely-functional representation into class. + public func unshare(xs : [X]) { + count := xs.size(); + if (count == 0) { + elems := [var]; + }; + elems := Prim.Array_init(count, xs[0]); + for (i in elems.keys()) { + elems[i] := xs[i]; + }; + }; + /// Adds a single element to the buffer. public func add(elem : X) { if (count == elems.size()) { diff --git a/src/HashMap.mo b/src/HashMap.mo index a0d978e9..ef59a7a0 100644 --- a/src/HashMap.mo +++ b/src/HashMap.mo @@ -35,6 +35,17 @@ public class HashMap ( var table : [var KVs] = [var]; var _count : Nat = 0; + /// Get purely-functional representation + public func share() : ([KVs], Nat) { + (A.freeze table, _count) + }; + + /// Put purely-functional representation into class. Need to make sure the tree is constructed with the same Eq and Hash functions + public func unsafeUnshare(t : [KVs], count : Nat) { + table := A.thaw(t); + _count := count; + }; + /// Returns the number of entries in this HashMap. public func size() : Nat = _count; diff --git a/src/RBTree.mo b/src/RBTree.mo index 84770b65..18d253d2 100644 --- a/src/RBTree.mo +++ b/src/RBTree.mo @@ -25,12 +25,17 @@ public class RBTree(compareTo:(X, X) -> O.Order) { /// Tree as share data. /// /// Get non-OO, purely-functional representation: - /// for drawing, pretty-printing and non-OO contexts + /// for drawing, pretty-printing, upgrades and non-OO contexts /// (e.g., async args and results): public func share() : Tree { tree }; + /// Put purely-functional representation into class. Need to make sure the tree is constructed with the same compare function + public func unsafeUnshare(t: Tree) { + tree := t; + }; + /// Get the value associated with a given key. public func get(x:X) : ?Y = getRec(x, compareTo, tree);