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
// Copyright 2018 the Tectonic Project
// Licensed under the MIT License.

#![deny(missing_docs)]

//! A decoder for the XDV and SPX file formats used by Tectonic and XeTeX.
//!
//! Both of these file formats are derived from the venerable “device
//! independent” (DVI) format used by TeX. The XDV format (name presumably
//! meaning something like “XeTeX DVI” or “extended DVI”) adds a few codes
//! needed to express native fonts in the output. The SPX format
//! (“semantically-paginated XDV”) is essentially the same as XDV, but
//! expresses output that is not paginated for print — this is what Tectonic
//! uses to produce its HTML output.

use byteorder::{BigEndian, ByteOrder};
use std::error;
use std::fmt::{Debug, Display, Error as FmtError, Formatter};
use std::io::{Error as IoError, Read};
use std::marker::PhantomData;
use std::mem;

/// Errors that can occur when parsing XDV/SPX files.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum XdvError {
    /// The file is malformed in some way. The error occurred at the byte
    /// offset indicated in the error value.
    Malformed(u64),

    /// An illegal opcode was encountered. The error occurred at the byte
    /// offset indicated in the error value.
    IllegalOpcode(u8, u64),

    /// Stream ended before expected.
    UnexpectedEndOfStream,
}

impl Display for XdvError {
    fn fmt(&self, f: &mut Formatter) -> Result<(), FmtError> {
        match *self {
            XdvError::Malformed(offset) => {
                write!(f, "unexpected XDV data at byte offset {}", offset)
            }
            XdvError::IllegalOpcode(opcode, offset) => {
                write!(f, "illegal XDV opcode {} at byte offset {}", opcode, offset)
            }
            XdvError::UnexpectedEndOfStream => write!(f, "stream ended unexpectedly soon"),
        }
    }
}

impl error::Error for XdvError {
    fn description(&self) -> &str {
        match *self {
            XdvError::Malformed(_) => "malformed XDV data",
            XdvError::IllegalOpcode(_, _) => "illegal XDV opcode",
            XdvError::UnexpectedEndOfStream => "stream ended unexpectedly soon",
        }
    }

    fn cause(&self) -> Option<&dyn error::Error> {
        None
    }
}

/// In case you want to use String as your error type.
impl From<XdvError> for String {
    fn from(e: XdvError) -> Self {
        format!("{}", e)
    }
}

impl XdvError {
    /// We can't implement this as a From trait on InternalError because it
    /// conflicts with the generic From: XdvError satisfies `Debug +
    /// From<XdvError>`!
    fn into_internal<T: Debug + From<XdvError>>(self) -> InternalError<T> {
        InternalError::Other(self.into())
    }
}

/// This internal error type lets us leverage Results to conveniently
/// check for the need-more-data case, while not exporting that type
/// to the outside world. If NeedMoreData were part of XdvError, there
/// would also be a problem checking for NeedMoreData once that type
/// was converted into the caller's Error type.
#[derive(Debug)]
enum InternalError<T: Debug + From<XdvError>> {
    NeedMoreData,
    Other(T),
}

type InternalResult<T, E> = Result<T, InternalError<E>>;

impl<T: Debug + From<XdvError>> From<T> for InternalError<T> {
    fn from(e: T) -> Self {
        InternalError::Other(e)
    }
}

/// Types implementing this trait accept events from the XDV parser.
pub trait XdvEvents {
    /// An error type returned by the handler functions defined in this trait. It
    /// must implement `From<XdvError>`.
    type Error: Debug + From<XdvError>;

    /// Handle the XDV header
    #[allow(unused)] // <= prevents underscore-prefixed names from showing up in docs
    fn handle_header(&mut self, filetype: FileType, comment: &[u8]) -> Result<(), Self::Error> {
        Ok(())
    }

    /// Begin a new page.
    #[allow(unused)]
    fn handle_begin_page(
        &mut self,
        counters: &[i32],
        previous_bop: i32,
    ) -> Result<(), Self::Error> {
        Ok(())
    }

    /// Handle a `\special`.
    #[allow(unused)]
    fn handle_special(&mut self, contents: &[u8]) -> Result<(), Self::Error> {
        Ok(())
    }

    /// Handle a sequence of characters without intervening commands
    #[allow(unused)]
    fn handle_char_run(&mut self, chars: &[i32]) -> Result<(), Self::Error> {
        Ok(())
    }
}

/// State for parsing an XDV file.
#[derive(Debug)]
pub struct XdvParser<T: XdvEvents> {
    events: T,
    filetype: FileType,
    state: ParserState,
    stack: Vec<State>,
    cur_font_num: Option<i32>,
    offset: u64,
    cur_char_run: Vec<i32>,
}

