lightning/io/
mod.rs

1pub use bitcoin::io::*;
2
3/// Emulation of std::io::Cursor
4///
5/// This is not exported to bindings users as serialization is done via a bindings-specific
6/// pipeline.
7#[derive(Clone, Debug, Default, Eq, PartialEq)]
8pub struct Cursor<T> {
9	inner: T,
10	pos: u64,
11}
12
13impl<T> Cursor<T> {
14	/// Creates a `Cursor` by wrapping `inner`.
15	#[inline]
16	pub fn new(inner: T) -> Cursor<T> {
17		Cursor { pos: 0, inner }
18	}
19
20	/// Returns the position read up to thus far.
21	#[inline]
22	pub fn position(&self) -> u64 {
23		self.pos
24	}
25
26	/// Returns the inner buffer.
27	///
28	/// This is the whole wrapped buffer, including the bytes already read.
29	#[inline]
30	pub fn into_inner(self) -> T {
31		self.inner
32	}
33
34	/// Gets a reference to the underlying value in this cursor.
35	pub fn get_ref(&self) -> &T {
36		&self.inner
37	}
38
39	/// Gets a mutable reference to the underlying value in this cursor.
40	///
41	/// Care should be taken to avoid modifying the internal I/O state of the
42	/// underlying value as it may corrupt this cursor's position.
43	pub fn get_mut(&mut self) -> &mut T {
44		&mut self.inner
45	}
46
47	/// Sets the position of this cursor.
48	pub fn set_position(&mut self, pos: u64) {
49		self.pos = pos;
50	}
51}
52
53impl<T: AsRef<[u8]>> Read for Cursor<T> {
54	fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
55		let n = Read::read(&mut self.fill_buf()?, buf)?;
56		self.pos += n as u64;
57		Ok(n)
58	}
59
60	fn read_exact(&mut self, buf: &mut [u8]) -> Result<()> {
61		let n = buf.len();
62		Read::read_exact(&mut self.fill_buf()?, buf)?;
63		self.pos += n as u64;
64		Ok(())
65	}
66}
67
68impl<T: AsRef<[u8]>> BufRead for Cursor<T> {
69	fn fill_buf(&mut self) -> Result<&[u8]> {
70		let amt = core::cmp::min(self.pos, self.inner.as_ref().len() as u64);
71		Ok(&self.inner.as_ref()[(amt as usize)..])
72	}
73	fn consume(&mut self, amt: usize) {
74		self.pos += amt as u64;
75	}
76}