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
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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
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
use alloc::{vec, vec::Vec};
use core::{alloc::Layout, cmp, mem};

use crate::{IoSlice, IoSliceMut, SeekFrom};

mod block;

use self::block::Block;

#[derive(Debug, Copy, Clone, PartialEq, Eq)]
struct Seeker {
    current_block: usize,
    current_pos_in_block: usize,
    current_pos: usize,
    end_pos: usize,
}

impl Seeker {
    fn with_len(len: usize) -> Seeker {
        Seeker {
            current_block: 0,
            current_pos_in_block: 0,
            current_pos: 0,
            end_pos: len,
        }
    }

    #[inline]
    fn is_at_end(&self) -> bool {
        self.current_pos >= self.end_pos
    }

    fn read(&mut self, mut buf: &mut [impl IoSliceMut], blocks: &[Block]) -> Result<usize, usize> {
        let mut read_len = 0;
        loop {
            let block = blocks.get(self.current_block).ok_or(read_len)?;
            let len = block.read(self.current_pos_in_block, &mut buf);
            if len > 0 {
                read_len += len;
                self.advance(len, blocks).expect("Inconsistent seeker");
            } else {
                break Ok(read_len);
            }
        }
    }

    fn write(
        &mut self,
        buf: &mut &mut [impl IoSlice],
        blocks: &mut [Block],
    ) -> Result<usize, usize> {
        let mut written_len = 0;
        loop {
            let block = blocks.get_mut(self.current_block).ok_or(written_len)?;
            let len = block.write(self.current_pos_in_block, buf);
            if len > 0 {
                written_len += len;
                self.advance(len, blocks).expect("Inconsistent seeker");
            } else {
                break Ok(written_len);
            }
        }
    }

    fn append_end(&mut self, extra: usize) {
        if self.current_pos >= self.end_pos {
            self.current_pos += extra;
            self.end_pos = self.current_pos;
        } else {
            self.end_pos += extra;
        }
    }

    fn append_new(&mut self, block: &Block) {
        if self.current_pos == self.end_pos {
            self.current_pos += block.len();
            self.current_block += 1;
            self.current_pos_in_block = block.len();
        }
        self.end_pos += block.len();
    }

    fn extend_end(&mut self, extra: usize, last: &Block) {
        if (self.end_pos..(self.end_pos + extra)).contains(&self.current_pos) {
            self.current_block -= 1;
            self.current_pos_in_block += last.len() - extra;
        } else if self.current_pos >= self.end_pos + extra {
            self.current_pos_in_block -= extra;
        }
        self.end_pos += extra;
    }

    fn extend_new(&mut self, len: usize) {
        if self.current_pos_in_block >= len {
            self.current_block += 1;
            self.current_pos_in_block -= len;
        }
        self.end_pos += len;
    }

    fn truncate(&mut self, new_pos: usize, blocks: &[Block]) -> Option<(usize, usize)> {
        if self.end_pos <= new_pos {
            return None;
        }
        self.end_pos = new_pos;

        match self.current_pos.cmp(&new_pos) {
            cmp::Ordering::Less => {
                if blocks.len() <= self.current_block {
                    None
                } else {
                    let mut pos = self.current_pos - self.current_pos_in_block;
                    for (bi_delta, block) in blocks[self.current_block..].iter().enumerate() {
                        if new_pos < block.len() + pos {
                            return Some((self.current_block + bi_delta, new_pos - pos));
                        }
                        pos += block.len();
                    }
                    None
                }
            }
            cmp::Ordering::Equal => Some(if self.current_pos_in_block > 0 {
                self.current_block += 1;
                let pos_in_block = mem::replace(&mut self.current_pos_in_block, 0);
                (self.current_block - 1, pos_in_block)
            } else {
                (self.current_block, 0)
            }),
            cmp::Ordering::Greater => {
                let mut pos = self.current_pos_in_block;
                for (bi_delta, block) in blocks[..self.current_block].iter().rev().enumerate() {
                    pos += block.len();
                    if self.current_pos <= new_pos + pos {
                        self.current_block -= bi_delta;
                        self.current_pos_in_block = self.current_pos - new_pos;
                        return Some((self.current_block - 1, pos + new_pos - self.current_pos));
                    }
                }
                unreachable!()
            }
        }
    }