/// Which type of file is being parsed.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum FileType {
    /// Traditional XDV.
    Xdv,

    /// Tectonic’s SPX (“semanticallly-paginated XDV”).
    Spx,
}

impl Display for FileType {
    fn fmt(&self, f: &mut Formatter) -> Result<(), FmtError> {
        write!(
            f,
            "{}",
            match *self {
                FileType::Xdv => "XDV",
                FileType::Spx => "SPX",
            }
        )
    }
}

/// The current state of the parser.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum ParserState {
    /// We have just started parsing.
    Preamble,

    /// Between pages.
    BetweenPages,

    /// In a page.
    InPage,

    /// Reading font definitions and nops in the postamble.
    PostambleFontDefinitions,

    /// We read through the post-postamble and are satisfied with this file.
    Finished,
}

impl<T: XdvEvents> XdvParser<T> {
    /// Create a new XDV/SPX parser.
    ///
    /// Methods implemented by *events* will be called as various items are
    /// encountered in the file.
    pub fn new(events: T) -> Self {
        XdvParser {
            events,
            filetype: FileType::Xdv,
            state: ParserState::Preamble,
            stack: Vec::new(),
            cur_font_num: None,
            offset: 0,
            cur_char_run: Vec::new(),
        }
    }

    /// Parse an entire XDV/SPX stream.
    ///
    /// Returns the input “events” variable and the number of bytes that were
    /// processed.
    ///
    /// Because the `io::Read` trait is used, the event result type must
    /// implement `From<io::Error>` as well as `From<XdvError>`.
    ///
    /// The initial buffer size is hardcoded to 4096 bytes. It doubles in size
    /// every time the parser is unable to make any progress at all in the
    /// current chunk, which should be a rare circumstance.
    pub fn process<R: Read>(mut stream: R, events: T) -> Result<(T, u64), T::Error>
    where
        T::Error: From<IoError>,
    {
        const BUF_SIZE: usize = 4096;
        let mut parser = Self::new(events);
        let mut buf = Vec::with_capacity(BUF_SIZE);
        unsafe {
            buf.set_len(BUF_SIZE);
        }
        let mut n_saved_bytes = 0;

        loop {
            let n_read = stream.read(&mut buf[n_saved_bytes..])?;
            let n_in_buffer = n_saved_bytes + n_read;
            let n_consumed = parser.parse(&buf[..n_in_buffer])?;
            n_saved_bytes = n_in_buffer - n_consumed;

            if n_consumed != 0 && n_saved_bytes != 0 {
                // The current parse did not consume the full buffer, so we
                // must copy the un-parsed bytes to its beginning. The next
                // time that we read data, we will append to these
                // already-read bytes so that the parser gets a nice
                // contiguous set of bytes to look at. The copy may involve
                // overlapping memory regions (imagine we read 4096 bytes but
                // only consume 1) so we have to get unsafe.
                use std::ptr;
                let ptr = buf.as_mut_ptr();
                unsafe {
                    ptr::copy(ptr.add(n_consumed), ptr, n_saved_bytes);
                }
            }

            if n_in_buffer != 0 && n_consumed == 0 {
                // We're going to need a bigger buffer in order to handle whatever
                // we're reading. Let's double it.
                let len = buf.len();
                buf.reserve(len);
                unsafe {
                    buf.set_len(2 * len);
                }
            }

            if n_read == 0 {
                break;
            }
        }

        let n_bytes = parser.current_offset();
        Ok((parser.finish()?, n_bytes))
    }

