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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
//! Serialization to the DjVu transfer format.
//!
//! If you have a Rust data type that represents a DjVu document, implementing this module's
//! [`Serialize`] trait allows you to turn a value of that type into a blob of bytes in the
//! transfer format. The structure of the document is expressed by a sequence of method calls on
//! various "serializer" objects, such as [`Serializer`], [`SerializeMultiPageBundled`], etc. This
//! approach should be familiar from APIs like `std::fmt::Debug` and `serde::Serialize`.
//!
//! ## Two-pass approach
//!
//! Various fields in the DjVu transfer format describe the size/length or offset of some part of
//! the document. Let's call these "length fields". A core goal of this module is to take complete
//! responsibility for computing the correct values for such fields, since these computations are
//! tightly coupled to the gritty details of the transfer format.
//!
//! Length fields present some obstacles to an elegant serialization API. Consider the `DIRM`
//! chunk, which appears at the beginning of a multi-page document and contains some metadata about
//! the components, including their offsets and sizes. The offsets appear in the "plain"
//! (uncompressed) portion of the `DIRM` chunk, but the sizes are BZZ-compressed. This makes it
//! impossible to emit a well-formed `DIRM` chunk until we know the entire structure of the
//! document in detail, so that we can compute the size of each component, compress that data,
//! and then compute the final offset of each component. (Because the `DIRM` chunk appears before
//! the components, and because the size of the BZZ-compressed portion can't be determined without
//! compressing the exact data in question, we really have to do things in this order.)
//!
//! The only solution, if we care about hiding the intricacies of the transfer format from
//! downstream, is to split serialization into two passes. On the first pass, we don't emit any
//! bytes, but only collect enough information to compute the value of every length field. On the
//! second pass, we use that stored information to emit the bytes of the document, in order, with
//! their correct values.
//!
//! The trick that this module pulls off is to *encapsulate* the two-pass nature of serialization.
//! You just implement [`Serialize`], and a function like [`to_vec`] takes care internally of
//! calling [`Serialize::serialize`] twice, with two different [`Serializer`]s, one for the first
//! pass and one for the second.

#![deny(clippy::integer_arithmetic)]

use crate::{
    ComponentKind, DirmVersion, FgbzVersion, InfoVersion,
    Iw44ColorSpace, Iw44Version, PageRotation, PaletteEntry,
    TxtVersion, Zone, ZoneKind,
};
use core::fmt::{Debug, Display, Formatter};
use core::mem::replace;
use alloc::string::String;
use alloc::vec::Vec;
#[cfg(feature = "backtrace")]
use std::backtrace::Backtrace;

const CHUNK_HEADER_SIZE: u32 = 8;
const COMPONENT_HEADER_SIZE: u32 = 12;

/// Trivial error type for checked arithmetic.
#[derive(Debug)]
struct OverflowError;

impl Display for OverflowError {
    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
        write!(f, "arithmetic overflow while computing value for length or offset field")
    }
}

#[cfg(feature = "std")]
impl std::error::Error for OverflowError {}

#[derive(Debug)]
enum ErrorKind {
    Overflow,
    #[cfg(feature = "std")]
    Io(std::io::Error),
}

/// An error encountered during serialization.
///
/// Contains a backtrace if the `backtrace` crate feature is enabled.
#[derive(Debug)]
pub struct Error {
    kind: ErrorKind,
    #[cfg(feature = "backtrace")]
    _backtrace: Backtrace,
}

// Backtrace before Rust 1.73.0 wasn't RefUnwindSafe. Explicitly implement it for Error
// to avoid either increasing MSRV or having the properties of this type depend on the Rust
// version.
impl core::panic::RefUnwindSafe for Error {}

impl Display for Error {
    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
        match self.kind {
            ErrorKind::Overflow => write!(f, "{}", OverflowError)?,
            #[cfg(feature = "std")]
            ErrorKind::Io(ref e) => write!(f, "{e}")?,
        }
        Ok(())
    }
}

#[cfg(feature = "std")]
impl std::error::Error for Error {}

impl Error {
    #[cfg(feature = "std")]
    fn io(e: std::io::Error) -> Self {
        Self {
            kind: ErrorKind::Io(e),
            #[cfg(feature = "backtrace")]
            _backtrace: Backtrace::capture(),
        }
    }
}

impl From<OverflowError> for Error {
    fn from(_: OverflowError) -> Self {
        Self {
            kind: ErrorKind::Overflow,
            #[cfg(feature = "backtrace")]
            _backtrace: Backtrace::capture(),
        }
    }
}

macro_rules! checked_sum {
    ( $( $a:expr ),* $( , )? ) => {
        (|| -> Result<u32, OverflowError> {
            let mut total = 0u32;
            $(
                total = total.checked_add($a).ok_or(OverflowError)?;
            )*
            Ok(total)
        })()
    };
}

