synlestidae / rustorrent

Modern, easy-to-use BitTorrent library for the Rust ecosystem (WIP)
Apache License 2.0
5 stars 0 forks source link

Implement TryFrom<...>, From<...>, TryInto<...>, Into<...> for Bencode data structures #8

Closed synlestidae closed 8 years ago

synlestidae commented 8 years ago

Only after I wrote the bulk of the code for #7 did I realise that having From and Into traits implemented for our basic data structures like Bencode, BInt, etc could be hella useful.

As an example of this utility, suppose Bencode implemented TryInto. Then on the BDict impl I could write the get method like

pub fn get<A: TryInto<B>>(&self) -> Option<B> { ... }
...
let field_private: Option<u32> = some_dict.get("private");

This takes advantage of Rust's type inference. Can this work? I hope it does. Currently my MetaInfo parser has a lot of functions that take a value out of a BDict, check if it exists, check if the type matches and converts it. I could remove a lot of that code in metainfo.rs and make it more readable.

MatejLach commented 8 years ago

@synlestidae Great idea, I think implementing From and TryFrom should give us the corresponding Into trait implementations 'for 'free' as well. Will look into it!

synlestidae commented 8 years ago

Just learnt that TryFrom, TryInto are unstable features :/ so would have to either use right nightly or roll my own TryFrom, TryInto trait (which can't be too hard right?)

src/bencode/mod.rs:41:5: 41:28 error: use of unstable library feature 'try_from' (see issue #33417)
src/bencode/mod.rs:41     type Err = DecodeError;
synlestidae commented 8 years ago

Fixed in #6