Coverage Report

Created: 2026-10-31 06:48

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/image-png/src/text_metadata.rs
Line
Count
Source
1
//! # Text chunks (tEXt/zTXt/iTXt) structs and functions
2
//!
3
//! The [PNG spec](https://www.w3.org/TR/2003/REC-PNG-20031110/#11textinfo) optionally allows for
4
//! embedded text chunks in the file. They may appear either before or after the image data
5
//! chunks. There are three kinds of text chunks.
6
//!  -   `tEXt`: This has a `keyword` and `text` field, and is ISO 8859-1 encoded.
7
//!  -   `zTXt`: This is semantically the same as `tEXt`, i.e. it has the same fields and
8
//!      encoding, but the `text` field is compressed before being written into the PNG file.
9
//!  -   `iTXt`: This chunk allows for its `text` field to be any valid UTF-8, and supports
10
//!      compression of the text field as well.
11
//!
12
//!  The `ISO 8859-1` encoding technically doesn't allow any control characters
13
//!  to be used, but in practice these values are encountered anyway. This can
14
//!  either be the extended `ISO-8859-1` encoding with control characters or the
15
//!  `Windows-1252` encoding. This crate assumes the `ISO-8859-1` encoding is
16
//!  used.
17
//!
18
//!  ## Reading text chunks
19
//!
20
//!  As a PNG is decoded, any text chunk encountered is appended the
21
//!  [`Info`](`crate::common::Info`) struct, in the `uncompressed_latin1_text`,
22
//!  `compressed_latin1_text`, and the `utf8_text` fields depending on whether the encountered
23
//!  chunk is `tEXt`, `zTXt`, or `iTXt`.
24
//!
25
//!  ```
26
//!  use std::fs::File;
27
//!  use std::io::BufReader;
28
//!  use std::path::PathBuf;
29
//!
30
//!  // Opening a png file that has a zTXt chunk
31
//!  let decoder = png::Decoder::new(
32
//!      BufReader::new(File::open("tests/text_chunk_examples/ztxt_example.png").unwrap())
33
//!  );
34
//!  let mut reader = decoder.read_info().unwrap();
35
//!  // If the text chunk is before the image data frames, `reader.info()` already contains the text.
36
//!  for text_chunk in &reader.info().compressed_latin1_text {
37
//!      println!("{:?}", text_chunk.keyword); // Prints the keyword
38
//!      println!("{:#?}", text_chunk); // Prints out the text chunk.
39
//!      // To get the uncompressed text, use the `get_text` method.
40
//!      println!("{}", text_chunk.get_text().unwrap());
41
//!  }
42
//!  ```
43
//!
44
//!  ## Writing text chunks
45
//!
46
//!  There are two ways to write text chunks: the first is to add the appropriate text structs directly to the encoder header before the header is written to file.
47
//!  To add a text chunk at any point in the stream, use the `write_text_chunk` method.
48
//!
49
//!  ```
50
//!  # use png::text_metadata::{ITXtChunk, ZTXtChunk};
51
//!  # use std::env;
52
//!  # use std::fs::File;
53
//!  # use std::io::BufWriter;
54
//!  # use std::path::PathBuf;
55
//!  # let file = File::create(PathBuf::from_iter(["target", "text_chunk.png"])).unwrap();
56
//!  # let ref mut w = BufWriter::new(file);
57
//!  let mut encoder = png::Encoder::new(w, 2, 1); // Width is 2 pixels and height is 1.
58
//!  encoder.set_color(png::ColorType::Rgba);
59
//!  encoder.set_depth(png::BitDepth::Eight);
60
//!  // Adding text chunks to the header
61
//!  encoder
62
//!     .add_text_chunk(
63
//!         "Testing tEXt".to_string(),
64
//!         "This is a tEXt chunk that will appear before the IDAT chunks.".to_string(),
65
//!     )
66
//!     .unwrap();
67
//!  encoder
68
//!      .add_ztxt_chunk(
69
//!          "Testing zTXt".to_string(),
70
//!          "This is a zTXt chunk that is compressed in the png file.".to_string(),
71
//!      )
72
//!      .unwrap();
73
//!  encoder
74
//!      .add_itxt_chunk(
75
//!          "Testing iTXt".to_string(),
76
//!          "iTXt chunks support all of UTF8. Example: हिंदी.".to_string(),
77
//!      )
78
//!      .unwrap();
79
//!
80
//!  let mut writer = encoder.write_header().unwrap();
81
//!
82
//!  let data = [255, 0, 0, 255, 0, 0, 0, 255]; // An array containing a RGBA sequence. First pixel is red and second pixel is black.
83
//!  writer.write_image_data(&data).unwrap(); // Save
84
//!
85
//!  // We can add a tEXt/zTXt/iTXt at any point before the encoder is dropped from scope. These chunks will be at the end of the png file.
86
//!  let tail_ztxt_chunk = ZTXtChunk::new("Comment".to_string(), "A zTXt chunk after the image data.".to_string());
87
//!  writer.write_text_chunk(&tail_ztxt_chunk).unwrap();
88
//!
89
//!  // The fields of the text chunk are public, so they can be mutated before being written to the file.
90
//!  let mut tail_itxt_chunk = ITXtChunk::new("Author".to_string(), "सायंतन खान".to_string());
91
//!  tail_itxt_chunk.compressed = true;
92
//!  tail_itxt_chunk.language_tag = "hi".to_string();
93
//!  tail_itxt_chunk.translated_keyword = "लेखक".to_string();
94
//!  writer.write_text_chunk(&tail_itxt_chunk).unwrap();
95
//!  ```
96
97
#![warn(missing_docs)]
98
99
use crate::{chunk, encoder, DecodingError, EncodingError};
100
use fdeflate::BoundedDecompressionError;
101
use flate2::write::ZlibEncoder;
102
use flate2::Compression;
103
use std::io::Write;
104
105
/// Default decompression limit for compressed text chunks.
106
pub const DECOMPRESSION_LIMIT: usize = 2097152; // 2 MiB
107
108
/// Text encoding errors that is wrapped by the standard EncodingError type
109
#[derive(Debug, Clone, Copy)]
110
pub(crate) enum TextEncodingError {
111
    /// Unrepresentable characters in string
112
    Unrepresentable,
113
    /// Keyword longer than 79 bytes or empty
114
    InvalidKeywordSize,
115
    /// Error encountered while compressing text
116
    CompressionError,
117
}
118
119
/// Text decoding error that is wrapped by the standard DecodingError type
120
#[derive(Debug, Clone, Copy)]
121
pub(crate) enum TextDecodingError {
122
    /// Unrepresentable characters in string
123
    Unrepresentable,
124
    /// Keyword longer than 79 bytes or empty
125
    InvalidKeywordSize,
126
    /// Missing null separator
127
    MissingNullSeparator,
128
    /// Compressed text cannot be uncompressed
129
    InflationError,
130
    /// Needs more space to decompress
131
    OutOfDecompressionSpace,
132
    /// Using an unspecified value for the compression method
133
    InvalidCompressionMethod,
134
    /// Using a byte that is not 0 or 255 as compression flag in iTXt chunk
135
    InvalidCompressionFlag,
136
    /// Missing the compression flag
137
    MissingCompressionFlag,
138
}
139
140
/// A generalized text chunk trait
141
pub trait EncodableTextChunk {
142
    /// Encode text chunk as `Vec<u8>` to a `Write`
143
    fn encode<W: Write>(&self, w: &mut W) -> Result<(), EncodingError>;
144
}
145
146
/// Struct representing a tEXt chunk
147
#[derive(Clone, Debug, PartialEq, Eq)]
148
pub struct TEXtChunk {
149
    /// Keyword field of the tEXt chunk. Needs to be between 1-79 bytes when encoded as Latin-1.
150
    pub keyword: String,
151
    /// Text field of tEXt chunk. Can be at most 2GB.
152
    pub text: String,
153
}
154
155
432k
pub(crate) fn decode_iso_8859_1(text: &[u8]) -> String {
156
4.01M
    text.iter().map(|&b| b as char).collect()
157
432k
}
158
159
0
pub(crate) fn encode_iso_8859_1(text: &str) -> Result<Vec<u8>, TextEncodingError> {
160
0
    encode_iso_8859_1_iter(text).collect()
161
0
}
162
163
0
fn encode_iso_8859_1_into(buf: &mut Vec<u8>, text: &str) -> Result<(), TextEncodingError> {
164
0
    for b in encode_iso_8859_1_iter(text) {
165
0
        buf.push(b?);
166
    }
167
0
    Ok(())
168
0
}
169
170
0
fn encode_iso_8859_1_iter(text: &str) -> impl Iterator<Item = Result<u8, TextEncodingError>> + '_ {
171
0
    text.chars()
