use crate::errors::IntegerOverflowError;
use near_gas::NearGas;
#[derive(
borsh::BorshDeserialize,
borsh::BorshSerialize,
derive_more::Display,
derive_more::FromStr,
serde::Deserialize,
Clone,
Copy,
PartialEq,
Eq,
PartialOrd,
Ord,
Default,
Hash,
)]
#[repr(transparent)]
pub struct Gas(NearGas);
impl Gas {
pub const MAX: Gas = Gas::from_gas(u64::MAX);
pub const ZERO: Gas = Gas::from_gas(0);
pub const fn from_teragas(inner: u64) -> Self {
Self(NearGas::from_tgas(inner))
}
pub const fn from_gigagas(inner: u64) -> Self {
Self(NearGas::from_ggas(inner))
}
pub const fn from_gas(inner: u64) -> Self {
Self(NearGas::from_gas(inner))
}
pub const fn as_gas(self) -> u64 {
self.0.as_gas()
}
pub const fn as_gigagas(self) -> u64 {
self.0.as_ggas()
}
pub const fn as_teragas(self) -> u64 {
self.0.as_tgas()
}
pub const fn checked_add(self, rhs: Gas) -> Option<Self> {
if let Some(result) = self.0.checked_add(rhs.0) { Some(Self(result)) } else { None }
}
pub fn checked_add_result(self, rhs: Gas) -> Result<Self, IntegerOverflowError> {
self.checked_add(rhs).ok_or(IntegerOverflowError)
}
pub const fn checked_sub(self, rhs: Gas) -> Option<Self> {
if let Some(result) = self.0.checked_sub(rhs.0) { Some(Self(result)) } else { None }
}
pub const fn checked_mul(self, rhs: u64) -> Option<Self> {
if let Some(result) = self.0.checked_mul(rhs) { Some(Self(result)) } else { None }
}
pub const fn checked_div(self, rhs: u64) -> Option<Self> {
if let Some(result) = self.0.checked_div(rhs) { Some(Self(result)) } else { None }
}
pub const fn saturating_add(self, rhs: Gas) -> Gas {
Self(self.0.saturating_add(rhs.0))
}
pub const fn saturating_sub(self, rhs: Gas) -> Gas {
Self(self.0.saturating_sub(rhs.0))
}
pub const fn saturating_mul(self, rhs: u64) -> Gas {
Self(self.0.saturating_mul(rhs))
}
pub const fn saturating_div(self, rhs: u64) -> Gas {
if rhs == 0 {
return Gas::ZERO;
}
Self(self.0.saturating_div(rhs))
}
}
impl serde::Serialize for Gas {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
serializer.serialize_u64(self.as_gas())
}
}
impl core::fmt::Debug for Gas {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "{}", self.as_gas())
}
}
#[cfg(feature = "schemars")]
impl schemars::JsonSchema for Gas {
fn schema_name() -> std::borrow::Cow<'static, str> {
"NearGas".to_string().into()
}
fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
schemars::json_schema!({
"format": "uint64",
"minimum": 0,
"type": "integer"
})
}
}