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
use crate::{
	Asn1DerError, error::ErrorChain,
	rust::{ slice, iter }
};


/// A trait defining a byte source
pub trait Source: Sized {
	/// Reads the next element
	fn read(&mut self) -> Result<u8, Asn1DerError>;
	
	/// Creates a counting source
	#[cfg_attr(feature = "no_panic", no_panic::no_panic)]
	fn counting_source(self, ctr: &mut usize) -> CountingSource<Self> {
		CountingSource{ source: self, ctr }
	}
	/// Creates a copying source
	#[cfg_attr(feature = "no_panic", no_panic::no_panic)]
	fn copying_source<U: Sink>(self, sink: U) -> CopyingSource<Self, U> {
		CopyingSource{ source: self, sink }
	}
}
impl<S: Source> Source for &mut S {
	#[cfg_attr(feature = "no_panic", no_panic::no_panic)]
	fn read(&mut self) -> Result<u8, Asn1DerError> {
		(*self).read()
	}
}
impl<'a> Source for slice::Iter<'a, u8> {
	#[cfg_attr(feature = "no_panic", no_panic::no_panic)]
	fn read(&mut self) -> Result<u8, Asn1DerError> {
		match self.next() {
			Some(e) => Ok(*e),
			None => Err(eio!("Cannot read beyond end of slice-iterator"))
		}
	}
}
impl<'a, A: Iterator<Item = &'a u8>, B: Iterator<Item = &'a u8>> Source for iter::Chain<A, B> {
	#[cfg_attr(feature = "no_panic", no_panic::no_panic)]
	fn read(&mut self) -> Result<u8, Asn1DerError> {
		match self.next() {
			Some(e) => Ok(*e),
			None => Err(eio!("Cannot read beyond end of chain-iterator"))
		}
	}
}
impl<'a, I: Iterator<Item = &'a u8> + 'a> Source for iter::Skip<I> {
	#[cfg_attr(feature = "no_panic", no_panic::no_panic)]
	fn read(&mut self) -> Result<u8, Asn1DerError> {
		match self.next() {
			Some(e) => Ok(*e),
			None => Err(eio!("Cannot read beyond end of chain-iterator"))
		}
	}
}


/// A source that counts the amount of elements read
///
/// __Warning: if a call to `read` would cause `ctr` to exceed `usize::max_value()`, this source
/// will return an error and the element that has been read from the underlying source will be
/// lost__
pub struct CountingSource<'a, S: Source> {
	source: S,
	ctr: &'a mut usize
}
impl<'a, S: Source> Source for CountingSource<'a, S> {
	#[cfg_attr(feature = "no_panic", no_panic::no_panic)]
	fn read(&mut self) -> Result<u8, Asn1DerError> {
		let e = self.source.read().propagate(e!("Failed to read element from underlying source"))?;
		match self.ctr.checked_add(1) {
			Some(ctr_next) => {
				*self.ctr = ctr_next;
				Ok(e)
			},
			_ => Err(eio!("Cannot read more because the position counter would overflow"))
		}
	}
}


/// A source that also copies each read element to the `sink`
///
/// __Warning: if a call to `write` fails, this source will return an error and the element that has
/// been read from the underlying source will be lost__
pub struct CopyingSource<S: Source, U: Sink> {
	source: S,
	sink: U
}
impl<S: Source, U: Sink> CopyingSource<S, U> {
	/// Copies the next element
	#[cfg_attr(feature = "no_panic", no_panic::no_panic)]
	pub fn copy_next(&mut self) -> Result<(), Asn1DerError> {
		Ok({ self.read()?; })
	}
	/// Copies the next `n` elements
	#[cfg_attr(feature = "no_panic", no_panic::no_panic)]
	pub fn copy_n(&mut self, n: usize) -> Result<(), Asn1DerError> {
		(0..n).try_for_each(|_| self.copy_next())
	}
}
impl<S: Source, U: Sink> Source for CopyingSource<S, U> {
	#[cfg_attr(feature = "no_panic", no_panic::no_panic)]
	fn read(&mut self) -> Result<u8, Asn1DerError> {
		let e = self.source.read().propagate(e!("Failed to read element from underlying source"))?;
		self.sink.write(e).propagate(e!("Failed to copy element to sink"))?;
		Ok(e)
	}
}