    fn advance(&mut self, delta: usize, blocks: &[Block]) -> Option<usize> {
        let new_pos = self.current_pos + delta;
        if new_pos >= self.end_pos {
            self.current_block = blocks.len();
            self.current_pos_in_block = new_pos - self.end_pos;
            self.current_pos = new_pos;
            self.end_pos = new_pos;
            return Some(new_pos);
        }
        let mut pos = self.current_pos_in_block + delta;
        for (bi_delta, block) in blocks[self.current_block..].iter().enumerate() {
            if pos < block.len() {
                self.current_block += bi_delta;
                self.current_pos_in_block = pos;
                self.current_pos = new_pos;
                return Some(new_pos);
            }
            pos -= block.len();
        }
        None
    }

    fn seek_from_start(&mut self, start: usize, blocks: &[Block]) -> Option<usize> {
        let new_pos = start;
        if new_pos >= self.end_pos {
            self.current_block = blocks.len();
            self.current_pos_in_block = new_pos - self.end_pos;
            self.current_pos = new_pos;
            self.end_pos = new_pos;
            return Some(new_pos);
        }
        let mut pos = start;
        for (bi, block) in blocks.iter().enumerate() {
            if pos < block.len() {
                self.current_block = bi;
                self.current_pos_in_block = pos;
                self.current_pos = new_pos;
                return Some(new_pos);
            }
            pos -= block.len();
        }
        None
    }

    fn seek_from_end(&mut self, end: isize, blocks: &[Block]) -> Option<usize> {
        if end >= 0 {
            self.current_block = blocks.len();
            self.current_pos_in_block = end as usize;
            self.current_pos = self.end_pos + end as usize;
            return Some(self.current_pos);
        }

        let pos_delta = (-end) as usize;
        if self.end_pos < pos_delta {
            return None;
        }
        let new_pos = self.end_pos - pos_delta;
        if new_pos == 0 {
            self.current_block = 0;
            self.current_pos_in_block = 0;
            self.current_pos = 0;
            return Some(0);
        }

        let mut pos = 0;
        for (bi, block) in blocks.iter().enumerate().rev() {
            pos += block.len();
            if pos >= pos_delta {
                self.current_block = bi;
                self.current_pos_in_block = pos - pos_delta;
                self.current_pos = new_pos;
                return Some(new_pos);
            }
        }
        None
    }

    fn seek_from_current(&mut self, current: isize, blocks: &[Block]) -> Option<usize> {
        match current.cmp(&0) {
            cmp::Ordering::Equal => Some(self.current_pos),
            cmp::Ordering::Greater => self.advance(current as usize, blocks),
            cmp::Ordering::Less => {
                let pos_delta = (-current) as usize;
                if self.current_pos < pos_delta {
                    return None;
                }
                let new_pos = self.current_pos - pos_delta;
                if new_pos == 0 {
                    self.current_block = 0;
                    self.current_pos_in_block = 0;
                    self.current_pos = 0;
                    return Some(0);
                }

                if self.current_pos_in_block >= pos_delta {
                    self.current_pos_in_block -= pos_delta;
                    self.current_pos = new_pos;
                    return Some(new_pos);
                }

                let mut pos = self.current_pos_in_block;
                for (bi_delta, block) in blocks[..self.current_block].iter().rev().enumerate() {
                    pos += block.len();
                    if pos >= pos_delta {
                        self.current_block -= bi_delta + 1;
                        self.current_pos_in_block = pos - pos_delta;
                        self.current_pos = new_pos;
                        return Some(new_pos);
                    }
                }

                None
            }
        }
    }
}

/// A vector of blocks.
///
/// See the [module documentation](crate) for details.
#[derive(Debug)]
pub struct BlockedVec {
    blocks: Vec<Block>,
    layout: Layout,
    len: usize,
    seeker: Option<Seeker>,
}

