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
//! sndjvu_format is a library for working with the transfer format for DjVu documents.
//!
//! The "transfer format" is the canonical DjVu file format defined by the DjVu v3 standard. You
//! can use this library to parse a DjVu file or create one programmatically. The lowest-level
//! details of the format are abstracted away, but you still need to understand the structure of a
//! DjVu document at the "chunk" level (see below) to use this library effectively.
//!
//! ## Overview of the DjVu v3 document model
//!
//! (This overview is not intended to substitute for reading the relevant parts of the DjVu v3
//! standard.)
//!
//! A DjVu document is either *single-page* or *multi-page*. A single-page document consists of a
//! single *component*; a multi-page document consists of zero or more components, plus some
//! metadata.
//!
//! DjVu components come in three types: `DJVU`, `DJVI`, and `THUM`. A `DJVU` component represents
//! a page, a `DJVI` component holds data that's shared between several pages, and a `THUM`
//! component holds thumbnail images for several pages. The single component of a single-page
//! document must be of type `DJVU`.
//!
//! Every piece of data in a DjVu document is contained in a *chunk*, and each chunk has a type.
//! Most chunks are contained in a components; the exceptions are the `DIRM` and `NAVM` chunks that
//! contain the metadata for a multi-page document. A chunk of type `INFO` can only appear at the
//! start of a `DJVU` component (and is mandatory in that position); it describes some basic
//! properties of the corresponding page, like its width and height in pixels. Other than the
//! `INFO` chunk, the same types of chunk can appear in the `DJVU` and `DJVI` components. A chunk
//! of one of these types is called an *element*, and describes one aspect of the page or pages
//! with which it is associated (image data, OCRed text, annotations, etc.).

#![no_std]
#![deny(
    elided_lifetimes_in_paths,
    unsafe_op_in_unsafe_fn,
    unused_must_use,

    clippy::pattern_type_mismatch,
)]
#![cfg_attr(sndjvu_doc_cfg, feature(doc_cfg, doc_auto_cfg))]

extern crate alloc;
#[cfg(feature = "std")]
extern crate std;

use core::fmt::{Debug, Display, Formatter};

/// Version information associated with the `TXTa` and `TXTz` chunks.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct TxtVersion(pub u8);

impl TxtVersion {
    /// The current version, according to the most recent DjVu spec.
    pub const CURRENT: Self = Self(1);

    fn pack(self) -> [u8; 1] {
        [self.0]
    }
}

impl Display for TxtVersion {
    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
        write!(f, "{}", self.0)
    }
}

/// Version information associated with the `BG44`, `FG44`, and `TH44` chunks.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct Iw44Version {
    major: u8,
    minor: u8,
}

impl Iw44Version {
    /// The current version, according to the most recent DjVu spec.
    pub const CURRENT: Self = Self { major: 1, minor: 2 };

    fn pack(self, color_space: Iw44ColorSpace) -> [u8; 2] {
        [self.major | ((color_space as u8) << 7), self.minor]
    }
}

impl Display for Iw44Version {
    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
        write!(f, "{}.{}", self.major, self.minor)
    }
}

/// Version information associated with the `FGbz` chunk.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct FgbzVersion(u8);

impl FgbzVersion {
    /// The current version, according to the most recent DjVu spec.
    pub const CURRENT: Self = Self(0);

    fn pack(self, has_indices: bool) -> [u8; 1] {
        [((has_indices as u8) << 7) | self.0]
    }
}

impl Display for FgbzVersion {
    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
        write!(f, "{}", self.0)
    }
}

/// Version information associated with the `INFO` chunk.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct InfoVersion {
    /// The major version.
    pub major: u8,
    /// The minor version.
    pub minor: u8,
}

impl InfoVersion {
    /// The current version, according to the most recent DjVu spec.
    pub const CURRENT: Self = Self { major: 0, minor: 26 };

    fn pack(self) -> [u8; 2] {
        [self.minor, self.major]
    }
}

impl Display for InfoVersion {
    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
        write!(f, "{}.{}", self.major, self.minor)
    }
}