macro_rules! tame {
    ( $( $tt:tt )* ) => {
        {
            #[allow(clippy::integer_arithmetic)]
            let x = { $($tt)* };
            x
        }
    };
}

enum ErasedOutMut<'wr> {
    Vec(&'wr mut Vec<u8>),
    #[cfg(feature = "std")]
    Writer(&'wr mut (dyn std::io::Write + 'wr)),
}

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

impl<'wr> ErasedOutMut<'wr> {
    fn put(&mut self, data: &[&[u8]]) -> Result<(), Error> {
        match *self {
            Self::Vec(ref mut vec) => {
                for slice in data {
                    vec.extend_from_slice(slice);
                }
            }
            #[cfg(feature = "std")]
            Self::Writer(ref mut writer) => {
                for slice in data {
                    writer.write_all(slice).map_err(Error::io)?;
                }
            }
        }
        Ok(())
    }
}

macro_rules! out {
    ( $o:expr ; $( $b:expr ),* $( , )? ) => {
        $o.put(&[$( $b.as_ref() ),*])
    };
}

// Note: the sizes stored in this type are as they appear in (the compressed portion of)
// the DIRM chunk, so they include the 12 bytes FORM:$len:$kind
#[derive(Debug)]
struct ComponentSizes {
    buf: Vec<[u8; 3]>,
}

impl ComponentSizes {
    fn new() -> Self {
        Self { buf: Vec::new() }
    }

    fn push(&mut self, size: u32) -> Result<(), Error> {
        let size = checked_sum!(size, COMPONENT_HEADER_SIZE)?;
        if let [0, b1, b2, b3] = size.to_be_bytes() {
            self.buf.push([b1, b2, b3]);
            Ok(())
        } else {
            Err(OverflowError.into())
        }
    }

    fn as_bytes(&self) -> &[u8] {
        crate::shim::arrays_as_slice(&self.buf)
    }

    fn iter(&self) -> impl Iterator<Item = u32> + '_ {
        self.buf.iter().map(|&[b1, b2, b3]| u32::from_be_bytes([0, b1, b2, b3]))
    }

    fn into_lengths(self) -> ComponentLengths {
        ComponentLengths { inner: self.buf.into_iter() }
    }
}

#[derive(Debug)]
struct ComponentLengths {
    inner: <Vec<[u8; 3]> as IntoIterator>::IntoIter,
}

impl Iterator for ComponentLengths {
    type Item = u32;

    fn next(&mut self) -> Option<Self::Item> {
        // yielded values are suitable for the length field of the component header:
        // the four kind bytes are included, but not the FORM:$len
        self.inner.next().map(|[b1, b2, b3]| tame!(u32::from_be_bytes([0, b1, b2, b3]) - CHUNK_HEADER_SIZE))
    }
}

#[derive(Debug)]
struct ComponentMeta {
    flags_buf: Vec<u8>,
    ids_buf: Vec<u8>,
}

impl ComponentMeta {
    fn new() -> Self {
        Self {
            flags_buf: Vec::new(),
            ids_buf: Vec::new(),
        }
    }

    fn push(&mut self, kind: ComponentKind, id: &str) {
        self.flags_buf.push(kind as u8);
        self.ids_buf.extend_from_slice(id.as_bytes());
        self.ids_buf.push(b'\0');
    }
}

/// Opaque token returned from successful serialization.
#[derive(Debug)]
pub struct Okay {
    num_components: u16,
    dirm_data: Vec<u8>,
    chunk_lens: Vec<u32>,
    component_sizes: ComponentSizes,
    total: u32,
}

impl Okay {
    fn dummy() -> Self {
        Self {
            num_components: 0,
            dirm_data: Vec::new(),
            chunk_lens: Vec::new(),
            component_sizes: ComponentSizes::new(),
            total: 0,
        }
    }
}

#[derive(Debug)]
enum Cur {
    // empty document, neither start_component nor start_chunk called
    Start,
    // empty component, start_component called but not start_chunk
    InComponent,
    // non-empty component, start_component and start_chunk called
    InChunk {
        // count of bytes in the content of the current (in-progress) chunk
        chunk: u32,
        // count of bytes in the content of the current component,
        // not including the chunk in progress or the header of that chunk,
        // but including the padding before that chunk, if any
        // (why this specific accounting? idk, it just makes sense to me)
        component: u32,
    },
}

#[derive(Debug)]
struct First {
    chunk_lens: Vec<u32>,
    component_sizes: ComponentSizes,
    component_meta: ComponentMeta,
    num_components: u16,
    cur: Cur,
    // when Cur::Start, this is 16 (magic + document header)
    // when Cur::InComponent, this is the count of bytes up to the end of the header
    // of the current (in-progress) component
    // when Cur::InChunk, this is the count of bytes up to the beginning of the header
    // of the current chunk
    total: u32,
}

