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
use std::{marker::PhantomData, mem::replace};

use anyhow::Result;

use super::ObjectWriter;

/// Wrap an object writer so it can receive chunks.
pub struct ChunkWriter<T, W>
where
    W: ObjectWriter<T>,
{
    _phantom: PhantomData<T>,
    delegate: W,
}

impl<T, W> ChunkWriter<T, W>
where
    W: ObjectWriter<T>,
{
    pub fn new(delegate: W) -> ChunkWriter<T, W> {
        ChunkWriter {
            _phantom: PhantomData,
            delegate,
        }
    }
}

impl<T, W> ObjectWriter<Vec<T>> for ChunkWriter<T, W>
where
    W: ObjectWriter<T>,
{
    fn write_object(&mut self, chunk: Vec<T>) -> Result<()> {
        self.delegate.write_all_objects(chunk.into_iter())?;
        Ok(())
    }

    fn finish(self) -> Result<usize> {
        self.delegate.finish()
    }
}

/// Wrap a writer of chunks to take individual values.
pub struct UnchunkWriter<T, W>
where
    W: ObjectWriter<Vec<T>>,
{
    delegate: W,
    chunk: Vec<T>,
    chunk_size: usize,
}

impl<T, W> UnchunkWriter<T, W>
where
    W: ObjectWriter<Vec<T>>,
{
    #[allow(dead_code)]
    pub fn new(delegate: W) -> UnchunkWriter<T, W> {
        UnchunkWriter::with_size(delegate, 1024)
    }

    pub fn with_size(delegate: W, size: usize) -> UnchunkWriter<T, W> {
        UnchunkWriter {
            delegate,
            chunk: Vec::with_capacity(size),
            chunk_size: size,
        }
    }
}

impl<T, W> ObjectWriter<T> for UnchunkWriter<T, W>
where
    W: ObjectWriter<Vec<T>>,
{
    fn write_object(&mut self, obj: T) -> Result<()> {
        self.chunk.push(obj);
        if self.chunk.len() >= self.chunk_size {
            let chunk = replace(&mut self.chunk, Vec::with_capacity(self.chunk_size));
            self.delegate.write_object(chunk)?;
        }
        Ok(())
    }

    fn finish(mut self) -> Result<usize> {
        if self.chunk.len() > 0 {
            self.delegate.write_object(self.chunk)?;
        }
        self.delegate.finish()
    }
}