Skip to content

Commit

Permalink
add BoxValue value getter and TryFrom, Into impl (made in #51);
Browse files Browse the repository at this point in the history
  • Loading branch information
greenhat committed Jun 26, 2020
1 parent e6d8dbc commit dd841bd
Showing 1 changed file with 39 additions and 8 deletions.
47 changes: 39 additions & 8 deletions sigma-tree/src/chain/ergo_box/box_value.rs
Expand Up @@ -4,26 +4,57 @@
use serde::{Deserialize, Serialize};
use sigma_ser::serializer::{SerializationError, SigmaSerializable};
use sigma_ser::vlq_encode;
use std::io;
use std::{convert::TryFrom, io};

/// Box value
#[derive(PartialEq, Eq, Hash, Debug, Clone)]
#[cfg_attr(feature = "with-serde", derive(Serialize, Deserialize))]
pub struct BoxValue(u64);

impl BoxValue {
/// Create new value (with bounds check)
pub fn new(v: u64) -> Option<BoxValue> {
const MIN_RAW: u64 = 1;
const MAX_RAW: u64 = i64::MAX as u64;

/// Minimal value
pub const MIN: BoxValue = BoxValue(BoxValue::MIN_RAW);

/// Create from u64 with bounds check
pub fn new(v: u64) -> Result<BoxValue, BoxValueError> {
BoxValue::try_from(v)
}

/// Check if a value is in bounds
pub fn within_bounds(v: u64) -> bool {
v >= BoxValue::MIN_RAW && v <= BoxValue::MAX_RAW
}

/// Get u64 value
pub fn value(&self) -> u64 {
self.0
}
}

/// BoxValue errors
#[derive(PartialEq, Eq, Debug, Clone)]
pub enum BoxValueError {
/// Value is out of bounds
OutOfBounds,
}

impl TryFrom<u64> for BoxValue {
type Error = BoxValueError;
fn try_from(v: u64) -> Result<Self, Self::Error> {
if BoxValue::within_bounds(v) {
Some(BoxValue(v))
Ok(BoxValue(v))
} else {
None
Err(BoxValueError::OutOfBounds)
}
}
}

/// Check if a value is in bounds
pub fn within_bounds(v: u64) -> bool {
v >= 1 && v <= i64::MAX as u64
impl Into<u64> for BoxValue {
fn into(self) -> u64 {
self.0
}
}

Expand Down

0 comments on commit dd841bd

Please sign in to comment.