    /// Parse the next chunk of XDV data.
    ///
    /// Returns the number of bytes consumed from the input buffer. If this is
    /// not the same as the buffer size, some of the existing bytes must be
    /// re-fed to the parser. If the returned value is 0, you need a bigger
    /// buffer in order to be able to parse the next directive.
    #[allow(clippy::cognitive_complexity)]
    pub fn parse(&mut self, chunk: &[u8]) -> Result<usize, T::Error> {
        let mut cursor = Cursor::new(chunk, self.offset);

        while cursor.remaining() > 0 {
            if self.state == ParserState::Finished {
                cursor.consume_remainder();
                break;
            }

            let opcode = cursor.get_u8().unwrap();
            let mut char_run_ended = true; // most commands end runs of characters

            let rv = match opcode {
                // This is the least ugly way I've found to map the u8 to the
                // symbolic enum values.
                oc if oc == Opcode::Noop as u8 => {
                    char_run_ended = false;
                    Ok(())
                }

                oc if oc >= Opcode::DefineFont1 as u8 && oc <= Opcode::DefineFont4 as u8 => {
                    char_run_ended = false;
                    self.do_define_font(oc, &mut cursor)
                }

                oc if oc == Opcode::DefineNativeFont as u8 => {
                    char_run_ended = false;
                    self.do_define_native_font(oc, &mut cursor)
                }

                oc if oc == Opcode::BeginningOfPage as u8 => {
                    self.do_beginning_of_page(oc, &mut cursor)
                }

                oc if oc == Opcode::EndOfPage as u8 => self.do_end_of_page(oc, &mut cursor),

                oc if oc == Opcode::PushStack as u8 => {
                    char_run_ended = false;
                    self.do_push_stack(oc, &mut cursor)
                }

                oc if oc == Opcode::PopStack as u8 => self.do_pop_stack(oc, &mut cursor),

                oc if oc >= Opcode::Right1 as u8 && oc <= Opcode::Right4 as u8 => {
                    self.do_right(oc, &mut cursor)
                }

                oc if oc == Opcode::RightByW as u8 => self.do_right_by_w(oc, &mut cursor),

                oc if oc >= Opcode::SetW1 as u8 && oc <= Opcode::SetW4 as u8 => {
                    self.do_set_w(oc, &mut cursor)
                }

                oc if oc == Opcode::RightByX as u8 => self.do_right_by_x(oc, &mut cursor),

                oc if oc >= Opcode::SetX1 as u8 && oc <= Opcode::SetX4 as u8 => {
                    self.do_set_x(oc, &mut cursor)
                }

                oc if oc >= Opcode::Down1 as u8 && oc <= Opcode::Down4 as u8 => {
                    self.do_down(oc, &mut cursor)
                }

                oc if oc == Opcode::DownByY as u8 => self.do_down_by_y(oc, &mut cursor),

                oc if oc >= Opcode::SetY1 as u8 && oc <= Opcode::SetY4 as u8 => {
                    self.do_set_y(oc, &mut cursor)
                }

                oc if oc == Opcode::DownByZ as u8 => self.do_down_by_z(oc, &mut cursor),

                oc if oc >= Opcode::SetZ1 as u8 && oc <= Opcode::SetZ4 as u8 => {
                    self.do_set_z(oc, &mut cursor)
                }

                oc if oc >= Opcode::SetFontNumber0 as u8 && oc <= Opcode::SetFontNumber63 as u8 => {
                    self.do_set_font_number(oc, &mut cursor)
                }

                oc if oc >= Opcode::SetFont1 as u8 && oc <= Opcode::SetFont4 as u8 => {
                    self.do_set_font(oc, &mut cursor)
                }

                oc if oc >= Opcode::SetCharNumber0 as u8
                    && oc <= Opcode::SetCharNumber127 as u8 =>
                {
                    char_run_ended = false;
                    self.do_set_char_number(oc, &mut cursor)
                }

                oc if oc >= Opcode::SetChar1 as u8 && oc <= Opcode::SetChar4 as u8 => {
                    char_run_ended = false;
                    self.do_set_char(oc, &mut cursor)
                }

                oc if oc == Opcode::SetGlyphs as u8 => self.do_set_glyphs(oc, &mut cursor),

                oc if oc == Opcode::SetTextAndGlyphs as u8 => {
                    self.do_set_text_and_glyphs(oc, &mut cursor)
                }

                oc if oc >= Opcode::Special1 as u8 && oc <= Opcode::Special4 as u8 => {
                    self.do_special(oc, &mut cursor)
                }

                oc if oc == Opcode::Preamble as u8 => self.do_preamble(oc, &mut cursor),

                oc if oc == Opcode::Postamble as u8 => self.do_postamble(oc, &mut cursor),

                oc if oc == Opcode::DoublePostamble as u8 => {
                    self.do_double_postamble(oc, &mut cursor)
                }

                _ => {
                    return Err(XdvError::IllegalOpcode(opcode, cursor.global_offset()).into());
                }
            };

            match rv {
                Ok(()) => {
                    cursor.checkpoint(); // Opcode was successfully processed.
                }
                Err(InternalError::NeedMoreData) => {
                    break;
                }
                Err(InternalError::Other(e)) => {
                    return Err(e);
                }
            }

            if char_run_ended && !self.cur_char_run.is_empty() {
                self.events.handle_char_run(&self.cur_char_run)?;
                self.cur_char_run.clear();
            }
        }

        self.offset += cursor.checkpoint as u64;
        Ok(cursor.checkpoint)
    }

    fn do_preamble(&mut self, opcode: u8, cursor: &mut Cursor<T>) -> InternalResult<(), T::Error> {
        if self.state != ParserState::Preamble {
            return Err(XdvError::IllegalOpcode(opcode, cursor.global_offset()).into_internal());
        }

        self.filetype = match cursor.get_u8()? {
            b if b == IdByte::Xdv as u8 => FileType::Xdv,
            b if b == IdByte::Spx as u8 => FileType::Spx,
            _ => {
                return Err(XdvError::Malformed(cursor.global_offset()).into_internal());
            }
        };

        cursor.assert_u32(25_400_000)?; // dimensions unit numerator
        cursor.assert_u32(473_628_672)?; // dimensions unit denominator
        cursor.get_u32()?; // 'mag' factor
        let n_comment = cursor.get_u8()?;
        self.events
            .handle_header(self.filetype, cursor.get_slice(n_comment as usize)?)?;

        self.state = ParserState::BetweenPages;
        Ok(())
    }

