Skip to main content

Hash

Struct Hash 

Source
pub struct Hash(/* private fields */);
Expand description

A SHA-256 hash: of a chunk’s bytes, or of the bytes that describe a file, a folder or a tree.

Implementations§

Source§

impl Hash

Source

pub const ZERO: Self

What an empty list has in place of a hash.

Source

pub const fn from_bytes(bytes: [u8; 32]) -> Self

Source

pub const fn as_bytes(&self) -> &[u8; 32]

Examples found in repository?
examples/speed.rs (line 58)
43fn main() -> Result<(), Box<dyn std::error::Error>> {
44    let megabytes: usize = match std::env::args().nth(1) {
45        Some(argument) => argument.parse()?,
46        None => 1024,
47    };
48    let data = filler(megabytes << 20);
49
50    let started = Instant::now();
51    let chunks = Chunking::FastCdcV1.cut(&data);
52    report("chunked", started, data.len());
53    println!("{:<22} {} chunks", "", chunks.len());
54
55    let started = Instant::now();
56    let mut mixed = 0_u8;
57    for chunk in &chunks {
58        mixed ^= Hash::of(chunk).as_bytes()[0];
59    }
60    report("hashed", started, data.len());
61
62    let store = MemoryStore::new();
63    let started = Instant::now();
64    let mut builder = Builder::new(&store, Chunking::FastCdcV1);
65    let file = builder.file_from_bytes(&data)?;
66    report("built", started, data.len());
67
68    let root = builder.finish(file, ExtraData::new())?;
69    let started = Instant::now();
70    verify(&store, &root)?;
71    report("checked", started, data.len());
72    println!("root {root} ({mixed:02x})");
73
74    // The tree is fetched from the first store into a second one, as a
75    // receiver would take it from a peer, and then written as a bundle and
76    // read back into a third. Each checks every byte as it comes.
77    let fetched = MemoryStore::new();
78    let started = Instant::now();
79    fetch(&fetched, &root, &mut Responder::new(&store))?;
80    report("fetched", started, data.len());
81
82    let imported = MemoryStore::new();
83    let mut bundle = Vec::with_capacity(data.len() + (1 << 20));
84    let started = Instant::now();
85    export(&store, &root, &mut bundle)?;
86    import(&imported, &root, &mut bundle.as_slice())?;
87    report("bundled", started, data.len());
88
89    if let Some(folder) = std::env::args().nth(2) {
90        let mut best = f64::MAX;
91        let (mut bytes, mut files) = (0, 0);
92        for _ in 0..5 {
93            let store = MemoryStore::new();
94            let started = Instant::now();
95            let root = build(&store, &folder, &BuildOptions::new())?;
96            best = best.min(started.elapsed().as_secs_f64());
97            bytes = record_of(&store, &root)?.top().size;
98            files = store.count(Stored::FileList);
99        }
100        let rate = bytes as f64 / (1 << 20) as f64 / best.max(1e-9);
101        println!("{:<22} {best:>7.3} s  {rate:>8.0} MiB/s", "built from disk");
102        println!("{:<22} {files} different files, {bytes} bytes", "");
103    }
104    Ok(())
105}
Source

pub fn of(bytes: &[u8]) -> Self

The SHA-256 of bytes.

