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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
// extends memory allocation to work with ribosome encodings

use holochain_core_types::{
    bits_n_pieces::{u64_merge_bits, u64_split_bits},
    error::{
        HolochainError, RibosomeEncodedAllocation, RibosomeEncodedValue, RibosomeEncodingBits,
        RibosomeErrorCode,
    },
};

use holochain_json_api::json::JsonString;

use memory::{
    allocation::{AllocationError, AllocationResult, WasmAllocation},
    stack::WasmStack,
    MemoryBits,
};
use std::convert::TryFrom;

impl TryFrom<RibosomeEncodedAllocation> for WasmAllocation {
    type Error = AllocationError;
    fn try_from(
        ribosome_memory_allocation: RibosomeEncodedAllocation,
    ) -> Result<Self, Self::Error> {
        let (offset, length) = u64_split_bits(MemoryBits::from(ribosome_memory_allocation));
        WasmAllocation::new(offset.into(), length.into())
    }
}

impl From<WasmAllocation> for RibosomeEncodedAllocation {
    fn from(wasm_allocation: WasmAllocation) -> Self {
        u64_merge_bits(
            wasm_allocation.offset().into(),
            wasm_allocation.length().into(),
        )
        .into()
    }
}

impl From<WasmAllocation> for RibosomeEncodedValue {
    fn from(wasm_allocation: WasmAllocation) -> Self {
        RibosomeEncodedValue::Allocation(RibosomeEncodedAllocation::from(wasm_allocation))
    }
}

impl From<AllocationError> for RibosomeErrorCode {
    fn from(allocation_error: AllocationError) -> Self {
        match allocation_error {
            AllocationError::OutOfBounds => RibosomeErrorCode::OutOfMemory,
            AllocationError::ZeroLength => RibosomeErrorCode::ZeroSizedAllocation,
            AllocationError::BadStackAlignment => RibosomeErrorCode::NotAnAllocation,
            AllocationError::Serialization => RibosomeErrorCode::NotAnAllocation,
        }
    }
}

impl From<AllocationError> for RibosomeEncodedValue {
    fn from(allocation_error: AllocationError) -> Self {
        RibosomeEncodedValue::Failure(RibosomeErrorCode::from(allocation_error))
    }
}

impl AllocationError {
    pub fn as_ribosome_encoding(&self) -> RibosomeEncodingBits {
        RibosomeEncodedValue::from(self.clone()).into()
    }
}

impl WasmAllocation {
    /// equivalent to TryFrom<RibosomeEncodingBits> for WasmAllocation
    /// not implemented as a trait because RibosomeEncodingBits is a primitive and that would couple
    /// allocations to ribosome encoding
    pub fn try_from_ribosome_encoding(encoded_value: RibosomeEncodingBits) -> AllocationResult {
        match RibosomeEncodedValue::from(encoded_value) {
            RibosomeEncodedValue::Success => Err(AllocationError::ZeroLength),
            RibosomeEncodedValue::Failure(_) => Err(AllocationError::OutOfBounds),
            RibosomeEncodedValue::Allocation(ribosome_allocation) => {
                WasmAllocation::try_from(ribosome_allocation)
            }
        }
    }

    pub fn as_ribosome_encoding(self) -> RibosomeEncodingBits {
        RibosomeEncodedValue::from(self).into()
    }
}

impl WasmStack {
    /// equivalent to TryFrom<RibosomeEncodingBits> for WasmStack
    /// not implemented as a trait because RibosomeEncodingBits is a primitive and that would couple
    /// stacks to ribosome encoding
    /// wraps WasmAllocation::try_from_ribosome_encoding internally but has a "higher level"
    /// return signature intended for direct use/return in/from ribosome fns
    pub fn try_from_ribosome_encoding(
        maybe_encoded_allocation: RibosomeEncodingBits,
    ) -> Result<WasmStack, RibosomeEncodedValue> {
        match WasmAllocation::try_from_ribosome_encoding(maybe_encoded_allocation) {
            Err(allocation_error) => Err(allocation_error),
            Ok(allocation) => match WasmStack::try_from(allocation) {
                Err(allocation_error) => Err(allocation_error),
                Ok(stack) => Ok(stack),
            },
        }
        .map_err(|e| e.as_ribosome_encoding().into())
    }
}

