pub struct ReadBuf<'a> { /* private fields */ }
Expand description

A local memory slice to read from memory

Implementations§

Create a readbuf from a slice

Examples found in repository?
src/chain_core/mempack.rs (line 149)
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
    pub fn split_to(&mut self, sz: usize) -> Result<ReadBuf<'a>, ReadError> {
        let slice = self.get_slice(sz)?;
        Ok(ReadBuf::from(slice))
    }

    /// Peek at the next u8 from the buffer. the cursor is **not** advanced to the next byte.
    pub fn peek_u8(&mut self) -> Result<u8, ReadError> {
        self.assure_size(1)?;
        let v = self.data[self.offset];
        Ok(v)
    }

    /// Return the next u8 from the buffer
    pub fn get_u8(&mut self) -> Result<u8, ReadError> {
        self.assure_size(1)?;
        let v = self.data[self.offset];
        self.offset += 1;
        Ok(v)
    }

    /// Return the next u16 from the buffer
    pub fn get_u16(&mut self) -> Result<u16, ReadError> {
        const SIZE: usize = 2;
        let mut buf = [0u8; SIZE];
        buf.copy_from_slice(self.get_slice(SIZE)?);
        Ok(u16::from_be_bytes(buf))
    }

    /// Return the next u32 from the buffer
    pub fn get_u32(&mut self) -> Result<u32, ReadError> {
        const SIZE: usize = 4;
        let mut buf = [0u8; SIZE];
        buf.copy_from_slice(self.get_slice(SIZE)?);
        Ok(u32::from_be_bytes(buf))
    }

    pub fn get_nz_u32(&mut self) -> Result<NonZeroU32, ReadError> {
        let v = self.get_u32()?;
        NonZeroU32::new(v).ok_or(ReadError::StructureInvalid("received zero u32".to_string()))
    }

    /// Return the next u64 from the buffer
    pub fn get_u64(&mut self) -> Result<u64, ReadError> {
        const SIZE: usize = 8;
        let mut buf = [0u8; SIZE];
        buf.copy_from_slice(self.get_slice(SIZE)?);
        Ok(u64::from_be_bytes(buf))
    }

    pub fn get_nz_u64(&mut self) -> Result<NonZeroU64, ReadError> {
        let v = self.get_u64()?;
        NonZeroU64::new(v).ok_or(ReadError::StructureInvalid("received zero u64".to_string()))
    }

    /// Return the next u128 from the buffer
    pub fn get_u128(&mut self) -> Result<u128, ReadError> {
        const SIZE: usize = 16;
        let mut buf = [0u8; SIZE];
        buf.copy_from_slice(self.get_slice(SIZE)?);
        Ok(u128::from_be_bytes(buf))
    }

    /*
    pub fn trace(&mut self, s: &str) {
        self.trace.push((self.offset, s.to_string()))
    }
    */

    pub fn debug(&self) -> String {
        let mut s = String::new();
        for (i, x) in self.data.iter().enumerate() {
            //self.trace.iter().find(|(ofs,_)| ofs == &i).map(|(_,name)| { s.push_str(&name); s.push(' ') });
            if i == self.offset {
                s.push_str(&".. ");
            }
            let bytes = format!("{:02x} ", x);
            s.push_str(&bytes);
        }
        s
    }
}

pub trait Readable: Sized {
    fn read<'a>(buf: &mut ReadBuf<'a>) -> Result<Self, ReadError>;

    fn read_validate<'a>(buf: &mut ReadBuf<'a>) -> Result<(), ReadError> {
        Self::read(buf).map(|_| ())
    }
}

impl Readable for () {
    fn read<'a>(_: &mut ReadBuf<'a>) -> Result<(), ReadError> {
        Ok(())
    }
    fn read_validate<'a>(buf: &mut ReadBuf<'a>) -> Result<(), ReadError> {
        Self::read(buf)
    }
}

macro_rules! read_prim_impl {
    ($Ty: ty, $meth: ident) => {
        impl Readable for $Ty {
            fn read<'a>(buf: &mut ReadBuf<'a>) -> Result<Self, ReadError> {
                buf.$meth()
            }
        }
    };
}

read_prim_impl! { u8, get_u8 }
read_prim_impl! { u16, get_u16 }
read_prim_impl! { u32, get_u32 }
read_prim_impl! { u64, get_u64 }
read_prim_impl! { u128, get_u128 }

macro_rules! read_array_impls {
    ($($N: expr)+) => {
        $(
        impl Readable for [u8; $N] {
            fn read<'a>(readbuf: &mut ReadBuf<'a>) -> Result<Self, ReadError> {
                let mut buf = [0u8; $N];
                buf.copy_from_slice(readbuf.get_slice($N)?);
                Ok(buf)
            }
        }
        )+
    };
}

read_array_impls! {
    4 8 12 16 20 24 28 32 64 96 128
}

/// read N times for a T elements in sequences
pub fn read_vec<'a, T: Readable>(readbuf: &mut ReadBuf<'a>, n: usize) -> Result<Vec<T>, ReadError> {
    let mut v = Vec::with_capacity(n);
    for _ in 0..n {
        let t = T::read(readbuf)?;
        v.push(t)
    }
    Ok(v)
}

/// Fill a mutable slice with as many T as filling requires
pub fn read_mut_slice<'a, T: Readable>(
    readbuf: &mut ReadBuf<'a>,
    v: &mut [T],
) -> Result<(), ReadError> {
    for i in 0..v.len() {
        let t = T::read(readbuf)?;
        v[i] = t
    }
    Ok(())
}

