I am kind of confused by the Buffer.copy api in node.js in the meaning of the buffer indexes. I was expecting it to be similar to memcpy in C/Unix but it does not seem to be the case
As per the API doc and an example provided in http://nodejs.org/docs/latest/api/buffers.html#buffer.copy
buffer.copy(targetBuffer, [targetStart], [sourceStart], [sourceEnd])
means the targetStart is not the index into targetBuffer with index starting with 0, same is the case with sourceStart. Rather the indexes seem to start with 1 and not 0. The most confusing is the sourceEnd. From the example looks like it the bytes before before the sourceEnd byte are copied, then how would the last byte be copied
The example in node.js doc is
Example: build two Buffers, then copy buf1 from byte 16 through byte 19 into buf2, starting at the 8th byte in buf2.
For this the statement is
buf1 = new Buffer(26);
buf2 = new Buffer(26);
buf1.copy(buf2, 8, 16, 20);
What if I wanted to copy till the 26th byte, do I need to specify 27 as sourceEnd ? looks very odd that I need to provide a value greater than the length of the source buffer
Can someone provide a clear explanation as to why node.js selected this kind of behaviour rather than remain similar to memcpy ?
The reason for choosing these (potentially confusing) index conventions likely has to do with the precedent set by core JavaScript functions such as
String.slice.Remember, node.js is based on JavaScript, not C/POSIX after all =)