/// Equivalent to From<AllocationResult> for RibosomeEncodedValue
/// not possible to implement the trait as Result and RibosomeEncodedValue from different crates
pub fn return_code_for_allocation_result(result: AllocationResult) -> RibosomeEncodedValue {
    match result {
        Ok(allocation) => RibosomeEncodedValue::from(allocation),
        Err(allocation_error) => RibosomeEncodedValue::from(allocation_error),
    }
}

pub fn load_ribosome_encoded_string(
    encoded_value: RibosomeEncodingBits,
) -> Result<String, HolochainError> {
    // almost the same as WasmAllocation::try_from_ribosome_encoding but maps to HolochainError
    match RibosomeEncodedValue::from(encoded_value) {
        RibosomeEncodedValue::Success => Err(HolochainError::Ribosome(
            RibosomeErrorCode::ZeroSizedAllocation,
        )),
        RibosomeEncodedValue::Failure(err_code) => Err(HolochainError::Ribosome(err_code)),
        RibosomeEncodedValue::Allocation(ribosome_allocation) => {
            Ok(WasmAllocation::try_from(ribosome_allocation)?.read_to_string())
        }
    }
}

pub fn load_ribosome_encoded_json<J: TryFrom<JsonString>>(
    encoded_value: RibosomeEncodingBits,
) -> Result<J, HolochainError>
where
    J::Error: Into<HolochainError>,
{
    let s = load_ribosome_encoded_string(encoded_value)?;
    let j = JsonString::from_json(&s);

    J::try_from(j).map_err(|e| e.into())
}

#[cfg(test)]
pub mod tests {

    use holochain_core_types::{
        bits_n_pieces::u64_merge_bits,
        error::{
            RibosomeEncodedAllocation, RibosomeEncodedValue, RibosomeEncodingBits,
            RibosomeErrorCode,
        },
    };
    use memory::{
        allocation::{AllocationError, Length, Offset, WasmAllocation},
        ribosome::return_code_for_allocation_result,
        stack::{Top, WasmStack},
    };
    use std::convert::TryFrom;

    #[test]
    fn try_allocation_from_ribosome_allocation_test() {
        assert_eq!(
            Err(AllocationError::ZeroLength),
            WasmAllocation::try_from(RibosomeEncodedAllocation::from(0)),
        );

        assert_eq!(
            Err(AllocationError::OutOfBounds),
            WasmAllocation::try_from(RibosomeEncodedAllocation::from(u64_merge_bits(
                std::u32::MAX,
                std::u32::MAX
            ))),
        );

        assert_eq!(
            Ok(WasmAllocation {
                offset: Offset::from(4),
                length: Length::from(8)
            }),
            WasmAllocation::try_from(RibosomeEncodedAllocation::from(
                0b000000000000000000000000000000100_00000000000000000000000000001000
            )),
        );
    }

    #[test]
    fn ribosome_allocation_from_allocation_test() {
        assert_eq!(
            RibosomeEncodedAllocation::from(
                0b00000000000000000000000000000100_00000000000000000000000000001000
            ),
            RibosomeEncodedAllocation::from(WasmAllocation {
                offset: Offset::from(4),
                length: Length::from(8)
            }),
        );
    }

    #[test]
    fn ribosome_encoded_value_from_allocation_test() {
        assert_eq!(
            RibosomeEncodedValue::Allocation(RibosomeEncodedAllocation::from(
                0b00000000000000000000000000000100_00000000000000000000000000001000
            )),
            RibosomeEncodedValue::from(WasmAllocation {
                offset: Offset::from(4),
                length: Length::from(8)
            }),
        );
    }

