buffer-browserify icon indicating copy to clipboard operation
buffer-browserify copied to clipboard

slicing support

Open husio-org opened this issue 11 years ago • 4 comments

Hi!

I need slicing for a library that i am porting.

I have started to look into how to make it work. The main issue seems to me that Buffer.slice and Array.slice work in a different way. The first references to the original buffer, and modifications alter the original buffer, while the second generates a new copy.

Did you started to look into this? comments / directions are welcome!

husio-org avatar Jul 01 '13 07:07 husio-org

Hi,

I haven't started on this yet so feel free to submit a PR for it.

I don't think that it'll be possible to have the sliced buffer share its elements with the original. Hopefully, this is a feature that is not widely used...

toots avatar Jul 01 '13 14:07 toots

Yes, I am working on it, because I need it with something I am porting. Will send PR when I have something.

The particular use case is splitting a received buffer into several sub packets. It seems to be read-only slices.

I will try to comply with the original functionality, but I also think its going to be hard. I am currently looking into getters/setters and pure prototypal inheritance...

If it is not possible, we could log a warning and encourage people to migrate buffer[]= to buffer.set() if they want to write to slices updating the original buffer.

husio-org avatar Jul 02 '13 07:07 husio-org

I needed this fixed too, so to minimize my changes I simply copied the data from one buffer to another, like so:

for (var i = 0; i < this.length; i++) {
  this[i] = subject.get(i+offset);
}

This was sufficient to get the project I'm working on up and running.

I have a fork up, but I have not submitted a PR. Since the buffer was being copied during normal creation, I figured this was a good approach, but I'd still like to hear your thoughts.

danthegoodman avatar Jul 02 '13 14:07 danthegoodman

I have been looking at how to do this as clean as possible...

The option would be to complete the implementation of get and set, using the parent and traslating the index with offset.

Then using Object.defineProperty on the index properties: 0,1,2... to use delegate on get/set.

That would get this working for modern browsers only, coz IE8 does not support Object.defineProperty unless on a DOM object.

Whatever the case, something is going to break.

I would say that the use case of updating a slice and specting the parent to get updated also is much less frequent than old browsers.

I would go with dan suggestion... I am going to test it in our particular case...

husio-org avatar Jul 04 '13 11:07 husio-org