    fn do_define_font(
        &mut self,
        opcode: u8,
        cursor: &mut Cursor<T>,
    ) -> InternalResult<(), T::Error> {
        if self.state == ParserState::Preamble {
            return Err(XdvError::IllegalOpcode(opcode, cursor.global_offset()).into_internal());
        }

        let _font_num = cursor.get_compact_i32_smpos(opcode - Opcode::DefineFont1 as u8)?;
        let _checksum = cursor.get_u32()?;
        let _scale_factor = cursor.get_u32()?;
        let _design_size = cursor.get_u32()?;
        let area_len = cursor.get_u8()?;
        let name_len = cursor.get_u8()?;
        // XXX TEMP
        use std::str::from_utf8;
        let _area_str = from_utf8(cursor.get_slice(area_len as usize)?)
            .unwrap()
            .to_owned();
        let _name_str = from_utf8(cursor.get_slice(name_len as usize)?)
            .unwrap()
            .to_owned();
        Ok(())
    }

    fn do_define_native_font(
        &mut self,
        opcode: u8,
        cursor: &mut Cursor<T>,
    ) -> InternalResult<(), T::Error> {
        if self.state == ParserState::Preamble {
            return Err(XdvError::IllegalOpcode(opcode, cursor.global_offset()).into_internal());
        }

        let _font_num = cursor.get_i32()?;
        let _size = cursor.get_i32()?; // fixed-point
        let flags = cursor.get_u16()?;
        let name_len = cursor.get_u8()?;
        // XXX TEMP
        use std::str::from_utf8;
        let _name_str = from_utf8(cursor.get_slice(name_len as usize)?)
            .unwrap()
            .to_owned();
        let _face_index = cursor.get_u32()?;

        let _color_rgba = if flags & NativeFontFlags::Colored as u16 != 0 {
            Some(cursor.get_u32()?)
        } else {
            None
        };

        let _extend = if flags & NativeFontFlags::Extend as u16 != 0 {
            Some(cursor.get_u32()?) // fixed-point
        } else {
            None
        };

        let _slant = if flags & NativeFontFlags::Slant as u16 != 0 {
            Some(cursor.get_u32()?) // fixed-point
        } else {
            None
        };

        let _embolden = if flags & NativeFontFlags::Embolden as u16 != 0 {
            Some(cursor.get_u32()?) // fixed-point
        } else {
            None
        };

        Ok(())
    }

    fn do_beginning_of_page(
        &mut self,
        opcode: u8,
        cursor: &mut Cursor<T>,
    ) -> InternalResult<(), T::Error> {
        if self.state != ParserState::BetweenPages {
            return Err(XdvError::IllegalOpcode(opcode, cursor.global_offset()).into_internal());
        }

        let mut counters = [0i32; 10];

        for counter in &mut counters {
            *counter = cursor.get_i32()?;
        }

        let previous_bop = cursor.get_i32()?; // previous beginning-of-page marker
        self.events.handle_begin_page(&counters, previous_bop)?;

        self.state = ParserState::InPage;
        self.stack.clear();
        self.stack.push(State::new());
        self.cur_font_num = None;
        Ok(())
    }

    fn do_end_of_page(
        &mut self,
        opcode: u8,
        cursor: &mut Cursor<T>,
    ) -> InternalResult<(), T::Error> {
        if self.state != ParserState::InPage {
            return Err(XdvError::IllegalOpcode(opcode, cursor.global_offset()).into_internal());
        }

        if self.stack.len() != 1 {
            return Err(XdvError::Malformed(cursor.global_offset()).into_internal());
        }

        self.state = ParserState::BetweenPages;
        Ok(())
    }

    fn do_push_stack(
        &mut self,
        opcode: u8,
        cursor: &mut Cursor<T>,
    ) -> InternalResult<(), T::Error> {
        if self.state != ParserState::InPage {
            return Err(XdvError::IllegalOpcode(opcode, cursor.global_offset()).into_internal());
        }

        let dup = self.stack.last().unwrap().clone();
        self.stack.push(dup);
        Ok(())
    }

    fn do_pop_stack(&mut self, opcode: u8, cursor: &mut Cursor<T>) -> InternalResult<(), T::Error> {
        if self.state != ParserState::InPage {
            return Err(XdvError::IllegalOpcode(opcode, cursor.global_offset()).into_internal());
        }

        if self.stack.len() < 2 {
            return Err(XdvError::Malformed(cursor.global_offset()).into_internal());
        }

        self.stack.pop();
        Ok(())
    }

