simple_bytes/
util.rs

1
2use std::io;
3use std::error::Error;
4
5pub(crate) fn io_other<E>(error: E) -> io::Error
6where E: Into<Box<dyn Error + Send + Sync>> {
7	io::Error::new(io::ErrorKind::Other, error)
8}
9
10pub(crate) fn io_eof<E>(error: E) -> io::Error
11where E: Into<Box<dyn Error + Send + Sync>> {
12	io::Error::new(io::ErrorKind::UnexpectedEof, error)
13}
14
15pub(crate) fn seek_from_to_n_pos(
16	inner_len: usize,
17	pos: usize,
18	seek_from: io::SeekFrom
19) -> io::Result<usize> {
20	let n_pos = match seek_from {
21		io::SeekFrom::Start(start) => start.try_into().map_err(io_eof)?,
22		io::SeekFrom::End(end) => {
23			let max: i64 = inner_len.try_into().map_err(io_other)?;
24			let new = max - end;
25			new.try_into().map_err(io_eof)?
26		},
27		io::SeekFrom::Current(curr) => {
28			let pos: i64 = pos.try_into().map_err(io_other)?;
29			let new = pos + curr;
30			new.try_into().map_err(io_eof)?
31		}
32	};
33
34	Ok(n_pos)
35}
36
37// returns the new position
38pub(crate) fn write_or_alloc(
39	vec: &mut Vec<u8>,
40	pos: usize,
41	slice: &[u8]
42) -> usize {
43	let rem_len = vec.len() - pos;
44
45	// if has enough space
46	if slice.len() <= rem_len {
47		vec[pos..][..slice.len()].copy_from_slice(slice);
48		return pos + slice.len()
49	}
50
51	// not enough space
52	if rem_len > 0 {
53		vec[pos..][..rem_len].copy_from_slice(&slice[..rem_len]);
54	}
55
56	vec.extend_from_slice(&slice[rem_len..]);
57	pos + slice.len()
58}