cfb 0.14.0

Read/write Compound File Binary (structured storage) files
Documentation
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
use crate::internal::{consts, MiniAllocator, ObjType, SectorInit};
use std::io::{self, BufRead, Read, Seek, SeekFrom, Write};
use std::sync::{Arc, RwLock, Weak};

//===========================================================================//

use crate::internal::stream_buffer::StreamBuffer;

//===========================================================================//

/// A stream entry in a compound file, much like a filesystem file.
pub struct Stream<F> {
    minialloc: Weak<RwLock<MiniAllocator<F>>>,
    stream_id: u32,
    total_len: u64,
    buffer: StreamBuffer,
    buf_offset_from_start: u64,
    flusher: Option<Box<dyn Flusher<F>>>,
}

impl<F> Stream<F> {
    pub(crate) fn new(
        minialloc: &Arc<RwLock<MiniAllocator<F>>>,
        stream_id: u32,
        max_buffer_size: usize,
    ) -> Stream<F> {
        let total_len =
            minialloc.read().unwrap().dir_entry(stream_id).stream_len;
        Stream {
            minialloc: Arc::downgrade(minialloc),
            stream_id,
            total_len,
            buffer: StreamBuffer::new(max_buffer_size),
            buf_offset_from_start: 0,
            flusher: None,
        }
    }

    fn minialloc(&self) -> io::Result<Arc<RwLock<MiniAllocator<F>>>> {
        self.minialloc
            .upgrade()
            .ok_or_else(|| io::Error::other("CompoundFile was dropped"))
    }

    /// Returns the current length of the stream, in bytes.
    pub fn len(&self) -> u64 {
        self.total_len
    }

    /// Returns true if the stream is empty.
    pub fn is_empty(&self) -> bool {
        self.total_len == 0
    }

    fn current_position(&self) -> u64 {
        self.buf_offset_from_start + (self.buffer.cursor() as u64)
    }

    fn flush_changes(&mut self) -> io::Result<()> {
        if let Some(flusher) = self.flusher.take() {
            flusher.flush_changes(self)?;
        }
        Ok(())
    }
}

impl<F: Read + Write + Seek> Stream<F> {
    /// Truncates or extends the stream, updating the size of this stream to
    /// become `size`.
    ///
    /// If `size` is less than the stream's current size, then the stream will
    /// be shrunk.  If it is greater than the stream's current size, then the
    /// stream will be padded with zero bytes.
    ///
    /// Does not change the current read/write position within the stream,
    /// unless the stream is truncated to before the current position, in which
    /// case the position becomes the new end of the stream.
    pub fn set_len(&mut self, size: u64) -> io::Result<()> {
        if size != self.total_len {
            let new_position = self.current_position().min(size);
            self.flush_changes()?;
            let minialloc = self.minialloc()?;
            resize_stream(
                &mut minialloc.write().unwrap(),
                self.stream_id,
                size,
            )?;
            self.total_len = size;
            self.buf_offset_from_start = new_position;
            self.buffer.clear();
        }
        Ok(())
    }

    fn mark_modified(&mut self) {
        if self.flusher.is_none() {
            let flusher: Box<dyn Flusher<F>> = Box::new(FlushBuffer);
            self.flusher = Some(flusher);
        }
    }
}

impl<F: Read + Seek> BufRead for Stream<F> {
    fn fill_buf(&mut self) -> io::Result<&[u8]> {
        if !self.buffer.has_remaining()
            && self.current_position() < self.total_len
        {
            self.flush_changes()?;
            self.buf_offset_from_start += self.buffer.cursor() as u64;
            let remaining = self.total_len - self.buf_offset_from_start;
            let stream_id = self.stream_id;
            let offset = self.buf_offset_from_start;
            let minialloc = self.minialloc()?;
            self.buffer.refill_with(remaining, |buf| {
                read_data_from_stream(
                    &mut minialloc.write().unwrap(),
                    stream_id,
                    offset,
                    buf,
                )
            })?;
        }
        Ok(self.buffer.remaining_slice())
    }

    fn consume(&mut self, amt: usize) {
        self.buffer.consume(amt);
    }
}

impl<F: Read + Seek> Read for Stream<F> {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        let mut buffered_data = self.fill_buf()?;
        let num_bytes = buffered_data.read(buf)?;
        self.consume(num_bytes);
        Ok(num_bytes)
    }
}