#[derive(Debug)]
struct Second<'wr> {
    chunk_lens: <Vec<u32> as IntoIterator>::IntoIter,
    component_lens: ComponentLengths,
    // the number of bytes written so far, updated with every write
    running: u32,
    out: ErasedOutMut<'wr>,
}

impl<'wr> Second<'wr> {
    fn put(&mut self, data: &[&[u8]]) -> Result<(), Error> {
        self.out.put(data)?;
        let len: u32 = data.iter().map(|x| x.len()).sum::<usize>().try_into().map_err(|_| OverflowError)?;
        self.running = checked_sum!(self.running, len)?;
        Ok(())
    }
}

#[derive(Debug)]
enum Pass<'wr> {
    First(First),
    Second(Second<'wr>),
}

impl<'wr> Pass<'wr> {
    fn put(&mut self, data: &[&[u8]]) -> Result<(), Error> {
        match *self {
            Pass::First(ref mut first) => {
                // in practice it seems we only use this to write chunk data,
                // which means calling it without Cur::InChunk is a bug
                // the behavior is to forward to the underlying Out and also
                // increment the chunk counter
                let len: u32 = data.iter().map(|x| x.len()).sum::<usize>().try_into().map_err(|_| OverflowError)?;
                match first.cur {
                    Cur::InChunk { ref mut chunk, .. } => {
                        *chunk = checked_sum!(*chunk, len)?;
                    }
                    _ => unreachable!(),
                }
            }
            Pass::Second(ref mut second) => second.put(data)?,
        }
        Ok(())
    }

    fn start_component(&mut self, kind: ComponentKind, id: &str) -> Result<(), Error> {
        match *self {
            Self::First(ref mut first) => {
                match replace(&mut first.cur, Cur::InComponent) {
                    Cur::Start => {},
                    Cur::InComponent => {
                        // previous component was empty: record its size as 12 bytes (just the header)
                        first.component_sizes.push(COMPONENT_HEADER_SIZE).unwrap();
                    }
                    Cur::InChunk { chunk, mut component } => {
                        first.chunk_lens.push(chunk);
                        // final chunk of the previous component
                        component = checked_sum!(component, CHUNK_HEADER_SIZE, chunk)?;
                        first.total = checked_sum!(first.total, CHUNK_HEADER_SIZE, chunk)?;
                        first.component_sizes.push(component)?;
                        // padding before the new component
                        if first.total % 2 != 0 {
                            first.total = checked_sum!(first.total, 1)?;
                        } 
                    }
                }

                first.num_components = first.num_components.checked_add(1).ok_or(OverflowError)?;
                first.total = checked_sum!(first.total, COMPONENT_HEADER_SIZE)?;
                first.component_meta.push(kind, id);
            }
            Self::Second(ref mut second) => {
                if second.running % 2 != 0 {
                    out!(second; [0])?;
                }
                let len = second.component_lens.next().unwrap();
                out!(second; b"FORM", len.to_be_bytes(), kind.name())?;
            }
        }
        Ok(())
    }

    fn start_chunk(&mut self, id: &[u8; 4]) -> Result<(), Error> {
        match *self {
            Self::First(ref mut first) => {
                let component = match first.cur {
                    Cur::Start => unreachable!(),
                    Cur::InComponent => 0,
                    Cur::InChunk { chunk, mut component } => {
                        first.chunk_lens.push(chunk);
                        first.total = checked_sum!(first.total, CHUNK_HEADER_SIZE, chunk)?;
                        component = checked_sum!(component, CHUNK_HEADER_SIZE, chunk)?;
                        // padding before the new chunk
                        if first.total % 2 != 0 {
                            first.total = checked_sum!(first.total, 1)?;
                            component = checked_sum!(component, 1)?;
                        }
                        component
                    }
                };
                first.cur = Cur::InChunk { chunk: 0, component };
            }
            Self::Second(ref mut second) => {
                if second.running % 2 != 0 {
                    out!(second; [0])?;
                }
                let len = second.chunk_lens.next().unwrap();
                out!(second; id, len.to_be_bytes())?;
            }
        }
        Ok(())
    }
}

#[derive(Debug)]
enum SerializerRepr<'wr> {
    First(First),
    Second(SerializeMultiPageHead<'wr>),
}

/// The starting point for serialization.
///
/// An implementation of [`Serialize::serialize`] should call one of the methods of this type to
/// select what kind of document is being serialized. Currently, only the bundled multi-page
/// document format is supported.
#[derive(Debug)]
pub struct Serializer<'wr> {
    repr: SerializerRepr<'wr>,
}

/// Interface for describing the structure of a DjVu document.
pub trait Serialize {
    fn serialize(&self, serializer: Serializer<'_>) -> Result<Okay, Error>;
}

impl<'wr> Serializer<'wr> {
    fn first_pass() -> Self {
        Self {
            repr: SerializerRepr::First(First {
                chunk_lens: Vec::new(),
                component_sizes: ComponentSizes::new(),
                component_meta: ComponentMeta::new(),
                num_components: 0,
                total: 0,
                cur: Cur::Start,
            }),
        }
    }

