Skip to main content

rustolio_db/
value.rs

1//
2// SPDX-License-Identifier: MPL-2.0
3//
4// Copyright (c) 2026 Tobias Binnewies. All rights reserved.
5//
6// This Source Code Form is subject to the terms of the Mozilla Public
7// License, v. 2.0. If a copy of the MPL was not distributed with this
8// file, You can obtain one at http://mozilla.org/MPL/2.0/.
9//
10
11use std::hash::Hash;
12
13use rustolio_utils::bytes::encoding::{decode_from_bytes, encode_to_bytes};
14use rustolio_utils::bytes::Bytes;
15use rustolio_utils::crypto::signature::PublicKey;
16use rustolio_utils::prelude::*;
17
18#[derive(Debug, Clone, PartialEq, Eq, Hash, Decode, Encode)]
19pub struct Value {
20    // Signer must be first to enable partial decoding of a file to check if the signer match
21    signer: Option<PublicKey>,
22    encoded: Bytes,
23}
24
25impl Value {
26    pub fn from_value(t: &impl Encode) -> rustolio_utils::Result<Self> {
27        Ok(Value {
28            signer: None,
29            encoded: encode_to_bytes(t).context("Failed to encode value")?,
30        })
31    }
32
33    pub fn signed_from_value(t: &impl Encode, signer: PublicKey) -> rustolio_utils::Result<Self> {
34        Ok(Value {
35            signer: Some(signer),
36            encoded: encode_to_bytes(t).context("Failed to encode value")?,
37        })
38    }
39
40    pub fn into_value<T: Decode>(self) -> rustolio_utils::Result<T> {
41        decode_from_bytes(self.encoded).context("Failed to decode value")
42    }
43
44    pub fn signer(&self) -> Option<PublicKey> {
45        self.signer
46    }
47}