    fn do_right(&mut self, opcode: u8, cursor: &mut Cursor<T>) -> InternalResult<(), T::Error> {
        if self.state != ParserState::InPage {
            return Err(XdvError::IllegalOpcode(opcode, cursor.global_offset()).into_internal());
        }

        let n = cursor.get_compact_i32_smneg(opcode - Opcode::Right1 as u8)?;
        self.stack.last_mut().unwrap().h += n;
        Ok(())
    }

    fn do_right_by_w(
        &mut self,
        opcode: u8,
        cursor: &mut Cursor<T>,
    ) -> InternalResult<(), T::Error> {
        if self.state != ParserState::InPage {
            return Err(XdvError::IllegalOpcode(opcode, cursor.global_offset()).into_internal());
        }

        let state = self.stack.last_mut().unwrap();
        state.h += state.w;
        Ok(())
    }

    fn do_set_w(&mut self, opcode: u8, cursor: &mut Cursor<T>) -> InternalResult<(), T::Error> {
        if self.state != ParserState::InPage {
            return Err(XdvError::IllegalOpcode(opcode, cursor.global_offset()).into_internal());
        }

        let n = cursor.get_compact_i32_smneg(opcode - Opcode::SetW1 as u8)?;
        let state = self.stack.last_mut().unwrap();
        state.w = n;
        state.h += n;
        Ok(())
    }

    fn do_right_by_x(
        &mut self,
        opcode: u8,
        cursor: &mut Cursor<T>,
    ) -> InternalResult<(), T::Error> {
        if self.state != ParserState::InPage {
            return Err(XdvError::IllegalOpcode(opcode, cursor.global_offset()).into_internal());
        }

        let state = self.stack.last_mut().unwrap();
        state.h += state.x;
        Ok(())
    }

    fn do_set_x(&mut self, opcode: u8, cursor: &mut Cursor<T>) -> InternalResult<(), T::Error> {
        if self.state != ParserState::InPage {
            return Err(XdvError::IllegalOpcode(opcode, cursor.global_offset()).into_internal());
        }

        let n = cursor.get_compact_i32_smneg(opcode - Opcode::SetX1 as u8)?;
        let state = self.stack.last_mut().unwrap();
        state.x = n;
        state.h += n;
        Ok(())
    }

    fn do_down(&mut self, opcode: u8, cursor: &mut Cursor<T>) -> InternalResult<(), T::Error> {
        if self.state != ParserState::InPage {
            return Err(XdvError::IllegalOpcode(opcode, cursor.global_offset()).into_internal());
        }

        let n = cursor.get_compact_i32_smneg(opcode - Opcode::Down1 as u8)?;
        self.stack.last_mut().unwrap().v += n;
        Ok(())
    }

    fn do_down_by_y(&mut self, opcode: u8, cursor: &mut Cursor<T>) -> InternalResult<(), T::Error> {
        if self.state != ParserState::InPage {
            return Err(XdvError::IllegalOpcode(opcode, cursor.global_offset()).into_internal());
        }

        let state = self.stack.last_mut().unwrap();
        state.v += state.y;
        Ok(())
    }

    fn do_set_y(&mut self, opcode: u8, cursor: &mut Cursor<T>) -> InternalResult<(), T::Error> {
        if self.state != ParserState::InPage {
            return Err(XdvError::IllegalOpcode(opcode, cursor.global_offset()).into_internal());
        }

        let n = cursor.get_compact_i32_smneg(opcode - Opcode::SetY1 as u8)?;
        let state = self.stack.last_mut().unwrap();
        state.y = n;
        state.v += n;
        Ok(())
    }

    fn do_down_by_z(&mut self, opcode: u8, cursor: &mut Cursor<T>) -> InternalResult<(), T::Error> {
        if self.state != ParserState::InPage {
            return Err(XdvError::IllegalOpcode(opcode, cursor.global_offset()).into_internal());
        }

        let state = self.stack.last_mut().unwrap();
        state.v += state.z;
        Ok(())
    }

    fn do_set_z(&mut self, opcode: u8, cursor: &mut Cursor<T>) -> InternalResult<(), T::Error> {
        if self.state != ParserState::InPage {
            return Err(XdvError::IllegalOpcode(opcode, cursor.global_offset()).into_internal());
        }

        let n = cursor.get_compact_i32_smneg(opcode - Opcode::SetZ1 as u8)?;
        let state = self.stack.last_mut().unwrap();
        state.z = n;
        state.v += n;
        Ok(())
    }

