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
// Copyright (c) DUSK NETWORK. All rights reserved.
// Licensed under the MPL 2.0 license. See LICENSE file in the project root for details.

use std::collections::HashMap;
use std::fmt;
use std::sync::Arc;

use parking_lot::RwLock;
use wasmi;

use canonical::{
    ByteSink, Canon, DrySink, Id32, InvalidEncoding, Sink, Source, Store,
};
use canonical_derive::Canon;

#[derive(Default, Debug)]
struct MemStoreInner(HashMap<Id32, Vec<u8>>);

/// An in-memory store implemented with a hashmap
#[derive(Default, Debug, Clone)]
pub struct MemStore(Arc<RwLock<MemStoreInner>>);

impl MemStore {
    /// Create a new MemStore
    pub fn new() -> Self {
        Default::default()
    }
}

struct MemSink<S> {
    bytes: Vec<u8>,
    store: S,
}

struct MemSource<'a, S> {
    bytes: &'a [u8],
    offset: usize,
    store: S,
}

#[derive(Canon, Debug, Clone)]
pub enum MemError {
    MissingValue,
    InvalidEncoding,
}

impl fmt::Display for MemError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Self::MissingValue => write!(f, "Missing Value"),
            Self::InvalidEncoding => write!(f, "InvalidEncoding"),
        }
    }
}

impl wasmi::HostError for MemError {}

impl From<InvalidEncoding> for MemError {
    fn from(_: InvalidEncoding) -> Self {
        MemError::InvalidEncoding
    }
}

impl Store for MemStore {
    type Ident = Id32;
    type Error = MemError;

    fn fetch(
        &self,
        id: &Self::Ident,
        into: &mut [u8],
    ) -> Result<(), Self::Error> {
        self.0
            .read()
            .0
            .get(id)
            .map(|bytes| {
                let len = bytes.len();
                into[0..len].copy_from_slice(&bytes[..]);
                Ok(())
            })
            .unwrap_or(Err(MemError::MissingValue))
    }

    fn get<T: Canon<Self>>(&self, id: &Self::Ident) -> Result<T, Self::Error> {
        self.0
            .read()
            .0
            .get(id)
            .map(|bytes| {
                let mut source = MemSource {
                    bytes,
                    offset: 0,
                    store: self.clone(),
                };
                T::read(&mut source)
            })
            .unwrap_or_else(|| Err(MemError::MissingValue))
    }

    fn put<T: Canon<Self>>(&self, t: &T) -> Result<Self::Ident, Self::Error> {
        let len = t.encoded_len();
        let mut bytes = Vec::with_capacity(len);
        bytes.resize_with(len, || 0);

        let mut sink = ByteSink::new(&mut bytes, self.clone());
        Canon::<Self>::write(t, &mut sink)?;
        let ident = sink.fin();

        self.0.write().0.insert(ident, bytes);
        Ok(ident)
    }

    fn put_raw(&self, bytes: &[u8]) -> Result<Self::Ident, Self::Error> {
        let mut sink = DrySink::<Self>::new();
        sink.copy_bytes(bytes);
        let ident = sink.fin();
        self.0.write().0.insert(ident, bytes.to_vec());
        Ok(ident)
    }
}

impl<S: Store> Sink<S> for MemSink<S> {
    fn copy_bytes(&mut self, bytes: &[u8]) {
        let ofs = self.bytes.len();
        self.bytes.resize_with(ofs + bytes.len(), || 0);
        self.bytes[ofs..].clone_from_slice(bytes)
    }

    fn recur<T: Canon<S>>(&self, t: &T) -> Result<S::Ident, S::Error> {
        self.store.put(t)
    }

    fn fin(self) -> S::Ident {
        todo!()
    }
}

impl<'a, S> Source<S> for MemSource<'a, S>
where
    S: Store,
{
    fn read_bytes(&mut self, n: usize) -> &[u8] {
        let ofs = self.offset;
        self.offset += n;
        &self.bytes[ofs..self.offset]
    }

    fn store(&self) -> &S {
        &self.store
    }
}