    fn second_pass(okay: Okay, out: ErasedOutMut<'wr>) -> Self {
        let Okay { num_components, dirm_data, chunk_lens, component_sizes, total } = okay;
        let _ = total; // not used
        Self {
            repr: SerializerRepr::Second(SerializeMultiPageHead {
                num_components,
                dirm_data,
                chunk_lens,
                component_sizes,
                out,
            }),
        }
    }

    /// Begin serializing a bundled multi-page document.
    pub fn multi_page_bundled(self) -> SerializeMultiPageBundled<'wr> {
        match self.repr {
            SerializerRepr::First(first) => SerializeMultiPageBundled::Components(
                SerializeComponents { pass: Pass::First(first) },
            ),
            SerializerRepr::Second(compress_dirm) => SerializeMultiPageBundled::Head(compress_dirm),
        }
    }

    // TODO other document formats?
}

/// Serializer for a bundled multi-page document.
///
/// The two variants of this type expose the two-pass nature of the serialization process. On the
/// first pass, an implementation of [`Serialize::serialize`] will be presented with the
/// `Components` variant and proceed directly to describing the components of the document. On the
/// second pass, after enough information has been gathered to compute the contents of the `DIRM`
/// chunk, the implementation is presented with the `Head` variant and must compress (a portion of)
/// the `DIRM` data and pass it back to the serializer.
#[derive(Debug)]
pub enum SerializeMultiPageBundled<'wr> {
    Components(SerializeComponents<'wr>),
    Head(SerializeMultiPageHead<'wr>),
}

/// Serializer for the "head" data of a multi-page document (`DIRM` and `NAVM` chunks).
#[derive(Debug)]
pub struct SerializeMultiPageHead<'wr> {
    num_components: u16,
    dirm_data: Vec<u8>,
    chunk_lens: Vec<u32>,
    component_sizes: ComponentSizes,
    out: ErasedOutMut<'wr>,
}

impl<'wr> SerializeMultiPageHead<'wr> {
    /// Access raw data for BZZ compression.
    ///
    /// The returned bytes should be compressed using a BZZ implementation, and the compressed data
    /// passed as the first argument to [`SerializeMultiPageHead::dirm_navm`] to continue
    /// serialization.
    pub fn raw(&self) -> &[u8] {
        &self.dirm_data
    }

    /// Provide compressed `DIRM` and `NAVM` data to continue with serialization.
    ///
    /// Create the `NAVM` data by building up a [`BookmarkBuf`] and passing the output of
    /// [`BookmarkBuf::as_bytes`] to a BZZ compressor.
    pub fn dirm_navm(mut self, bzz: &[u8], navm: Option<&[u8]>) -> Result<SerializeComponents<'wr>, Error> {
        // accumulate offsets
        let mut off: u32 = tame!(4 + COMPONENT_HEADER_SIZE); // AT&T:FORM:$len:DJVM
        tame!(off += CHUNK_HEADER_SIZE); // DIRM:$len
        let mut dirm_len = tame!(1 + 2); // $flags:$num_components
        let addl = 4u32.checked_mul(self.num_components.into()).ok_or(OverflowError)?;
        dirm_len = checked_sum!(dirm_len, addl)?;
        let addl: u32 = bzz.len().try_into().map_err(|_| OverflowError)?;
        dirm_len = checked_sum!(dirm_len, addl)?;
        off = checked_sum!(off, dirm_len)?;
        let navm_with_len = if let Some(navm) = navm {
            Some((navm, navm.len().try_into().map_err(|_| OverflowError)?))
        } else {
            None
        };
        if let Some((_, navm_len)) = navm_with_len {
            if off % 2 != 0 {
                off = checked_sum!(off, 1)?;
            }
            off = checked_sum!(off, CHUNK_HEADER_SIZE, navm_len)?;
        }
        let running = off; // save for later
        let mut offsets = Vec::new();
        for size in self.component_sizes.iter() {
            if off % 2 != 0 {
                off = checked_sum!(off, 1)?;
            }
            offsets.push(off.to_be_bytes());
            off = checked_sum!(off, size)?;
        }
        let full_len = tame!(off - 12);
        
        out!(
            self.out;
            b"AT&T", b"FORM", full_len.to_be_bytes(), b"DJVM",
            b"DIRM", dirm_len.to_be_bytes(),
            DirmVersion::CURRENT.pack(true), self.num_components.to_be_bytes(),
            crate::shim::arrays_as_slice(&offsets),
            bzz,
        )?;
        if let Some((navm, navm_len)) = navm_with_len {
            if dirm_len % 2 != 0 {
                out!(self.out; [0])?;
            }
            out!(self.out; b"NAVM", navm_len.to_be_bytes(), navm)?;
        }