    /// This variant uses the opcode to encode the font number.
    fn do_set_font_number(
        &mut self,
        opcode: u8,
        cursor: &mut Cursor<T>,
    ) -> InternalResult<(), T::Error> {
        if self.state != ParserState::InPage {
            return Err(XdvError::IllegalOpcode(opcode, cursor.global_offset()).into_internal());
        }

        self.cur_font_num = Some(i32::from(opcode - Opcode::SetFontNumber0 as u8));
        Ok(())
    }

    /// This variant takes an argument that encodes the font number.
    fn do_set_font(&mut self, opcode: u8, cursor: &mut Cursor<T>) -> InternalResult<(), T::Error> {
        if self.state != ParserState::InPage {
            return Err(XdvError::IllegalOpcode(opcode, cursor.global_offset()).into_internal());
        }

        self.cur_font_num = Some(cursor.get_compact_i32_smpos(opcode - Opcode::SetFont1 as u8)?);
        Ok(())
    }

    /// This variant uses the opcode to encode the character number.
    fn do_set_char_number(
        &mut self,
        opcode: u8,
        cursor: &mut Cursor<T>,
    ) -> InternalResult<(), T::Error> {
        if self.state != ParserState::InPage {
            return Err(XdvError::IllegalOpcode(opcode, cursor.global_offset()).into_internal());
        }

        let char_num = opcode - Opcode::SetCharNumber0 as u8;
        self.cur_char_run.push(i32::from(char_num));
        Ok(())
    }

    /// This variant takes an argument that encodes the character number.
    fn do_set_char(&mut self, opcode: u8, cursor: &mut Cursor<T>) -> InternalResult<(), T::Error> {
        if self.state != ParserState::InPage {
            return Err(XdvError::IllegalOpcode(opcode, cursor.global_offset()).into_internal());
        }

        let char_num = cursor.get_compact_i32_smpos(opcode - Opcode::SetChar1 as u8)?;
        self.cur_char_run.push(char_num as i32);
        Ok(())
    }

    fn do_set_glyphs(
        &mut self,
        opcode: u8,
        cursor: &mut Cursor<T>,
    ) -> InternalResult<(), T::Error> {
        if self.state != ParserState::InPage {
            return Err(XdvError::IllegalOpcode(opcode, cursor.global_offset()).into_internal());
        }

        let _width = cursor.get_i32()?;
        let n_glyphs = cursor.get_u16()?;

        for _ in 0..n_glyphs {
            let _x = cursor.get_u32()?;
            let _y = cursor.get_u32()?;
        }

        for _ in 0..n_glyphs {
            let _glyph_id = cursor.get_i16()?;
        }

        Ok(())
    }

    fn do_set_text_and_glyphs(
        &mut self,
        opcode: u8,
        cursor: &mut Cursor<T>,
    ) -> InternalResult<(), T::Error> {
        if self.state != ParserState::InPage {
            return Err(XdvError::IllegalOpcode(opcode, cursor.global_offset()).into_internal());
        }

        let n_chars = cursor.get_u16()?;
        let mut chars = Vec::new();

        for _ in 0..n_chars {
            chars.push(cursor.get_u16()?);
        }

        let _width = cursor.get_i32()?;
        let n_glyphs = cursor.get_u16()?;

        for _ in 0..n_glyphs {
            let _x = cursor.get_u32()?;
            let _y = cursor.get_u32()?;
        }

        for _ in 0..n_glyphs {
            let _glyph_id = cursor.get_i16()?;
        }

        Ok(())
    }

    fn do_special(&mut self, opcode: u8, cursor: &mut Cursor<T>) -> InternalResult<(), T::Error> {
        if self.state != ParserState::InPage {
            return Err(XdvError::IllegalOpcode(opcode, cursor.global_offset()).into_internal());
        }

        let n = cursor.get_compact_u32(opcode - Opcode::Special1 as u8)?;
        self.events.handle_special(cursor.get_slice(n as usize)?)?;

        Ok(())
    }

    fn do_postamble(&mut self, opcode: u8, cursor: &mut Cursor<T>) -> InternalResult<(), T::Error> {
        if self.state != ParserState::BetweenPages {
            return Err(XdvError::IllegalOpcode(opcode, cursor.global_offset()).into_internal());
        }

        cursor.get_u32()?; // last_bop
        cursor.assert_u32(25_400_000)?; // dimensions unit numerator
        cursor.assert_u32(473_628_672)?; // dimensions unit denominator
        cursor.get_u32()?; // 'mag' factor
        cursor.get_u32()?; // largest height+depth of tallest page
        cursor.get_u32()?; // largest width of widest page
        cursor.get_u16()?; // maximum stack depth
        cursor.get_u16()?; // number of pages

        self.state = ParserState::PostambleFontDefinitions;
        Ok(())
    }

