|
| 1 | +use crate::UDP_BODY_LEN; |
| 2 | +use alloc::{vec, vec::Vec}; |
| 3 | +use thiserror::Error; |
| 4 | + |
| 5 | +const PACKET_LEN: usize = UDP_BODY_LEN - 32; |
| 6 | +const HEADER_LEN: usize = 2; |
| 7 | +const BODY_LEN: usize = PACKET_LEN - HEADER_LEN; |
| 8 | + |
| 9 | +const MIN_SIZE: usize = HEADER_LEN; |
| 10 | +const MAX_SIZE: usize = PACKET_LEN; |
| 11 | + |
| 12 | +#[derive(Error, Debug)] |
| 13 | +pub enum DecoderError { |
| 14 | + #[error("Packet too small; got {0} bytes, expected at least {MIN_SIZE} bytes")] |
| 15 | + PacketTooSmall(usize), |
| 16 | + #[error("Packet too big; got {0} bytes, expected at most {MAX_SIZE} bytes")] |
| 17 | + PacketTooBig(usize), |
| 18 | + #[error("Invalid index: 0x{0:04x}")] |
| 19 | + InvalidIndex(u16), |
| 20 | +} |
| 21 | + |
| 22 | +pub struct Decoder { |
| 23 | + data: Vec<u8>, |
| 24 | + missing_packet: Vec<bool>, |
| 25 | + missing_packets_per_group: [u16; 32], |
| 26 | + missing_groups: u16, |
| 27 | +} |
| 28 | + |
| 29 | +impl Decoder { |
| 30 | + pub fn new(size: usize) -> Self { |
| 31 | + let num_packets = size.div_ceil(BODY_LEN); |
| 32 | + let data = vec![0; 32 * BODY_LEN + size]; |
| 33 | + let missing_packet = vec![true; 32 + num_packets]; |
| 34 | + let missing_packets_per_group: [u16; 32] = (0..32) |
| 35 | + .map(|i| ((num_packets + 31 - i) / 32) as u16) |
| 36 | + .collect::<Vec<_>>() |
| 37 | + .try_into() |
| 38 | + .unwrap(); |
| 39 | + let missing_groups = missing_packets_per_group |
| 40 | + .iter() |
| 41 | + .map(|&x| (x != 0) as u16) |
| 42 | + .sum(); |
| 43 | + Decoder { |
| 44 | + data, |
| 45 | + missing_packet, |
| 46 | + missing_packets_per_group, |
| 47 | + missing_groups, |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + pub fn add_packet(&mut self, buf: &[u8]) -> Result<(), DecoderError> { |
| 52 | + if buf.len() < MIN_SIZE { |
| 53 | + return Err(DecoderError::PacketTooSmall(buf.len())); |
| 54 | + } |
| 55 | + if buf.len() > MAX_SIZE { |
| 56 | + return Err(DecoderError::PacketTooBig(buf.len())); |
| 57 | + } |
| 58 | + |
| 59 | + let index = u16::from_le_bytes(buf[..2].try_into().unwrap()); |
| 60 | + |
| 61 | + let rot_index = index.wrapping_add(32) as usize; |
| 62 | + let missing = self |
| 63 | + .missing_packet |
| 64 | + .get_mut(rot_index) |
| 65 | + .ok_or(DecoderError::InvalidIndex(index))?; |
| 66 | + match missing { |
| 67 | + false => return Ok(()), |
| 68 | + x @ true => *x = false, |
| 69 | + } |
| 70 | + |
| 71 | + let start = rot_index * BODY_LEN; |
| 72 | + self.data[start..start + buf.len() - 2].clone_from_slice(&buf[2..]); |
| 73 | + |
| 74 | + let group = index & 31; |
| 75 | + match &mut self.missing_packets_per_group[group as usize] { |
| 76 | + 0 => return Ok(()), |
| 77 | + x @ 1 => *x = 0, |
| 78 | + x @ 2.. => { |
| 79 | + *x -= 1; |
| 80 | + return Ok(()); |
| 81 | + } |
| 82 | + } |
| 83 | + |
| 84 | + match &mut self.missing_groups { |
| 85 | + 0 => unreachable!(), |
| 86 | + x @ 1.. => *x -= 1, |
| 87 | + } |
| 88 | + |
| 89 | + Ok(()) |
| 90 | + } |
| 91 | + |
| 92 | + pub fn finish(&mut self) -> Option<Vec<u8>> { |
| 93 | + if self.missing_groups != 0 { |
| 94 | + return None; |
| 95 | + } |
| 96 | + |
| 97 | + let mut xor = [[0; BODY_LEN]; 32]; |
| 98 | + for packet in 0..self.missing_packet.len() { |
| 99 | + if !self.missing_packet[packet] { |
| 100 | + let group = packet & 31; |
| 101 | + self.data[BODY_LEN * packet..] |
| 102 | + .iter() |
| 103 | + .zip(xor[group].iter_mut()) |
| 104 | + .for_each(|(a, b)| *b ^= a); |
| 105 | + } |
| 106 | + } |
| 107 | + for packet in 0..self.missing_packet.len() { |
| 108 | + if self.missing_packet[packet] { |
| 109 | + let group = packet & 31; |
| 110 | + self.data[BODY_LEN * packet..] |
| 111 | + .iter_mut() |
| 112 | + .zip(xor[group].iter()) |
| 113 | + .for_each(|(a, b)| *a = *b); |
| 114 | + } |
| 115 | + } |
| 116 | + Some(self.data[32 * BODY_LEN..].to_vec()) |
| 117 | + } |
| 118 | +} |
| 119 | + |
| 120 | +pub struct Encoder { |
| 121 | + data: Vec<u8>, |
| 122 | + groups: usize, |
| 123 | + idx: usize, |
| 124 | +} |
| 125 | + |
| 126 | +impl Encoder { |
| 127 | + pub fn new(data: Vec<u8>) -> Self { |
| 128 | + let idx = 0; |
| 129 | + let groups = data.len().div_ceil(BODY_LEN).min(32); |
| 130 | + Encoder { data, groups, idx } |
| 131 | + } |
| 132 | + |
| 133 | + pub fn next_packet(&mut self, out_buf: &mut [u8]) -> Option<usize> { |
| 134 | + let start = self.idx * BODY_LEN; |
| 135 | + if start < self.data.len() { |
| 136 | + let end = self.data.len().min(start + BODY_LEN); |
| 137 | + let len = end - start; |
| 138 | + out_buf[0..2].copy_from_slice(&(self.idx as u16).to_le_bytes()); |
| 139 | + out_buf[2..2 + len].copy_from_slice(&self.data[start..end]); |
| 140 | + self.idx += 1; |
| 141 | + Some(2 + len) |
| 142 | + } else if self.groups > 0 { |
| 143 | + self.groups -= 1; |
| 144 | + out_buf[0..2].copy_from_slice(&(self.groups as u16).wrapping_sub(32).to_le_bytes()); |
| 145 | + out_buf[2..].fill(0); |
| 146 | + (0..) |
| 147 | + .map(|x| (x * 32 + self.groups) * BODY_LEN) |
| 148 | + .take_while(|x| *x < self.data.len()) |
| 149 | + .for_each(|start| { |
| 150 | + let end = self.data.len().min(start + BODY_LEN); |
| 151 | + out_buf[2..2 + end - start] |
| 152 | + .iter_mut() |
| 153 | + .zip(self.data[start..end].iter()) |
| 154 | + .for_each(|(a, b)| *a ^= *b); |
| 155 | + }); |
| 156 | + Some(2 + BODY_LEN.min(self.data.len() - self.groups * BODY_LEN)) |
| 157 | + } else { |
| 158 | + None |
| 159 | + } |
| 160 | + } |
| 161 | +} |
| 162 | + |
| 163 | +#[cfg(test)] |
| 164 | +mod tests { |
| 165 | + use super::*; |
| 166 | + use crate::UDP_BODY_LEN; |
| 167 | + |
| 168 | + fn test_chunk_skip_packet(chunk: &[u8]) { |
| 169 | + let mut encoder = Encoder::new(chunk.to_vec()); |
| 170 | + let mut packets = Vec::new(); |
| 171 | + let mut buf = [0u8; UDP_BODY_LEN]; |
| 172 | + while let Some(len) = encoder.next_packet(&mut buf) { |
| 173 | + packets.push(buf[..len].to_vec()); |
| 174 | + } |
| 175 | + |
| 176 | + packets.sort_by_key(|p| { |
| 177 | + p.iter().take(6).fold(0u64, |acc, &x| { |
| 178 | + acc.wrapping_mul(0x5DEECE66D).wrapping_add(x as u64) |
| 179 | + }) |
| 180 | + }); |
| 181 | + |
| 182 | + for skip_idx in 0..packets.len() { |
| 183 | + let mut decoder = Decoder::new(chunk.len()); |
| 184 | + for (idx, packet) in packets.iter().enumerate() { |
| 185 | + if idx != skip_idx { |
| 186 | + decoder.add_packet(packet).expect("Failed to add packet"); |
| 187 | + } |
| 188 | + } |
| 189 | + let decoded = decoder.finish().expect("Failed to decode chunk"); |
| 190 | + assert_eq!( |
| 191 | + decoded, chunk, |
| 192 | + "Failed to decode chunk with skip index {skip_idx}" |
| 193 | + ); |
| 194 | + } |
| 195 | + |
| 196 | + let mut decoder = Decoder::new(chunk.len()); |
| 197 | + for (idx, packet) in packets.iter().enumerate() { |
| 198 | + if !(idx.is_multiple_of(33) && idx / 33 < 32) { |
| 199 | + decoder.add_packet(packet).expect("Failed to add packet"); |
| 200 | + } |
| 201 | + } |
| 202 | + let decoded = decoder.finish().expect("Failed to decode chunk"); |
| 203 | + assert_eq!(decoded, chunk, "Failed to decode chunk with multiple skips"); |
| 204 | + } |
| 205 | + |
| 206 | + #[test] |
| 207 | + fn test_small_chunk() { |
| 208 | + let mut chunk = vec![0u8; 20]; |
| 209 | + let mut val = u64::MAX / 5; |
| 210 | + for x in &mut chunk { |
| 211 | + val = val.wrapping_mul(0x5DEECE66D).wrapping_add(0xB); |
| 212 | + *x = val.to_be_bytes()[0]; |
| 213 | + } |
| 214 | + test_chunk_skip_packet(&chunk); |
| 215 | + } |
| 216 | + |
| 217 | + #[test] |
| 218 | + fn test_big_chunk() { |
| 219 | + let mut chunk = vec![0u8; 200 << 10]; |
| 220 | + let mut val = u64::MAX / 5; |
| 221 | + for x in &mut chunk { |
| 222 | + val = val.wrapping_mul(0x5DEECE66D).wrapping_add(0xB); |
| 223 | + *x = val.to_be_bytes()[0]; |
| 224 | + } |
| 225 | + test_chunk_skip_packet(&chunk); |
| 226 | + } |
| 227 | +} |
0 commit comments