ipld: Implement From trait.

This commit is contained in:
David Craven 2019-02-23 23:31:46 +01:00
parent 9d4c53ad4b
commit e2d2bc8541
No known key found for this signature in database
GPG Key ID: DF438712EA50DBB1
2 changed files with 78 additions and 7 deletions

View File

@ -82,7 +82,7 @@ mod tests {
#[test]
fn test_resolve_array_elem() {
let mut dag = IpldDag::new();
let data = Ipld::Array(vec![Ipld::U64(1), Ipld::U64(2), Ipld::U64(3)]);
let data = vec![1, 2, 3].into();
let cid = dag.put(&data).unwrap();
let mut path = IpldPath::new(cid);
@ -109,10 +109,9 @@ mod tests {
#[test]
fn test_resolve_object_elem() {
let mut dag = IpldDag::new();
let mut map = HashMap::new();
map.insert("key".to_string(), Ipld::Bool(false));
let data = Ipld::Object(map);
let cid = dag.put(&data).unwrap();
let mut data = HashMap::new();
data.insert("key", false);
let cid = dag.put(&data.into()).unwrap();
let mut path = IpldPath::new(cid);
path.push("key");
@ -124,9 +123,9 @@ mod tests {
#[test]
fn test_resolve_cid_elem() {
let mut dag = IpldDag::new();
let data1 = Ipld::Array(vec![Ipld::U64(1)]);
let data1 = vec![1].into();
let cid1 = dag.put(&data1).unwrap();
let data2 = Ipld::Array(vec![Ipld::Cid(cid1)]);
let data2 = vec![cid1].into();
let cid2 = dag.put(&data2).unwrap();
let mut path = IpldPath::new(cid2);

View File

@ -106,3 +106,75 @@ impl Encodable for Ipld {
}
}
}
impl From<u32> for Ipld {
fn from(u: u32) -> Self {
Ipld::U64(u as u64)
}
}
impl From<u64> for Ipld {
fn from(u: u64) -> Self {
Ipld::U64(u)
}
}
impl From<i32> for Ipld {
fn from(i: i32) -> Self {
Ipld::I64(i as i64)
}
}
impl From<i64> for Ipld {
fn from(i: i64) -> Self {
Ipld::I64(i)
}
}
impl From<Vec<u8>> for Ipld {
fn from(bytes: Vec<u8>) -> Self {
Ipld::Bytes(bytes)
}
}
impl From<String> for Ipld {
fn from(string: String) -> Self {
Ipld::String(string)
}
}
impl<T: Into<Ipld>> From<Vec<T>> for Ipld {
fn from(vec: Vec<T>) -> Self {
Ipld::Array(vec.into_iter().map(|ipld| ipld.into()).collect())
}
}
impl<T: Into<Ipld>> From<HashMap<String, T>> for Ipld {
fn from(map: HashMap<String, T>) -> Self {
Ipld::Object(map.into_iter().map(|(k, v)| (k, v.into())).collect())
}
}
impl<T: Into<Ipld>> From<HashMap<&str, T>> for Ipld {
fn from(map: HashMap<&str, T>) -> Self {
Ipld::Object(map.into_iter().map(|(k, v)| (k.to_string(), v.into())).collect())
}
}
impl From<f64> for Ipld {
fn from(f: f64) -> Self {
Ipld::F64(f)
}
}
impl From<bool> for Ipld {
fn from(b: bool) -> Self {
Ipld::Bool(b)
}
}
impl From<Cid> for Ipld {
fn from(cid: Cid) -> Self {
Ipld::Cid(cid)
}
}