darkfi_serial/types/
hash.rs

1/* This file is part of DarkFi (https://dark.fi)
2 *
3 * Copyright (C) 2020-2026 Dyne.org foundation
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU Affero General Public License as
7 * published by the Free Software Foundation, either version 3 of the
8 * License, or (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 * GNU Affero General Public License for more details.
14 *
15 * You should have received a copy of the GNU Affero General Public License
16 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
17 */
18
19use std::io::{Read, Result, Write};
20
21#[cfg(feature = "async")]
22use crate::{
23    async_lib::{AsyncReadExt, AsyncWriteExt},
24    async_trait, AsyncDecodable, AsyncEncodable, AsyncRead, AsyncWrite,
25};
26
27use crate::{Decodable, Encodable, ReadExt, WriteExt};
28
29#[cfg(feature = "blake3")]
30impl Encodable for blake3::Hash {
31    fn encode<S: Write>(&self, s: &mut S) -> Result<usize> {
32        s.write_slice(self.as_bytes())?;
33        Ok(blake3::OUT_LEN)
34    }
35}
36
37#[cfg(all(feature = "blake3", feature = "async"))]
38#[async_trait]
39impl AsyncEncodable for blake3::Hash {
40    async fn encode_async<S: AsyncWrite + Unpin + Send>(&self, s: &mut S) -> Result<usize> {
41        s.write_slice_async(self.as_bytes()).await?;
42        Ok(blake3::OUT_LEN)
43    }
44}
45
46#[cfg(feature = "blake3")]
47impl Decodable for blake3::Hash {
48    fn decode<D: Read>(d: &mut D) -> Result<Self> {
49        let mut bytes = [0u8; blake3::OUT_LEN];
50        d.read_slice(&mut bytes)?;
51        Ok(bytes.into())
52    }
53}
54
55#[cfg(all(feature = "blake3", feature = "async"))]
56#[async_trait]
57impl AsyncDecodable for blake3::Hash {
58    async fn decode_async<D: AsyncRead + Unpin + Send>(d: &mut D) -> Result<Self> {
59        let mut bytes = [0u8; blake3::OUT_LEN];
60        d.read_slice_async(&mut bytes).await?;
61        Ok(bytes.into())
62    }
63}