randomx_rust_wrapper/
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 serde::Deserialize;
19use serde::Serialize;
20
21pub const RANDOMX_RESULT_SIZE: usize = 32;
22
23type ResultHashInner = [u8; RANDOMX_RESULT_SIZE];
24
25#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
26#[serde(transparent)]
27#[repr(transparent)]
28pub struct ResultHash(ResultHashInner);
29
30impl ResultHash {
31    pub fn from_slice(hash: ResultHashInner) -> Self {
32        Self(hash)
33    }
34
35    pub fn into_slice(self) -> ResultHashInner {
36        self.0
37    }
38
39    pub(crate) fn empty() -> Self {
40        Self([0u8; RANDOMX_RESULT_SIZE])
41    }
42
43    pub(crate) fn as_raw_mut(&mut self) -> *mut std::ffi::c_void {
44        self.0.as_mut_ptr() as *mut std::ffi::c_void
45    }
46}
47
48impl AsRef<ResultHashInner> for ResultHash {
49    fn as_ref(&self) -> &ResultHashInner {
50        &self.0
51    }
52}
53
54impl FromHex for ResultHash {
55    type Error = <[u8; 32] as FromHex>::Error;
56
57    fn from_hex<T: AsRef<[u8]>>(hex: T) -> Result<Self, Self::Error> {
58        ResultHashInner::from_hex(hex).map(Self)
59    }
60}