pdfium_render/
utils.rs

1pub(crate) mod pixels {
2
3    const BYTES_PER_GRAYSCALE_PIXEL: usize = 1;
4    const BYTES_PER_THREE_CHANNEL_PIXEL: usize = 3;
5    const BYTES_PER_FOUR_CHANNEL_PIXEL: usize = 4;
6
7    /// Converts the given byte array, containing pixel data encoded as three-channel RGB,
8    /// into pixel data encoded as four-channel RGBA. A new alpha channel is created with full opacity.
9    ///
10    /// This function assumes that the RGB pixel data does not include any additional alignment bytes.
11    /// If the source data includes alignment bytes, then the [aligned_bgr_to_rgba()] function
12    /// should be used instead.
13    #[allow(unused)]
14    pub(crate) fn unaligned_rgb_to_rgba(rgb: &[u8]) -> Vec<u8> {
15        rgb.chunks_exact(BYTES_PER_THREE_CHANNEL_PIXEL)
16            .flat_map(|channels| [channels[0], channels[1], channels[2], 255])
17            .collect::<Vec<_>>()
18    }
19
20    /// Converts the given byte array, containing pixel data encoded as three-channel RGB with
21    /// one or more empty alignment bytes, into pixel data encoded as four-channel RGBA.
22    /// A new alpha channel is created with full opacity.
23    ///
24    /// Alignment bytes are used to ensure that the stride of a bitmap - the length in bytes of
25    /// a single scanline - is always a multiple of four, irrespective of the pixel data format.
26    /// The number of empty alignment bytes to be skipped is determined from the given width
27    /// and stride parameters.
28    ///
29    /// If alignment bytes are not used in the source pixel data, then the [unaligned_rgb_to_rgba()]
30    /// function should be used instead.
31    #[inline]
32    pub(crate) fn aligned_rgb_to_rgba(rgb: &[u8], width: usize, stride: usize) -> Vec<u8> {
33        rgb.chunks_exact(stride)
34            .flat_map(|scanline| {
35                scanline[..width * BYTES_PER_THREE_CHANNEL_PIXEL]
36                    .chunks_exact(BYTES_PER_THREE_CHANNEL_PIXEL)
37            })
38            .flat_map(|channels| [channels[0], channels[1], channels[2], 255])
39            .collect::<Vec<_>>()
40    }
41
42    /// Converts the given byte array, containing pixel data encoded as three-channel BGR,
43    /// into pixel data encoded as four-channel RGBA. A new alpha channel is created with full opacity.
44    ///
45    /// This function assumes that the BGR pixel data does not include any additional alignment bytes.
46    /// If the source data includes alignment bytes, then the [aligned_bgr_to_rgba()] function
47    /// should be used instead.
48    #[inline]
49    pub(crate) fn unaligned_bgr_to_rgba(bgr: &[u8]) -> Vec<u8> {
50        bgr.chunks_exact(BYTES_PER_THREE_CHANNEL_PIXEL)
51            .flat_map(|channels| [channels[2], channels[1], channels[0], 255])
52            .collect::<Vec<_>>()
53    }
54
55    /// Converts the given byte array, containing pixel data encoded as three-channel BGR with
56    /// one or more empty alignment bytes, into pixel data encoded as four-channel RGBA.
57    /// A new alpha channel is created with full opacity.
58    ///
59    /// Alignment bytes are used to ensure that the stride of a bitmap - the length in bytes of
60    /// a single scanline - is always a multiple of four, irrespective of the pixel data format.
61    /// The number of empty alignment bytes to be skipped is determined from the given width
62    /// and stride parameters.
63    ///
64    /// If alignment bytes are not used in the source pixel data, then the [unaligned_bgr_to_rgba()]
65    /// function should be used instead.
66    #[inline]
67    pub(crate) fn aligned_bgr_to_rgba(bgr: &[u8], width: usize, stride: usize) -> Vec<u8> {
68        bgr.chunks_exact(stride)
69            .flat_map(|scanline| {
70                scanline[..width * BYTES_PER_THREE_CHANNEL_PIXEL]
71                    .chunks_exact(BYTES_PER_THREE_CHANNEL_PIXEL)
72            })
73            .flat_map(|channels| [channels[2], channels[1], channels[0], 255])
74            .collect::<Vec<_>>()
75    }
76
77    /// Converts the given byte array, containing pixel data encoded as four-channel BGRA,
78    /// into pixel data encoded as four-channel RGBA.
79    #[inline]
80    pub(crate) fn bgra_to_rgba(bgra: &[u8]) -> Vec<u8> {
81        bgra.chunks_exact(BYTES_PER_FOUR_CHANNEL_PIXEL)
82            .flat_map(|channels| [channels[2], channels[1], channels[0], channels[3]])
83            .collect::<Vec<_>>()
84    }
85
86    /// Converts the given byte array, containing pixel data encoded as three-channel RGB,
87    /// into pixel data encoded as four-channel BGRA. A new alpha channel is created with full opacity.
88    #[inline]
89    pub(crate) fn unaligned_rgb_to_bgra(rgb: &[u8]) -> Vec<u8> {
90        // RGB <-> BGR is an invertible operation where we simply swap bytes 0 and 2.
91        unaligned_bgr_to_rgba(rgb)
92    }
93
94    /// Converts the given byte array, containing pixel data encoded as four-channel RGBA,
95    /// into pixel data encoded as four-channel BGRA.
96    #[inline]
97    pub(crate) fn rgba_to_bgra(rgba: &[u8]) -> Vec<u8> {
98        // RGBA <-> BGRA is an invertible operation where we simply swap bytes 0 and 2.
99        bgra_to_rgba(rgba)
100    }
101
102    /// Converts the given byte array, containing pixel data encoded as three-channel BGR,
103    /// into pixel data encoded as four-channel BGRA. A new alpha channel is created with full opacity.
104    ///
105    /// This function assumes that the BGR pixel data does not include any additional alignment bytes.
106    /// If the source data includes alignment bytes, then the [aligned_bgr_to_rgba()] function
107    /// should be used instead.
108    #[allow(unused)]
109    #[inline]
110    pub(crate) fn unaligned_bgr_to_bgra(bgr: &[u8]) -> Vec<u8> {
111        // Expanding from three-channel to four-channel pixel data by adding an alpha channel
112        // is the same irrespective of the pixel color format.
113        unaligned_rgb_to_rgba(bgr)
114    }
115
116    /// Converts the given byte array, containing pixel data encoded as three-channel BGR with
117    /// one or more empty alignment bytes, into pixel data encoded as four-channel BGRA.
118    /// A new alpha channel is created with full opacity.
119    ///
120    /// Alignment bytes are used to ensure that the stride of a bitmap - the length in bytes of
121    /// a single scanline - is always a multiple of four, irrespective of the pixel data format.
122    /// The number of empty alignment bytes to be skipped is determined from the given width
123    /// and stride parameters.
124    ///
125    /// If alignment bytes are not used in the source pixel data, then the [unaligned_rgb_to_rgba()]
126    /// function should be used instead.
127    #[allow(unused)]
128    #[inline]
129    pub(crate) fn aligned_bgr_to_bgra(bgr: &[u8], width: usize, stride: usize) -> Vec<u8> {
130        // Expanding from three-channel to four-channel pixel data by adding an alpha channel
131        // is the same irrespective of the pixel color format.
132        aligned_rgb_to_rgba(bgr, width, stride)
133    }
134
135    /// Converts the given byte array, containing pixel data encoded as one-channel grayscale
136    /// with one or more empty alignment bytes alignment bytes, into unaligned pixel data.
137    ///
138    /// Alignment bytes are used to ensure that the stride of a bitmap - the length in bytes of
139    /// a single scanline - is always a multiple of four, irrespective of the pixel data format.
140    /// The number of empty alignment bytes to be skipped is determined from the given width
141    /// and stride parameters.
142    #[inline]
143    pub(crate) fn aligned_grayscale_to_unaligned(
144        grayscale: &[u8],
145        width: usize,
146        stride: usize,
147    ) -> Vec<u8> {
148        grayscale
149            .chunks_exact(stride)
150            .flat_map(|scanline| &scanline[..width * BYTES_PER_GRAYSCALE_PIXEL])
151            .copied()
152            .collect::<Vec<_>>()
153    }
154}
155
156pub(crate) mod dates {
157    use chrono::prelude::*;
158    use std::fmt::Display;
159
160    /// Converts a [DateTime] to a formatted PDF date string, as defined in The PDF Reference
161    /// Manual, sixth edition, section 3.8.3, on page 160.
162    #[inline]
163    pub(crate) fn date_time_to_pdf_string<T, O>(date: DateTime<T>) -> String
164    where
165        T: TimeZone<Offset = O>,
166        O: Display,
167    {
168        let date_part = date.format("%Y%m%d%H%M%S");
169
170        let timezone_part = format!("{}'", date.format("%:z"))
171            .replace("+00:00'", "Z00'00'")
172            .replace(':', "'");
173
174        format!("D:{date_part}{timezone_part}")
175    }
176}
177
178pub(crate) mod mem {
179    /// Creates an empty byte buffer of the given length.
180    #[inline]
181    pub(crate) fn create_byte_buffer(length: usize) -> Vec<u8> {
182        create_sized_buffer::<u8>(length)
183    }
184
185    /// Creates an empty buffer of the given type with the given capacity.
186    /// The contents of the buffer will be uninitialized.
187    #[inline]
188    #[allow(clippy::uninit_vec)]
189    pub(crate) fn create_sized_buffer<T>(capacity: usize) -> Vec<T> {
190        let mut buffer = Vec::<T>::with_capacity(capacity);
191
192        unsafe {
193            buffer.set_len(capacity);
194        }
195
196        buffer
197    }
198}
199
200pub(crate) mod utf16le {
201    use utf16string::{LittleEndian, WString};
202
203    /// Converts the given Rust &str into an UTF16-LE encoded byte buffer.
204    #[inline]
205    pub(crate) fn get_pdfium_utf16le_bytes_from_str(str: &str) -> Vec<u8> {
206        let mut bytes = WString::<LittleEndian>::from(str).into_bytes();
207
208        // Pdfium appears to expect C-style null termination. Since we are dealing with
209        // wide (16-bit) characters, we need two bytes of nulls.
210
211        bytes.push(0);
212        bytes.push(0);
213
214        bytes
215    }
216
217    /// Converts the bytes in the given buffer from UTF16-LE to a standard Rust String.
218    #[allow(unused_mut)] // The buffer must be mutable when compiling to WASM.
219    pub(crate) fn get_string_from_pdfium_utf16le_bytes(mut buffer: Vec<u8>) -> Option<String> {
220        #[cfg(target_arch = "wasm32")]
221        {
222            use web_sys::TextDecoder;
223
224            // Attempt to perform the conversion using the browser's native TextDecoder
225            // functionality; if that doesn't work, fall back to using the same WString method
226            // used in non-WASM builds.
227
228            if let Ok(decoder) = TextDecoder::new_with_label("utf-16le") {
229                if let Ok(result) = decoder.decode_with_u8_array(&mut buffer) {
230                    let result = result.trim_end_matches(char::from(0));
231
232                    if !result.is_empty() {
233                        return Some(result.to_owned());
234                    } else {
235                        return None;
236                    }
237                }
238            }
239        }
240
241        if let Ok(string) = WString::<LittleEndian>::from_utf16(buffer) {
242            // Trim any trailing nulls. UTF-16LE strings returned from Pdfium are generally
243            // terminated by two null bytes.
244
245            let result = string.to_utf8().trim_end_matches(char::from(0)).to_owned();
246
247            if !result.is_empty() {
248                Some(result)
249            } else {
250                None
251            }
252        } else {
253            None
254        }
255    }
256}
257
258pub(crate) mod files {
259    use crate::bindgen::{FPDF_FILEACCESS, FPDF_FILEWRITE};
260    use std::io::{Read, Seek, SeekFrom, Write};
261    use std::ops::Deref;
262    use std::os::raw::{c_int, c_uchar, c_ulong, c_void};
263    use std::ptr::null_mut;
264    use std::slice;
265
266    // These functions return wrapped versions of Pdfium's file access structs. They are used
267    // in callback functions to connect Pdfium's file access operations to an underlying
268    // Rust reader or writer.
269
270    // C++ examples such as https://github.com/lydstory/pdfium_example/blob/master/pdfium_rect.cpp
271    // demonstrate that the intention is for the implementor to use C++'s "struct inheritance"
272    // feature to derive their own struct from FPDF_FILEACCESS or FPDF_FILEWRITE that contains
273    // whatever additional custom data they wish.
274
275    // Since Rust does not provide struct inheritance, we define new structs with the same field
276    // layout as Pdfium's PDF_FILEACCESS and PDF_FILEWRITE, adding to each a custom field
277    // that stores the user-provided Rust reader or writer. The callback function invoked by Pdfium
278    // can then access the relevant Rust reader or writer directly in order to fulfil Pdfium's
279    // file access request.
280
281    // The writer will be used immediately and synchronously. It can be dropped as soon as it
282    // is used. The reader, however, can be used repeatedly throughout the lifetime of a document
283    // as Pdfium streams in data from the underlying provider on an as-needed basis. This has two
284    // important ramifications: (a) we must connect the lifetime of the reader to the PdfDocument
285    // we create, so that the reader is not dropped before the document is closed with a call to
286    // FPDF_CloseDocument(); and (b) we must box the reader, so that transferring it into the
287    // PdfDocument will not change its memory location. Breaking either of these two invariants
288    // will result in a segfault.
289
290    /// Returns a wrapped Pdfium `FPDF_FILEACCESS` struct that uses the given reader as an
291    /// input source for Pdfium's file access callback function.
292    ///
293    /// Because Pdfium must know the total content length in advance prior to loading
294    /// any portion of it, the given reader must implement the `Seek` trait as well as
295    /// the `Read` trait.
296    #[cfg_attr(target_arch = "wasm32", allow(dead_code))]
297    // This function is never used when compiling to WASM.
298    pub(crate) fn get_pdfium_file_accessor_from_reader<'a, R: Read + Seek + 'a>(
299        mut reader: R,
300    ) -> Box<FpdfFileAccessExt<'a>> {
301        let content_length = reader.seek(SeekFrom::End(0)).unwrap_or(0) as c_ulong;
302
303        let mut result = Box::new(FpdfFileAccessExt {
304            content_length,
305            get_block: Some(read_block_from_callback),
306            file_access_ptr: null_mut(), // We'll set this value in just a moment.
307            reader: Box::new(reader),
308        });
309
310        // Update the struct with a pointer to its own memory location. This pointer will
311        // be passed to the callback function that Pdfium invokes, allowing that callback to
312        // retrieve this FpdfFileAccessExt struct and, from there, the boxed Rust reader.
313
314        let file_access_ptr: *const FpdfFileAccessExt = result.deref();
315
316        result.as_mut().file_access_ptr = file_access_ptr as *mut FpdfFileAccessExt;
317
318        result
319    }
320
321    trait PdfiumDocumentReader: Read + Seek {
322        // A tiny trait that lets us perform type-erasure on the user-provided Rust reader.
323        // This means FpdfFileAccessExt does not need to carry a generic parameter, which in turn
324        // means that any PdfDocument containing a bound FpdfFileAccessExt does not need to carry
325        // a generic parameter either.
326    }
327
328    impl<R: Read + Seek> PdfiumDocumentReader for R {}
329
330    #[repr(C)]
331    pub(crate) struct FpdfFileAccessExt<'a> {
332        // An extension of Pdfium's FPDF_FILEACCESS struct that adds an extra field to carry the
333        // user-provided Rust reader.
334        content_length: c_ulong,
335        get_block: Option<
336            unsafe extern "C" fn(
337                reader_ptr: *mut FpdfFileAccessExt,
338                position: c_ulong,
339                buf: *mut c_uchar,
340                size: c_ulong,
341            ) -> c_int,
342        >,
343        file_access_ptr: *mut FpdfFileAccessExt<'a>,
344        reader: Box<dyn PdfiumDocumentReader + 'a>, // Type-erased equivalent of <R: Read + Seek>
345    }
346
347    impl<'a> FpdfFileAccessExt<'a> {
348        /// Returns an `FPDF_FILEACCESS` pointer suitable for passing to `FPDF_LoadCustomDocument()`.
349        #[cfg_attr(target_arch = "wasm32", allow(dead_code))]
350        // This function is never used when compiling to WASM.
351        #[cfg_attr(feature = "thread_safe", allow(dead_code))]
352        // This function is never used when compiling with the thread_safe feature enabled.
353        #[inline]
354        pub(crate) fn as_fpdf_file_access_mut_ptr(&mut self) -> &mut FPDF_FILEACCESS {
355            unsafe { &mut *(self as *mut FpdfFileAccessExt as *mut FPDF_FILEACCESS) }
356        }
357    }
358
359    // The callback function invoked by Pdfium.
360    pub(crate) extern "C" fn read_block_from_callback(
361        file_access_ptr: *mut FpdfFileAccessExt,
362        position: c_ulong,
363        buf: *mut c_uchar,
364        size: c_ulong,
365    ) -> c_int {
366        unsafe {
367            let reader = (*file_access_ptr).reader.as_mut();
368
369            #[allow(clippy::unnecessary_cast)]
370            // c_ulong isn't guaranteed to be u64 on all platforms
371            let result = match reader.seek(SeekFrom::Start(position as u64)) {
372                Ok(_) => reader
373                    .read(slice::from_raw_parts_mut(buf, size as usize))
374                    .unwrap_or(0),
375                Err(_) => 0,
376            };
377
378            result as c_int
379        }
380    }
381
382    /// Returns a wrapped Pdfium `FPDF_FILEWRITE` struct that uses the given writer as an
383    /// output source for Pdfium's file writing callback function.
384    pub(crate) fn get_pdfium_file_writer_from_writer<W: Write + 'static>(
385        writer: &mut W,
386    ) -> FpdfFileWriteExt {
387        FpdfFileWriteExt {
388            version: 1,
389            write_block: Some(write_block_from_callback),
390            writer,
391        }
392    }
393
394    trait PdfiumDocumentWriter: Write {
395        // A tiny trait that lets us perform type-erasure on the user-provided Rust writer.
396        // This means FpdfFileWriteExt does not need to carry a generic parameter, which simplifies
397        // callback overloading in the WASM bindings implementation.
398
399        // Additionally, since Pdfium's save operations are synchronous and immediate, we do
400        // not need to take ownership of the user-provided Rust writer; a temporary mutable
401        // reference is sufficient.
402    }
403
404    impl<W: Write> PdfiumDocumentWriter for W {}
405
406    #[repr(C)]
407    pub(crate) struct FpdfFileWriteExt<'a> {
408        // An extension of Pdfium's FPDF_FILEWRITE struct that adds an extra field to carry the
409        // user-provided Rust writer.
410        version: c_int,
411        write_block: Option<
412            unsafe extern "C" fn(
413                file_write_ext_ptr: *mut FpdfFileWriteExt,
414                buf: *const c_void,
415                size: c_ulong,
416            ) -> c_int,
417        >,
418        writer: &'a mut dyn PdfiumDocumentWriter, // Type-erased equivalent of <W: Write>
419    }
420
421    impl<'a> FpdfFileWriteExt<'a> {
422        /// Returns an `FPDF_FILEWRITE` pointer suitable for passing to `FPDF_SaveAsCopy()`
423        /// or `FPDF_SaveWithVersion()`.
424        #[inline]
425        pub(crate) fn as_fpdf_file_write_mut_ptr(&mut self) -> &mut FPDF_FILEWRITE {
426            unsafe { &mut *(self as *mut FpdfFileWriteExt as *mut FPDF_FILEWRITE) }
427        }
428
429        /// Flushes the buffer of the underlying Rust writer.
430        #[inline]
431        pub(crate) fn flush(&mut self) -> std::io::Result<()> {
432            self.writer.flush()
433        }
434    }
435
436    // The callback function invoked by Pdfium.
437    pub(crate) extern "C" fn write_block_from_callback(
438        file_write_ext_ptr: *mut FpdfFileWriteExt,
439        buf: *const c_void,
440        size: c_ulong,
441    ) -> c_int {
442        let result = unsafe {
443            match (*file_write_ext_ptr)
444                .writer
445                .write_all(slice::from_raw_parts(buf as *const u8, size as usize))
446            {
447                Ok(()) => 1,
448                Err(_) => 0,
449            }
450        };
451
452        result
453    }
454}
455
456#[cfg(test)]
457pub(crate) mod test {
458    // Provides a function that binds to the correct Pdfium configuration during unit tests,
459    // depending on selected crate features.
460
461    use crate::pdfium::Pdfium;
462
463    #[inline]
464    #[cfg(feature = "static")]
465    pub(crate) fn test_bind_to_pdfium() -> Pdfium {
466        Pdfium::default()
467    }
468
469    #[inline]
470    #[cfg(not(feature = "static"))]
471    pub(crate) fn test_bind_to_pdfium() -> Pdfium {
472        Pdfium::new(
473            Pdfium::bind_to_library(Pdfium::pdfium_platform_library_name_at_path("./"))
474                .or_else(|_| Pdfium::bind_to_system_library())
475                .unwrap(),
476        )
477    }
478}
479
480#[cfg(test)]
481mod tests {
482    use crate::utils::dates::*;
483    use crate::utils::pixels::*;
484    use crate::utils::utf16le::*;
485    use chrono::prelude::*;
486
487    // Tests of color conversion functions.
488
489    #[test]
490    fn test_unaligned_bgr_to_rgba() {
491        let data: [u8; 15] = [2, 1, 0, 3, 6, 5, 4, 7, 10, 9, 8, 11, 14, 13, 12];
492
493        let result = unaligned_rgb_to_bgra(data.as_slice());
494
495        assert_eq!(
496            result,
497            [0, 1, 2, 255, 5, 6, 3, 255, 10, 7, 4, 255, 11, 8, 9, 255, 12, 13, 14, 255]
498        );
499    }
500
501    #[test]
502    fn test_aligned_bgr_to_rgba() {
503        let data: [u8; 24] = [
504            0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23,
505        ];
506
507        // Interpret the sample data as four-byte scanlines with each line consisting of
508        // one pixel (taking three bytes) followed by one alignment byte.
509
510        let result = aligned_bgr_to_rgba(data.as_slice(), 1, 4);
511
512        assert_eq!(
513            result,
514            [
515                2, 1, 0, 255, 6, 5, 4, 255, 10, 9, 8, 255, 14, 13, 12, 255, 18, 17, 16, 255, 22,
516                21, 20, 255
517            ]
518        );
519
520        // Interpret the data as eight-byte scanlines with each line consisting of two pixels
521        // (each taking three bytes) each followed by one alignment byte.
522
523        let result = aligned_bgr_to_rgba(data.as_slice(), 2, 8);
524
525        assert_eq!(
526            result,
527            [
528                2, 1, 0, 255, 5, 4, 3, 255, 10, 9, 8, 255, 13, 12, 11, 255, 18, 17, 16, 255, 21,
529                20, 19, 255
530            ]
531        );
532
533        // Interpret the data as 12-byte scanlines with each line consisting of three pixels
534        // (each taking three bytes) each followed by one alignment byte.
535
536        let result = aligned_bgr_to_rgba(data.as_slice(), 3, 12);
537
538        assert_eq!(
539            result,
540            [
541                2, 1, 0, 255, 5, 4, 3, 255, 8, 7, 6, 255, 14, 13, 12, 255, 17, 16, 15, 255, 20, 19,
542                18, 255
543            ]
544        );
545
546        // Interpret the data as 12-byte scanlines with each line consisting of four pixels
547        // (each taking three bytes) with no alignment bytes.
548
549        let result = aligned_bgr_to_rgba(data.as_slice(), 4, 12);
550
551        assert_eq!(
552            result,
553            [
554                2, 1, 0, 255, 5, 4, 3, 255, 8, 7, 6, 255, 11, 10, 9, 255, 14, 13, 12, 255, 17, 16,
555                15, 255, 20, 19, 18, 255, 23, 22, 21, 255
556            ]
557        );
558    }
559
560    #[test]
561    fn test_bgra_to_rgba() {
562        let data: [u8; 16] = [2, 1, 0, 3, 6, 5, 4, 7, 10, 9, 8, 11, 14, 13, 12, 15];
563
564        let result = bgra_to_rgba(data.as_slice());
565
566        assert_eq!(
567            result,
568            [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
569        );
570    }
571
572    #[test]
573    fn test_rgb_to_bgra() {
574        let data: [u8; 15] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14];
575
576        let result = unaligned_rgb_to_bgra(data.as_slice());
577
578        assert_eq!(
579            result,
580            [2, 1, 0, 255, 5, 4, 3, 255, 8, 7, 6, 255, 11, 10, 9, 255, 14, 13, 12, 255]
581        );
582    }
583
584    #[test]
585    fn test_rgba_to_bgra() {
586        let data: [u8; 16] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
587
588        let result = rgba_to_bgra(data.as_slice());
589
590        assert_eq!(
591            result,
592            [2, 1, 0, 3, 6, 5, 4, 7, 10, 9, 8, 11, 14, 13, 12, 15]
593        );
594    }
595
596    #[test]
597    fn test_aligned_grayscale_to_unaligned() {
598        let data: [u8; 16] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
599
600        let result = aligned_grayscale_to_unaligned(data.as_slice(), 1, 4);
601
602        assert_eq!(result, [0, 4, 8, 12]);
603    }
604
605    // Tests of date time conversion functions.
606
607    #[test]
608    fn test_date_time_to_pdf_date_string() {
609        assert_eq!(
610            date_time_to_pdf_string(Utc.with_ymd_and_hms(1998, 12, 23, 19, 52, 00).unwrap()),
611            "D:19981223195200Z00'00'"
612        );
613
614        assert_eq!(
615            date_time_to_pdf_string(
616                FixedOffset::west_opt(8 * 3600)
617                    .unwrap()
618                    .from_local_datetime(
619                        &NaiveDate::from_ymd_opt(1998, 12, 23)
620                            .unwrap()
621                            .and_hms_opt(19, 52, 00)
622                            .unwrap()
623                    )
624                    .unwrap()
625            ),
626            "D:19981223195200-08'00'"
627        )
628    }
629
630    #[test]
631    fn test_valid_utf16le_from_emoji() {
632        let emoji = "💁👵🧕";
633
634        assert_eq!(
635            get_string_from_pdfium_utf16le_bytes(get_pdfium_utf16le_bytes_from_str(emoji)).unwrap(),
636            emoji
637        );
638    }
639}