add: dagpb getters to ipfs-unixfs
This commit is contained in:
parent
da7f2b4882
commit
ba98835a7e
37
unixfs/src/dagpb.rs
Normal file
37
unixfs/src/dagpb.rs
Normal file
@ -0,0 +1,37 @@
|
||||
///! dag-pb support operations. Placing this module inside unixfs module is a bit unfortunate but
|
||||
///! follows from the inseparability of dag-pb and UnixFS.
|
||||
|
||||
use std::convert::TryFrom;
|
||||
use std::borrow::Cow;
|
||||
use cid::Cid;
|
||||
use crate::pb::PBNode;
|
||||
use crate::InvalidCidInLink;
|
||||
|
||||
/// Extracts the PBNode::Data field from the block as it appears on the block.
|
||||
pub fn node_data(block: &[u8]) -> Result<Option<&[u8]>, quick_protobuf::Error> {
|
||||
let doc = PBNode::try_from(block)?;
|
||||
Ok(match doc.Data {
|
||||
Some(Cow::Borrowed(slice)) => Some(slice),
|
||||
Some(Cow::Owned(_)) => unreachable!("never converted to owned"),
|
||||
None => None,
|
||||
})
|
||||
}
|
||||
|
||||
/// Extracts the PBNode::Links as Cids usable for the ipfs `refs` operation.
|
||||
pub fn nameless_links(block: &[u8]) -> Result<Result<Vec<Cid>, InvalidCidInLink>, quick_protobuf::Error> {
|
||||
let doc = PBNode::try_from(block)?;
|
||||
|
||||
Ok(doc.Links.into_iter()
|
||||
.enumerate()
|
||||
.map(|(nth, link)| {
|
||||
let hash = link.Hash.as_deref().unwrap_or_default();
|
||||
|
||||
match Cid::try_from(hash) {
|
||||
Ok(cid) => Ok(cid),
|
||||
Err(e) => Err(InvalidCidInLink::from((nth, link, e))),
|
||||
}
|
||||
})
|
||||
.collect::<Result<Vec<_>, _>>())
|
||||
}
|
||||
|
||||
|
@ -15,6 +15,9 @@ pub use dir::{resolve, LookupError, MaybeResolved, ResolveError};
|
||||
mod pb;
|
||||
use crate::pb::UnixFsType;
|
||||
|
||||
/// Support operations for the dag-pb, the outer shell of UnixFS.
|
||||
pub mod dagpb;
|
||||
|
||||
/// A link could not be transformed into a Cid.
|
||||
#[derive(Debug)]
|
||||
pub struct InvalidCidInLink {
|
||||
|
Loading…
Reference in New Issue
Block a user