Function spectrusty_formats::tap::checksum
source · pub fn checksum<I: IntoIterator<Item = B>, B: Borrow<u8>>(iter: I) -> u8
Expand description
Calculates bit toggle checksum from the given iterator of u8
.
Examples found in repository?
More examples
src/tap.rs (line 583)
575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730
pub fn to_tap_chunk(&self) -> TapChunk<[u8;HEADER_SIZE]> {
let mut buffer = <[u8;HEADER_SIZE]>::default();
buffer[0] = HEAD_BLOCK_FLAG;
buffer[1] = self.block_type.into();
buffer[2..12].copy_from_slice(&self.name);
buffer[12..14].copy_from_slice(&self.length.to_le_bytes());
buffer[14..16].copy_from_slice(&self.par1);
buffer[16..18].copy_from_slice(&self.par2);
buffer[18] = checksum(buffer[0..18].iter());
TapChunk::from(buffer)
}
}
impl TryFrom<&'_[u8]> for Header {
type Error = Error;
fn try_from(header: &[u8]) -> Result<Self> {
if header.len() != HEADER_SIZE - 2 {
return Err(Error::new(ErrorKind::InvalidData, "Not a proper TAP header: invalid length"));
}
let block_type = BlockType::try_from(header[0])?;
let mut name: [u8; 10] = Default::default();
name.copy_from_slice(&header[1..11]);
let mut length: [u8; 2] = Default::default();
length.copy_from_slice(&header[11..13]);
let length = u16::from_le_bytes(length);
let mut par1: [u8; 2] = Default::default();
par1.copy_from_slice(&header[13..15]);
let mut par2: [u8; 2] = Default::default();
par2.copy_from_slice(&header[15..17]);
Ok(Header { length, block_type, name, par1, par2 })
}
}
impl TapChunkInfo {
/// Returns size in bytes of this chunk.
pub fn tap_chunk_size(&self) -> usize {
match self {
TapChunkInfo::Head(_) => HEADER_SIZE,
&TapChunkInfo::Data {length, ..} => length as usize + 2,
&TapChunkInfo::Unknown {size, ..} => size as usize,
TapChunkInfo::Empty => 0
}
}
}
impl TryFrom<&'_[u8]> for TapChunkInfo {
type Error = Error;
#[inline]
fn try_from(bytes: &[u8]) -> Result<Self> {
let size = match bytes.len() {
0 => {
return Ok(TapChunkInfo::Empty);
}
1 => {
return Ok(TapChunkInfo::Unknown { size: 1, flag: bytes[0] })
}
size if size > u16::max_value().into() => {
return Err(Error::new(ErrorKind::InvalidData, "Not a proper TAP chunk: too large"));
}
size => size
};
match bytes.first() {
Some(&HEAD_BLOCK_FLAG) if size == HEADER_SIZE && checksum(bytes) == 0 => {
Header::try_from(&bytes[1..HEADER_SIZE-1])
.map(TapChunkInfo::Head)
.or(Ok(TapChunkInfo::Unknown { size: size as u16, flag: HEAD_BLOCK_FLAG }))
}
Some(&DATA_BLOCK_FLAG) => {
let checksum = checksum(bytes);
Ok(TapChunkInfo::Data{ length: size as u16 - 2, checksum })
}
Some(&flag) => {
Ok(TapChunkInfo::Unknown { size: size as u16, flag })
}
_ => unreachable!()
}
}
}
impl<T> From<T> for TapChunk<T> where T: AsRef<[u8]> {
fn from(data: T) -> Self {
TapChunk { data }
}
}
impl<T> AsRef<[u8]> for TapChunk<T> where T: AsRef<[u8]> {
#[inline(always)]
fn as_ref(&self) -> &[u8] {
self.data.as_ref()
}
}
impl<T> AsMut<[u8]> for TapChunk<T> where T: AsMut<[u8]> {
#[inline(always)]
fn as_mut(&mut self) -> &mut [u8] {
self.data.as_mut()
}
}
impl<T> TapChunk<T> {
/// Returns the underlying bytes container.
pub fn into_inner(self) -> T {
self.data
}
}
impl<T> TapChunk<T> where T: AsRef<[u8]> {
/// Attempts to create an instance of [TapChunkInfo] from underlying data.
pub fn info(&self) -> Result<TapChunkInfo> {
TapChunkInfo::try_from(self.data.as_ref())
}
/// Calculates bit-xor checksum of underlying data.
pub fn checksum(&self) -> u8 {
checksum(self.data.as_ref())
}
/// Checks if this *TAP* chunk is a [Header] block.
pub fn is_head(&self) -> bool {
matches!(self.data.as_ref().get(0..2),
Some(&[HEAD_BLOCK_FLAG, t]) if t & 3 == t)
}
/// Checks if this *TAP* chunk is a data block.
pub fn is_data(&self) -> bool {
matches!(self.data.as_ref().first(), Some(&DATA_BLOCK_FLAG))
}
/// Checks if this *TAP* chunk is a valid data or [Header] block.
pub fn is_valid(&self) -> bool {
self.validate().is_ok()
}
/// Validates if this *TAP* chunk is a valid data or [Header] block returning `self` on success.
pub fn validated(self) -> Result<Self> {
self.validate().map(|_| self)
}
/// Validates if this *TAP* chunk is a valid data or [Header] block.
pub fn validate(&self) -> Result<()> {
let data = self.data.as_ref();
match data.get(0..2) {
Some(&[HEAD_BLOCK_FLAG, t]) if t & 3 == t => {
if data.len() != HEADER_SIZE {
return Err(Error::new(ErrorKind::InvalidData, "Not a proper TAP header: invalid length"));
}
}
Some(&[DATA_BLOCK_FLAG, _]) => {}
_ => return Err(Error::new(ErrorKind::InvalidData, "Not a proper TAP chunk: Invalid block head byte"))
}
if checksum(data) != 0 {
return Err(Error::new(ErrorKind::InvalidData, "Not a proper TAP chunk: Invalid checksum"))
}
Ok(())
}
src/tap/read.rs (line 162)
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 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
fn try_from(rd: &mut Take<R>) -> Result<Self> {
let limit = match rd.limit() {
0 => {
return Ok(TapChunkInfo::Empty)
}
limit if limit > u16::max_value().into() => {
return Err(Error::new(ErrorKind::InvalidData, "Not a proper TAP chunk: too large"));
}
limit => limit
};
let mut flag: u8 = 0;
rd.read_exact(slice::from_mut(&mut flag))?;
if limit == 1 {
return Ok(TapChunkInfo::Unknown { size: 1, flag })
}
match flag {
HEAD_BLOCK_FLAG if limit == HEADER_SIZE as u64 => {
let mut header: [u8; HEADER_SIZE - 1] = Default::default();
rd.read_exact(&mut header)?;
if checksum(header) != flag {
Ok(TapChunkInfo::Unknown { size: limit as u16, flag })
}
else {
Header::try_from(&header[..HEADER_SIZE - 2])
.map(TapChunkInfo::Head)
.or(Ok(TapChunkInfo::Unknown { size: limit as u16, flag }))
}
}
DATA_BLOCK_FLAG => {
let checksum = try_checksum(rd.by_ref().bytes())? ^ flag;
if rd.limit() != 0 {
return Err(Error::new(ErrorKind::InvalidData, "Not a proper TAP block: invalid length"));
}
Ok(TapChunkInfo::Data{ length: limit as u16 - 2, checksum })
}
flag => {
// TODO: perhaps check length and read to eof
Ok(TapChunkInfo::Unknown { size: limit as u16, flag })
}
}
}
}
impl<R> TapChunkReader<R> {
/// Returns the wrapped reader.
pub fn into_inner(self) -> R {
self.inner.into_inner()
}
/// Returns a reference to the chunk's [Take] reader.
pub fn get_ref(&self) -> &Take<R> {
&self.inner
}
/// Returns a mutable reference to the chunk's [Take] reader.
pub fn get_mut(&mut self) -> &mut Take<R> {
&mut self.inner
}
}
impl<R: Read + Seek> TapChunkReader<R> {
/// Creates a new instance of [TapChunkReader] from the reader with an assumption that the next
/// two bytes read from it will form the next chunk header.
///
/// `chunk_no` should be the chunk number of the previous chunk.
pub fn try_from_current(mut rd: R, chunk_no: u32) -> Result<Self> {
let next_pos = rd.seek(SeekFrom::Current(0))?;
let inner = rd.take(0);
Ok(TapChunkReader { next_pos, chunk_index: chunk_no, checksum: 0, inner })
}
/// Creates a clone of self but with a mutable reference to the underlying reader.
///
/// Returns a guard that, when dropped, will try to restore the original position
/// of the reader. However to check if it succeeded it's better to use [TapChunkReaderMut::done]
/// method directly on the guard which returns a result from the seek operation.
pub fn try_clone_mut(&mut self) -> Result<TapChunkReaderMut<'_, R>> {
let limit = self.inner.limit();
let inner = self.inner.get_mut().take(limit);
TapChunkReader {
checksum: self.checksum,
next_pos: self.next_pos,
chunk_index: self.chunk_index,
inner
}.try_into()
}
}
impl<R: Read + Seek> TapChunkRead for TapChunkReader<R> {
fn chunk_no(&self) -> u32 {
self.chunk_index
}
fn chunk_limit(&self) -> u16 {
self.inner.limit() as u16
}
fn rewind(&mut self) {
self.inner.set_limit(0);
self.checksum = 0;
self.chunk_index = 0;
self.next_pos = 0;
}
/// Also clears [TapChunkReader::checksum].
fn next_chunk(&mut self) -> Result<Option<u16>> {
let rd = self.inner.get_mut();
if self.next_pos != rd.seek(SeekFrom::Start(self.next_pos))? {
return Err(Error::new(ErrorKind::UnexpectedEof, "stream unexpectedly ended"));
}
let mut size: [u8; 2] = Default::default();
if !rd.read_exact_or_none(&mut size)? {
self.inner.set_limit(0);
return Ok(None)
}
let size = u16::from_le_bytes(size);
self.chunk_index += 1;
self.checksum = 0;
self.inner.set_limit(size as u64);
self.next_pos += size as u64 + 2;
Ok(Some(size))
}
}
impl<R: Read> Read for TapChunkReader<R> {
#[inline]
fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
match self.inner.read(buf) {
Ok(size) => {
self.checksum ^= checksum(&buf[..size]);
Ok(size)
}
e => e
}
}
#[inline]
fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize> {
match self.inner.read_to_end(buf) {
Ok(size) => {
self.checksum ^= checksum(&buf[buf.len() - size..]);
Ok(size)
}
e => e
}
}