impl<F: Read + Seek> Seek for Stream<F> {
    fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
        let new_pos: u64 =
            match pos {
                SeekFrom::Start(delta) => {
                    if delta > self.total_len {
                        invalid_input!(
                        "Cannot seek to {} bytes from start, because stream \
                         length is only {} bytes",
                        delta, self.total_len,
                    );
                    }
                    delta
                }
                SeekFrom::End(delta) => {
                    if delta > 0 {
                        invalid_input!(
                        "Cannot seek to {} bytes past the end of the stream",
                        delta,
                    );
                    } else {
                        let delta = (-delta) as u64;
                        if delta > self.total_len {
                            invalid_input!(
                                "Cannot seek to {} bytes before end, because \
                             stream length is only {} bytes",
                                delta,
                                self.total_len,
                            );
                        }
                        self.total_len - delta
                    }
                }
                SeekFrom::Current(delta) => {
                    let old_pos = self.current_position();
                    debug_assert!(old_pos <= self.total_len);
                    if delta < 0 {
                        let delta = (-delta) as u64;
                        if delta > old_pos {
                            invalid_input!(
                            "Cannot seek to {} bytes before current position, \
                             which is only {}",
                            delta, old_pos,
                        );
                        }
                        old_pos - delta
                    } else {
                        let delta = delta as u64;
                        let remaining = self.total_len - old_pos;
                        if delta > remaining {
                            invalid_input!(
                            "Cannot seek to {} bytes after current position, \
                             because there are only {} bytes remaining in the \
                             stream",
                            delta, remaining,
                        );
                        }
                        old_pos + delta
                    }
                }
            };
        if new_pos < self.buf_offset_from_start
            || new_pos
                > self.buf_offset_from_start + self.buffer.filled_len() as u64
        {
            self.flush_changes()?;
            self.buf_offset_from_start = new_pos;
            self.buffer.clear();
        } else {
            self.buffer.seek((new_pos - self.buf_offset_from_start) as usize);
        }
        Ok(new_pos)
    }
}

impl<F: Read + Write + Seek> Write for Stream<F> {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        let num_bytes_written = match self.buffer.write_bytes(buf) {
            Some(count) => count,
            None => {
                self.flush_changes()?;
                self.buf_offset_from_start += self.buffer.cursor() as u64;
                self.buffer.clear();
                self.buffer.write_bytes(buf).unwrap_or(0)
            }
        };
        if num_bytes_written > 0 {
            self.mark_modified();
            self.total_len = self.total_len.max(
                self.buf_offset_from_start + self.buffer.filled_len() as u64,
            );
        }
        Ok(num_bytes_written)
    }

    fn flush(&mut self) -> io::Result<()> {
        self.flush_changes()?;
        let minialloc = self.minialloc()?;
        minialloc.write().unwrap().flush()?;
        Ok(())
    }
}

impl<F> Drop for Stream<F> {
    fn drop(&mut self) {
        let _ = self.flush_changes();
    }
}

//===========================================================================//

trait Flusher<F> {
    fn flush_changes(&self, stream: &mut Stream<F>) -> io::Result<()>;
}

struct FlushBuffer;

impl<F: Read + Write + Seek> Flusher<F> for FlushBuffer {
    fn flush_changes(&self, stream: &mut Stream<F>) -> io::Result<()> {
        let minialloc = stream.minialloc()?;
        write_data_to_stream(
            &mut minialloc.write().unwrap(),
            stream.stream_id,
            stream.buf_offset_from_start,
            stream.buffer.filled_slice(),
        )?;
        debug_assert_eq!(
            minialloc.read().unwrap().dir_entry(stream.stream_id).stream_len,
            stream.total_len
        );
        Ok(())
    }
}

//===========================================================================//

fn read_data_from_stream<F: Read + Seek>(
    minialloc: &mut MiniAllocator<F>,
    stream_id: u32,
    buf_offset_from_start: u64,
    buf: &mut [u8],
) -> io::Result<usize> {
    let (start_sector, stream_len) = {
        let dir_entry = minialloc.dir_entry(stream_id);
        debug_assert_eq!(dir_entry.obj_type, ObjType::Stream);
        (dir_entry.start_sector, dir_entry.stream_len)
    };
    let num_bytes = if buf_offset_from_start >= stream_len {
        0
    } else {
        let remaining = stream_len - buf_offset_from_start;
        if remaining < buf.len() as u64 {
            remaining as usize
        } else {
            buf.len()
        }
    };
    if num_bytes > 0 {
        if stream_len < consts::MINI_STREAM_CUTOFF as u64 {
            let mut chain = minialloc.open_mini_chain(start_sector)?;
            chain.seek(SeekFrom::Start(buf_offset_from_start))?;
            chain.read_exact(&mut buf[..num_bytes])?;
        } else {
            let mut chain =
                minialloc.open_chain(start_sector, SectorInit::Zero)?;
            chain.seek(SeekFrom::Start(buf_offset_from_start))?;
            chain.read_exact(&mut buf[..num_bytes])?;
        }
    }
    Ok(num_bytes)
}

