Buffer.fromArray() missing from motoko base lib

I wanted to know if there is a reason why there is no fromArray fn for the Buffer class. All the other class data structures in the lib have a fromArray or fromEntries method that allows for instantiation from stable data structures.
Does having a fromArray method in the Buffer class have unexpected consequences like with the Array.append() fn? If not, I think it would be beneficial to include it in the base lib instead of devs implementing it in each project.
Would it also be possible for me to make a PR to the base repo with this feature?

2 Likes

I see no reason for not having this (@MatthewHammer whaddya think?). And do feel free to open a PR.

1 Like

It’s hard to recall, but I seem to remember some pressure to keep the API very small, because it enlarges each Buffer instance to have more methods?

Separately, I’m curious what reasonable semantics doing b.fromArray(a) would mean if b was non-empty? Would it erase those existing elements, or append to them? Either way seems confusing to me, personally.

But how about another place for this bufferFromArray functionality, which I agree is missing and reasonable?

For instance, I think a toBuffer function makes sense in the existing Array module, where it would be static, and not associated with any existing buffer object. Likewise, having a special array method toBuffer() would also be reasonable, but perhaps more work to add.

What do you think @tomijaga and @claudio ?

Here’s a PR `Array.buffer` by matthewhammer · Pull Request #387 · dfinity/motoko-base · GitHub

2 Likes

I was thinking of adding it as a static method in the Buffer module. This method would only instantiate a Buffer with all the elements in an array
So users would be able to instantiate buffers from an existing array like this:
let b = Buffer.fromArray([1, 2])

I like that you made a pr with this exact functionality in the Array module, but I think adding it to the Buffer would be more intuitive.

3 Likes

There is PR for Buffer.fromArray Add fromArray method to Buffer by xlaywan · Pull Request #368 · dfinity/motoko-base · GitHub

1 Like

Thanks, this is the exact functionality I was referring to.
I noticed that this pr uses the add buffer method for the fromArray method. The problem with that the given array could be significantly bigger than the size of the buffer. In this case, the buffer could resize and copy all its values more than once to add all the elements of the array. I made a PR that only resizes the array once if this happens. Efficient addArray and fromArray buffer methods by tomijaga · Pull Request #388 · dfinity/motoko-base · GitHub

2 Likes