    fn do_double_postamble(
        &mut self,
        opcode: u8,
        cursor: &mut Cursor<T>,
    ) -> InternalResult<(), T::Error> {
        if self.state != ParserState::PostambleFontDefinitions {
            return Err(XdvError::IllegalOpcode(opcode, cursor.global_offset()).into_internal());
        }

        cursor.get_u32()?; // pointer to postamble
        cursor.assert_u8(match self.filetype {
            FileType::Xdv => IdByte::Xdv,
            FileType::Spx => IdByte::Spx,
        } as u8)?;
        cursor.assert_u32(0xDFDF_DFDF)?; // at least four 0xDF's

        self.state = ParserState::Finished;
        Ok(())
    }

    /// Get the current byte offset of the parsing.
    pub fn current_offset(&self) -> u64 {
        self.offset
    }

    /// Finish parsing, consume this object, and return the underlying event
    /// handler, assuming all went well.
    pub fn finish(self) -> Result<T, T::Error> {
        if self.state != ParserState::Finished {
            return Err(XdvError::UnexpectedEndOfStream.into());
        }

        Ok(self.events)
    }
}

/// The states that may be stacked while processing the DVI.
#[derive(Clone, Debug, Eq, PartialEq)]
struct State {
    pub h: i32,
    pub v: i32,
    pub w: i32,
    pub x: i32,
    pub y: i32,
    pub z: i32,
}

impl State {
    pub fn new() -> Self {
        State {
            h: 0,
            v: 0,
            w: 0,
            x: 0,
            y: 0,
            z: 0,
        }
    }
}

/// A simple cursor on a buffer.
#[derive(Debug)]
struct Cursor<'a, T: XdvEvents> {
    /// The *remaining* unprocessed bytes.
    buf: &'a [u8],

    /// How many bytes from the *original* chunk buffer have been fully processed.
    pub checkpoint: usize,

    /// How many bytes from the *original* chunk buffer we have looked at.
    offset: usize,

    /// The offset into the *total stream* that the original chunk buffer was
    /// at.
    global_offset: u64,

    /// Helps us avoid tedious type annotations.
    _events: PhantomData<T>,
}

impl<'a, T: XdvEvents> Cursor<'a, T> {
    pub fn new(buf: &'a [u8], global_offset: u64) -> Self {
        Cursor {
            buf,
            checkpoint: 0,
            offset: 0,
            global_offset,
            _events: PhantomData,
        }
    }

    pub fn remaining(&self) -> usize {
        self.buf.len()
    }

    pub fn global_offset(&self) -> u64 {
        self.global_offset + self.offset as u64
    }

    pub fn checkpoint(&mut self) {
        self.checkpoint = self.offset;
    }

    pub fn consume_remainder(&mut self) {
        self.offset += self.buf.len();
        self.checkpoint();
        self.buf = &[0u8; 0];
    }

    pub fn get_u8(&mut self) -> InternalResult<u8, T::Error> {
        if self.buf.is_empty() {
            return Err(InternalError::NeedMoreData);
        }

        let rv = self.buf[0];
        self.buf = &self.buf[1..];
        self.offset += 1;
        Ok(rv)
    }

    pub fn assert_u8(&mut self, expected: u8) -> InternalResult<(), T::Error> {
        if self.get_u8()? == expected {
            Ok(())
        } else {
            Err(XdvError::Malformed(self.global_offset + self.offset as u64 - 1).into_internal())
        }
    }

    pub fn get_i8(&mut self) -> InternalResult<i8, T::Error> {
        if self.buf.is_empty() {
            return Err(InternalError::NeedMoreData);
        }

        let rv = unsafe { mem::transmute(self.buf[0]) };
        self.buf = &self.buf[1..];
        self.offset += 1;
        Ok(rv)
    }

    pub fn get_u16(&mut self) -> InternalResult<u16, T::Error> {
        if self.buf.len() < 2 {
            return Err(InternalError::NeedMoreData);
        }

        let rv = BigEndian::read_u16(&self.buf[..2]);
        self.buf = &self.buf[2..];
        self.offset += 2;
        Ok(rv)
    }

    pub fn get_i16(&mut self) -> InternalResult<i16, T::Error> {
        if self.buf.len() < 2 {
            return Err(InternalError::NeedMoreData);
        }

        let rv = BigEndian::read_i16(&self.buf[..2]);
        self.buf = &self.buf[2..];
        self.offset += 2;
        Ok(rv)
    }

    pub fn get_u24(&mut self) -> InternalResult<u32, T::Error> {
        if self.buf.len() < 3 {
            return Err(InternalError::NeedMoreData);
        }

        let rv = BigEndian::read_u24(&self.buf[..3]);
        self.buf = &self.buf[3..];
        self.offset += 3;
        Ok(rv)
    }

