GGist / bip-rs

BitTorrent Infrastructure Project In Rust
Apache License 2.0
296 stars 33 forks source link

Support Write Interface For Bencode Encoding #131

Open GGist opened 7 years ago

GGist commented 7 years ago

Many times we have some data that we want to bencode right before we write out to the network (or right when we need to check what the size of the data on the wire will be...). Often times, we will have to encode to a buffer that the bip_bencode library allocates and hands back to us.

However, for most use cases (and at least for tokio), users will be using dedicated network buffers. What will happen is that they will encode to the Vec that we return, and then just copy the contents to the network buffer. Instead, we should support writing directly to types like this via Write.

An additional use case for this is determining how many bytes an encoded bencode structure will use before actually encoding. We can expose such a method, but internally calling the encode with a custom Write object that just keeps a counter of bytes written, and return that to the user. This would allow for a zero allocation method to determine the size.

GGist commented 7 years ago

Update UtMetadata* messages to use this when available for things like caching the size of the bencode portion of the message.