impl BlockedVec {
    /// Creates a new [`BlockedVec`].
    ///
    /// # Panics
    ///
    /// Panics if the queried page size cannot be made into a layout.
    #[cfg(feature = "std")]
    pub fn new() -> Self {
        let ps = page_size::get();
        let layout = Layout::from_size_align(ps, ps).expect("Invalid layout");
        Self::new_paged(layout)
    }

    /// Creates a new [`BlockedVec`] with a given page layout.
    pub fn new_paged(page_layout: Layout) -> Self {
        BlockedVec {
            blocks: Vec::new(),
            layout: page_layout,
            len: 0,
            seeker: None,
        }
    }

    /// Creates a new [`BlockedVec`] with an initial length, with the cursor
    /// placed at the front.
    ///
    /// # Panics
    ///
    /// Panics if the queried page size cannot be made into a layout.
    #[cfg(feature = "std")]
    pub fn with_len(len: usize) -> Self {
        let ps = page_size::get();
        let layout = Layout::from_size_align(ps, ps).expect("Invalid layout");
        Self::with_len_paged(len, layout)
    }

    /// Creates a new [`BlockedVec`] with a given page layout and an initial
    /// length, with the cursor placed at the front.
    pub fn with_len_paged(len: usize, page_layout: Layout) -> Self {
        match Block::with_len(page_layout, len) {
            Some(block) => BlockedVec {
                blocks: vec![block],
                layout: page_layout,
                len: 0,
                seeker: Some(Seeker::with_len(len)),
            },
            None => Self::new_paged(page_layout),
        }
    }

    /// Returns the length of this [`BlockedVec`].
    pub fn len(&self) -> usize {
        self.len
    }

