1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
use holochain_core_types::error::HolochainError;
use holochain_json_api::{error::JsonError, json::JsonString};

use memory::{MemoryBits, MemoryInt, MEMORY_INT_MAX};

#[derive(Copy, Clone, Debug, PartialEq)]
pub struct Offset(MemoryInt);
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct Length(MemoryInt);

impl From<Offset> for MemoryInt {
    fn from(offset: Offset) -> Self {
        offset.0
    }
}

impl From<Offset> for MemoryBits {
    fn from(offset: Offset) -> Self {
        MemoryBits::from(offset.0)
    }
}

impl From<MemoryInt> for Offset {
    fn from(i: MemoryInt) -> Self {
        Offset(i)
    }
}

impl From<Length> for MemoryInt {
    fn from(length: Length) -> Self {
        length.0
    }
}

impl From<Length> for MemoryBits {
    fn from(length: Length) -> Self {
        MemoryBits::from(length.0)
    }
}

impl From<MemoryInt> for Length {
    fn from(i: MemoryInt) -> Self {
        Length(i)
    }
}

impl From<Length> for usize {
    fn from(length: Length) -> Self {
        length.0 as usize
    }
}

#[derive(Serialize, Deserialize, Debug, DefaultJson, Clone, PartialEq)]
pub enum AllocationError {
    /// (de)allocation is either too large or implies negative values
    OutOfBounds,
    /// cannot allocate zero data
    ZeroLength,
    /// (de)allocation must occur at the top of the stack
    BadStackAlignment,
    /// writes can fail to serialize data before allocation occurs e.g. json
    Serialization,
}

impl From<AllocationError> for String {
    fn from(allocation_error: AllocationError) -> Self {
        match allocation_error {
            AllocationError::OutOfBounds => "Allocation out of bounds",
            AllocationError::ZeroLength => "Allocation is zero length",
            AllocationError::BadStackAlignment => "Allocation not aligned with stack",
            AllocationError::Serialization => "Allocation could not serialize data",
        }
        .into()
    }
}

impl From<AllocationError> for HolochainError {
    fn from(allocation_error: AllocationError) -> Self {
        HolochainError::ErrorGeneric(String::from(allocation_error))
    }
}

#[derive(Copy, Clone, Debug, PartialEq)]
pub struct WasmAllocation {
    // public fields to the crate for tests
    pub(in crate::memory) offset: Offset,
    pub(in crate::memory) length: Length,
}

impl WasmAllocation {
    // represent the max as MemoryBits type to allow gt comparisons
    pub fn max() -> MemoryBits {
        MEMORY_INT_MAX
    }

    pub fn new(offset: Offset, length: Length) -> AllocationResult {
        if (MemoryBits::from(offset) + MemoryBits::from(length)) > WasmAllocation::max() {
            Err(AllocationError::OutOfBounds)
        } else if MemoryInt::from(length) == 0 {
            Err(AllocationError::ZeroLength)
        } else {
            Ok(WasmAllocation { offset, length })
        }
    }

    pub fn offset(self) -> Offset {
        self.offset
    }

    pub fn length(self) -> Length {
        self.length
    }
}

pub type AllocationResult = Result<WasmAllocation, AllocationError>;

#[cfg(test)]
pub mod tests {

    use holochain_core_types::{bits_n_pieces::U16_MAX, error::HolochainError};
    use memory::{
        allocation::{AllocationError, Length, Offset, WasmAllocation},
        MemoryBits, MemoryInt, MEMORY_INT_MAX,
    };

    pub fn fake_offset() -> Offset {
        Offset(12345)
    }

    pub fn fake_length() -> Length {
        Length(12345)
    }

    #[test]
    pub fn memory_int_from_offset_test() {
        assert_eq!(12345 as MemoryInt, MemoryInt::from(fake_offset()),);
    }

    #[test]
    pub fn memory_bits_from_offset_test() {
        assert_eq!(12345 as MemoryBits, MemoryBits::from(fake_offset()),);
    }

    #[test]
    pub fn offset_from_memory_int_test() {
        assert_eq!(fake_offset(), Offset::from(12345 as MemoryInt),);
    }

    #[test]
    pub fn memory_int_from_length_test() {
        assert_eq!(12345 as MemoryInt, MemoryInt::from(fake_length()),);
    }

    #[test]
    pub fn memory_bits_from_length_test() {
        assert_eq!(12345 as MemoryBits, MemoryBits::from(fake_length()),);
    }

    #[test]
    pub fn length_from_memory_int_test() {
        assert_eq!(fake_length(), Length::from(12345 as MemoryInt),);
    }

    #[test]
    pub fn usize_from_length_test() {
        assert_eq!(usize::from(fake_length()), 12345 as usize,);
    }

    #[test]
    pub fn string_from_allocation_test() {
        assert_eq!(
            String::from("Allocation out of bounds"),
            String::from(AllocationError::OutOfBounds),
        );
        assert_eq!(
            String::from("Allocation is zero length"),
            String::from(AllocationError::ZeroLength),
        );
        assert_eq!(
            String::from("Allocation not aligned with stack"),
            String::from(AllocationError::BadStackAlignment),
        );
        assert_eq!(
            String::from("Allocation could not serialize data"),
            String::from(AllocationError::Serialization),
        );
    }

    #[test]
    pub fn holochain_error_from_allocation_error_test() {
        assert_eq!(
            HolochainError::from("Allocation out of bounds"),
            HolochainError::from(AllocationError::OutOfBounds),
        );
        assert_eq!(
            HolochainError::from("Allocation is zero length"),
            HolochainError::from(AllocationError::ZeroLength),
        );
        assert_eq!(
            HolochainError::from("Allocation not aligned with stack"),
            HolochainError::from(AllocationError::BadStackAlignment),
        );
        assert_eq!(
            HolochainError::from("Allocation could not serialize data"),
            HolochainError::from(AllocationError::Serialization),
        );
    }

    #[test]
    pub fn allocation_max_test() {
        assert_eq!(MEMORY_INT_MAX, WasmAllocation::max(),);
    }

    #[test]
    pub fn allocation_new_test() {
        assert_eq!(
            Err(AllocationError::OutOfBounds),
            WasmAllocation::new(Offset::from(std::u32::MAX), Length::from(1)),
        );

        assert_eq!(
            Err(AllocationError::ZeroLength),
            WasmAllocation::new(Offset::from(1), Length::from(0)),
        );

        assert_eq!(
            Ok(WasmAllocation {
                offset: Offset::from(1),
                length: Length::from(1)
            }),
            WasmAllocation::new(Offset::from(1), Length::from(1)),
        );

        // allocation larger than 1 wasm page
        let big = U16_MAX * 2;
        assert_eq!(
            Ok(WasmAllocation {
                offset: Offset::from(big),
                length: Length::from(big),
            }),
            WasmAllocation::new(Offset::from(big), Length::from(big)),
        );
    }

    #[test]
    pub fn allocation_offset_test() {
        assert_eq!(
            Offset::from(1),
            WasmAllocation::new(Offset::from(1), Length::from(1))
                .unwrap()
                .offset(),
        );
    }

    #[test]
    pub fn allocation_length_test() {
        assert_eq!(
            Length::from(1),
            WasmAllocation::new(Offset::from(1), Length::from(1))
                .unwrap()
                .length(),
        );
    }
}