Add fromArray method to Buffer#368
Conversation
Useful to use in pre/post upgrade in combination with `b.toArray()`
| /// Construct a buffer from an array. | ||
| public func fromArray<T>(arr: [T]): Buffer<T> { | ||
| let count = arr.size(); | ||
| let buffer = Buffer<T>(count); | ||
|
|
||
| var i = 0; | ||
| label l loop { | ||
| if (i >= count) break l; | ||
| buffer.add(arr[i]); | ||
| i += 1; | ||
| }; | ||
|
|
||
| buffer | ||
| }; |
There was a problem hiding this comment.
Thanks! Why not simply
| /// Construct a buffer from an array. | |
| public func fromArray<T>(arr: [T]): Buffer<T> { | |
| let count = arr.size(); | |
| let buffer = Buffer<T>(count); | |
| var i = 0; | |
| label l loop { | |
| if (i >= count) break l; | |
| buffer.add(arr[i]); | |
| i += 1; | |
| }; | |
| buffer | |
| }; | |
| /// Construct a buffer from an array. | |
| public func fromArray<T>(arr: [T]): Buffer<T> { | |
| return { count = arr.size(); elems = Array.thaw(arr) } | |
| } |
There was a problem hiding this comment.
Looks definitely better!
But can it create an instance of the Buffer class? Motoko Playground shows error:

It was intended to be a static method like let buf = Buffer.fromArray<Nat>([1, 2, 3]);
Probably it will work as an instance method like:
let buf = Buffer.Buffer<Nat>(0);
buf.fromArray([1, 2, 3]);Not sure we can leave the name fromArray in this case, because in other files in base lib from* methods are static.
Link to the playground https://m7sm4-2iaaa-aaaab-qabra-cai.raw.ic0.app/?tag=2337373062
There was a problem hiding this comment.
Ah, right, Motoko classes have only one constructor usually…
Maybe first add buffer.addArray (which can be implemented efficiently using Array.thraw, especially if the buffer is empty before), and then the fromArray function.
|
This looks closely related to #387. Perhaps it can be closed now? @matthewhammer ? |
|
The discussion here seems stalled on the most efficient way to do the operation. In a closely related PR, we are proposing the same method functionality and name, but with the naive implementation. Maybe we can start there and refine? |
d52aecd to
08507fc
Compare

Useful to use in postupgrade in combination with
buffer.toArray()in preupgrade