    /// Checks if this [`BlockedVec`] is empty.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.len == 0
    }

    fn append_inner(&mut self, buf: &mut &mut [impl IoSlice]) -> usize {
        match &mut self.seeker {
            Some(seeker) => {
                let last = self.blocks.last_mut().expect("Inconsistent seeker");
                let skip = if seeker.is_at_end() {
                    let skip = mem::replace(&mut seeker.current_pos_in_block, 0);
                    seeker.current_pos -= skip;
                    skip
                } else {
                    0
                };
                match last.extend(skip, buf) {
                    Ok(len) => {
                        seeker.append_end(len);
                        self.len += len;
                        len - skip
                    }
                    Err(len) => {
                        seeker.append_end(len);
                        self.len += len;

                        let skip2 = if len > skip { 0 } else { skip - len };

                        if let Some((new, len2)) = Block::from_buf(self.layout, skip2, buf) {
                            seeker.append_new(&new);
                            self.len += new.len();
                            self.blocks.push(new);

                            len + len2 - skip + skip2
                        } else {
                            len - skip
                        }
                    }
                }
            }
            None => match Block::from_buf(self.layout, 0, buf) {
                Some((block, len)) => {
                    let mut seeker = Seeker::with_len(block.len());
                    seeker.current_block = 1;
                    seeker.current_pos = seeker.end_pos;
                    self.seeker = Some(seeker);
                    self.len = block.len();
                    self.blocks = vec![block];
                    len
                }
                None => 0,
            },
        }
    }

    /// Extend the `BlockedVec`, with the possible additional areas filled with
    /// zero.
    ///
    /// # Panics
    ///
    /// Panics if the seeker or blocks are inconsistent.
    pub fn extend(&mut self, additional: usize) {
        match &mut self.seeker {
            Some(seeker) => {
                let last = self.blocks.last_mut().expect("Inconsistent seeker");
                match last.extend(additional, &mut (&mut [] as &mut [&[u8]])) {
                    Ok(len) => {
                        seeker.extend_end(len, last);
                        self.len += len
                    }
                    Err(len) => {
                        seeker.extend_end(len, last);
                        self.len += len;

                        let len2 = additional - len;
                        let (new, _) =
                            Block::from_buf(self.layout, len2, &mut (&mut [] as &mut [&[u8]]))
                                .expect("Inconsistent blocks");
                        seeker.extend_new(len2);
                        self.len += len2;
                        self.blocks.push(new);
                    }
                }
            }
            None => *self = Self::with_len_paged(additional, self.layout),
        }
    }

    /// Append a bunch of buffers to the `BlockedVec`.
    ///
    /// # Returns
    ///
    /// The actual length of the buffers appended.
    ///
    /// # Panics
    ///
    /// Panics if the seeker is inconsistent.
    pub fn append_vectored(&mut self, mut buf: &mut [impl IoSlice]) -> usize {
        self.seek(SeekFrom::End(0)).expect("Inconsistent seeker");
        self.append_inner(&mut buf)
    }

    /// Append a buffer to the `BlockedVec`.
    ///
    /// # Returns
    ///
    /// The actual length of the buffer appended.
    pub fn append(&mut self, buf: &[u8]) -> usize {
        self.append_vectored(&mut [buf])
    }

    /// Like `read`, except that it reads into a slice of buffers.
    pub fn read_vectored(&mut self, buf: &mut [impl IoSliceMut]) -> usize {
        let seeker = match &mut self.seeker {
            Some(seeker) => seeker,
            None => return 0,
        };
        match seeker.read(buf, &self.blocks) {
            Ok(len) => len,
            Err(len) => len,
        }
    }

    /// Like `read_at`, except that it reads into a slice of buffers.
    pub fn read_at_vectored(&mut self, pos: usize, buf: &mut [impl IoSliceMut]) -> usize {
        let mut seeker = match self.seeker {
            Some(mut seeker) => match seeker.seek_from_start(pos, &self.blocks) {
                Some(_) => seeker,
                None => return 0,
            },
            None => return 0,
        };
        match seeker.read(buf, &self.blocks) {
            Ok(len) => len,
            Err(len) => len,
        }
    }

    /// Pull some bytes from this [`BlockedVec`] into the specified buffer,
    /// returning how many bytes were read.
    #[inline]
    pub fn read(&mut self, buf: &mut [u8]) -> usize {
        self.read_vectored(&mut [buf])
    }

    /// Pull some bytes from this [`BlockedVec`] into the specified buffer at a
    /// specified position, returning how many bytes were read.
    #[inline]
    pub fn read_at(&mut self, pos: usize, buf: &mut [u8]) -> usize {
        self.read_at_vectored(pos, &mut [buf])
    }

    /// Like [`write`], except that it writes from a slice of buffers.
    ///
    /// [`write`]: BlockedVec::write
    pub fn write_vectored(&mut self, mut buf: &mut [impl IoSlice]) -> usize {
        let seeker = match &mut self.seeker {
            Some(seeker) => seeker,
            None => return 0,
        };
        match seeker.write(&mut buf, &mut self.blocks) {
            Ok(len) => len,
            Err(len) => self.append_inner(&mut buf) + len,
        }
    }

    /// Like [`write_at`], except that it writes from a slice of buffers.
    ///
    /// [`write_at`]: BlockedVec::write_at
    pub fn write_at_vectored(&mut self, pos: usize, mut buf: &mut [impl IoSlice]) -> usize {
        let mut seeker = match self.seeker {
            Some(mut seeker) => match seeker.seek_from_start(pos, &self.blocks) {
                Some(_) => seeker,
                None => return 0,
            },
            None => return 0,
        };
        match seeker.write(&mut buf, &mut self.blocks) {
            Ok(len) => len,
            Err(len) => self.append_inner(&mut buf) + len,
        }
    }

    /// Write a buffer into this writer, returning how many bytes were written.
    #[inline]
    pub fn write(&mut self, buf: &[u8]) -> usize {
        self.write_vectored(&mut [buf])
    }

    /// Write a buffer into this writer at a specified position, returning how
    /// many bytes were written.
    #[inline]
    pub fn write_at(&mut self, pos: usize, buf: &[u8]) -> usize {
        self.write_at_vectored(pos, &mut [buf])
    }

    /// Seek to an offset, in bytes, in this [`BlockedVec`].
    pub fn seek(&mut self, pos: SeekFrom) -> Option<usize> {
        match &mut self.seeker {
            Some(seeker) => match pos {
                SeekFrom::Start(start) => seeker.seek_from_start(start as usize, &self.blocks),
                SeekFrom::End(end) => seeker.seek_from_end(end as isize, &self.blocks),
                SeekFrom::Current(current) => {
                    seeker.seek_from_current(current as isize, &self.blocks)
                }
            },
            _ if pos == SeekFrom::End(0) => Some(0),
            _ => None,
        }
    }

    /// Shortens this `BlockedVec` to the specified length.
    pub fn truncate(&mut self, len: usize) -> bool {
        match &mut self.seeker {
            Some(seeker) => match seeker.truncate(len, &self.blocks) {
                Some((bi, pos_in_block)) => {
                    let bi = match self.blocks[bi].truncate(pos_in_block) {
                        Some(true) => bi,
                        _ => bi + 1,
                    };
                    if bi < self.blocks.len() {
                        self.blocks.truncate(bi);
                    }
                    self.len = len;
                    true
                }
                None => {
                    self.len = len;
                    seeker.end_pos > len
                }
            },
            None => false,
        }
    }

    /// Resizes the `BlockedVec` in-place so that `len` is equal to `new_len`,
    /// with the possible additional area filled with zero.
    pub fn resize(&mut self, new_len: usize) {
        if self.len < new_len {
            let extra = new_len - self.len;
            self.extend(extra)
        } else {
            self.truncate(new_len);
        }
    }
}

