Skip to main content

pdf_lib_rs/core/objects/
pdf_stream.rs

1use std::fmt;
2use crate::core::syntax::CharCodes;
3use super::pdf_dict::PdfDict;
4use super::pdf_name::PdfName;
5use super::pdf_number::PdfNumber;
6use super::pdf_object::{PdfObject, PdfObjectTrait};
7
8/// Base trait for PDF stream objects.
9/// A stream consists of a dictionary followed by binary content.
10#[allow(dead_code)]
11pub trait PdfStreamTrait: PdfObjectTrait {
12    fn dict(&self) -> &PdfDict;
13    fn dict_mut(&mut self) -> &mut PdfDict;
14    fn get_contents(&self) -> &[u8];
15    fn get_contents_size(&self) -> usize {
16        self.get_contents().len()
17    }
18
19    /// Update the /Length entry in the stream dictionary.
20    fn update_dict(&mut self) {
21        let size = self.get_contents_size();
22        self.dict_mut().set(
23            PdfName::length(),
24            PdfObject::Number(PdfNumber::of(size as f64)),
25        );
26    }
27}
28
29/// Placeholder for PdfStream in the object hierarchy.
30/// Concrete implementations use PdfRawStream.
31#[derive(Debug, Clone)]
32pub struct PdfStream {
33    pub dict: PdfDict,
34}
35
36impl PdfStream {
37    pub fn new(dict: PdfDict) -> Self {
38        PdfStream { dict }
39    }
40}
41
42impl PartialEq for PdfStream {
43    fn eq(&self, _other: &Self) -> bool {
44        false
45    }
46}
47
48impl fmt::Display for PdfStream {
49    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
50        write!(f, "{}\nstream\n...data...\nendstream", self.dict)
51    }
52}
53
54impl PdfObjectTrait for PdfStream {
55    fn size_in_bytes(&self) -> usize {
56        self.dict.size_in_bytes() + 18 // dict + \nstream\n...\nendstream
57    }
58
59    fn copy_bytes_into(&self, buffer: &mut [u8], offset: usize) -> usize {
60        let initial_offset = offset;
61        let mut off = offset;
62        off += self.dict.copy_bytes_into(buffer, off);
63        buffer[off] = CharCodes::Newline;
64        off += 1;
65        for &b in b"stream\n" {
66            buffer[off] = b;
67            off += 1;
68        }
69        for &b in b"\nendstream" {
70            buffer[off] = b;
71            off += 1;
72        }
73        off - initial_offset
74    }
75}