fn write_data_to_stream<F: Read + Write + Seek>(
    minialloc: &mut MiniAllocator<F>,
    stream_id: u32,
    buf_offset_from_start: u64,
    buf: &[u8],
) -> io::Result<()> {
    let (old_start_sector, old_stream_len) = {
        let dir_entry = minialloc.dir_entry(stream_id);
        debug_assert_eq!(dir_entry.obj_type, ObjType::Stream);
        (dir_entry.start_sector, dir_entry.stream_len)
    };
    debug_assert!(buf_offset_from_start <= old_stream_len);
    let new_stream_len =
        old_stream_len.max(buf_offset_from_start + buf.len() as u64);
    let new_start_sector = if old_start_sector == consts::END_OF_CHAIN {
        // Case 1: The stream has no existing chain.  The stream is empty, and
        // we are writing at the start.
        debug_assert_eq!(old_stream_len, 0);
        debug_assert_eq!(buf_offset_from_start, 0);
        if new_stream_len < consts::MINI_STREAM_CUTOFF as u64 {
            // Case 1a: The data we're writing is small enough that it
            // should be placed into a new mini chain.
            let mut chain = minialloc.open_mini_chain(consts::END_OF_CHAIN)?;
            chain.write_all(buf)?;
            chain.start_sector_id()
        } else {
            // Case 1b: The data we're writing is large enough that it should be placed
            // into a new regular chain.
            let mut chain = minialloc
                .open_chain(consts::END_OF_CHAIN, SectorInit::Zero)?;
            chain.write_all(buf)?;
            chain.start_sector_id()
        }
    } else if old_stream_len < consts::MINI_STREAM_CUTOFF as u64 {
        // Case 2: The stream currently exists in a mini chain.
        if new_stream_len < consts::MINI_STREAM_CUTOFF as u64 {
            // Case 2a: After the write, the stream will still be small enough
            // to stay in the mini stream.  Therefore, we should write into
            // this stream's existing mini chain.
            let mut chain = minialloc.open_mini_chain(old_start_sector)?;
            chain.seek(SeekFrom::Start(buf_offset_from_start))?;
            chain.write_all(buf)?;
            debug_assert_eq!(chain.start_sector_id(), old_start_sector);
            old_start_sector
        } else {
            // Case 2b: After the write, the stream will be large enough that
            // it cannot be in the mini stream.  Therefore, we should migrate
            // the stream into a new regular chain.
            debug_assert!(
                buf_offset_from_start < consts::MINI_STREAM_CUTOFF as u64
            );
            let mut tmp = vec![0u8; buf_offset_from_start as usize];
            let mut chain = minialloc.open_mini_chain(old_start_sector)?;
            chain.read_exact(&mut tmp)?;
            chain.free()?;
            let mut chain = minialloc
                .open_chain(consts::END_OF_CHAIN, SectorInit::Zero)?;
            chain.write_all(&tmp)?;
            chain.write_all(buf)?;
            chain.start_sector_id()
        }
    } else {
        // Case 3: The stream currently exists in a regular chain.  After the
        // write, it will of course still be too big to be in the mini stream.
        // Therefore, we should write into this stream's existing chain.
        debug_assert!(new_stream_len >= consts::MINI_STREAM_CUTOFF as u64);
        let mut chain =
            minialloc.open_chain(old_start_sector, SectorInit::Zero)?;
        chain.seek(SeekFrom::Start(buf_offset_from_start))?;
        chain.write_all(buf)?;
        debug_assert_eq!(chain.start_sector_id(), old_start_sector);
        old_start_sector
    };
    // Update the directory entry for this stream.
    minialloc.with_dir_entry_mut(stream_id, |dir_entry| {
        dir_entry.start_sector = new_start_sector;
        dir_entry.stream_len = new_stream_len;
    })
}