Examples found in repository?
examples/speed.rs (line 58)
43fn main() -> Result<(), Box<dyn std::error::Error>> {
44    let megabytes: usize = match std::env::args().nth(1) {
45        Some(argument) => argument.parse()?,
46        None => 1024,
47    };
48    let data = filler(megabytes << 20);
49
50    let started = Instant::now();
51    let chunks = Chunking::FastCdcV1.cut(&data);
52    report("chunked", started, data.len());
53    println!("{:<22} {} chunks", "", chunks.len());
54
55    let started = Instant::now();
56    let mut mixed = 0_u8;
57    for chunk in &chunks {
58        mixed ^= Hash::of(chunk).as_bytes()[0];
59    }
60    report("hashed", started, data.len());
61
62    let store = MemoryStore::new();
63    let started = Instant::now();
64    let mut builder = Builder::new(&store, Chunking::FastCdcV1);
65    let file = builder.file_from_bytes(&data)?;
66    report("built", started, data.len());
67
68    let root = builder.finish(file, ExtraData::new())?;
69    let started = Instant::now();
70    verify(&store, &root)?;
71    report("checked", started, data.len());
72    println!("root {root} ({mixed:02x})");
73
74    // The tree is fetched from the first store into a second one, as a
75    // receiver would take it from a peer, and then written as a bundle and
76    // read back into a third. Each checks every byte as it comes.
77    let fetched = MemoryStore::new();
78    let started = Instant::now();
79    fetch(&fetched, &root, &mut Responder::new(&store))?;
80    report("fetched", started, data.len());
81
82    let imported = MemoryStore::new();
83    let mut bundle = Vec::with_capacity(data.len() + (1 << 20));
84    let started = Instant::now();
85    export(&store, &root, &mut bundle)?;
86    import(&imported, &root, &mut bundle.as_slice())?;
87    report("bundled", started, data.len());
88
89    if let Some(folder) = std::env::args().nth(2) {
90        let mut best = f64::MAX;
91        let (mut bytes, mut files) = (0, 0);
92        for _ in 0..5 {
93            let store = MemoryStore::new();
94            let started = Instant::now();
95            let root = build(&store, &folder, &BuildOptions::new())?;
96            best = best.min(started.elapsed().as_secs_f64());
97            bytes = record_of(&store, &root)?.top().size;
98            files = store.count(Stored::FileList);
99        }
100        let rate = bytes as f64 / (1 << 20) as f64 / best.max(1e-9);
101        println!("{:<22} {best:>7.3} s  {rate:>8.0} MiB/s", "built from disk");
102        println!("{:<22} {files} different files, {bytes} bytes", "");
103    }
104    Ok(())
105}
Source

pub fn from_slice(bytes: &[u8]) -> Result<Self>

Reads a hash from exactly 32 bytes.

Source

pub fn to_hex(&self) -> String

The hash as 64 lowercase hex digits.

Examples found in repository?
examples/roundtrip.rs (line 64)
57    fn path(&self, kind: Stored, hash: &Hash) -> PathBuf {
58        let kind = match kind {
59            Stored::Chunk => "chunks",
60            Stored::FileList => "files",
61            Stored::FolderList => "folders",
62            Stored::Record => "records",
63        };
64        let name = hash.to_hex();
65        self.dir.join(kind).join(&name[..2]).join(name)
66    }
Source

pub fn from_hex(text: &str) -> Result<Self>

Reads 64 lowercase hex digits.

Trait Implementations§

Source§

impl Clone for Hash

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Copy for Hash

Source§

impl Debug for Hash

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for Hash

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Eq for Hash

Source§

impl From<[u8; 32]> for Hash

Source§

fn from(bytes: [u8; 32]) -> Self

Converts to this type from the input type.
Source§

impl Hash for Hash

Source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl Ord for Hash

Source§

fn cmp(&self, other: &Self) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 (const: unstable) · Source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 (const: unstable) · Source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 (const: unstable) · Source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized,

Restrict a value to a certain interval. Read more
Source§

fn clamp_to<R>(self, range: R) -> Self
where Self: Sized, R: ClampBounds<Self>,

🔬This is a nightly-only experimental API. (clamp_to)
Restrict a value to a certain range. Read more
Source§

impl PartialEq for Hash

Source§

fn eq(&self, other: &Self) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl PartialOrd for Hash

Source§

fn partial_cmp(&self, other: &Self) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 (const: unstable) · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 (const: unstable) · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 (const: unstable) · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 (const: unstable) · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl StructuralPartialEq for Hash

Auto Trait Implementations§

§

impl Forget for Hash

§

impl Freeze for Hash

§

impl Move for Hash

§

impl RefUnwindSafe for Hash

§

impl Send for Hash

§

impl Sync for Hash

§

impl Unpin for Hash

§

impl UnsafeUnpin for Hash

§

impl UnwindSafe for Hash

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.