ccp_randomx_types/
result_hash.rs

1/*
2 * Copyright 2024 Fluence Labs Limited
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *     http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17use hex::FromHex;
18use hex::ToHex;
19use serde::Deserialize;
20use serde::Serialize;
21
22pub const RANDOMX_RESULT_SIZE: usize = 32;
23
24type ResultHashInner = [u8; RANDOMX_RESULT_SIZE];
25
26#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
27#[serde(transparent)]
28#[repr(transparent)]
29pub struct ResultHash(ResultHashInner);
30
31impl ResultHash {
32    pub fn from_slice(hash: ResultHashInner) -> Self {
33        Self(hash)
34    }
35
36    pub fn into_slice(self) -> ResultHashInner {
37        self.0
38    }
39}
40
41impl AsRef<ResultHashInner> for ResultHash {
42    fn as_ref(&self) -> &ResultHashInner {
43        &self.0
44    }
45}
46
47impl AsMut<ResultHashInner> for ResultHash {
48    fn as_mut(&mut self) -> &mut ResultHashInner {
49        &mut self.0
50    }
51}
52
53impl FromHex for ResultHash {
54    type Error = <[u8; 32] as FromHex>::Error;
55
56    fn from_hex<T: AsRef<[u8]>>(hex: T) -> Result<Self, Self::Error> {
57        ResultHashInner::from_hex(hex).map(Self)
58    }
59}
60
61impl ToHex for ResultHash {
62    fn encode_hex<T: std::iter::FromIterator<char>>(&self) -> T {
63        ToHex::encode_hex(&self.0)
64    }
65
66    fn encode_hex_upper<T: std::iter::FromIterator<char>>(&self) -> T {
67        ToHex::encode_hex_upper(&self.0)
68    }
69}