172
0
        .map(|c| u8::try_from(c as u32).map_err(|_| TextEncodingError::Unrepresentable))
173
0
}
174
175
151k
fn decode_ascii(text: &[u8]) -> Result<&str, TextDecodingError> {
176
151k
    if text.is_ascii() {
177
        // `from_utf8` cannot panic because we're already checked that `text` is ASCII-7.
178
        // And this is the only safe way to get ASCII-7 string from `&[u8]`.
179
149k
        Ok(std::str::from_utf8(text).expect("unreachable"))
180
    } else {
181
1.42k
        Err(TextDecodingError::Unrepresentable)
182
    }
183
151k
}
184
185
impl TEXtChunk {
186
    /// Constructs a new TEXtChunk.
187
    /// Not sure whether it should take &str or String.
188
    pub fn new(keyword: impl Into<String>, text: impl Into<String>) -> Self {
189
        Self {
190
            keyword: keyword.into(),
191
            text: text.into(),
192
        }
193
    }
194
195
    /// Decodes a slice of bytes to a String using Latin-1 decoding.
196
    /// The decoder runs in strict mode, and any decoding errors are passed along to the caller.
197
112k
    pub(crate) fn decode(
198
112k
        keyword_slice: &[u8],
199
112k
        text_slice: &[u8],
200
112k
    ) -> Result<Self, TextDecodingError> {
201
112k
        if keyword_slice.is_empty() || keyword_slice.len() > 79 {
202
0
            return Err(TextDecodingError::InvalidKeywordSize);
203
112k
        }
204
205
112k
        Ok(Self {
206
112k
            keyword: decode_iso_8859_1(keyword_slice),
207
112k
            text: decode_iso_8859_1(text_slice),
208
112k
        })
209
112k
    }
210
}
211
212
impl EncodableTextChunk for TEXtChunk {
213
    /// Encodes TEXtChunk to a Writer. The keyword and text are separated by a byte of zeroes.
214
0
    fn encode<W: Write>(&self, w: &mut W) -> Result<(), EncodingError> {
215
0
        let mut data = encode_iso_8859_1(&self.keyword)?;
216
217
0
        if data.is_empty() || data.len() > 79 {
218
0
            return Err(TextEncodingError::InvalidKeywordSize.into());
219
0
        }
220
221
0
        data.push(0);
222
223
0
        encode_iso_8859_1_into(&mut data, &self.text)?;
224
225
0
        encoder::write_chunk(w, chunk::tEXt, &data)
226
0
    }
227
}
228
229
/// Struct representing a zTXt chunk
230
#[derive(Clone, Debug, PartialEq, Eq)]
231
pub struct ZTXtChunk {
232
    /// Keyword field of the tEXt chunk. Needs to be between 1-79 bytes when encoded as Latin-1.
233
    pub keyword: String,
234
    /// Text field of zTXt chunk. It is compressed by default, but can be uncompressed if necessary.
235
    text: OptCompressed,
236
}
237
238
/// Private enum encoding the compressed and uncompressed states of zTXt/iTXt text field.
239
#[derive(Clone, Debug, PartialEq, Eq)]
240
enum OptCompressed {
241
    /// Compressed version of text field. Can be at most 2GB.
242
    Compressed(Vec<u8>),
243
    /// Uncompressed text field.
244
    Uncompressed(String),
245
}
246
247
impl ZTXtChunk {
248
    /// Creates a new ZTXt chunk.
249
    pub fn new(keyword: impl Into<String>, text: impl Into<String>) -> Self {
250
        Self {
251
            keyword: keyword.into(),
252
            text: OptCompressed::Uncompressed(text.into()),
253
        }
254
    }
255
256
54.6k
    pub(crate) fn decode(
257
54.6k
        keyword_slice: &[u8],
258
54.6k
        compression_method: u8,
259
54.6k
        text_slice: &[u8],
260
54.6k
    ) -> Result<Self, TextDecodingError> {
261
54.6k
        if keyword_slice.is_empty() || keyword_slice.len() > 79 {
262
0
            return Err(TextDecodingError::InvalidKeywordSize);
263
54.6k
        }
264
265
54.6k
        if compression_method != 0 {
266
594
            return Err(TextDecodingError::InvalidCompressionMethod);
267
54.0k
        }
268
269
54.0k
        Ok(Self {
270
54.0k
            keyword: decode_iso_8859_1(keyword_slice),
271
54.0k
            text: OptCompressed::Compressed(text_slice.to_vec()),
272
54.0k
        })
273
54.6k
    }
274
275
    /// Decompresses the inner text, mutating its own state. Can only handle decompressed text up to `DECOMPRESSION_LIMIT` bytes.
276
0
    pub fn decompress_text(&mut self) -> Result<(), DecodingError> {
277
0
        self.decompress_text_with_limit(DECOMPRESSION_LIMIT)
278
0
    }
279
280
    /// Decompresses the inner text, mutating its own state. Can only handle decompressed text up to `limit` bytes.
281
0
    pub fn decompress_text_with_limit(&mut self, limit: usize) -> Result<(), DecodingError> {
282
0
        match &self.text {
283
0
            OptCompressed::Compressed(v) => {
284
0
                let uncompressed_raw = match fdeflate::decompress_to_vec_bounded(&v[..], limit) {
285
0
                    Ok(s) => s,
286
                    Err(BoundedDecompressionError::OutputTooLarge { .. }) => {
287
0
                        return Err(DecodingError::from(
288
0
                            TextDecodingError::OutOfDecompressionSpace,
289
0
                        ));
290
                    }
291
                    Err(_) => {
292
0
                        return Err(DecodingError::from(TextDecodingError::InflationError));
293
                    }
294
                };
295
0
                self.text = OptCompressed::Uncompressed(decode_iso_8859_1(&uncompressed_raw));
296
            }
297
0
            OptCompressed::Uncompressed(_) => {}
298
        };
299
0
        Ok(())
300
0
    }
301
302
    /// Decompresses the inner text, and returns it as a `String`.
303
    /// If decompression uses more the 2MiB, first call decompress with limit, and then this method.
304
0
    pub fn get_text(&self) -> Result<String, DecodingError> {
305
0
        match &self.text {
306
0
            OptCompressed::Compressed(v) => {
307
0
                let uncompressed_raw = fdeflate::decompress_to_vec(v)
308
0
                    .map_err(|_| DecodingError::from(TextDecodingError::InflationError))?;
309
0
                Ok(decode_iso_8859_1(&uncompressed_raw))
310
            }
311
0
            OptCompressed::Uncompressed(s) => Ok(s.clone()),
312
        }
313
0
    }
314
315
    /// Compresses the inner text, mutating its own state.
316
0
    pub fn compress_text(&mut self) -> Result<(), EncodingError> {
317
0
        match &self.text {
318
0
            OptCompressed::Uncompressed(s) => {
319
0
                let uncompressed_raw = encode_iso_8859_1(s)?;
320
0
                let mut encoder = ZlibEncoder::new(Vec::new(), Compression::fast());
321
0
                encoder
322
0
                    .write_all(&uncompressed_raw)
323
0
                    .map_err(|_| EncodingError::from(TextEncodingError::CompressionError))?;
324
0
                self.text = OptCompressed::Compressed(
325
0
                    encoder
326
0
                        .finish()
327
0
                        .map_err(|_| EncodingError::from(TextEncodingError::CompressionError))?,
328
                );
329
            }
330
0
            OptCompressed::Compressed(_) => {}
331
        }
332
333
0
        Ok(())
334
0
    }
335
}
336
337
impl EncodableTextChunk for ZTXtChunk {
338
0
    fn encode<W: Write>(&self, w: &mut W) -> Result<(), EncodingError> {
339
0
        let mut data = encode_iso_8859_1(&self.keyword)?;
340
341
0
        if data.is_empty() || data.len() > 79 {
342
0
            return Err(TextEncodingError::InvalidKeywordSize.into());
343
0
        }
344
345
        // Null separator
346
0
        data.push(0);
347
348
        // Compression method: the only valid value is 0, as of 2021.
349
0
        data.push(0);
350
351
0
        match &self.text {
352
0
            OptCompressed::Compressed(v) => {
353
0
                data.extend_from_slice(&v[..]);
354
0
            }
355
0
            OptCompressed::Uncompressed(s) => {
356
                // This code may have a bug. Check for correctness.
357
0
                let uncompressed_raw = encode_iso_8859_1(s)?;
358
0
                let mut encoder = ZlibEncoder::new(data, Compression::fast());
359
0
                encoder
360
0
                    .write_all(&uncompressed_raw)
361
0
                    .map_err(|_| EncodingError::from(TextEncodingError::CompressionError))?;
362
0
                data = encoder
363
0
                    .finish()
364
0
                    .map_err(|_| EncodingError::from(TextEncodingError::CompressionError))?;
365
            }
366
        };
367
368
0
        encoder::write_chunk(w, chunk::zTXt, &data)
369
0
    }
370
}
371
372
/// Struct encoding an iTXt chunk
373
#[derive(Clone, Debug, PartialEq, Eq)]
374
pub struct ITXtChunk {
375
    /// The keyword field. This needs to be between 1-79 bytes when encoded as Latin-1.
376
    pub keyword: String,
377
    /// Indicates whether the text will be (or was) compressed in the PNG.
378
    pub compressed: bool,
379
    /// A hyphen separated list of languages that the keyword is translated to. This is ASCII-7 encoded.
380
    pub language_tag: String,
381
    /// Translated keyword. This is UTF-8 encoded.
382
    pub translated_keyword: String,
383
    /// Text field of iTXt chunk. It is compressed by default, but can be uncompressed if necessary.
384
    text: OptCompressed,
385
}
386
387
impl ITXtChunk {
388
    /// Constructs a new iTXt chunk. Leaves all but keyword and text to default values.
389
    pub fn new(keyword: impl Into<String>, text: impl Into<String>) -> Self {
390
        Self {
391
            keyword: keyword.into(),
392
            compressed: false,
393
            language_tag: "".to_string(),
394
            translated_keyword: "".to_string(),
395
            text: OptCompressed::Uncompressed(text.into()),
396
        }
397
    }
398
399
152k
    pub(crate) fn decode(
400
152k
        keyword_slice: &[u8],
401
152k
        compression_flag: u8,
402
152k
        compression_method: u8,
403
152k
        language_tag_slice: &[u8],
404
152k
        translated_keyword_slice: &[u8],
405
152k
        text_slice: &[u8],
406
152k
    ) -> Result<Self, TextDecodingError> {
407
152k
        if keyword_slice.is_empty() || keyword_slice.len() > 79 {
408
0
            return Err(TextDecodingError::InvalidKeywordSize);
409
152k
        }
410
152k
        let keyword = decode_iso_8859_1(keyword_slice);
411
412
152k
        let compressed = match compression_flag {
413
140k
            0 => false,
414
11.1k
            1 => true,
415
946
            _ => return Err(TextDecodingError::InvalidCompressionFlag),
416
        };
417
418
151k
        if compressed && compression_method != 0 {
419
471
            return Err(TextDecodingError::InvalidCompressionMethod);
420
151k
        }
421
422
151k
        let language_tag = decode_ascii(language_tag_slice)?.to_owned();
423
424
149k
        let translated_keyword = std::str::from_utf8(translated_keyword_slice)
425
149k
            .map_err(|_| TextDecodingError::Unrepresentable)?
426
149k
            .to_string();
427
149k
        let text = if compressed {
428
10.4k
            OptCompressed::Compressed(text_slice.to_vec())
429
        } else {
430
            OptCompressed::Uncompressed(
431
138k
                String::from_utf8(text_slice.to_vec())
432
138k
                    .map_err(|_| TextDecodingError::Unrepresentable)?,
433
            )
434
        };
435
436
146k
        Ok(Self {
437
146k
            keyword,
438
146k
            compressed,
439
146k
            language_tag,
440
146k
            translated_keyword,
441
146k
            text,
442
146k
        })
443
152k
    }
444
445
    /// Decompresses the inner text, mutating its own state. Can only handle decompressed text up to `DECOMPRESSION_LIMIT` bytes.
446
0
    pub fn decompress_text(&mut self) -> Result<(), DecodingError> {
447
0
        self.decompress_text_with_limit(DECOMPRESSION_LIMIT)
448
0
    }
449
450
    /// Decompresses the inner text, mutating its own state. Can only handle decompressed text up to `limit` bytes.
451
0
    pub fn decompress_text_with_limit(&mut self, limit: usize) -> Result<(), DecodingError> {
452
0
        match &self.text {
453
0
            OptCompressed::Compressed(v) => {
454
0
                let uncompressed_raw = match fdeflate::decompress_to_vec_bounded(v, limit) {
455
0
                    Ok(s) => s,
456
                    Err(BoundedDecompressionError::OutputTooLarge { .. }) => {
457
0
                        return Err(DecodingError::from(
458
0
                            TextDecodingError::OutOfDecompressionSpace,
459
0
                        ));
460
                    }
461
                    Err(_) => {
462
0
                        return Err(DecodingError::from(TextDecodingError::InflationError));
463
                    }
464
                };
465
0
                self.text = OptCompressed::Uncompressed(
466
0
                    String::from_utf8(uncompressed_raw)
467
0
                        .map_err(|_| TextDecodingError::Unrepresentable)?,
468
                );
469
            }
470
0
            OptCompressed::Uncompressed(_) => {}
471
        };
472
0
        Ok(())
473
0
    }
474
475
    /// Decompresses the inner text, and returns it as a `String`.
476
    /// If decompression takes more than 2 MiB, try `decompress_text_with_limit` followed by this method.
477
0
    pub fn get_text(&self) -> Result<String, DecodingError> {
478
0
        match &self.text {
479
0
            OptCompressed::Compressed(v) => {
480
0
                let uncompressed_raw = fdeflate::decompress_to_vec(v)
481
0
                    .map_err(|_| DecodingError::from(TextDecodingError::InflationError))?;
482
0
                String::from_utf8(uncompressed_raw)
483
0
                    .map_err(|_| TextDecodingError::Unrepresentable.into())
484
            }
485
0
            OptCompressed::Uncompressed(s) => Ok(s.clone()),
486
        }
487
0
    }
488
489
    /// Compresses the inner text, mutating its own state.
490
0
    pub fn compress_text(&mut self) -> Result<(), EncodingError> {
491
0
        match &self.text {
492
0
            OptCompressed::Uncompressed(s) => {
493
0
                let uncompressed_raw = s.as_bytes();
494
0
                let mut encoder = ZlibEncoder::new(Vec::new(), Compression::fast());
495
0
                encoder
496
0
                    .write_all(uncompressed_raw)
497
0
                    .map_err(|_| EncodingError::from(TextEncodingError::CompressionError))?;
498
0
                self.text = OptCompressed::Compressed(
499
0
                    encoder
500
0
                        .finish()
501
0
                        .map_err(|_| EncodingError::from(TextEncodingError::CompressionError))?,
502
                );
503
            }
504
0
            OptCompressed::Compressed(_) => {}
505
        }
506
507
0
        Ok(())
508
0
    }
509
}
510
511
impl EncodableTextChunk for ITXtChunk {
512
0
    fn encode<W: Write>(&self, w: &mut W) -> Result<(), EncodingError> {
513
        // Keyword
514
0
        let mut data = encode_iso_8859_1(&self.keyword)?;
515
516
0
        if data.is_empty() || data.len() > 79 {
517
0
            return Err(TextEncodingError::InvalidKeywordSize.into());
518
0
        }
519
520
        // Null separator
521
0
        data.push(0);
522
523
        // Compression flag
524
0
        if self.compressed {
525
0
            data.push(1);
526
0
        } else {
527
0
            data.push(0);
528
0
        }
529
530
        // Compression method
531
0
        data.push(0);
532
533
        // Language tag
534
0
        if !self.language_tag.is_ascii() {
535
0
            return Err(EncodingError::from(TextEncodingError::Unrepresentable));
536
0
        }
537
0
        data.extend(self.language_tag.as_bytes());
538
539
        // Null separator
540
0
        data.push(0);
541
542
        // Translated keyword
543
0
        data.extend_from_slice(self.translated_keyword.as_bytes());
544
545
        // Null separator
546
0
        data.push(0);
547
548
        // Text
549
0
        if self.compressed {
550
0
            match &self.text {
551
0
                OptCompressed::Compressed(v) => {
552
0
                    data.extend_from_slice(&v[..]);
553
0
                }
554
0
                OptCompressed::Uncompressed(s) => {
555
0
                    let uncompressed_raw = s.as_bytes();
556
0
                    let mut encoder = ZlibEncoder::new(data, Compression::fast());
557
0
                    encoder
558
0
                        .write_all(uncompressed_raw)
559
0
                        .map_err(|_| EncodingError::from(TextEncodingError::CompressionError))?;
560
0
                    data = encoder
561
0
                        .finish()
562
0
                        .map_err(|_| EncodingError::from(TextEncodingError::CompressionError))?;
563
                }
564
            }
565
        } else {
566
0
            match &self.text {
567
0
                OptCompressed::Compressed(v) => {
568
0
                    let uncompressed_raw = fdeflate::decompress_to_vec(v)
569
0
                        .map_err(|_| EncodingError::from(TextEncodingError::CompressionError))?;
570
0
                    data.extend_from_slice(&uncompressed_raw[..]);
571
                }
572
0
                OptCompressed::Uncompressed(s) => {
573
0
                    data.extend_from_slice(s.as_bytes());
574
0
                }
575
            }
576
        }
577
578
0
        encoder::write_chunk(w, chunk::iTXt, &data)
579
0
    }
580
}