    pub fn get_i24(&mut self) -> InternalResult<i32, T::Error> {
        if self.buf.len() < 3 {
            return Err(InternalError::NeedMoreData);
        }

        let rv = BigEndian::read_i24(&self.buf[..3]);
        self.buf = &self.buf[3..];
        self.offset += 3;
        Ok(rv)
    }

    pub fn get_u32(&mut self) -> InternalResult<u32, T::Error> {
        if self.buf.len() < 4 {
            return Err(InternalError::NeedMoreData);
        }

        let rv = BigEndian::read_u32(&self.buf[..4]);
        self.buf = &self.buf[4..];
        self.offset += 4;
        Ok(rv)
    }

    pub fn get_compact_u32(&mut self, size_marker: u8) -> InternalResult<u32, T::Error> {
        match size_marker {
            0 => Ok(u32::from(self.get_u8()?)),
            1 => Ok(u32::from(self.get_u16()?)),
            2 => Ok(self.get_u24()?),
            3 => self.get_u32(),
            _ => Err(XdvError::Malformed(self.global_offset()).into_internal()),
        }
    }

    pub fn assert_u32(&mut self, expected: u32) -> InternalResult<(), T::Error> {
        if self.get_u32()? == expected {
            Ok(())
        } else {
            Err(XdvError::Malformed(self.global_offset + self.offset as u64 - 4).into_internal())
        }
    }

    pub fn get_i32(&mut self) -> InternalResult<i32, T::Error> {
        if self.buf.len() < 4 {
            return Err(InternalError::NeedMoreData);
        }

        let rv = BigEndian::read_i32(&self.buf[..4]);
        self.buf = &self.buf[4..];
        self.offset += 4;
        Ok(rv)
    }

    /// This variation lets small values be signed (used by right, down, etc).
    pub fn get_compact_i32_smneg(&mut self, size_marker: u8) -> InternalResult<i32, T::Error> {
        match size_marker {
            0 => Ok(i32::from(self.get_i8()?)),
            1 => Ok(i32::from(self.get_i16()?)),
            2 => Ok(self.get_i24()?),
            3 => self.get_i32(),
            _ => Err(XdvError::Malformed(self.global_offset()).into_internal()),
        }
    }

    /// This variation has unsigned small values (used by fnt_def).
    pub fn get_compact_i32_smpos(&mut self, size_marker: u8) -> InternalResult<i32, T::Error> {
        match size_marker {
            0 => Ok(i32::from(self.get_u8()?)),
            1 => Ok(i32::from(self.get_u16()?)),
            2 => Ok(self.get_u24()? as i32),
            3 => self.get_i32(),
            _ => Err(XdvError::Malformed(self.global_offset()).into_internal()),
        }
    }

    pub fn get_slice(&mut self, n: usize) -> InternalResult<&[u8], T::Error> {
        if self.buf.len() < n {
            return Err(InternalError::NeedMoreData);
        }

        let (rv, remainder) = self.buf.split_at(n);
        self.buf = remainder;
        self.offset += n;
        Ok(rv)
    }
}

/// XDV opcodes.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[repr(u8)]
enum Opcode {
    SetCharNumber0 = 0,
    SetCharNumber127 = 127,
    SetChar1 = 128,
    SetChar4 = 131,
    Noop = 138,
    BeginningOfPage = 139,
    EndOfPage = 140,
    PushStack = 141,
    PopStack = 142,
    Right1 = 143,
    Right4 = 146,
    RightByW = 147,
    SetW1 = 148,
    SetW4 = 151,
    RightByX = 152,
    SetX1 = 153,
    SetX4 = 156,
    Down1 = 157,
    Down4 = 160,
    DownByY = 161,
    SetY1 = 162,
    SetY4 = 165,
    DownByZ = 166,
    SetZ1 = 167,
    SetZ4 = 170,
    SetFontNumber0 = 171,
    SetFontNumber63 = 234,
    SetFont1 = 235,
    SetFont4 = 238,
    Special1 = 239,
    Special4 = 242,
    DefineFont1 = 243,
    DefineFont4 = 246,
    Preamble = 247,
    Postamble = 248,
    DoublePostamble = 249,
    DefineNativeFont = 252,
    SetGlyphs = 253,        // "SET_GLYPHS", "XDV_GLYPHS"
    SetTextAndGlyphs = 254, // "SET_TEXT_AND_GLYPHS", "XDV_TEXT_AND_GLYPHS"
}

/// Identifier bytes used by the XDV writing code.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[repr(u8)]
enum IdByte {
    Xdv = 7,
    Spx = 100,
}

/// Flags for XeTeX native fonts
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[repr(u16)]
#[allow(unused)]
enum NativeFontFlags {
    Vertical = 0x0100,
    Colored = 0x0200,
    Extend = 0x1000,
    Slant = 0x2000,
    Embolden = 0x4000,
}