    #[test]
    fn ribosome_error_from_allocation_error_test() {
        assert_eq!(
            RibosomeErrorCode::OutOfMemory,
            RibosomeErrorCode::from(AllocationError::OutOfBounds),
        );

        assert_eq!(
            RibosomeErrorCode::ZeroSizedAllocation,
            RibosomeErrorCode::from(AllocationError::ZeroLength),
        );

        assert_eq!(
            RibosomeErrorCode::NotAnAllocation,
            RibosomeErrorCode::from(AllocationError::BadStackAlignment),
        );

        assert_eq!(
            RibosomeErrorCode::NotAnAllocation,
            RibosomeErrorCode::from(AllocationError::Serialization),
        );
    }

    #[test]
    fn ribosome_code_from_allocation_error_test() {
        assert_eq!(
            RibosomeEncodedValue::Failure(RibosomeErrorCode::OutOfMemory),
            RibosomeEncodedValue::from(AllocationError::OutOfBounds),
        );

        assert_eq!(
            RibosomeEncodedValue::Failure(RibosomeErrorCode::ZeroSizedAllocation),
            RibosomeEncodedValue::from(AllocationError::ZeroLength),
        );

        assert_eq!(
            RibosomeEncodedValue::Failure(RibosomeErrorCode::NotAnAllocation),
            RibosomeEncodedValue::from(AllocationError::BadStackAlignment),
        );

        assert_eq!(
            RibosomeEncodedValue::Failure(RibosomeErrorCode::NotAnAllocation),
            RibosomeEncodedValue::from(AllocationError::Serialization),
        );
    }

    #[test]
    fn ribosome_encoding_test() {
        assert_eq!(
            RibosomeEncodingBits::from(RibosomeEncodedValue::Failure(
                RibosomeErrorCode::OutOfMemory
            )),
            AllocationError::OutOfBounds.as_ribosome_encoding(),
        );
        assert_eq!(
            RibosomeEncodingBits::from(RibosomeEncodedValue::Failure(
                RibosomeErrorCode::ZeroSizedAllocation
            )),
            AllocationError::ZeroLength.as_ribosome_encoding(),
        );
        assert_eq!(
            RibosomeEncodingBits::from(RibosomeEncodedValue::Failure(
                RibosomeErrorCode::NotAnAllocation
            )),
            AllocationError::BadStackAlignment.as_ribosome_encoding(),
        );
        assert_eq!(
            RibosomeEncodingBits::from(RibosomeEncodedValue::Failure(
                RibosomeErrorCode::NotAnAllocation
            )),
            AllocationError::Serialization.as_ribosome_encoding(),
        );
    }

    #[test]
    fn stack_from_encoding_test() {
        assert_eq!(
            Err(RibosomeEncodedValue::from(AllocationError::OutOfBounds)),
            WasmStack::try_from_ribosome_encoding(u64_merge_bits(std::u32::MAX, std::u32::MAX)),
        );

        assert_eq!(
            Err(RibosomeEncodedValue::from(AllocationError::ZeroLength)),
            WasmStack::try_from_ribosome_encoding(0),
        );

        assert_eq!(
            Ok(WasmStack { top: Top(4) }),
            // 2 + 2 = 4
            WasmStack::try_from_ribosome_encoding(
                0b00000000000000000000000000000010_00000000000000000000000000000010
            ),
        );
    }

    #[test]
    fn return_code_for_allocation_result_test() {
        assert_eq!(
            RibosomeEncodedValue::from(AllocationError::OutOfBounds),
            return_code_for_allocation_result(Err(AllocationError::OutOfBounds)),
        );
        assert_eq!(
            RibosomeEncodedValue::from(AllocationError::ZeroLength),
            return_code_for_allocation_result(Err(AllocationError::ZeroLength)),
        );
        assert_eq!(
            RibosomeEncodedValue::from(AllocationError::BadStackAlignment),
            return_code_for_allocation_result(Err(AllocationError::BadStackAlignment)),
        );
        assert_eq!(
            RibosomeEncodedValue::from(AllocationError::Serialization),
            return_code_for_allocation_result(Err(AllocationError::Serialization)),
        );
        let allocation = WasmAllocation {
            offset: Offset::from(5),
            length: Length::from(5),
        };
        assert_eq!(
            RibosomeEncodedValue::from(allocation),
            return_code_for_allocation_result(Ok(allocation)),
        );
    }
}