        Ok(SerializeComponents {
            pass: Pass::Second(Second {
                chunk_lens: self.chunk_lens.into_iter(),
                component_lens: self.component_sizes.into_lengths(),
                running,
                out: self.out,
            })
        })
    }
}

/// Serializer for the components of a multi-page document.
#[derive(Debug)]
pub struct SerializeComponents<'wr> {
    pass: Pass<'wr>,
}

impl<'wr> SerializeComponents<'wr> {
    /// Begin serializing a `DJVI` component.
    pub fn djvi(&mut self, id: &str) -> Result<SerializeElements<'_, 'wr>, Error> {
        self.pass.start_component(ComponentKind::Djvi, id)?;
        Ok(SerializeElements { pass: &mut self.pass })
    }

    /// Begin serializing a `DJVU` component.
    pub fn djvu(
        &mut self,
        id: &str,
        width: u16,
        height: u16,
        dpi: u16,
        gamma: u8,
        rotation: PageRotation,
    ) -> Result<SerializeElements<'_, 'wr>, Error> {
        self.pass.start_component(ComponentKind::Djvu, id)?;
        self.pass.start_chunk(b"INFO")?;
        out!(
            self.pass;
            width.to_be_bytes(),
            height.to_be_bytes(),
            InfoVersion::CURRENT.pack(),
            dpi.to_le_bytes(),
            [gamma],
            [rotation as u8],
        )?;
        Ok(SerializeElements { pass: &mut self.pass })
    }

    /// Begin serializing a `THUM` component.
    pub fn thum(&mut self, id: &str) -> Result<SerializeThumbnails<'_, 'wr>, Error> {
        self.pass.start_component(ComponentKind::Thum, id)?;
        Ok(SerializeThumbnails { pass: &mut self.pass })
    }

    /// Finish serialization after all components have been described.
    pub fn finish(self) -> Result<Okay, Error> {
        match self.pass {
            Pass::First(First {
                mut chunk_lens,
                mut component_sizes,
                component_meta,
                num_components,
                cur,
                mut total,
            }) => {
                match cur {
                    Cur::Start => {},
                    Cur::InComponent => component_sizes.push(0).unwrap(),
                    Cur::InChunk { mut component, chunk } => {
                        chunk_lens.push(chunk);
                        // final chunk of the previous component
                        component = checked_sum!(component, CHUNK_HEADER_SIZE, chunk)?;
                        total = checked_sum!(total, CHUNK_HEADER_SIZE, chunk)?;
                        component_sizes.push(component)?;
                    }
                }
                let mut dirm_data = Vec::with_capacity(tame!(
                    component_sizes.as_bytes().len() +
                    component_meta.flags_buf.len() +
                    component_meta.ids_buf.len()
                ));
                dirm_data.extend_from_slice(component_sizes.as_bytes());
                dirm_data.extend_from_slice(&component_meta.flags_buf);
                dirm_data.extend_from_slice(&component_meta.ids_buf);
                Ok(Okay {
                    num_components,
                    dirm_data,
                    chunk_lens,
                    component_sizes,
                    total,
                })
            }
            Pass::Second(_) => Ok(Okay::dummy()),
        }
    }
}

/// Serializer for the elements of a `DJVU` or `DJVI` component.
#[derive(Debug)]
pub struct SerializeElements<'co, 'wr: 'co> {
    pass: &'co mut Pass<'wr>,
}