#[cfg(feature = "std")]
impl Default for BlockedVec {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(feature = "std")]
impl std::io::Seek for BlockedVec {
    #[inline]
    fn seek(&mut self, pos: std::io::SeekFrom) -> std::io::Result<u64> {
        self.seek(pos.into())
            .map(|pos| pos as u64)
            .ok_or_else(|| std::io::ErrorKind::InvalidInput.into())
    }
}

#[cfg(feature = "std")]
impl std::io::Read for BlockedVec {
    #[inline]
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        Ok(self.read(buf))
    }

    #[inline]
    fn read_vectored(&mut self, bufs: &mut [std::io::IoSliceMut<'_>]) -> std::io::Result<usize> {
        Ok(self.read_vectored(bufs))
    }
}

#[cfg(feature = "std")]
impl std::io::Write for BlockedVec {
    #[inline]
    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
        Ok(self.write(buf))
    }

    #[inline]
    fn write_vectored(&mut self, bufs: &[std::io::IoSlice<'_>]) -> std::io::Result<usize> {
        Ok(self.write_vectored(&mut Vec::from(bufs)))
    }

    #[inline]
    fn flush(&mut self) -> std::io::Result<()> {
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use std::io::{Read, Seek, Write};

    use super::*;

    fn test_inner() -> Option<()> {
        let layout = Layout::new::<[u8; 4]>();
        let mut vec = BlockedVec::new_paged(layout);
        vec.append(&[1, 2, 3, 4, 5]);
        vec.seek(SeekFrom::Start(3))?;
        vec.write_all(&[6, 7, 8, 9, 10]).unwrap();
        vec.seek(SeekFrom::End(-3))?;
        vec.write_all(&[11, 12, 13, 14, 15]).unwrap();
        vec.seek(SeekFrom::Current(-7))?;
        vec.seek(SeekFrom::Current(1))?;
        vec.write_all(&[16, 17, 18, 19, 20]).unwrap();
        vec.seek(SeekFrom::End(3))?;
        vec.write_all(&[21, 22, 23, 24, 25]).unwrap();
        vec.resize(6);
        vec.seek(SeekFrom::Current(-3))?;
        vec.resize(12);
        vec.append(&[26, 27, 28, 29, 30]);

        vec.rewind().unwrap();
        let mut buf = [0; 17];
        vec.read_exact(&mut buf).unwrap();
        assert_eq!(
            buf,
            [1, 2, 3, 6, 16, 17, 0, 0, 0, 0, 0, 0, 26, 27, 28, 29, 30]
        );
        Some(())
    }

    #[test]
    fn test() {
        test_inner().expect("Failed to seek")
    }
}