janestreet / bin_prot

Binary protocol generator
MIT License
73 stars 21 forks source link

Query about read/write interface: why does read have a pos_ref, and write have a pos? #22

Closed tomjridge closed 4 years ago

tomjridge commented 4 years ago

Question as title. I don't mind, I just thought it looked a bit odd. What was the reasoning behind making the interfaces different in this way?

Thanks

aalekseyev commented 4 years ago

The reason is that the read function needs to return both the position it read to and the resulting value. We could return both of these values by wrapping them in a tuple, but that incurs an extra allocation. Storing the int into the ref using side-effect lets us avoid that allocation.

There is no corresponding problem with write because write only needs to return one thing, so we use the simpler interface.

tomjridge commented 4 years ago

Thank you @aalekseyev ! I had not considered the cost of the extra allocation.