assembler.rs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  1. use core::fmt;
  2. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  3. pub struct TooManyHolesError;
  4. /// A contiguous chunk of absent data, followed by a contiguous chunk of present data.
  5. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  6. #[cfg_attr(feature = "defmt", derive(defmt::Format))]
  7. struct Contig {
  8. hole_size: usize,
  9. data_size: usize
  10. }
  11. impl fmt::Display for Contig {
  12. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  13. if self.has_hole() { write!(f, "({})", self.hole_size)?; }
  14. if self.has_hole() && self.has_data() { write!(f, " ")?; }
  15. if self.has_data() { write!(f, "{}", self.data_size)?; }
  16. Ok(())
  17. }
  18. }
  19. impl Contig {
  20. fn empty() -> Contig {
  21. Contig { hole_size: 0, data_size: 0 }
  22. }
  23. fn hole(size: usize) -> Contig {
  24. Contig { hole_size: size, data_size: 0 }
  25. }
  26. fn hole_and_data(hole_size: usize, data_size: usize) -> Contig {
  27. Contig { hole_size, data_size }
  28. }
  29. fn has_hole(&self) -> bool {
  30. self.hole_size != 0
  31. }
  32. fn has_data(&self) -> bool {
  33. self.data_size != 0
  34. }
  35. fn total_size(&self) -> usize {
  36. self.hole_size + self.data_size
  37. }
  38. fn is_empty(&self) -> bool {
  39. self.total_size() == 0
  40. }
  41. fn expand_data_by(&mut self, size: usize) {
  42. self.data_size += size;
  43. }
  44. fn shrink_hole_by(&mut self, size: usize) {
  45. self.hole_size -= size;
  46. }
  47. fn shrink_hole_to(&mut self, size: usize) {
  48. debug_assert!(self.hole_size >= size);
  49. let total_size = self.total_size();
  50. self.hole_size = size;
  51. self.data_size = total_size - size;
  52. }
  53. }
  54. #[cfg(feature = "std")]
  55. use std::boxed::Box;
  56. #[cfg(all(feature = "alloc", not(feature = "std")))]
  57. use alloc::boxed::Box;
  58. #[cfg(any(feature = "std", feature = "alloc"))]
  59. const CONTIG_COUNT: usize = 32;
  60. #[cfg(not(any(feature = "std", feature = "alloc")))]
  61. const CONTIG_COUNT: usize = 4;
  62. /// A buffer (re)assembler.
  63. ///
  64. /// Currently, up to a hardcoded limit of 4 or 32 holes can be tracked in the buffer.
  65. #[derive(Debug)]
  66. #[cfg_attr(test, derive(PartialEq, Eq, Clone))]
  67. #[cfg_attr(feature = "defmt", derive(defmt::Format))]
  68. pub struct Assembler {
  69. #[cfg(not(any(feature = "std", feature = "alloc")))]
  70. contigs: [Contig; CONTIG_COUNT],
  71. #[cfg(any(feature = "std", feature = "alloc"))]
  72. contigs: Box<[Contig; CONTIG_COUNT]>,
  73. }
  74. impl fmt::Display for Assembler {
  75. fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
  76. write!(f, "[ ")?;
  77. for contig in self.contigs.iter() {
  78. if contig.is_empty() { break }
  79. write!(f, "{} ", contig)?;
  80. }
  81. write!(f, "]")?;
  82. Ok(())
  83. }
  84. }
  85. impl Assembler {
  86. /// Create a new buffer assembler for buffers of the given size.
  87. pub fn new(size: usize) -> Assembler {
  88. #[cfg(not(any(feature = "std", feature = "alloc")))]
  89. let mut contigs = [Contig::empty(); CONTIG_COUNT];
  90. #[cfg(any(feature = "std", feature = "alloc"))]
  91. let mut contigs = Box::new([Contig::empty(); CONTIG_COUNT]);
  92. contigs[0] = Contig::hole(size);
  93. Assembler { contigs }
  94. }
  95. /// FIXME(whitequark): remove this once I'm certain enough that the assembler works well.
  96. #[allow(dead_code)]
  97. pub(crate) fn total_size(&self) -> usize {
  98. self.contigs
  99. .iter()
  100. .map(|contig| contig.total_size())
  101. .sum()
  102. }
  103. fn front(&self) -> Contig {
  104. self.contigs[0]
  105. }
  106. fn back(&self) -> Contig {
  107. self.contigs[self.contigs.len() - 1]
  108. }
  109. /// Return whether the assembler contains no data.
  110. pub fn is_empty(&self) -> bool {
  111. !self.front().has_data()
  112. }
  113. /// Remove a contig at the given index, and return a pointer to the first contig
  114. /// without data.
  115. fn remove_contig_at(&mut self, at: usize) -> &mut Contig {
  116. debug_assert!(!self.contigs[at].is_empty());
  117. for i in at..self.contigs.len() - 1 {
  118. self.contigs[i] = self.contigs[i + 1];
  119. if !self.contigs[i].has_data() {
  120. self.contigs[i + 1] = Contig::empty();
  121. return &mut self.contigs[i]
  122. }
  123. }
  124. // Removing the last one.
  125. self.contigs[at] = Contig::empty();
  126. &mut self.contigs[at]
  127. }
  128. /// Add a contig at the given index, and return a pointer to it.
  129. fn add_contig_at(&mut self, at: usize) -> Result<&mut Contig, TooManyHolesError> {
  130. debug_assert!(!self.contigs[at].is_empty());
  131. if !self.back().is_empty() { return Err(TooManyHolesError) }
  132. for i in (at + 1..self.contigs.len()).rev() {
  133. self.contigs[i] = self.contigs[i - 1];
  134. }
  135. self.contigs[at] = Contig::empty();
  136. Ok(&mut self.contigs[at])
  137. }
  138. /// Add a new contiguous range to the assembler, and return `Ok(())`,
  139. /// or return `Err(())` if too many discontiguities are already recorded.
  140. pub fn add(&mut self, mut offset: usize, mut size: usize) -> Result<(), TooManyHolesError> {
  141. let mut index = 0;
  142. while index != self.contigs.len() && size != 0 {
  143. let contig = self.contigs[index];
  144. if offset >= contig.total_size() {
  145. // The range being added does not cover this contig, skip it.
  146. index += 1;
  147. } else if offset == 0 && size >= contig.hole_size && index > 0 {
  148. // The range being added covers the entire hole in this contig, merge it
  149. // into the previous config.
  150. self.contigs[index - 1].expand_data_by(contig.total_size());
  151. self.remove_contig_at(index);
  152. index += 0;
  153. } else if offset == 0 && size < contig.hole_size && index > 0 {
  154. // The range being added covers a part of the hole in this contig starting
  155. // at the beginning, shrink the hole in this contig and expand data in
  156. // the previous contig.
  157. self.contigs[index - 1].expand_data_by(size);
  158. self.contigs[index].shrink_hole_by(size);
  159. index += 1;
  160. } else if offset <= contig.hole_size && offset + size >= contig.hole_size {
  161. // The range being added covers both a part of the hole and a part of the data
  162. // in this contig, shrink the hole in this contig.
  163. self.contigs[index].shrink_hole_to(offset);
  164. index += 1;
  165. } else if offset + size >= contig.hole_size {
  166. // The range being added covers only a part of the data in this contig, skip it.
  167. index += 1;
  168. } else if offset + size < contig.hole_size {
  169. // The range being added covers a part of the hole but not of the data
  170. // in this contig, add a new contig containing the range.
  171. {
  172. let inserted = self.add_contig_at(index)?;
  173. *inserted = Contig::hole_and_data(offset, size);
  174. }
  175. // Previous contigs[index] got moved to contigs[index+1]
  176. self.contigs[index+1].shrink_hole_by(offset + size);
  177. index += 2;
  178. } else {
  179. unreachable!()
  180. }
  181. // Skip the portion of the range covered by this contig.
  182. if offset >= contig.total_size() {
  183. offset = offset.saturating_sub(contig.total_size());
  184. } else {
  185. size = (offset + size).saturating_sub(contig.total_size());
  186. offset = 0;
  187. }
  188. }
  189. debug_assert!(size == 0);
  190. Ok(())
  191. }
  192. /// Remove a contiguous range from the front of the assembler and `Some(data_size)`,
  193. /// or return `None` if there is no such range.
  194. pub fn remove_front(&mut self) -> Option<usize> {
  195. let front = self.front();
  196. if front.has_hole() {
  197. None
  198. } else {
  199. let last_hole = self.remove_contig_at(0);
  200. last_hole.hole_size += front.data_size;
  201. debug_assert!(front.data_size > 0);
  202. Some(front.data_size)
  203. }
  204. }
  205. /// Iterate over all of the contiguous data ranges.
  206. ///
  207. /// This is used in calculating what data ranges have been received. The offset indicates the
  208. /// number of bytes of contiguous data received before the beginnings of this Assembler.
  209. ///
  210. /// Data Hole Data
  211. /// |--- 100 ---|--- 200 ---|--- 100 ---|
  212. ///
  213. /// An offset of 1500 would return the ranges: ``(1500, 1600), (1800, 1900)``
  214. pub fn iter_data(&self, first_offset: usize) -> AssemblerIter {
  215. AssemblerIter::new(self, first_offset)
  216. }
  217. }
  218. pub struct AssemblerIter<'a> {
  219. assembler: &'a Assembler,
  220. offset: usize,
  221. index: usize,
  222. left: usize,
  223. right: usize
  224. }
  225. impl<'a> AssemblerIter<'a> {
  226. fn new(assembler: &'a Assembler, offset: usize) -> AssemblerIter<'a> {
  227. AssemblerIter {
  228. assembler: assembler,
  229. offset: offset,
  230. index: 0,
  231. left: 0,
  232. right: 0
  233. }
  234. }
  235. }
  236. impl<'a> Iterator for AssemblerIter<'a> {
  237. type Item = (usize, usize);
  238. fn next(&mut self) -> Option<(usize, usize)> {
  239. let mut data_range = None;
  240. while data_range.is_none() && self.index < self.assembler.contigs.len() {
  241. let contig = self.assembler.contigs[self.index];
  242. self.left += contig.hole_size;
  243. self.right = self.left + contig.data_size;
  244. data_range = if self.left < self.right {
  245. let data_range = (self.left + self.offset, self.right + self.offset);
  246. self.left = self.right;
  247. Some(data_range)
  248. } else {
  249. None
  250. };
  251. self.index += 1;
  252. }
  253. data_range
  254. }
  255. }
  256. #[cfg(test)]
  257. mod test {
  258. use std::vec::Vec;
  259. use super::*;
  260. impl From<Vec<(usize, usize)>> for Assembler {
  261. fn from(vec: Vec<(usize, usize)>) -> Assembler {
  262. #[cfg(not(any(feature = "std", feature = "alloc")))]
  263. let mut contigs = [Contig::empty(); CONTIG_COUNT];
  264. #[cfg(any(feature = "std", feature = "alloc"))]
  265. let mut contigs = Box::new([Contig::empty(); CONTIG_COUNT]);
  266. for (i, &(hole_size, data_size)) in vec.iter().enumerate() {
  267. contigs[i] = Contig { hole_size, data_size };
  268. }
  269. Assembler { contigs }
  270. }
  271. }
  272. macro_rules! contigs {
  273. [$( $x:expr ),*] => ({
  274. Assembler::from(vec![$( $x ),*])
  275. })
  276. }
  277. #[test]
  278. fn test_new() {
  279. let assr = Assembler::new(16);
  280. assert_eq!(assr.total_size(), 16);
  281. assert_eq!(assr, contigs![(16, 0)]);
  282. }
  283. #[test]
  284. fn test_empty_add_full() {
  285. let mut assr = Assembler::new(16);
  286. assert_eq!(assr.add(0, 16), Ok(()));
  287. assert_eq!(assr, contigs![(0, 16)]);
  288. }
  289. #[test]
  290. fn test_empty_add_front() {
  291. let mut assr = Assembler::new(16);
  292. assert_eq!(assr.add(0, 4), Ok(()));
  293. assert_eq!(assr, contigs![(0, 4), (12, 0)]);
  294. }
  295. #[test]
  296. fn test_empty_add_back() {
  297. let mut assr = Assembler::new(16);
  298. assert_eq!(assr.add(12, 4), Ok(()));
  299. assert_eq!(assr, contigs![(12, 4)]);
  300. }
  301. #[test]
  302. fn test_empty_add_mid() {
  303. let mut assr = Assembler::new(16);
  304. assert_eq!(assr.add(4, 8), Ok(()));
  305. assert_eq!(assr, contigs![(4, 8), (4, 0)]);
  306. }
  307. #[test]
  308. fn test_partial_add_front() {
  309. let mut assr = contigs![(4, 8), (4, 0)];
  310. assert_eq!(assr.add(0, 4), Ok(()));
  311. assert_eq!(assr, contigs![(0, 12), (4, 0)]);
  312. }
  313. #[test]
  314. fn test_partial_add_back() {
  315. let mut assr = contigs![(4, 8), (4, 0)];
  316. assert_eq!(assr.add(12, 4), Ok(()));
  317. assert_eq!(assr, contigs![(4, 12)]);
  318. }
  319. #[test]
  320. fn test_partial_add_front_overlap() {
  321. let mut assr = contigs![(4, 8), (4, 0)];
  322. assert_eq!(assr.add(0, 8), Ok(()));
  323. assert_eq!(assr, contigs![(0, 12), (4, 0)]);
  324. }
  325. #[test]
  326. fn test_partial_add_front_overlap_split() {
  327. let mut assr = contigs![(4, 8), (4, 0)];
  328. assert_eq!(assr.add(2, 6), Ok(()));
  329. assert_eq!(assr, contigs![(2, 10), (4, 0)]);
  330. }
  331. #[test]
  332. fn test_partial_add_back_overlap() {
  333. let mut assr = contigs![(4, 8), (4, 0)];
  334. assert_eq!(assr.add(8, 8), Ok(()));
  335. assert_eq!(assr, contigs![(4, 12)]);
  336. }
  337. #[test]
  338. fn test_partial_add_back_overlap_split() {
  339. let mut assr = contigs![(4, 8), (4, 0)];
  340. assert_eq!(assr.add(10, 4), Ok(()));
  341. assert_eq!(assr, contigs![(4, 10), (2, 0)]);
  342. }
  343. #[test]
  344. fn test_partial_add_both_overlap() {
  345. let mut assr = contigs![(4, 8), (4, 0)];
  346. assert_eq!(assr.add(0, 16), Ok(()));
  347. assert_eq!(assr, contigs![(0, 16)]);
  348. }
  349. #[test]
  350. fn test_partial_add_both_overlap_split() {
  351. let mut assr = contigs![(4, 8), (4, 0)];
  352. assert_eq!(assr.add(2, 12), Ok(()));
  353. assert_eq!(assr, contigs![(2, 12), (2, 0)]);
  354. }
  355. #[test]
  356. fn test_rejected_add_keeps_state() {
  357. let mut assr = Assembler::new(CONTIG_COUNT*20);
  358. for c in 1..=CONTIG_COUNT-1 {
  359. assert_eq!(assr.add(c*10, 3), Ok(()));
  360. }
  361. // Maximum of allowed holes is reached
  362. let assr_before = assr.clone();
  363. assert_eq!(assr.add(1, 3), Err(TooManyHolesError));
  364. assert_eq!(assr_before, assr);
  365. }
  366. #[test]
  367. fn test_empty_remove_front() {
  368. let mut assr = contigs![(12, 0)];
  369. assert_eq!(assr.remove_front(), None);
  370. }
  371. #[test]
  372. fn test_trailing_hole_remove_front() {
  373. let mut assr = contigs![(0, 4), (8, 0)];
  374. assert_eq!(assr.remove_front(), Some(4));
  375. assert_eq!(assr, contigs![(12, 0)]);
  376. }
  377. #[test]
  378. fn test_trailing_data_remove_front() {
  379. let mut assr = contigs![(0, 4), (4, 4)];
  380. assert_eq!(assr.remove_front(), Some(4));
  381. assert_eq!(assr, contigs![(4, 4), (4, 0)]);
  382. }
  383. #[test]
  384. fn test_iter_empty() {
  385. let assr = Assembler::new(16);
  386. let segments: Vec<_> = assr.iter_data(10).collect();
  387. assert_eq!(segments, vec![]);
  388. }
  389. #[test]
  390. fn test_iter_full() {
  391. let mut assr = Assembler::new(16);
  392. assert_eq!(assr.add(0, 16), Ok(()));
  393. let segments: Vec<_> = assr.iter_data(10).collect();
  394. assert_eq!(segments, vec![(10, 26)]);
  395. }
  396. #[test]
  397. fn test_iter_offset() {
  398. let mut assr = Assembler::new(16);
  399. assert_eq!(assr.add(0, 16), Ok(()));
  400. let segments: Vec<_> = assr.iter_data(100).collect();
  401. assert_eq!(segments, vec![(100, 116)]);
  402. }
  403. #[test]
  404. fn test_iter_one_front() {
  405. let mut assr = Assembler::new(16);
  406. assert_eq!(assr.add(0, 4), Ok(()));
  407. let segments: Vec<_> = assr.iter_data(10).collect();
  408. assert_eq!(segments, vec![(10, 14)]);
  409. }
  410. #[test]
  411. fn test_iter_one_back() {
  412. let mut assr = Assembler::new(16);
  413. assert_eq!(assr.add(12, 4), Ok(()));
  414. let segments: Vec<_> = assr.iter_data(10).collect();
  415. assert_eq!(segments, vec![(22, 26)]);
  416. }
  417. #[test]
  418. fn test_iter_one_mid() {
  419. let mut assr = Assembler::new(16);
  420. assert_eq!(assr.add(4, 8), Ok(()));
  421. let segments: Vec<_> = assr.iter_data(10).collect();
  422. assert_eq!(segments, vec![(14, 22)]);
  423. }
  424. #[test]
  425. fn test_iter_one_trailing_gap() {
  426. let assr = contigs![(4, 8), (4, 0)];
  427. let segments: Vec<_> = assr.iter_data(100).collect();
  428. assert_eq!(segments, vec![(104, 112)]);
  429. }
  430. #[test]
  431. fn test_iter_two_split() {
  432. let assr = contigs![(2, 6), (4, 1), (1, 0)];
  433. let segments: Vec<_> = assr.iter_data(100).collect();
  434. assert_eq!(segments, vec![(102, 108), (112, 113)]);
  435. }
  436. #[test]
  437. fn test_iter_three_split() {
  438. let assr = contigs![(2, 6), (2, 1), (2, 2), (1, 0)];
  439. let segments: Vec<_> = assr.iter_data(100).collect();
  440. assert_eq!(segments, vec![(102, 108), (110, 111), (113, 115)]);
  441. }
  442. }