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::slice;
264
265 // These functions return wrapped versions of Pdfium's file access structs. They are used
266 // in callback functions to connect Pdfium's file access operations to an underlying
267 // Rust reader or writer.
268
269 // C++ examples such as https://github.com/lydstory/pdfium_example/blob/master/pdfium_rect.cpp
270 // demonstrate that the intention is for the implementor to use C++'s "struct inheritance"
271 // feature to derive their own struct from FPDF_FILEACCESS or FPDF_FILEWRITE that contains
272 // whatever additional custom data they wish.
273
274 // Since Rust does not provide struct inheritance, we define new structs with the same field
275 // layout as Pdfium's PDF_FILEACCESS and PDF_FILEWRITE, adding to each a custom field
276 // that stores the user-provided Rust reader or writer. The callback function invoked by Pdfium
277 // can then access the relevant Rust reader or writer directly in order to fulfil Pdfium's
278 // file access request.
279
280 // The writer will be used immediately and synchronously. It can be dropped as soon as it
281 // is used. The reader, however, can be used repeatedly throughout the lifetime of a document
282 // as Pdfium streams in data from the underlying provider on an as-needed basis. This has two
283 // important ramifications: (a) we must connect the lifetime of the reader to the PdfDocument
284 // we create, so that the reader is not dropped before the document is closed with a call to
285 // FPDF_CloseDocument(); and (b) we must box the reader, so that transferring it into the
286 // PdfDocument will not change its memory location. Breaking either of these two invariants
287 // will result in a segfault.
288
289 /// Returns a wrapped Pdfium `FPDF_FILEACCESS` struct that uses the given reader as an
290 /// input source for Pdfium's file access callback function.
291 ///
292 /// Because Pdfium must know the total content length in advance prior to loading
293 /// any portion of it, the given reader must implement the `Seek` trait as well as
294 /// the `Read` trait.
295 #[cfg_attr(target_arch = "wasm32", allow(dead_code))]
296 // This function is never used when compiling to WASM.
297 pub(crate) fn get_pdfium_file_accessor_from_reader<'a, R: Read + Seek + 'a>(
298 mut reader: R,
299 ) -> Box<FpdfFileAccessExt<'a>> {
300 let content_length = reader.seek(SeekFrom::End(0)).unwrap_or(0) as c_ulong;
301
302 let mut result = Box::new(FpdfFileAccessExt {
303 content_length,
304 get_block: Some(read_block_from_callback),
305 file_access_ptr: std::ptr::null_mut(), // We'll set this value in just a moment.
306 reader: Box::new(reader),
307 });
308
309 // Update the struct with a pointer to its own memory location. This pointer will
310 // be passed to the callback function that Pdfium invokes, allowing that callback to
311 // retrieve this FpdfFileAccessExt struct and, from there, the boxed Rust reader.
312
313 let file_access_ptr: *const FpdfFileAccessExt = result.deref();
314
315 result.as_mut().file_access_ptr = file_access_ptr as *mut FpdfFileAccessExt;
316
317 result
318 }
319
320 trait PdfiumDocumentReader: Read + Seek {
321 // A tiny trait that lets us perform type-erasure on the user-provided Rust reader.
322 // This means FpdfFileAccessExt does not need to carry a generic parameter, which in turn
323 // means that any PdfDocument containing a bound FpdfFileAccessExt does not need to carry
324 // a generic parameter either.
325 }
326
327 impl<R: Read + Seek> PdfiumDocumentReader for R {}
328
329 #[repr(C)]
330 pub(crate) struct FpdfFileAccessExt<'a> {
331 // An extension of Pdfium's FPDF_FILEACCESS struct that adds an extra field to carry the
332 // user-provided Rust reader.
333 content_length: c_ulong,
334 get_block: Option<
335 unsafe extern "C" fn(
336 reader_ptr: *mut FpdfFileAccessExt,
337 position: c_ulong,
338 buf: *mut c_uchar,
339 size: c_ulong,
340 ) -> c_int,
341 >,
342 file_access_ptr: *mut FpdfFileAccessExt<'a>,
343 reader: Box<dyn PdfiumDocumentReader + 'a>, // Type-erased equivalent of <R: Read + Seek>
344 }
345
346 impl<'a> FpdfFileAccessExt<'a> {
347 /// Returns an `FPDF_FILEACCESS` pointer suitable for passing to `FPDF_LoadCustomDocument()`.
348 #[cfg_attr(target_arch = "wasm32", allow(dead_code))]
349 // This function is never used when compiling to WASM.
350 #[cfg_attr(feature = "thread_safe", allow(dead_code))]
351 // This function is never used when compiling with the thread_safe feature enabled.
352 #[inline]
353 pub(crate) fn as_fpdf_file_access_mut_ptr(&mut self) -> &mut FPDF_FILEACCESS {
354 unsafe { &mut *(self as *mut FpdfFileAccessExt as *mut FPDF_FILEACCESS) }
355 }
356 }
357
358 // The callback function invoked by Pdfium.
359 pub(crate) extern "C" fn read_block_from_callback(
360 file_access_ptr: *mut FpdfFileAccessExt,
361 position: c_ulong,
362 buf: *mut c_uchar,
363 size: c_ulong,
364 ) -> c_int {
365 unsafe {
366 let reader = (*file_access_ptr).reader.as_mut();
367
368 #[allow(clippy::unnecessary_cast)]
369 // c_ulong isn't guaranteed to be u64 on all platforms
370 let result = match reader.seek(SeekFrom::Start(position as u64)) {
371 Ok(_) => reader
372 .read(slice::from_raw_parts_mut(buf, size as usize))
373 .unwrap_or(0),
374 Err(_) => 0,
375 };
376
377 result as c_int
378 }
379 }
380
381 /// Returns a wrapped Pdfium `FPDF_FILEWRITE` struct that uses the given writer as an
382 /// output source for Pdfium's file writing callback function.
383 pub(crate) fn get_pdfium_file_writer_from_writer<W: Write + 'static>(
384 writer: &mut W,
385 ) -> FpdfFileWriteExt<'_> {
386 FpdfFileWriteExt {
387 version: 1,
388 write_block: Some(write_block_from_callback),
389 writer,
390 }
391 }
392
393 trait PdfiumDocumentWriter: Write {
394 // A tiny trait that lets us perform type-erasure on the user-provided Rust writer.
395 // This means FpdfFileWriteExt does not need to carry a generic parameter, which simplifies
396 // callback overloading in the WASM bindings implementation.
397
398 // Additionally, since Pdfium's save operations are synchronous and immediate, we do
399 // not need to take ownership of the user-provided Rust writer; a temporary mutable
400 // reference is sufficient.
401 }
402
403 impl<W: Write> PdfiumDocumentWriter for W {}
404
405 #[repr(C)]
406 pub(crate) struct FpdfFileWriteExt<'a> {
407 // An extension of Pdfium's FPDF_FILEWRITE struct that adds an extra field to carry the
408 // user-provided Rust writer.
409 version: c_int,
410 write_block: Option<
411 unsafe extern "C" fn(
412 file_write_ext_ptr: *mut FpdfFileWriteExt,
413 buf: *const c_void,
414 size: c_ulong,
415 ) -> c_int,
416 >,
417 writer: &'a mut dyn PdfiumDocumentWriter, // Type-erased equivalent of <W: Write>
418 }
419
420 impl<'a> FpdfFileWriteExt<'a> {
421 /// Returns an `FPDF_FILEWRITE` pointer suitable for passing to `FPDF_SaveAsCopy()`
422 /// or `FPDF_SaveWithVersion()`.
423 #[inline]
424 pub(crate) fn as_fpdf_file_write_mut_ptr(&mut self) -> &mut FPDF_FILEWRITE {
425 unsafe { &mut *(self as *mut FpdfFileWriteExt as *mut FPDF_FILEWRITE) }
426 }
427
428 /// Flushes the buffer of the underlying Rust writer.
429 #[inline]
430 pub(crate) fn flush(&mut self) -> std::io::Result<()> {
431 self.writer.flush()
432 }
433 }
434
435 // The callback function invoked by Pdfium.
436 pub(crate) extern "C" fn write_block_from_callback(
437 file_write_ext_ptr: *mut FpdfFileWriteExt,
438 buf: *const c_void,
439 size: c_ulong,
440 ) -> c_int {
441 let result = unsafe {
442 match (*file_write_ext_ptr)
443 .writer
444 .write_all(slice::from_raw_parts(buf as *const u8, size as usize))
445 {
446 Ok(()) => 1,
447 Err(_) => 0,
448 }
449 };
450
451 result
452 }
453}
454
455#[cfg(test)]
456pub(crate) mod test {
457 // Provides a function that binds to the correct Pdfium configuration during unit tests,
458 // depending on selected crate features.
459
460 use crate::error::PdfiumError;
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 match Pdfium::bind_to_library(Pdfium::pdfium_platform_library_name_at_path("./"))
473 .or_else(|_| Pdfium::bind_to_system_library())
474 {
475 Ok(bindings) => Pdfium::new(bindings), // Create new bindings
476 Err(PdfiumError::PdfiumLibraryBindingsAlreadyInitialized) => Pdfium {}, // Re-use existing bindings
477 Err(e) => Err(e).unwrap(), // Explicitly re-throw the error
478 }
479 }
480}
481
482#[cfg(test)]
483mod tests {
484 use crate::utils::dates::*;
485 use crate::utils::pixels::*;
486 use crate::utils::utf16le::*;
487 use chrono::prelude::*;
488
489 // Tests of color conversion functions.
490
491 #[test]
492 fn test_unaligned_bgr_to_rgba() {
493 let data: [u8; 15] = [2, 1, 0, 3, 6, 5, 4, 7, 10, 9, 8, 11, 14, 13, 12];
494
495 let result = unaligned_rgb_to_bgra(data.as_slice());
496
497 assert_eq!(
498 result,
499 [0, 1, 2, 255, 5, 6, 3, 255, 10, 7, 4, 255, 11, 8, 9, 255, 12, 13, 14, 255]
500 );
501 }
502
503 #[test]
504 fn test_aligned_bgr_to_rgba() {
505 let data: [u8; 24] = [
506 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23,
507 ];
508
509 // Interpret the sample data as four-byte scanlines with each line consisting of
510 // one pixel (taking three bytes) followed by one alignment byte.
511
512 let result = aligned_bgr_to_rgba(data.as_slice(), 1, 4);
513
514 assert_eq!(
515 result,
516 [
517 2, 1, 0, 255, 6, 5, 4, 255, 10, 9, 8, 255, 14, 13, 12, 255, 18, 17, 16, 255, 22,
518 21, 20, 255
519 ]
520 );
521
522 // Interpret the data as eight-byte scanlines with each line consisting of two pixels
523 // (each taking three bytes) each followed by one alignment byte.
524
525 let result = aligned_bgr_to_rgba(data.as_slice(), 2, 8);
526
527 assert_eq!(
528 result,
529 [
530 2, 1, 0, 255, 5, 4, 3, 255, 10, 9, 8, 255, 13, 12, 11, 255, 18, 17, 16, 255, 21,
531 20, 19, 255
532 ]
533 );
534
535 // Interpret the data as 12-byte scanlines with each line consisting of three pixels
536 // (each taking three bytes) each followed by one alignment byte.
537
538 let result = aligned_bgr_to_rgba(data.as_slice(), 3, 12);
539
540 assert_eq!(
541 result,
542 [
543 2, 1, 0, 255, 5, 4, 3, 255, 8, 7, 6, 255, 14, 13, 12, 255, 17, 16, 15, 255, 20, 19,
544 18, 255
545 ]
546 );
547
548 // Interpret the data as 12-byte scanlines with each line consisting of four pixels
549 // (each taking three bytes) with no alignment bytes.
550
551 let result = aligned_bgr_to_rgba(data.as_slice(), 4, 12);
552
553 assert_eq!(
554 result,
555 [
556 2, 1, 0, 255, 5, 4, 3, 255, 8, 7, 6, 255, 11, 10, 9, 255, 14, 13, 12, 255, 17, 16,
557 15, 255, 20, 19, 18, 255, 23, 22, 21, 255
558 ]
559 );
560 }
561
562 #[test]
563 fn test_bgra_to_rgba() {
564 let data: [u8; 16] = [2, 1, 0, 3, 6, 5, 4, 7, 10, 9, 8, 11, 14, 13, 12, 15];
565
566 let result = bgra_to_rgba(data.as_slice());
567
568 assert_eq!(
569 result,
570 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
571 );
572 }
573
574 #[test]
575 fn test_rgb_to_bgra() {
576 let data: [u8; 15] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14];
577
578 let result = unaligned_rgb_to_bgra(data.as_slice());
579
580 assert_eq!(
581 result,
582 [2, 1, 0, 255, 5, 4, 3, 255, 8, 7, 6, 255, 11, 10, 9, 255, 14, 13, 12, 255]
583 );
584 }
585
586 #[test]
587 fn test_rgba_to_bgra() {
588 let data: [u8; 16] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
589
590 let result = rgba_to_bgra(data.as_slice());
591
592 assert_eq!(
593 result,
594 [2, 1, 0, 3, 6, 5, 4, 7, 10, 9, 8, 11, 14, 13, 12, 15]
595 );
596 }
597
598 #[test]
599 fn test_aligned_grayscale_to_unaligned() {
600 let data: [u8; 16] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
601
602 let result = aligned_grayscale_to_unaligned(data.as_slice(), 1, 4);
603
604 assert_eq!(result, [0, 4, 8, 12]);
605 }
606
607 // Tests of date time conversion functions.
608
609 #[test]
610 fn test_date_time_to_pdf_date_string() {
611 assert_eq!(
612 date_time_to_pdf_string(Utc.with_ymd_and_hms(1998, 12, 23, 19, 52, 00).unwrap()),
613 "D:19981223195200Z00'00'"
614 );
615
616 assert_eq!(
617 date_time_to_pdf_string(
618 FixedOffset::west_opt(8 * 3600)
619 .unwrap()
620 .from_local_datetime(
621 &NaiveDate::from_ymd_opt(1998, 12, 23)
622 .unwrap()
623 .and_hms_opt(19, 52, 00)
624 .unwrap()
625 )
626 .unwrap()
627 ),
628 "D:19981223195200-08'00'"
629 )
630 }
631
632 #[test]
633 fn test_valid_utf16le_from_emoji() {
634 let emoji = "💁👵🧕";
635
636 assert_eq!(
637 get_string_from_pdfium_utf16le_bytes(get_pdfium_utf16le_bytes_from_str(emoji)).unwrap(),
638 emoji
639 );
640 }
641}