/// Transform a raw buffer into a Header
pub fn read_from_raw<T: Readable>(raw: &[u8]) -> Result<T, std::io::Error> {
    let mut rbuf = ReadBuf::from(raw);
    match T::read(&mut rbuf) {
        Err(e) => {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                format!("invalid data {:?} {:?}", e, raw).to_owned(),
            ));
        }
        Ok(h) => match rbuf.expect_end() {
            Err(e) => {
                return Err(std::io::Error::new(
                    std::io::ErrorKind::InvalidData,
                    format!("end of data {:?}", e).to_owned(),
                ));
            }
            Ok(()) => Ok(h),
        },
    }
}

Check if everything has been properly consumed

Examples found in repository?
src/chain_core/mempack.rs (line 312)
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
pub fn read_from_raw<T: Readable>(raw: &[u8]) -> Result<T, std::io::Error> {
    let mut rbuf = ReadBuf::from(raw);
    match T::read(&mut rbuf) {
        Err(e) => {
            return Err(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                format!("invalid data {:?} {:?}", e, raw).to_owned(),
            ));
        }
        Ok(h) => match rbuf.expect_end() {
            Err(e) => {
                return Err(std::io::Error::new(
                    std::io::ErrorKind::InvalidData,
                    format!("end of data {:?}", e).to_owned(),
                ));
            }
            Ok(()) => Ok(h),
        },
    }
}

Check if we reach the end of the buffer

Skip a number of bytes from the buffer.

Return a slice of the next bytes from the buffer

Examples found in repository?
src/chain_core/mempack.rs (line 141)
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
    pub fn into_slice_mut(&mut self, slice: &mut [u8]) -> Result<(), ReadError> {
        let s = self.get_slice(slice.len())?;
        slice.copy_from_slice(s);
        Ok(())
    }

    /// Return a sub-buffer ending at the given byte offset
    pub fn split_to(&mut self, sz: usize) -> Result<ReadBuf<'a>, ReadError> {
        let slice = self.get_slice(sz)?;
        Ok(ReadBuf::from(slice))
    }

    /// Peek at the next u8 from the buffer. the cursor is **not** advanced to the next byte.
    pub fn peek_u8(&mut self) -> Result<u8, ReadError> {
        self.assure_size(1)?;
        let v = self.data[self.offset];
        Ok(v)
    }

    /// Return the next u8 from the buffer
    pub fn get_u8(&mut self) -> Result<u8, ReadError> {
        self.assure_size(1)?;
        let v = self.data[self.offset];
        self.offset += 1;
        Ok(v)
    }

    /// Return the next u16 from the buffer
    pub fn get_u16(&mut self) -> Result<u16, ReadError> {
        const SIZE: usize = 2;
        let mut buf = [0u8; SIZE];
        buf.copy_from_slice(self.get_slice(SIZE)?);
        Ok(u16::from_be_bytes(buf))
    }

    /// Return the next u32 from the buffer
    pub fn get_u32(&mut self) -> Result<u32, ReadError> {
        const SIZE: usize = 4;
        let mut buf = [0u8; SIZE];
        buf.copy_from_slice(self.get_slice(SIZE)?);
        Ok(u32::from_be_bytes(buf))
    }

    pub fn get_nz_u32(&mut self) -> Result<NonZeroU32, ReadError> {
        let v = self.get_u32()?;
        NonZeroU32::new(v).ok_or(ReadError::StructureInvalid("received zero u32".to_string()))
    }

    /// Return the next u64 from the buffer
    pub fn get_u64(&mut self) -> Result<u64, ReadError> {
        const SIZE: usize = 8;
        let mut buf = [0u8; SIZE];
        buf.copy_from_slice(self.get_slice(SIZE)?);
        Ok(u64::from_be_bytes(buf))
    }

    pub fn get_nz_u64(&mut self) -> Result<NonZeroU64, ReadError> {
        let v = self.get_u64()?;
        NonZeroU64::new(v).ok_or(ReadError::StructureInvalid("received zero u64".to_string()))
    }

    /// Return the next u128 from the buffer
    pub fn get_u128(&mut self) -> Result<u128, ReadError> {
        const SIZE: usize = 16;
        let mut buf = [0u8; SIZE];
        buf.copy_from_slice(self.get_slice(SIZE)?);
        Ok(u128::from_be_bytes(buf))
    }

Return a sub-buffer ending at the given byte offset

Peek at the next u8 from the buffer. the cursor is not advanced to the next byte.

Return the next u8 from the buffer

Return the next u16 from the buffer

Return the next u32 from the buffer

Examples found in repository?
src/chain_core/mempack.rs (line 184)
183
184
185
186
    pub fn get_nz_u32(&mut self) -> Result<NonZeroU32, ReadError> {
        let v = self.get_u32()?;
        NonZeroU32::new(v).ok_or(ReadError::StructureInvalid("received zero u32".to_string()))
    }

Return the next u64 from the buffer

Examples found in repository?
src/chain_core/mempack.rs (line 197)
196
197
198
199
    pub fn get_nz_u64(&mut self) -> Result<NonZeroU64, ReadError> {
        let v = self.get_u64()?;
        NonZeroU64::new(v).ok_or(ReadError::StructureInvalid("received zero u64".to_string()))
    }

Return the next u128 from the buffer

Examples found in repository?
src/chain_core/mempack.rs (line 99)
94
95
96
97
98
99
100
101
102
    fn assure_size(&self, expected: usize) -> Result<(), ReadError> {
        let left = self.left();
        if left >= expected {
            Ok(())
        } else {
            dbg!(self.debug());
            Err(ReadError::NotEnoughBytes(left, expected))
        }
    }

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Should always be Self
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.