impl<'co, 'wr: 'co> SerializeElements<'co, 'wr> {
    /// Serialize an `ANTa` chunk.
    ///
    /// The DjVu standard notes that "the use of the `ANTa` chunk is discouraged", the compressed
    /// `ANTz` chunk being preferred (see [`Self::antz`]).
    ///
    /// See [`AnnotBuf`] for a strongly-typed way to build up data for the `ant` argument.
    pub fn anta(&mut self, ant: &str) -> Result<(), Error> {
        self.pass.start_chunk(b"ANTa")?;
        out!(self.pass; ant.as_bytes())?;
        Ok(())
    }

    /// Serialize an `ANTz` chunk.
    ///
    /// See [`AnnotBuf`] for a strongly-typed way to build up data that can be compressed for the
    /// `bzz` argument.
    pub fn antz(&mut self, bzz: &[u8]) -> Result<(), Error> {
        self.pass.start_chunk(b"ANTz")?;
        out!(self.pass; bzz)?;
        Ok(())
    }

    /// Serialize a `TXTa` chunk.
    ///
    /// The DjVu standard notes that "the use of the `TXTa` chunk is discouraged", the compressed
    /// `TXTz` chunk being preferred (see [`Self::txtz`]).
    ///
    /// See [`ZoneBuf`] for a strongly-typed way to build up data for the `zones` argument.
    pub fn txta(&mut self, text: &str, zones: &[Zone]) -> Result<(), Error> {
        let len: U24 = text.len().try_into()?;
        self.pass.start_chunk(b"TXTa")?;
        out!(
            self.pass;
            len.to_be_bytes(),
            text,
            TxtVersion::CURRENT.pack(),
            crate::shim::arrays_as_slice(Zone::uncast_slice(zones)),
        )?;
        Ok(())
    }

    /// Serialize a `TXTz` chunk.
    ///
    /// See [`TxtBuf`] for a strongly-typed way to build up data that can be compressed for the
    /// `bzz` argument.
    pub fn txtz(&mut self, bzz: &[u8]) -> Result<(), Error> {
        self.pass.start_chunk(b"TXTz")?;
        out!(self.pass; bzz)?;
        Ok(())
    }

    /// Serialize a `Djbz` chunk.
    pub fn djbz(&mut self, jb2: &[u8]) -> Result<(), Error> {
        self.pass.start_chunk(b"Djbz")?;
        out!(self.pass; jb2)?;
        Ok(())
    }

    /// Serialize an `Sjbz` chunk.
    pub fn sjbz(&mut self, jb2: &[u8]) -> Result<(), Error> {
        self.pass.start_chunk(b"Sjbz")?;
        out!(self.pass; jb2)?;
        Ok(())
    }

    /// Serialize an `FG44` chunk.
    ///
    /// `initial_cdc` must not exceed 127.
    pub fn fg44(
        &mut self,
        num_slices: u8,
        color_space: Iw44ColorSpace,
        width: u16,
        height: u16,
        initial_cdc: u8,
        iw44: &[u8],
    ) -> Result<(), Error> {
        if initial_cdc > 0x7f {
            panic!()
        }
        self.pass.start_chunk(b"FG44")?;
        out!(
            self.pass;
            [0], // serial number
            [num_slices],
            Iw44Version::CURRENT.pack(color_space),
            width.to_be_bytes(),
            height.to_be_bytes(),
            [initial_cdc],
            iw44,
        )?;
        Ok(())
    }

    /// Begin serializing a sequence of `BG44` chunks.
    ///
    /// `initial_cdc` must not exceed 127.
    pub fn bg44(
        &mut self,
        num_slices: u8,
        color_space: Iw44ColorSpace,
        width: u16,
        height: u16,
        initial_cdc: u8,
        iw44: &[u8],
    ) -> Result<SerializeBg44Chunks<'_, 'wr>, Error> {
        if initial_cdc > 0x7f {
            panic!()
        }
        self.pass.start_chunk(b"BG44")?;
        out!(
            self.pass;
            [0], // serial number
            [num_slices],
            Iw44Version::CURRENT.pack(color_space),
            width.to_be_bytes(),
            height.to_be_bytes(),
            [initial_cdc],
            iw44,
        )?;
        Ok(SerializeBg44Chunks {
            serial: 1,
            pass: self.pass,
        })
    }

    /// Serialize an `FGbz` chunk.
    ///
    /// If `indices` are provided, the first element of the tuple should be the number of indices,
    /// and the second element should be the BZZ-compressed indices (pass the output of
    /// [`crate::PaletteIndex::slice_as_bytes`] to a BZZ compressor).
    pub fn fgbz(&mut self, palette: &[PaletteEntry], indices: Option<(usize, &[u8])>) -> Result<(), Error> {
        let palette_len: U24 = palette.len().try_into()?;
        out!(
            self.pass;
            FgbzVersion::CURRENT.pack(indices.is_some()),
            palette_len.to_be_bytes(),
            crate::shim::arrays_as_slice(PaletteEntry::uncast_slice(palette)),
        )?;
        if let Some((len, bzz)) = indices {
            let len: U24 = len.try_into()?;
            out!(
                self.pass;
                len.to_be_bytes(),
                bzz,
            )?;
        }
        Ok(())
    }

    /// Serialize an `INCL` chunk.
    pub fn incl(&mut self, target_id: &str) -> Result<(), Error> {
        self.pass.start_chunk(b"INCL")?;
        out!(self.pass; target_id.as_bytes())?;
        Ok(())
    }

    /// Serialize a `BGjp` chunk.
    pub fn bgjp(&mut self, jpeg: &[u8]) -> Result<(), Error> {
        self.pass.start_chunk(b"BGjp")?;
        out!(self.pass; jpeg)?;
        Ok(())
    }

    /// Serialize an `FGjp` chunk.
    pub fn fgjp(&mut self, jpeg: &[u8]) -> Result<(), Error> {
        self.pass.start_chunk(b"FGjp")?;
        out!(self.pass; jpeg)?;
        Ok(())
    }

    // TODO Smmr
    // TODO copy from crate::parsing::Element
}

/// Serializer for a sequence of `BG44` chunks within a `DJVI` or `DJVU` component.
#[derive(Debug)]
pub struct SerializeBg44Chunks<'el, 'wr: 'el> {
    serial: u8,
    pass: &'el mut Pass<'wr>,
}

