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
use std::io::{Cursor, Seek, SeekFrom, Write};
/// The kind of writer that should be used for writing chunks.
///
/// This is used to select what [`ChunkSink`] should be used by the MCAP writer.
#[derive(Default)]
pub(crate) enum ChunkMode {
/// Mode specifying that chunks should be written directly to the output
#[default]
Direct,
/// Mode specifying that chunks should be buffered before writing to the output
Buffered {
/// The reusable buffer used by the [`ChunkSink`] when writing to [`ChunkSink::Buffered`]
buffer: Vec<u8>,
},
}
/// The writer used for writing chunks.
///
/// If chunks are buffered they will be written to an internal buffer, which can be flushed to the
/// provided writer once the chunk is completed.
pub(crate) struct ChunkSink<W> {
pub inner: W,
pub buffer: Option<Cursor<Vec<u8>>>,
/// The compressor's frame header (see [`Self::hold_frame_header`]), held here until it is
/// written to `inner`. Only used when writing directly.
frame_header: Vec<u8>,
/// Whether the next write is the compressor's frame header and should be held back.
expecting_frame_header: bool,
}
impl<W> ChunkSink<W> {
pub fn new(writer: W, mode: ChunkMode) -> Self {
Self {
inner: writer,
buffer: match mode {
ChunkMode::Buffered { mut buffer } => {
// ensure the buffer is empty before using it for the chunk
buffer.clear();
Some(Cursor::new(buffer))
}
ChunkMode::Direct => None,
},
frame_header: Vec::new(),
expecting_frame_header: false,
}
}
/// Treats the next write as the compressor's frame header and keeps it in memory instead of
/// passing it to the underlying writer, so that it cannot fail. The frame header is written
/// through ahead of the next write, flush, seek, or [`Self::finish`], and any error surfaces
/// there instead.
///
/// This exists for compressors that take ownership of the sink while they write their frame
/// header, and drop the sink if that write fails. By the time the frame header is written
/// through, the caller owns the compressor and can always get the sink back from it. The sink
/// cannot tell where the frame header ends: it holds exactly one write, so the compressor
/// must emit its frame header as a single write.
///
/// This is the compressor's frame header, not the MCAP chunk header, which is written before
/// the compressor is set up.
///
/// Has no effect when chunks are buffered, since writes then go to memory anyway.
// Only the lz4 compressor needs this today.
#[cfg_attr(not(feature = "lz4"), allow(dead_code))]
pub fn hold_frame_header(&mut self) {
if self.buffer.is_none() {
self.expecting_frame_header = true;
}
}
}
impl<W: Write> ChunkSink<W> {
/// Writes a held frame header through to the underlying writer.
fn write_frame_header(&mut self) -> std::io::Result<()> {
if !self.frame_header.is_empty() {
self.inner.write_all(&self.frame_header)?;
self.frame_header.clear();
}
Ok(())
}
pub fn finish(self) -> (W, std::io::Result<ChunkMode>) {
let ChunkSink {
mut inner,
buffer,
frame_header,
..
} = self;
let mode = match buffer {
Some(buffer) => {
let buffer = buffer.into_inner();
if let Err(err) = inner.write_all(&buffer) {
return (inner, Err(err));
}
ChunkMode::Buffered { buffer }
}
None => {
if let Err(err) = inner.write_all(&frame_header) {
return (inner, Err(err));
}
ChunkMode::Direct
}
};
(inner, Ok(mode))
}
}
impl<W: Write + Seek> Seek for ChunkSink<W> {
fn seek(&mut self, pos: SeekFrom) -> std::io::Result<u64> {
match &mut self.buffer {
Some(buffer) => buffer.seek(pos),
None => {
self.write_frame_header()?;
self.inner.seek(pos)
}
}
}
fn stream_position(&mut self) -> std::io::Result<u64> {
match &mut self.buffer {
Some(buffer) => buffer.stream_position(),
None => {
self.write_frame_header()?;
self.inner.stream_position()
}
}
}
}
impl<W: Write> Write for ChunkSink<W> {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
match &mut self.buffer {
Some(buffer) => buffer.write(buf),
None if self.expecting_frame_header => {
self.expecting_frame_header = false;
self.frame_header.extend_from_slice(buf);
Ok(buf.len())
}
None => {
self.write_frame_header()?;
self.inner.write(buf)
}
}
}
fn flush(&mut self) -> std::io::Result<()> {
match &mut self.buffer {
Some(buffer) => buffer.flush(),
None => {
self.write_frame_header()?;
self.inner.flush()
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_util::FullDisk;
#[test]
fn frame_header_goes_through_ahead_of_the_next_operation() {
let mut sink = ChunkSink::new(Cursor::new(Vec::new()), ChunkMode::Direct);
sink.hold_frame_header();
sink.write_all(b"header").unwrap();
assert!(sink.inner.get_ref().is_empty());
assert_eq!(sink.stream_position().unwrap(), 6);
assert_eq!(sink.inner.get_ref(), b"header");
sink.write_all(b"data").unwrap();
assert_eq!(sink.inner.get_ref(), b"headerdata");
}
#[test]
fn frame_header_write_error_surfaces_later() {
let mut sink = ChunkSink::new(FullDisk::new(0), ChunkMode::Direct);
sink.hold_frame_header();
sink.write_all(b"header").unwrap();
assert!(sink.write_all(b"data").is_err());
assert!(sink.finish().1.is_err());
}
#[test]
fn holding_the_frame_header_has_no_effect_when_buffered() {
let mode = ChunkMode::Buffered { buffer: Vec::new() };
let mut sink = ChunkSink::new(FullDisk::new(0), mode);
sink.hold_frame_header();
sink.write_all(b"header").unwrap();
assert!(sink.frame_header.is_empty());
assert!(sink.finish().1.is_err());
}
}