/// The orientation of an encoded page.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PageRotation {
    Up = 1,
    Ccw = 6,
    Down = 2,
    Cw = 5,
}

/// Version information associated with the `DIRM` chunk.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub struct DirmVersion(u8);

impl DirmVersion {
    /// The current version, according to the most recent DjVu spec.
    pub const CURRENT: Self = Self(1);

    fn pack(self, is_bundled: bool) -> [u8; 1] {
        [self.0 | ((is_bundled as u8) << 7)]
    }
}

impl Display for DirmVersion {
    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
        write!(f, "{}", self.0)
    }
}

/// The type of a component in a multi-page DjVu document.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ComponentKind {
    /// `DJVI` component (elements shared between pages).
    Djvi,
    /// `DJVU` component (a page).
    Djvu,
    /// `THUM` component (page thumbnails).
    Thum,
}

impl ComponentKind {
    fn name(&self) -> &'static [u8; 4] {
        match *self {
            Self::Djvi => b"DJVI",
            Self::Djvu => b"DJVU",
            Self::Thum => b"THUM",
        }
    }
}

/// The type of a zone record in a `TXTa` or `TXTz` chunk.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(u8)]
pub enum ZoneKind {
    Page = 1,
    Column,
    Region,
    Paragraph,
    Line,
    Word,
    Character,
}

/// Color space of the image data in a `BG44`, `FG44`, or `TH44` chunk.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Iw44ColorSpace {
    YCbCr,
    Gray,
}

#[derive(Clone, Copy)]
struct Bstr<B>(B);

impl<B: AsRef<[u8]>> Debug for Bstr<B> {
    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
        // This logic is copied from Andrew Gallant's bstr library,
        // with thanks.

        fn len_following(byte: u8) -> Option<usize> {
            if byte <= 0x7F {
                Some(1)
            } else if byte & 0b1100_0000 == 0b1000_0000 {
                None
            } else if byte <= 0b1101_1111 {
                Some(2)
            } else if byte <= 0b1110_1111 {
                Some(3)
            } else if byte <= 0b1111_0111 {
                Some(4)
            } else {
                None
            }
        }

        fn decode_char(bytes: &[u8]) -> Option<Result<char, u8>> {
            if bytes.is_empty() {
                return None;
            }
            let len = match len_following(bytes[0]) {
                None => return Some(Err(bytes[0])),
                Some(len) if len > bytes.len() => return Some(Err(bytes[0])),
                Some(1) => return Some(Ok(bytes[0] as char)),
                Some(len) => len,
            };
            match core::str::from_utf8(&bytes[..len]) {
                Ok(s) => Some(Ok(s.chars().next().unwrap())),
                Err(_) => Some(Err(bytes[0])),
            }
        }

        write!(f, "\"")?;
        let mut bytes = self.0.as_ref();
        while let Some(result) = decode_char(bytes) {
            let ch = match result {
                Ok(ch) => ch,
                Err(byte) => {
                    write!(f, r"\x{:02x}", byte)?;
                    bytes = &bytes[1..];
                    continue;
                }
            };
            bytes = &bytes[ch.len_utf8()..];
            match ch {
                '\0' => write!(f, "\\0")?,
                // ASCII control characters except \0, \n, \r, \t
                '\x01'..='\x08'
                | '\x0b'
                | '\x0c'
                | '\x0e'..='\x19'
                | '\x7f' => {
                    write!(f, "\\x{:02x}", ch as u32)?;
                }
                /* '\n' | '\r' | '\t' | */ _ => {
                    write!(f, "{}", ch.escape_debug())?;
                }
            }
        }
        write!(f, "\"")?;
        Ok(())
    }
}

/// Index into the color palette of an `FGbz` chunk.
#[derive(Clone, Copy, Debug)]
#[repr(transparent)]
pub struct PaletteIndex([u8; 2]);

impl PaletteIndex {
    fn cast_slice(arrays: &[[u8; 2]]) -> &[Self] {
        // SAFETY PaletteIndex is repr(transparent)
        unsafe {
            core::slice::from_raw_parts(
                arrays.as_ptr().cast(),
                arrays.len(),
            )
        }
    }