impl<'el, 'wr: 'el> SerializeBg44Chunks<'el, 'wr> {
    /// Serialize the next chunk in the sequence.
    pub fn chunk(
        &mut self,
        num_slices: u8,
        iw44: &[u8],
    ) -> Result<(), Error> {
        self.pass.start_chunk(b"BG44")?;
        out!(
            self.pass;
            [self.serial],
            [num_slices],
            iw44,
        )?;
        self.serial = self.serial.checked_add(1).ok_or(OverflowError)?;
        Ok(())
    }
}

/// Serializer for the chunks of a `THUM` component.
#[derive(Debug)]
pub struct SerializeThumbnails<'co, 'wr: 'co> {
    pass: &'co mut Pass<'wr>,
}

impl<'co, 'wr: 'co> SerializeThumbnails<'co, 'wr> {
    /// Serialize a `TH44` chunk.
    ///
    /// `initial_cdc` must not exceed 127.
    pub fn th44(
        &mut self,
        num_slices: u8,
        color_space: Iw44ColorSpace,
        width: u16,
        height: u16,
        initial_cdc: u8,
        iw44: &[u8],
    ) -> Result<(), Error> {
        if initial_cdc > 0x7f {
            panic!()
        }
        self.pass.start_chunk(b"TH44")?;
        let version = Iw44Version::CURRENT;
        out!(
            self.pass;
            [0], // serial number
            [num_slices],
            version.pack(color_space),
            width.to_be_bytes(),
            height.to_be_bytes(),
            [initial_cdc],
            iw44,
        )?;
        Ok(())
    }
}

