wasmer_runtime_core_near/
units.rs1use crate::error::PageError;
4use borsh::{BorshDeserialize, BorshSerialize};
5use std::{
6 fmt,
7 ops::{Add, Sub},
8};
9
10pub const WASM_PAGE_SIZE: usize = 65_536;
12pub const WASM_MAX_PAGES: usize = 65_536;
14pub const WASM_MIN_PAGES: usize = 256;
17
18#[derive(
20 Serialize,
21 Deserialize,
22 Copy,
23 Clone,
24 PartialEq,
25 Eq,
26 PartialOrd,
27 Ord,
28 BorshSerialize,
29 BorshDeserialize,
30)]
31pub struct Pages(pub u32);
32
33impl Pages {
34 pub fn checked_add(self, rhs: Pages) -> Result<Pages, PageError> {
36 let added = (self.0 as usize) + (rhs.0 as usize);
37 if added <= WASM_MAX_PAGES {
38 Ok(Pages(added as u32))
39 } else {
40 Err(PageError::ExceededMaxPages(
41 self.0 as usize,
42 rhs.0 as usize,
43 added,
44 ))
45 }
46 }
47
48 pub fn bytes(self) -> Bytes {
50 self.into()
51 }
52}
53
54impl fmt::Debug for Pages {
55 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
56 write!(f, "{} pages", self.0)
57 }
58}
59
60impl From<u32> for Pages {
61 fn from(other: u32) -> Self {
62 Pages(other)
63 }
64}
65
66#[derive(Serialize, Deserialize, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
68pub struct Bytes(pub usize);
69
70impl fmt::Debug for Bytes {
71 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
72 write!(f, "{} bytes", self.0)
73 }
74}
75
76impl From<Pages> for Bytes {
77 fn from(pages: Pages) -> Bytes {
78 Bytes((pages.0 as usize) * WASM_PAGE_SIZE)
79 }
80}
81
82impl From<usize> for Bytes {
83 fn from(other: usize) -> Self {
84 Bytes(other)
85 }
86}
87
88impl<T> Sub<T> for Pages
89where
90 T: Into<Pages>,
91{
92 type Output = Pages;
93 fn sub(self, rhs: T) -> Pages {
94 Pages(self.0 - rhs.into().0)
95 }
96}
97
98impl<T> Add<T> for Pages
99where
100 T: Into<Pages>,
101{
102 type Output = Pages;
103 fn add(self, rhs: T) -> Pages {
104 Pages(self.0 + rhs.into().0)
105 }
106}
107
108impl From<Bytes> for Pages {
109 fn from(bytes: Bytes) -> Pages {
110 Pages((bytes.0 / WASM_PAGE_SIZE) as u32)
111 }
112}
113
114impl<T> Sub<T> for Bytes
115where
116 T: Into<Bytes>,
117{
118 type Output = Bytes;
119 fn sub(self, rhs: T) -> Bytes {
120 Bytes(self.0 - rhs.into().0)
121 }
122}
123
124impl<T> Add<T> for Bytes
125where
126 T: Into<Bytes>,
127{
128 type Output = Bytes;
129 fn add(self, rhs: T) -> Bytes {
130 Bytes(self.0 + rhs.into().0)
131 }
132}