Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions src/Buffer.mo
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@
/// determined at construction and cannot be changed).

import Prim "mo:⛔";
import Nat "Nat";
import Iter "Iter";

module {

Expand Down Expand Up @@ -47,6 +49,37 @@ module {
count += 1;
};

/// Adds all elements in the given array to this buffer.
public func addArray(arr : [X]) {
if (count + arr.size() >= elems.size()){
let size = if (count == 0) {
Nat.max(initCapacity, arr.size())
} else {
Nat.max(2 * elems.size(), count + arr.size())
};

let rng = Iter.range(0, size - 1);
let elemIter = Iter.map<Nat, X>(rng, func(i: Nat){
if (i < count) {
elems[i]
} else if (i < arr.size() + count) {
arr[i - count]
}else{
arr[0]
}
});

elems:= Iter.toArrayMut<X>(elemIter);
count += arr.size();
}else{
for (item in arr.vals()){
elems[count] := item;
count+=1;
};
};

};

/// Removes the item that was inserted last and returns it or `null` if no
/// elements had been added to the Buffer.
public func removeLast() : ?X {
Expand Down
16 changes: 16 additions & 0 deletions test/bufTest.mo
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,21 @@ do {
assert (c.toVarArray().size() == 2);
};

// regression test: initially-empty buffer grows to add elements in an array
do {
let buf = B.Buffer<Nat>(0);
assert (buf.size() == 0);

buf.addArray([1,2,3,4]);
assert (buf.toArray().size() == 4);
assert (buf.toArray() == [1,2,3,4]);

buf.addArray([5,6,7,8]);
assert (buf.toArray().size() == 8);
assert (buf.toArray() == [1,2,3,4,5,6,7,8]);

};

let {run;test;suite} = Suite;
run(suite("array",
[
Expand All @@ -111,3 +126,4 @@ run(suite("array",
M.equals(T.array<Nat>(T.natTestable, [0, 1, 2, 3]))
)
]));