    pub fn new(x: u16) -> Self {
        Self(x.to_be_bytes())
    }

    pub fn slice_as_bytes(selves: &[Self]) -> &[u8] {
        // SAFETY PaletteIndex is repr(transparent)
        let arrays: &[[u8; 2]] = unsafe {
            core::slice::from_raw_parts(
                selves.as_ptr().cast(),
                selves.len(),
            )
        };
        crate::shim::arrays_as_slice(arrays)
    }

    pub fn get(self) -> u16 {
        u16::from_be_bytes(self.0)
    }
}

/// A BGR8 color from the palette of an `FGbz` chunk.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[repr(C)]
pub struct PaletteEntry {
    pub b: u8,
    pub g: u8,
    pub r: u8,
}

impl PaletteEntry {
    fn cast_slice(arrays: &[[u8; 3]]) -> &[Self] {
        // SAFETY PaletteEntry is repr(C) with the same layout as [u8; 3]
        unsafe {
            core::slice::from_raw_parts(
                arrays.as_ptr().cast(),
                arrays.len(),
            )
        }
    }

    fn uncast_slice(slice: &[Self]) -> &[[u8; 3]] {
        // SAFETY PaletteEntry is repr(C) with the same layout as [u8; 3]
        unsafe {
            core::slice::from_raw_parts(
                slice.as_ptr().cast(),
                slice.len(),
            )
        }
    }
}

/// Zone record from a `TXTa` or `TXTz` chunk.
#[derive(Clone, Copy, Debug)]
#[repr(C)]
pub struct Zone {
    kind: crate::ZoneKind,
    x_offset: [u8; 2],
    y_offset: [u8; 2],
    width: [u8; 2],
    height: [u8; 2],
    _empty: [u8; 2],
    text_len: [u8; 3],
    num_children: [u8; 3],
}

fn cvt_zone_i16(bytes: [u8; 2]) -> i16 {
    i16::from_be_bytes(bytes) ^ (1 << 15)
}

impl Zone {
    fn as_bytes(&self) -> &[u8; 17] {
        unsafe { &*((self as *const Self).cast()) }
    }

    fn cast_slice(arrays: &[[u8; 17]]) -> Option<&[Self]> {
        for arr in arrays {
            let p = arr as *const _ as *const Zone;
            let x = unsafe { *core::ptr::addr_of!((*p).kind).cast::<u8>() };
            if !(1..=7).contains(&x) {
                return None;
            }
        }

        // SAFETY Zone has the same layout as [u8; 17], with no padding,
        // and we've checked that the kind fields have valid values
        let zones = unsafe {
            core::slice::from_raw_parts(
                arrays.as_ptr().cast(),
                arrays.len(),
            )
        };
        Some(zones)
    }

    fn uncast_slice(slice: &[Self]) -> &[[u8; 17]] {
        unsafe { 
            core::slice::from_raw_parts(
                slice.as_ptr().cast(),
                slice.len(),
            )
        }
    }

    pub fn kind(self) -> crate::ZoneKind {
        self.kind
    }

    pub fn x_offset(self) -> i16 {
        cvt_zone_i16(self.x_offset)
    }

    pub fn y_offset(self) -> i16 {
        cvt_zone_i16(self.y_offset)
    }

    pub fn width(self) -> i16 {
        cvt_zone_i16(self.width)
    }

    pub fn height(self) -> i16 {
        cvt_zone_i16(self.height)
    }

    pub fn text_len(self) -> u32 {
        let [b1, b2, b3] = self.text_len;
        u32::from_be_bytes([0, b1, b2, b3])
    }

    pub fn num_children(self) -> u32 {
        let [b1, b2, b3] = self.num_children;
        u32::from_be_bytes([0, b1, b2, b3])
    }
}

/// Uninhabited type, used to customize the [`Progress`](parsing::Progress) type.
///
/// This will eventually become a simple alias for [the canonical never
/// type](never).
#[derive(Debug)]
pub enum Never {}

pub mod annot;
pub mod parsing;
pub mod ser;
pub(crate) mod shim;