/// A trait defining a byte sink
pub trait Sink: Sized {
	/// Writes `e` to `self`
	fn write(&mut self, e: u8) -> Result<(), Asn1DerError>;
	/// Creates a counting sink
	#[cfg_attr(feature = "no_panic", no_panic::no_panic)]
	fn counting_sink(self, ctr: &mut usize) -> CountingSink<Self> {
		CountingSink{ sink: self, ctr }
	}
}
impl<S: Sink> Sink for &mut S {
	#[cfg_attr(feature = "no_panic", no_panic::no_panic)]
	fn write(&mut self, e: u8) -> Result<(), Asn1DerError> {
		(*self).write(e)
	}
}
impl<'a> Sink for slice::IterMut<'a, u8> {
	#[cfg_attr(feature = "no_panic", no_panic::no_panic)]
	fn write(&mut self, e: u8) -> Result<(), Asn1DerError> {
		match self.next() {
			Some(t) => Ok(*t = e),
			None => Err(eio!("Cannot write beyond end of slice-iterator"))
		}
	}
}
#[cfg(not(any(feature = "no_std", feature = "no_panic")))]
impl Sink for Vec<u8> {
	fn write(&mut self, e: u8) -> Result<(), Asn1DerError> {
		Ok(self.push(e))
	}
}


/// A sink that counts the amount of elements written
///
/// __Warning: if a call to `write` would cause `ctr` to exceed `usize::max_value()`, this sink
/// will return an error but the element is written nonetheless__
pub struct CountingSink<'a, S: Sink> {
	sink: S,
	ctr: &'a mut usize
}
impl<'a, S: Sink> Sink for CountingSink<'a, S> {
	#[cfg_attr(feature = "no_panic", no_panic::no_panic)]
	fn write(&mut self, e: u8) -> Result<(), Asn1DerError> {
		self.sink.write(e).propagate(e!("Failed to write element to underlying source"))?;
		*self.ctr = match self.ctr.checked_add(1) {
			Some(ctr_next) => ctr_next,
			None => Err(eio!("Cannot write more because the position counter would overflow"))?
		};
		Ok(())
	}
}


/// A slice-backed sink
pub struct SliceSink<'a> {
	slice: &'a mut[u8],
	pos: &'a mut usize
}
impl<'a> SliceSink<'a> {
	/// Creates a new `SliceSink` with `slice` as backing and `pos` as position counter
	#[cfg_attr(feature = "no_panic", no_panic::no_panic)]
	pub fn new(slice: &'a mut[u8], pos: &'a mut usize) -> Self {
		Self{ slice, pos }
	}
}
impl<'a> Sink for SliceSink<'a> {
	#[cfg_attr(feature = "no_panic", no_panic::no_panic)]
	fn write(&mut self, e: u8) -> Result<(), Asn1DerError> {
		match self.slice.get_mut(*self.pos) {
			Some(t) => match self.pos.checked_add(1) {
				Some(pos_next) => {
					*self.pos = pos_next;
					Ok(*t = e)
				},
				None => Err(eio!("Cannot write more because the position counter would overflow"))?
			},
			None => Err(eio!("Cannot write beyond the end-of-slice"))?
		}
	}
}
impl<'a> Into<&'a[u8]> for SliceSink<'a> {
	#[cfg_attr(feature = "no_panic", no_panic::no_panic)]
	fn into(self) -> &'a[u8] {
		match self.slice.len() {
			len if *self.pos < len => &self.slice[..*self.pos],
			_ => self.slice
		}
	}
}


/// A newtype wrapper around a `&'a mut Vec<u8>` that implements `Sink` and `Into<&'a [u8]>`
#[cfg(not(any(feature = "no_std", feature = "no_panic")))]
pub struct VecBacking<'a>(pub &'a mut Vec<u8>);
#[cfg(not(any(feature = "no_std", feature = "no_panic")))]
impl<'a> Sink for VecBacking<'a> {
	fn write(&mut self, e: u8) -> Result<(), Asn1DerError> {
		Ok(self.0.push(e))
	}
}
#[cfg(not(any(feature = "no_std", feature = "no_panic")))]
impl<'a> Into<&'a[u8]> for VecBacking<'a> {
	fn into(self) -> &'a[u8] {
		self.0.as_slice()
	}
}