/// Serialize a document into a provided writer.
///
/// The serializer makes many small writes, so make sure that the writer is buffered.
#[cfg(feature = "std")]
pub fn to_writer<T: Serialize + ?Sized>(doc: &T, writer: &mut (dyn std::io::Write + '_)) -> Result<(), Error> {
    let serializer = Serializer::first_pass();
    let okay = doc.serialize(serializer)?;
    let serializer = Serializer::second_pass(okay, ErasedOutMut::Writer(writer));
    let _okay = doc.serialize(serializer)?;
    Ok(())
}

/// Serialize a document into a buffer of bytes.
pub fn to_vec<T: Serialize + ?Sized>(doc: &T) -> Result<Vec<u8>, Error> {
    let serializer = Serializer::first_pass();
    let okay = doc.serialize(serializer)?;
    let mut buf = Vec::with_capacity(okay.total as usize);
    let serializer = Serializer::second_pass(okay, ErasedOutMut::Vec(&mut buf));
    let _okay = doc.serialize(serializer)?;
    Ok(buf)
}

#[derive(Clone, Copy, Debug)]
struct U24(u32);

impl U24 {
    fn to_be_bytes(self) -> [u8; 3] {
        let [_, b1, b2, b3] = self.0.to_be_bytes();
        [b1, b2, b3]
    }

    fn inc(&mut self) -> Result<(), OverflowError> {
        if tame!(self.0 + 1 < 1 << 24) {
            tame!(self.0 += 1);
            Ok(())
        } else {
            Err(OverflowError)
        }
    }
}

impl TryFrom<usize> for U24 {
    type Error = OverflowError;

    fn try_from(x: usize) -> Result<Self, Self::Error> {
        let x: u32 = x.try_into().map_err(|_| OverflowError)?;
        if let [0, _, _, _] = x.to_be_bytes() {
            Ok(Self(x))
        } else {
            Err(OverflowError)
        }
    }
}

/// Builder for the (uncompressed) data in an `ANTa` or `ANTz` chunk.
#[derive(Clone, Debug, Default)]
pub struct AnnotBuf {
    raw: String,
}

impl AnnotBuf {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn add(&mut self, annot: &crate::annot::Annot) -> &mut Self {
        use core::fmt::Write;
        if self.raw.is_empty() {
            let _ = write!(self.raw, "{annot}");
        } else {
            let _ = write!(self.raw, " {annot}");
        }
        self
    }

    pub fn as_str(&self) -> &str {
        &self.raw
    }
}

impl Zone {
    fn new(
        kind: ZoneKind,
        x_offset: i16,
        y_offset: i16,
        width: i16,
        height: i16,
        text_len: U24,
        num_children: U24,
    ) -> Self {
        fn cvt(x: i16) -> u16 {
            tame!((x as u16) ^ (1 << 15))
        }

        Zone {
            kind,
            x_offset: cvt(x_offset).to_be_bytes(),
            y_offset: cvt(y_offset).to_be_bytes(),
            width: cvt(width).to_be_bytes(),
            height: cvt(height).to_be_bytes(),
            _empty: [0, 0],
            text_len: text_len.to_be_bytes(),
            num_children: num_children.to_be_bytes(),
        }
    }
}

/// Builder for the (uncompressed) data in a `TXTz` chunk.
///
/// Calls to [`Self::start_zone`] and [`Self::end_zone`] must be balanced, and their nesting
/// determines the tree structure of the zones in the natural way.
#[derive(Clone, Debug)]
pub struct TxtBuf {
    raw: Vec<u8>,
    stack: Vec<(usize, U24)>,
}

impl TxtBuf {
    pub fn new(text: &str) -> Result<Self, Error> {
        let mut raw = Vec::new();
        let len: U24 = text.len().try_into()?;
        raw.extend_from_slice(&len.to_be_bytes());
        raw.extend_from_slice(text.as_bytes());
        raw.extend_from_slice(&TxtVersion::CURRENT.pack());
        Ok(Self {
            raw,
            stack: Vec::new(),
        })
    }

    pub fn start_zone(
        &mut self,
        kind: ZoneKind,
        x_offset: i16,
        y_offset: i16,
        width: i16,
        height: i16,
        text_len: usize,
    ) -> Result<(), Error> {
        let text_len: U24 = text_len.try_into()?;
        if let Some(&mut (_, ref mut count)) = self.stack.last_mut() {
            count.inc()?;
        }
        let pos = tame!(self.raw.len() + 14);
        let zone = Zone::new(
            kind,
            x_offset,
            y_offset,
            width,
            height,
            text_len,
            U24(0), // fixed up later
        );
        self.raw.extend_from_slice(zone.as_bytes());
        self.stack.push((pos, U24(0)));
        Ok(())
    }

    pub fn end_zone(&mut self) {
        let (pos, count) = self.stack.pop().unwrap();
        self.raw[pos..tame!(pos + 3)].copy_from_slice(&count.to_be_bytes());
    }

    pub fn as_bytes(&self) -> &[u8] {
        if !self.stack.is_empty() {
            panic!()
        }
        &self.raw
    }
}

/// Builder for the "zones" data in a `TXTa` chunk.
///
/// Calls to [`Self::start_zone`] and [`Self::end_zone`] must be balanced, and their nesting
/// determines the tree structure of the zones in the natural way.
#[derive(Clone, Debug, Default)]
pub struct ZoneBuf {
    stack: Vec<(usize, U24)>,
    inner: Vec<Zone>,
}

impl ZoneBuf {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn start_zone(
        &mut self,
        kind: ZoneKind,
        x_offset: i16,
        y_offset: i16,
        width: i16,
        height: i16,
        text_len: usize,
    ) -> Result<&mut Self, Error> {
        let text_len = text_len.try_into()?;
        if let Some(&mut (_, ref mut n)) = self.stack.last_mut() {
            n.inc()?;
        }
        let pos = self.inner.len();
        let zone = Zone::new(
            kind,
            x_offset,
            y_offset,
            width,
            height,
            text_len,
            U24(0), // fixed up later
        );
        self.inner.push(zone);
        self.stack.push((pos, U24(0)));
        Ok(self)
    }

    pub fn end_zone(&mut self) -> &mut Self {
        let (i, n) = self.stack.pop().unwrap();
        self.inner[i].num_children = n.to_be_bytes();
        self
    }

    pub fn as_zones(&self) -> &[Zone] {
        if !self.stack.is_empty() {
            panic!()
        }
        &self.inner
    }
}

/// Builder for the (uncompressed) data in a `NAVM` chunk.
///
/// Calls to [`Self::start_bookmark`] and [`Self::end_bookmark`] must be balanced, and their nesting
/// determines the tree structure of the bookmarks in the natural way.
#[derive(Clone, Debug, Default)]
pub struct BookmarkBuf {
    raw: Vec<u8>,
    count: u16,
    stack: Vec<(usize, u8)>,
}

impl BookmarkBuf {
    pub fn new() -> Self {
        Self { raw: alloc::vec![0, 0], count: 0, stack: Vec::new() }
    }

    pub fn start_bookmark(&mut self, description: &str, url: &str) -> Result<&mut Self, Error> {
        let description_len: U24 = description.len().try_into()?;
        let url_len: U24 = url.len().try_into()?;
        self.count = self.count.checked_add(1).ok_or(OverflowError)?;
        self.raw[0..2].copy_from_slice(&self.count.to_be_bytes());
        if let Some(&mut (_, ref mut n)) = self.stack.last_mut() {
            *n = (*n).checked_add(1).ok_or(OverflowError)?;
        }
        self.stack.push((self.raw.len(), 0));
        self.raw.push(0); // fixed up later
        self.raw.extend_from_slice(&description_len.to_be_bytes());
        self.raw.extend_from_slice(description.as_bytes());
        self.raw.extend_from_slice(&url_len.to_be_bytes());
        self.raw.extend_from_slice(url.as_bytes());
        Ok(self)
    }

    pub fn end_bookmark(&mut self) -> &mut Self {
        let (i, n) = self.stack.pop().unwrap();
        self.raw[i] = n;
        self
    }

    pub fn as_bytes(&self) -> &[u8] {
        if !self.stack.is_empty() {
            panic!()
        }
        &self.raw
    }
}