cff 0.5.0

A zero-allocation CFF parser.
// Copyright 2018 Kyle Mayes
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Error handling.

use tarrasque::{ExtractError};

/// The error code for mismatched operands and operators.
pub const MISMATCH: u32 = 0;
/// The error code for missing entries.
pub const MISSING: u32 = 1;
/// The error code for invalid offset sizes.
pub const OFFSET_SIZE: u32 = 2;
/// The error code for invalid operands.
pub const OPERAND: u32 = 3;
/// The error code for invalid operators.
pub const OPERATOR: u32 = 4;
/// The error code for charstring stack overflow.
pub const OVERFLOW: u32 = 5;
/// The error code for charstring undefined subroutines.
pub const UNDEFINED: u32 = 6;
/// The error code for charstring stack underflow.
pub const UNDERFLOW: u32 = 7;
/// The error code for unsupported formats and operations.
pub const UNSUPPORTED: u32 = 8;

/// An error encountered while parsing a CFF table.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum CffError<'s> {
    /// An error occurred while extracting a value from a stream of bytes.
    Extract(ExtractError<'s>),
    /// A `DICT` did not contain a required entry.
    Missing,
    /// A `DICT` contained a mismatched operand and operator.
    Mismatch,
    /// An invalid offset size was encountered.
    OffsetSize,
    /// A `DICT` contained an invalid operand.
    Operand,
    /// A `DICT` contained an invalid operator.
    Operator,
    /// A charstring stack overflowed.
    Overflow,
    /// A charstring attempted to call an undefined subroutine.
    Undefined,
    /// A charstring stack underflowed.
    Underflow,
    /// An unsupported format or operation was encountered.
    Unsupported,
}

impl<'s> From<ExtractError<'s>> for CffError<'s> {
    #[inline]
    fn from(error: ExtractError<'s>) -> Self {
        match error {
            ExtractError::Code(code) => match code {
                MISSING => CffError::Missing,
                MISMATCH => CffError::Mismatch,
                OFFSET_SIZE => CffError::OffsetSize,
                OPERAND => CffError::Operand,
                OPERATOR => CffError::Operator,
                OVERFLOW => CffError::Overflow,
                UNDEFINED => CffError::Undefined,
                UNDERFLOW => CffError::Underflow,
                UNSUPPORTED => CffError::Unsupported,
                _ => CffError::Extract(ExtractError::Code(code)),
            },
            error => CffError::Extract(error),
        }
    }
}