/// If `new_stream_len` is less than the stream's current length, then the
/// stream will be truncated.  If it is greater than the stream's current size,
/// then the stream will be padded with zero bytes.
fn resize_stream<F: Read + Write + Seek>(
    minialloc: &mut MiniAllocator<F>,
    stream_id: u32,
    new_stream_len: u64,
) -> io::Result<()> {
    let (old_start_sector, old_stream_len) = {
        let dir_entry = minialloc.dir_entry(stream_id);
        debug_assert_eq!(dir_entry.obj_type, ObjType::Stream);
        (dir_entry.start_sector, dir_entry.stream_len)
    };
    let new_start_sector = if old_start_sector == consts::END_OF_CHAIN {
        // Case 1: The stream has no existing chain.  We will allocate a new
        // chain that is all zeroes.
        debug_assert_eq!(old_stream_len, 0);
        if new_stream_len < consts::MINI_STREAM_CUTOFF as u64 {
            // Case 1a: The new length is small enough that it should be placed
            // into a new mini chain.
            let mut chain = minialloc.open_mini_chain(consts::END_OF_CHAIN)?;
            chain.set_len(new_stream_len)?;
            chain.start_sector_id()
        } else {
            // Case 1b: The new length is large enough that it should be placed
            // into a new regular chain.
            let mut chain = minialloc
                .open_chain(consts::END_OF_CHAIN, SectorInit::Zero)?;
            chain.set_len(new_stream_len)?;
            chain.start_sector_id()
        }
    } else if old_stream_len < consts::MINI_STREAM_CUTOFF as u64 {
        // Case 2: The stream currently exists in a mini chain.
        if new_stream_len == 0 {
            // Case 2a: The new length is zero.  Free the existing mini chain.
            minialloc.free_mini_chain(old_start_sector)?;
            consts::END_OF_CHAIN
        } else if new_stream_len < consts::MINI_STREAM_CUTOFF as u64 {
            // Case 2b: The new length is still small enough to fit in a mini
            // chain.  Therefore, we just need to adjust the length of the
            // existing chain.
            let mut chain = minialloc.open_mini_chain(old_start_sector)?;
            chain.set_len(new_stream_len)?;
            debug_assert_eq!(chain.start_sector_id(), old_start_sector);
            old_start_sector
        } else {
            // Case 2c: The new length is too large to fit in a mini chain.
            // Therefore, we should migrate the stream into a new regular
            // chain.
            let mut tmp = vec![0u8; old_stream_len as usize];
            let mut chain = minialloc.open_mini_chain(old_start_sector)?;
            chain.read_exact(&mut tmp)?;
            chain.free()?;
            let mut chain = minialloc
                .open_chain(consts::END_OF_CHAIN, SectorInit::Zero)?;
            chain.write_all(&tmp)?;
            chain.set_len(new_stream_len)?;
            chain.start_sector_id()
        }
    } else {
        // Case 3: The stream currently exists in a regular chain.
        if new_stream_len == 0 {
            // Case 3a: The new length is zero.  Free the existing chain.
            minialloc.free_chain(old_start_sector)?;
            consts::END_OF_CHAIN
        } else if new_stream_len < consts::MINI_STREAM_CUTOFF as u64 {
            // Case 3b: The new length is small enough to fit in a mini chain.
            // Therefore, we should migrate the stream into a new mini chain.
            debug_assert!(new_stream_len < old_stream_len);
            let mut tmp = vec![0u8; new_stream_len as usize];
            let mut chain =
                minialloc.open_chain(old_start_sector, SectorInit::Zero)?;
            chain.read_exact(&mut tmp)?;
            chain.free()?;
            let mut chain = minialloc.open_mini_chain(consts::END_OF_CHAIN)?;
            chain.write_all(&tmp)?;
            chain.start_sector_id()
        } else {
            // Case 3c: The new length is still too large to fit in a mini
            // chain.  Therefore, we just need to adjust the length of the
            // existing chain.
            let mut chain =
                minialloc.open_chain(old_start_sector, SectorInit::Zero)?;
            chain.set_len(new_stream_len)?;
            debug_assert_eq!(chain.start_sector_id(), old_start_sector);
            old_start_sector
        }
    };
    // Update the directory entry for this stream.
    minialloc.with_dir_entry_mut(stream_id, |dir_entry| {
        dir_entry.start_sector = new_start_sector;
        dir_entry.stream_len = new_stream_len;
    })
}

//===========================================================================//