// THIS FILE IS AUTOGENERATED.
// Any changes to this file will be overwritten.
// For more information about how codegen works, see font-codegen/README.md

#[allow(unused_imports)]
use crate::codegen_prelude::*;

impl<'a> MinByteRange<'a> for Gdef<'a> {
    fn min_byte_range(&self) -> Range<usize> {
        0..self.mark_attach_class_def_offset_byte_range().end
    }
    fn min_table_bytes(&self) -> &'a [u8] {
        let range = self.min_byte_range();
        self.data.as_bytes().get(range).unwrap_or_default()
    }
}

impl TopLevelTable for Gdef<'_> {
    /// `GDEF`
    const TAG: Tag = Tag::new(b"GDEF");
}

impl<'a> FontRead<'a> for Gdef<'a> {
    fn read(data: FontData<'a>) -> Result<Self, ReadError> {
        #[allow(clippy::absurd_extreme_comparisons)]
        if data.len() < Self::MIN_SIZE {
            return Err(ReadError::OutOfBounds);
        }
        Ok(Self { data })
    }
}

/// [GDEF](https://docs.microsoft.com/en-us/typography/opentype/spec/gdef#gdef-header) 1.0
#[derive(Clone)]
pub struct Gdef<'a> {
    data: FontData<'a>,
}

#[allow(clippy::needless_lifetimes)]
impl<'a> Gdef<'a> {
    pub const MIN_SIZE: usize = (MajorMinor::RAW_BYTE_LEN
        + Offset16::RAW_BYTE_LEN
        + Offset16::RAW_BYTE_LEN
        + Offset16::RAW_BYTE_LEN
        + Offset16::RAW_BYTE_LEN);
    basic_table_impls!(impl_the_methods);

    /// The major/minor version of the GDEF table
    pub fn version(&self) -> MajorMinor {
        let range = self.version_byte_range();
        self.data.read_at(range.start).ok().unwrap()
    }

    /// Offset to class definition table for glyph type, from beginning
    /// of GDEF header (may be NULL)
    pub fn glyph_class_def_offset(&self) -> Nullable<Offset16> {
        let range = self.glyph_class_def_offset_byte_range();
        self.data.read_at(range.start).ok().unwrap()
    }

    /// Attempt to resolve [`glyph_class_def_offset`][Self::glyph_class_def_offset].
    pub fn glyph_class_def(&self) -> Option<Result<ClassDef<'a>, ReadError>> {
        let data = self.data;
        self.glyph_class_def_offset().resolve(data)
    }

    /// Offset to attachment point list table, from beginning of GDEF
    /// header (may be NULL)
    pub fn attach_list_offset(&self) -> Nullable<Offset16> {
        let range = self.attach_list_offset_byte_range();
        self.data.read_at(range.start).ok().unwrap()
    }

    /// Attempt to resolve [`attach_list_offset`][Self::attach_list_offset].
    pub fn attach_list(&self) -> Option<Result<AttachList<'a>, ReadError>> {
        let data = self.data;
        self.attach_list_offset().resolve(data)
    }

    /// Offset to ligature caret list table, from beginning of GDEF
    /// header (may be NULL)
    pub fn lig_caret_list_offset(&self) -> Nullable<Offset16> {
        let range = self.lig_caret_list_offset_byte_range();
        self.data.read_at(range.start).ok().unwrap()
    }

    /// Attempt to resolve [`lig_caret_list_offset`][Self::lig_caret_list_offset].
    pub fn lig_caret_list(&self) -> Option<Result<LigCaretList<'a>, ReadError>> {
        let data = self.data;
        self.lig_caret_list_offset().resolve(data)
    }

    /// Offset to class definition table for mark attachment type, from
    /// beginning of GDEF header (may be NULL)
    pub fn mark_attach_class_def_offset(&self) -> Nullable<Offset16> {
        let range = self.mark_attach_class_def_offset_byte_range();
        self.data.read_at(range.start).ok().unwrap()
    }

    /// Attempt to resolve [`mark_attach_class_def_offset`][Self::mark_attach_class_def_offset].
    pub fn mark_attach_class_def(&self) -> Option<Result<ClassDef<'a>, ReadError>> {
        let data = self.data;
        self.mark_attach_class_def_offset().resolve(data)
    }

    /// Offset to the table of mark glyph set definitions, from
    /// beginning of GDEF header (may be NULL)
    pub fn mark_glyph_sets_def_offset(&self) -> Option<Nullable<Offset16>> {
        let range = self.mark_glyph_sets_def_offset_byte_range();
        (!range.is_empty())
            .then(|| self.data.read_at(range.start).ok())
            .flatten()
    }

    /// Attempt to resolve [`mark_glyph_sets_def_offset`][Self::mark_glyph_sets_def_offset].
    pub fn mark_glyph_sets_def(&self) -> Option<Result<MarkGlyphSets<'a>, ReadError>> {
        let data = self.data;
        self.mark_glyph_sets_def_offset().map(|x| x.resolve(data))?
    }

    /// Offset to the Item Variation Store table, from beginning of
    /// GDEF header (may be NULL)
    pub fn item_var_store_offset(&self) -> Option<Nullable<Offset32>> {
        let range = self.item_var_store_offset_byte_range();
        (!range.is_empty())
            .then(|| self.data.read_at(range.start).ok())
            .flatten()
    }

    /// Attempt to resolve [`item_var_store_offset`][Self::item_var_store_offset].
    pub fn item_var_store(&self) -> Option<Result<ItemVariationStore<'a>, ReadError>> {
        let data = self.data;
        self.item_var_store_offset().map(|x| x.resolve(data))?
    }

    pub fn version_byte_range(&self) -> Range<usize> {
        let start = 0;
        start..start + MajorMinor::RAW_BYTE_LEN
    }

    pub fn glyph_class_def_offset_byte_range(&self) -> Range<usize> {
        let start = self.version_byte_range().end;
        start..start + Offset16::RAW_BYTE_LEN
    }

    pub fn attach_list_offset_byte_range(&self) -> Range<usize> {
        let start = self.glyph_class_def_offset_byte_range().end;
        start..start + Offset16::RAW_BYTE_LEN
    }

    pub fn lig_caret_list_offset_byte_range(&self) -> Range<usize> {
        let start = self.attach_list_offset_byte_range().end;
        start..start + Offset16::RAW_BYTE_LEN
    }

    pub fn mark_attach_class_def_offset_byte_range(&self) -> Range<usize> {
        let start = self.lig_caret_list_offset_byte_range().end;
        start..start + Offset16::RAW_BYTE_LEN
    }

    pub fn mark_glyph_sets_def_offset_byte_range(&self) -> Range<usize> {
        let start = self.mark_attach_class_def_offset_byte_range().end;
        start
            ..(self.version().compatible((1u16, 2u16)))
                .then(|| start + Offset16::RAW_BYTE_LEN)
                .unwrap_or(start)
    }

    pub fn item_var_store_offset_byte_range(&self) -> Range<usize> {
        let start = self.mark_glyph_sets_def_offset_byte_range().end;
        start
            ..(self.version().compatible((1u16, 3u16)))
                .then(|| start + Offset32::RAW_BYTE_LEN)
                .unwrap_or(start)
    }
}

const _: () = assert!(FontData::default_data_long_enough(Gdef::MIN_SIZE));

impl Default for Gdef<'_> {
    fn default() -> Self {
        Self {
            data: FontData::default_table_data(),
        }
    }
}

#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for Gdef<'a> {
    fn type_name(&self) -> &str {
        "Gdef"
    }
    fn get_field(&self, idx: usize) -> Option<Field<'a>> {
        match idx {
            0usize => Some(Field::new("version", self.version())),
            1usize => Some(Field::new(
                "glyph_class_def_offset",
                FieldType::offset(self.glyph_class_def_offset(), self.glyph_class_def()),
            )),
            2usize => Some(Field::new(
                "attach_list_offset",
                FieldType::offset(self.attach_list_offset(), self.attach_list()),
            )),
            3usize => Some(Field::new(
                "lig_caret_list_offset",
                FieldType::offset(self.lig_caret_list_offset(), self.lig_caret_list()),
            )),
            4usize => Some(Field::new(
                "mark_attach_class_def_offset",
                FieldType::offset(
                    self.mark_attach_class_def_offset(),
                    self.mark_attach_class_def(),
                ),
            )),
            5usize if self.version().compatible((1u16, 2u16)) => Some(Field::new(
                "mark_glyph_sets_def_offset",
                FieldType::offset(
                    self.mark_glyph_sets_def_offset().unwrap(),
                    self.mark_glyph_sets_def(),
                ),
            )),
            6usize if self.version().compatible((1u16, 3u16)) => Some(Field::new(
                "item_var_store_offset",
                FieldType::offset(self.item_var_store_offset().unwrap(), self.item_var_store()),
            )),
            _ => None,
        }
    }
}

#[cfg(feature = "experimental_traverse")]
#[allow(clippy::needless_lifetimes)]
impl<'a> std::fmt::Debug for Gdef<'a> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        (self as &dyn SomeTable<'a>).fmt(f)
    }
}

/// Used in the [Glyph Class Definition Table](https://docs.microsoft.com/en-us/typography/opentype/spec/gdef#glyph-class-definition-table)
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[repr(u16)]
#[allow(clippy::manual_non_exhaustive)]
pub enum GlyphClassDef {
    #[default]
    Base = 1,
    Ligature = 2,
    Mark = 3,
    Component = 4,
    #[doc(hidden)]
    /// If font data is malformed we will map unknown values to this variant
    Unknown,
}

impl GlyphClassDef {
    /// Create from a raw scalar.
    ///
    /// This will never fail; unknown values will be mapped to the `Unknown` variant
    pub fn new(raw: u16) -> Self {
        match raw {
            1 => Self::Base,
            2 => Self::Ligature,
            3 => Self::Mark,
            4 => Self::Component,
            _ => Self::Unknown,
        }
    }
}

impl font_types::Scalar for GlyphClassDef {
    type Raw = <u16 as font_types::Scalar>::Raw;
    fn to_raw(self) -> Self::Raw {
        (self as u16).to_raw()
    }
    fn from_raw(raw: Self::Raw) -> Self {
        let t = <u16>::from_raw(raw);
        Self::new(t)
    }
}

#[cfg(feature = "experimental_traverse")]
impl<'a> From<GlyphClassDef> for FieldType<'a> {
    fn from(src: GlyphClassDef) -> FieldType<'a> {
        (src as u16).into()
    }
}

impl<'a> MinByteRange<'a> for AttachList<'a> {
    fn min_byte_range(&self) -> Range<usize> {
        0..self.attach_point_offsets_byte_range().end
    }
    fn min_table_bytes(&self) -> &'a [u8] {
        let range = self.min_byte_range();
        self.data.as_bytes().get(range).unwrap_or_default()
    }
}

impl<'a> FontRead<'a> for AttachList<'a> {
    fn read(data: FontData<'a>) -> Result<Self, ReadError> {
        #[allow(clippy::absurd_extreme_comparisons)]
        if data.len() < Self::MIN_SIZE {
            return Err(ReadError::OutOfBounds);
        }
        Ok(Self { data })
    }
}

/// [Attachment Point List Table](https://docs.microsoft.com/en-us/typography/opentype/spec/gdef#attachment-point-list-table)
#[derive(Clone)]
pub struct AttachList<'a> {
    data: FontData<'a>,
}

#[allow(clippy::needless_lifetimes)]
impl<'a> AttachList<'a> {
    pub const MIN_SIZE: usize = (Offset16::RAW_BYTE_LEN + u16::RAW_BYTE_LEN);
    basic_table_impls!(impl_the_methods);

    /// Offset to Coverage table - from beginning of AttachList table
    pub fn coverage_offset(&self) -> Offset16 {
        let range = self.coverage_offset_byte_range();
        self.data.read_at(range.start).ok().unwrap()
    }

    /// Attempt to resolve [`coverage_offset`][Self::coverage_offset].
    pub fn coverage(&self) -> Result<CoverageTable<'a>, ReadError> {
        let data = self.data;
        self.coverage_offset().resolve(data)
    }

    /// Number of glyphs with attachment points
    pub fn glyph_count(&self) -> u16 {
        let range = self.glyph_count_byte_range();
        self.data.read_at(range.start).ok().unwrap()
    }

    /// Array of offsets to AttachPoint tables-from beginning of
    /// AttachList table-in Coverage Index order
    pub fn attach_point_offsets(&self) -> &'a [BigEndian<Offset16>] {
        let range = self.attach_point_offsets_byte_range();
        self.data.read_array(range).ok().unwrap_or_default()
    }

    /// A dynamically resolving wrapper for [`attach_point_offsets`][Self::attach_point_offsets].
    pub fn attach_points(&self) -> ArrayOfOffsets<'a, AttachPoint<'a>, Offset16> {
        let data = self.data;
        let offsets = self.attach_point_offsets();
        ArrayOfOffsets::new(offsets, data, ())
    }

    pub fn coverage_offset_byte_range(&self) -> Range<usize> {
        let start = 0;
        start..start + Offset16::RAW_BYTE_LEN
    }

    pub fn glyph_count_byte_range(&self) -> Range<usize> {
        let start = self.coverage_offset_byte_range().end;
        start..start + u16::RAW_BYTE_LEN
    }

    pub fn attach_point_offsets_byte_range(&self) -> Range<usize> {
        let glyph_count = self.glyph_count();
        let start = self.glyph_count_byte_range().end;
        start..start + (glyph_count as usize).saturating_mul(Offset16::RAW_BYTE_LEN)
    }
}

const _: () = assert!(FontData::default_data_long_enough(AttachList::MIN_SIZE));

impl Default for AttachList<'_> {
    fn default() -> Self {
        Self {
            data: FontData::default_table_data(),
        }
    }
}

#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for AttachList<'a> {
    fn type_name(&self) -> &str {
        "AttachList"
    }
    fn get_field(&self, idx: usize) -> Option<Field<'a>> {
        match idx {
            0usize => Some(Field::new(
                "coverage_offset",
                FieldType::offset(self.coverage_offset(), self.coverage()),
            )),
            1usize => Some(Field::new("glyph_count", self.glyph_count())),
            2usize => Some(Field::new(
                "attach_point_offsets",
                FieldType::from(self.attach_points()),
            )),
            _ => None,
        }
    }
}

#[cfg(feature = "experimental_traverse")]
#[allow(clippy::needless_lifetimes)]
impl<'a> std::fmt::Debug for AttachList<'a> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        (self as &dyn SomeTable<'a>).fmt(f)
    }
}

impl<'a> MinByteRange<'a> for AttachPoint<'a> {
    fn min_byte_range(&self) -> Range<usize> {
        0..self.point_indices_byte_range().end
    }
    fn min_table_bytes(&self) -> &'a [u8] {
        let range = self.min_byte_range();
        self.data.as_bytes().get(range).unwrap_or_default()
    }
}

impl<'a> FontRead<'a> for AttachPoint<'a> {
    fn read(data: FontData<'a>) -> Result<Self, ReadError> {
        #[allow(clippy::absurd_extreme_comparisons)]
        if data.len() < Self::MIN_SIZE {
            return Err(ReadError::OutOfBounds);
        }
        Ok(Self { data })
    }
}

/// Part of [AttachList]
#[derive(Clone)]
pub struct AttachPoint<'a> {
    data: FontData<'a>,
}

#[allow(clippy::needless_lifetimes)]
impl<'a> AttachPoint<'a> {
    pub const MIN_SIZE: usize = u16::RAW_BYTE_LEN;
    basic_table_impls!(impl_the_methods);

    /// Number of attachment points on this glyph
    pub fn point_count(&self) -> u16 {
        let range = self.point_count_byte_range();
        self.data.read_at(range.start).ok().unwrap()
    }

    /// Array of contour point indices -in increasing numerical order
    pub fn point_indices(&self) -> &'a [BigEndian<u16>] {
        let range = self.point_indices_byte_range();
        self.data.read_array(range).ok().unwrap_or_default()
    }

    pub fn point_count_byte_range(&self) -> Range<usize> {
        let start = 0;
        start..start + u16::RAW_BYTE_LEN
    }

    pub fn point_indices_byte_range(&self) -> Range<usize> {
        let point_count = self.point_count();
        let start = self.point_count_byte_range().end;
        start..start + (point_count as usize).saturating_mul(u16::RAW_BYTE_LEN)
    }
}

const _: () = assert!(FontData::default_data_long_enough(AttachPoint::MIN_SIZE));

impl Default for AttachPoint<'_> {
    fn default() -> Self {
        Self {
            data: FontData::default_table_data(),
        }
    }
}

#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for AttachPoint<'a> {
    fn type_name(&self) -> &str {
        "AttachPoint"
    }
    fn get_field(&self, idx: usize) -> Option<Field<'a>> {
        match idx {
            0usize => Some(Field::new("point_count", self.point_count())),
            1usize => Some(Field::new("point_indices", self.point_indices())),
            _ => None,
        }
    }
}

#[cfg(feature = "experimental_traverse")]
#[allow(clippy::needless_lifetimes)]
impl<'a> std::fmt::Debug for AttachPoint<'a> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        (self as &dyn SomeTable<'a>).fmt(f)
    }
}

impl<'a> MinByteRange<'a> for LigCaretList<'a> {
    fn min_byte_range(&self) -> Range<usize> {
        0..self.lig_glyph_offsets_byte_range().end
    }
    fn min_table_bytes(&self) -> &'a [u8] {
        let range = self.min_byte_range();
        self.data.as_bytes().get(range).unwrap_or_default()
    }
}

impl<'a> FontRead<'a> for LigCaretList<'a> {
    fn read(data: FontData<'a>) -> Result<Self, ReadError> {
        #[allow(clippy::absurd_extreme_comparisons)]
        if data.len() < Self::MIN_SIZE {
            return Err(ReadError::OutOfBounds);
        }
        Ok(Self { data })
    }
}

/// [Ligature Caret List Table](https://docs.microsoft.com/en-us/typography/opentype/spec/gdef#ligature-caret-list-table)
#[derive(Clone)]
pub struct LigCaretList<'a> {
    data: FontData<'a>,
}

#[allow(clippy::needless_lifetimes)]
impl<'a> LigCaretList<'a> {
    pub const MIN_SIZE: usize = (Offset16::RAW_BYTE_LEN + u16::RAW_BYTE_LEN);
    basic_table_impls!(impl_the_methods);

    /// Offset to Coverage table - from beginning of LigCaretList table
    pub fn coverage_offset(&self) -> Offset16 {
        let range = self.coverage_offset_byte_range();
        self.data.read_at(range.start).ok().unwrap()
    }

    /// Attempt to resolve [`coverage_offset`][Self::coverage_offset].
    pub fn coverage(&self) -> Result<CoverageTable<'a>, ReadError> {
        let data = self.data;
        self.coverage_offset().resolve(data)
    }

    /// Number of ligature glyphs
    pub fn lig_glyph_count(&self) -> u16 {
        let range = self.lig_glyph_count_byte_range();
        self.data.read_at(range.start).ok().unwrap()
    }

    /// Array of offsets to LigGlyph tables, from beginning of
    /// LigCaretList table —in Coverage Index order
    pub fn lig_glyph_offsets(&self) -> &'a [BigEndian<Offset16>] {
        let range = self.lig_glyph_offsets_byte_range();
        self.data.read_array(range).ok().unwrap_or_default()
    }

    /// A dynamically resolving wrapper for [`lig_glyph_offsets`][Self::lig_glyph_offsets].
    pub fn lig_glyphs(&self) -> ArrayOfOffsets<'a, LigGlyph<'a>, Offset16> {
        let data = self.data;
        let offsets = self.lig_glyph_offsets();
        ArrayOfOffsets::new(offsets, data, ())
    }

    pub fn coverage_offset_byte_range(&self) -> Range<usize> {
        let start = 0;
        start..start + Offset16::RAW_BYTE_LEN
    }

    pub fn lig_glyph_count_byte_range(&self) -> Range<usize> {
        let start = self.coverage_offset_byte_range().end;
        start..start + u16::RAW_BYTE_LEN
    }

    pub fn lig_glyph_offsets_byte_range(&self) -> Range<usize> {
        let lig_glyph_count = self.lig_glyph_count();
        let start = self.lig_glyph_count_byte_range().end;
        start..start + (lig_glyph_count as usize).saturating_mul(Offset16::RAW_BYTE_LEN)
    }
}

const _: () = assert!(FontData::default_data_long_enough(LigCaretList::MIN_SIZE));

impl Default for LigCaretList<'_> {
    fn default() -> Self {
        Self {
            data: FontData::default_table_data(),
        }
    }
}

#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for LigCaretList<'a> {
    fn type_name(&self) -> &str {
        "LigCaretList"
    }
    fn get_field(&self, idx: usize) -> Option<Field<'a>> {
        match idx {
            0usize => Some(Field::new(
                "coverage_offset",
                FieldType::offset(self.coverage_offset(), self.coverage()),
            )),
            1usize => Some(Field::new("lig_glyph_count", self.lig_glyph_count())),
            2usize => Some(Field::new(
                "lig_glyph_offsets",
                FieldType::from(self.lig_glyphs()),
            )),
            _ => None,
        }
    }
}

#[cfg(feature = "experimental_traverse")]
#[allow(clippy::needless_lifetimes)]
impl<'a> std::fmt::Debug for LigCaretList<'a> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        (self as &dyn SomeTable<'a>).fmt(f)
    }
}

impl<'a> MinByteRange<'a> for LigGlyph<'a> {
    fn min_byte_range(&self) -> Range<usize> {
        0..self.caret_value_offsets_byte_range().end
    }
    fn min_table_bytes(&self) -> &'a [u8] {
        let range = self.min_byte_range();
        self.data.as_bytes().get(range).unwrap_or_default()
    }
}

impl<'a> FontRead<'a> for LigGlyph<'a> {
    fn read(data: FontData<'a>) -> Result<Self, ReadError> {
        #[allow(clippy::absurd_extreme_comparisons)]
        if data.len() < Self::MIN_SIZE {
            return Err(ReadError::OutOfBounds);
        }
        Ok(Self { data })
    }
}

/// [Ligature Glyph Table](https://docs.microsoft.com/en-us/typography/opentype/spec/gdef#ligature-glyph-table)
#[derive(Clone)]
pub struct LigGlyph<'a> {
    data: FontData<'a>,
}

#[allow(clippy::needless_lifetimes)]
impl<'a> LigGlyph<'a> {
    pub const MIN_SIZE: usize = u16::RAW_BYTE_LEN;
    basic_table_impls!(impl_the_methods);

    /// Number of CaretValue tables for this ligature (components - 1)
    pub fn caret_count(&self) -> u16 {
        let range = self.caret_count_byte_range();
        self.data.read_at(range.start).ok().unwrap()
    }

    /// Array of offsets to CaretValue tables, from beginning of
    /// LigGlyph table — in increasing coordinate order
    pub fn caret_value_offsets(&self) -> &'a [BigEndian<Offset16>] {
        let range = self.caret_value_offsets_byte_range();
        self.data.read_array(range).ok().unwrap_or_default()
    }

    /// A dynamically resolving wrapper for [`caret_value_offsets`][Self::caret_value_offsets].
    pub fn caret_values(&self) -> ArrayOfOffsets<'a, CaretValue<'a>, Offset16> {
        let data = self.data;
        let offsets = self.caret_value_offsets();
        ArrayOfOffsets::new(offsets, data, ())
    }

    pub fn caret_count_byte_range(&self) -> Range<usize> {
        let start = 0;
        start..start + u16::RAW_BYTE_LEN
    }

    pub fn caret_value_offsets_byte_range(&self) -> Range<usize> {
        let caret_count = self.caret_count();
        let start = self.caret_count_byte_range().end;
        start..start + (caret_count as usize).saturating_mul(Offset16::RAW_BYTE_LEN)
    }
}

const _: () = assert!(FontData::default_data_long_enough(LigGlyph::MIN_SIZE));

impl Default for LigGlyph<'_> {
    fn default() -> Self {
        Self {
            data: FontData::default_table_data(),
        }
    }
}

#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for LigGlyph<'a> {
    fn type_name(&self) -> &str {
        "LigGlyph"
    }
    fn get_field(&self, idx: usize) -> Option<Field<'a>> {
        match idx {
            0usize => Some(Field::new("caret_count", self.caret_count())),
            1usize => Some(Field::new(
                "caret_value_offsets",
                FieldType::from(self.caret_values()),
            )),
            _ => None,
        }
    }
}

#[cfg(feature = "experimental_traverse")]
#[allow(clippy::needless_lifetimes)]
impl<'a> std::fmt::Debug for LigGlyph<'a> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        (self as &dyn SomeTable<'a>).fmt(f)
    }
}

/// [Caret Value Tables](https://docs.microsoft.com/en-us/typography/opentype/spec/gdef#caret-value-tables)
#[derive(Clone)]
pub enum CaretValue<'a> {
    Format1(CaretValueFormat1<'a>),
    Format2(CaretValueFormat2<'a>),
    Format3(CaretValueFormat3<'a>),
}

impl Default for CaretValue<'_> {
    fn default() -> Self {
        Self::Format1(Default::default())
    }
}

impl<'a> CaretValue<'a> {
    ///Return the `FontData` used to resolve offsets for this table.
    pub fn offset_data(&self) -> FontData<'a> {
        match self {
            Self::Format1(item) => item.offset_data(),
            Self::Format2(item) => item.offset_data(),
            Self::Format3(item) => item.offset_data(),
        }
    }

    /// Format identifier: format = 1
    pub fn caret_value_format(&self) -> u16 {
        match self {
            Self::Format1(item) => item.caret_value_format(),
            Self::Format2(item) => item.caret_value_format(),
            Self::Format3(item) => item.caret_value_format(),
        }
    }
}

impl<'a> FontRead<'a> for CaretValue<'a> {
    fn read(data: FontData<'a>) -> Result<Self, ReadError> {
        let format: u16 = data.read_at(0usize)?;
        match format {
            CaretValueFormat1::FORMAT => Ok(Self::Format1(FontRead::read(data)?)),
            CaretValueFormat2::FORMAT => Ok(Self::Format2(FontRead::read(data)?)),
            CaretValueFormat3::FORMAT => Ok(Self::Format3(FontRead::read(data)?)),
            other => Err(ReadError::InvalidFormat(other.into())),
        }
    }
}

impl<'a> MinByteRange<'a> for CaretValue<'a> {
    fn min_byte_range(&self) -> Range<usize> {
        match self {
            Self::Format1(item) => item.min_byte_range(),
            Self::Format2(item) => item.min_byte_range(),
            Self::Format3(item) => item.min_byte_range(),
        }
    }
    fn min_table_bytes(&self) -> &'a [u8] {
        match self {
            Self::Format1(item) => item.min_table_bytes(),
            Self::Format2(item) => item.min_table_bytes(),
            Self::Format3(item) => item.min_table_bytes(),
        }
    }
}

#[cfg(feature = "experimental_traverse")]
impl<'a> CaretValue<'a> {
    fn dyn_inner<'b>(&'b self) -> &'b dyn SomeTable<'a> {
        match self {
            Self::Format1(table) => table,
            Self::Format2(table) => table,
            Self::Format3(table) => table,
        }
    }
}

#[cfg(feature = "experimental_traverse")]
impl std::fmt::Debug for CaretValue<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.dyn_inner().fmt(f)
    }
}

#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for CaretValue<'a> {
    fn type_name(&self) -> &str {
        self.dyn_inner().type_name()
    }
    fn get_field(&self, idx: usize) -> Option<Field<'a>> {
        self.dyn_inner().get_field(idx)
    }
}

impl Format<u16> for CaretValueFormat1<'_> {
    const FORMAT: u16 = 1;
}

impl<'a> MinByteRange<'a> for CaretValueFormat1<'a> {
    fn min_byte_range(&self) -> Range<usize> {
        0..self.coordinate_byte_range().end
    }
    fn min_table_bytes(&self) -> &'a [u8] {
        let range = self.min_byte_range();
        self.data.as_bytes().get(range).unwrap_or_default()
    }
}

impl<'a> FontRead<'a> for CaretValueFormat1<'a> {
    fn read(data: FontData<'a>) -> Result<Self, ReadError> {
        #[allow(clippy::absurd_extreme_comparisons)]
        if data.len() < Self::MIN_SIZE {
            return Err(ReadError::OutOfBounds);
        }
        Ok(Self { data })
    }
}

/// [CaretValue Format 1](https://docs.microsoft.com/en-us/typography/opentype/spec/gdef#caretvalue-format-1)
#[derive(Clone)]
pub struct CaretValueFormat1<'a> {
    data: FontData<'a>,
}

#[allow(clippy::needless_lifetimes)]
impl<'a> CaretValueFormat1<'a> {
    pub const MIN_SIZE: usize = (u16::RAW_BYTE_LEN + i16::RAW_BYTE_LEN);
    basic_table_impls!(impl_the_methods);

    /// Format identifier: format = 1
    pub fn caret_value_format(&self) -> u16 {
        let range = self.caret_value_format_byte_range();
        self.data.read_at(range.start).ok().unwrap()
    }

    /// X or Y value, in design units
    pub fn coordinate(&self) -> i16 {
        let range = self.coordinate_byte_range();
        self.data.read_at(range.start).ok().unwrap()
    }

    pub fn caret_value_format_byte_range(&self) -> Range<usize> {
        let start = 0;
        start..start + u16::RAW_BYTE_LEN
    }

    pub fn coordinate_byte_range(&self) -> Range<usize> {
        let start = self.caret_value_format_byte_range().end;
        start..start + i16::RAW_BYTE_LEN
    }
}

const _: () = assert!(FontData::default_data_long_enough(
    CaretValueFormat1::MIN_SIZE
));

impl Default for CaretValueFormat1<'_> {
    fn default() -> Self {
        Self {
            data: FontData::default_format_1_u16_table_data(),
        }
    }
}

#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for CaretValueFormat1<'a> {
    fn type_name(&self) -> &str {
        "CaretValueFormat1"
    }
    fn get_field(&self, idx: usize) -> Option<Field<'a>> {
        match idx {
            0usize => Some(Field::new("caret_value_format", self.caret_value_format())),
            1usize => Some(Field::new("coordinate", self.coordinate())),
            _ => None,
        }
    }
}

#[cfg(feature = "experimental_traverse")]
#[allow(clippy::needless_lifetimes)]
impl<'a> std::fmt::Debug for CaretValueFormat1<'a> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        (self as &dyn SomeTable<'a>).fmt(f)
    }
}

impl Format<u16> for CaretValueFormat2<'_> {
    const FORMAT: u16 = 2;
}

impl<'a> MinByteRange<'a> for CaretValueFormat2<'a> {
    fn min_byte_range(&self) -> Range<usize> {
        0..self.caret_value_point_index_byte_range().end
    }
    fn min_table_bytes(&self) -> &'a [u8] {
        let range = self.min_byte_range();
        self.data.as_bytes().get(range).unwrap_or_default()
    }
}

impl<'a> FontRead<'a> for CaretValueFormat2<'a> {
    fn read(data: FontData<'a>) -> Result<Self, ReadError> {
        #[allow(clippy::absurd_extreme_comparisons)]
        if data.len() < Self::MIN_SIZE {
            return Err(ReadError::OutOfBounds);
        }
        Ok(Self { data })
    }
}

/// [CaretValue Format 2](https://docs.microsoft.com/en-us/typography/opentype/spec/gdef#caretvalue-format-2)
#[derive(Clone)]
pub struct CaretValueFormat2<'a> {
    data: FontData<'a>,
}

#[allow(clippy::needless_lifetimes)]
impl<'a> CaretValueFormat2<'a> {
    pub const MIN_SIZE: usize = (u16::RAW_BYTE_LEN + u16::RAW_BYTE_LEN);
    basic_table_impls!(impl_the_methods);

    /// Format identifier: format = 2
    pub fn caret_value_format(&self) -> u16 {
        let range = self.caret_value_format_byte_range();
        self.data.read_at(range.start).ok().unwrap()
    }

    /// Contour point index on glyph
    pub fn caret_value_point_index(&self) -> u16 {
        let range = self.caret_value_point_index_byte_range();
        self.data.read_at(range.start).ok().unwrap()
    }

    pub fn caret_value_format_byte_range(&self) -> Range<usize> {
        let start = 0;
        start..start + u16::RAW_BYTE_LEN
    }

    pub fn caret_value_point_index_byte_range(&self) -> Range<usize> {
        let start = self.caret_value_format_byte_range().end;
        start..start + u16::RAW_BYTE_LEN
    }
}

#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for CaretValueFormat2<'a> {
    fn type_name(&self) -> &str {
        "CaretValueFormat2"
    }
    fn get_field(&self, idx: usize) -> Option<Field<'a>> {
        match idx {
            0usize => Some(Field::new("caret_value_format", self.caret_value_format())),
            1usize => Some(Field::new(
                "caret_value_point_index",
                self.caret_value_point_index(),
            )),
            _ => None,
        }
    }
}

#[cfg(feature = "experimental_traverse")]
#[allow(clippy::needless_lifetimes)]
impl<'a> std::fmt::Debug for CaretValueFormat2<'a> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        (self as &dyn SomeTable<'a>).fmt(f)
    }
}

impl Format<u16> for CaretValueFormat3<'_> {
    const FORMAT: u16 = 3;
}

impl<'a> MinByteRange<'a> for CaretValueFormat3<'a> {
    fn min_byte_range(&self) -> Range<usize> {
        0..self.device_offset_byte_range().end
    }
    fn min_table_bytes(&self) -> &'a [u8] {
        let range = self.min_byte_range();
        self.data.as_bytes().get(range).unwrap_or_default()
    }
}

impl<'a> FontRead<'a> for CaretValueFormat3<'a> {
    fn read(data: FontData<'a>) -> Result<Self, ReadError> {
        #[allow(clippy::absurd_extreme_comparisons)]
        if data.len() < Self::MIN_SIZE {
            return Err(ReadError::OutOfBounds);
        }
        Ok(Self { data })
    }
}

/// [CaretValue Format 3](https://docs.microsoft.com/en-us/typography/opentype/spec/gdef#caretvalue-format-3)
#[derive(Clone)]
pub struct CaretValueFormat3<'a> {
    data: FontData<'a>,
}

#[allow(clippy::needless_lifetimes)]
impl<'a> CaretValueFormat3<'a> {
    pub const MIN_SIZE: usize = (u16::RAW_BYTE_LEN + i16::RAW_BYTE_LEN + Offset16::RAW_BYTE_LEN);
    basic_table_impls!(impl_the_methods);

    /// Format identifier-format = 3
    pub fn caret_value_format(&self) -> u16 {
        let range = self.caret_value_format_byte_range();
        self.data.read_at(range.start).ok().unwrap()
    }

    /// X or Y value, in design units
    pub fn coordinate(&self) -> i16 {
        let range = self.coordinate_byte_range();
        self.data.read_at(range.start).ok().unwrap()
    }

    /// Offset to Device table (non-variable font) / Variation Index
    /// table (variable font) for X or Y value-from beginning of
    /// CaretValue table
    pub fn device_offset(&self) -> Offset16 {
        let range = self.device_offset_byte_range();
        self.data.read_at(range.start).ok().unwrap()
    }

    /// Attempt to resolve [`device_offset`][Self::device_offset].
    pub fn device(&self) -> Result<DeviceOrVariationIndex<'a>, ReadError> {
        let data = self.data;
        self.device_offset().resolve(data)
    }

    pub fn caret_value_format_byte_range(&self) -> Range<usize> {
        let start = 0;
        start..start + u16::RAW_BYTE_LEN
    }

    pub fn coordinate_byte_range(&self) -> Range<usize> {
        let start = self.caret_value_format_byte_range().end;
        start..start + i16::RAW_BYTE_LEN
    }

    pub fn device_offset_byte_range(&self) -> Range<usize> {
        let start = self.coordinate_byte_range().end;
        start..start + Offset16::RAW_BYTE_LEN
    }
}

#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for CaretValueFormat3<'a> {
    fn type_name(&self) -> &str {
        "CaretValueFormat3"
    }
    fn get_field(&self, idx: usize) -> Option<Field<'a>> {
        match idx {
            0usize => Some(Field::new("caret_value_format", self.caret_value_format())),
            1usize => Some(Field::new("coordinate", self.coordinate())),
            2usize => Some(Field::new(
                "device_offset",
                FieldType::offset(self.device_offset(), self.device()),
            )),
            _ => None,
        }
    }
}

#[cfg(feature = "experimental_traverse")]
#[allow(clippy::needless_lifetimes)]
impl<'a> std::fmt::Debug for CaretValueFormat3<'a> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        (self as &dyn SomeTable<'a>).fmt(f)
    }
}

impl Format<u16> for MarkGlyphSets<'_> {
    const FORMAT: u16 = 1;
}

impl<'a> MinByteRange<'a> for MarkGlyphSets<'a> {
    fn min_byte_range(&self) -> Range<usize> {
        0..self.coverage_offsets_byte_range().end
    }
    fn min_table_bytes(&self) -> &'a [u8] {
        let range = self.min_byte_range();
        self.data.as_bytes().get(range).unwrap_or_default()
    }
}

impl<'a> FontRead<'a> for MarkGlyphSets<'a> {
    fn read(data: FontData<'a>) -> Result<Self, ReadError> {
        #[allow(clippy::absurd_extreme_comparisons)]
        if data.len() < Self::MIN_SIZE {
            return Err(ReadError::OutOfBounds);
        }
        Ok(Self { data })
    }
}

/// [Mark Glyph Sets Table](https://docs.microsoft.com/en-us/typography/opentype/spec/gdef#mark-glyph-sets-table)
#[derive(Clone)]
pub struct MarkGlyphSets<'a> {
    data: FontData<'a>,
}

#[allow(clippy::needless_lifetimes)]
impl<'a> MarkGlyphSets<'a> {
    pub const MIN_SIZE: usize = (u16::RAW_BYTE_LEN + u16::RAW_BYTE_LEN);
    basic_table_impls!(impl_the_methods);

    /// Format identifier == 1
    pub fn format(&self) -> u16 {
        let range = self.format_byte_range();
        self.data.read_at(range.start).ok().unwrap()
    }

    /// Number of mark glyph sets defined
    pub fn mark_glyph_set_count(&self) -> u16 {
        let range = self.mark_glyph_set_count_byte_range();
        self.data.read_at(range.start).ok().unwrap()
    }

    /// Array of offsets to mark glyph set coverage tables, from the
    /// start of the MarkGlyphSets table.
    pub fn coverage_offsets(&self) -> &'a [BigEndian<Offset32>] {
        let range = self.coverage_offsets_byte_range();
        self.data.read_array(range).ok().unwrap_or_default()
    }

    /// A dynamically resolving wrapper for [`coverage_offsets`][Self::coverage_offsets].
    pub fn coverages(&self) -> ArrayOfOffsets<'a, CoverageTable<'a>, Offset32> {
        let data = self.data;
        let offsets = self.coverage_offsets();
        ArrayOfOffsets::new(offsets, data, ())
    }

    pub fn format_byte_range(&self) -> Range<usize> {
        let start = 0;
        start..start + u16::RAW_BYTE_LEN
    }

    pub fn mark_glyph_set_count_byte_range(&self) -> Range<usize> {
        let start = self.format_byte_range().end;
        start..start + u16::RAW_BYTE_LEN
    }

    pub fn coverage_offsets_byte_range(&self) -> Range<usize> {
        let mark_glyph_set_count = self.mark_glyph_set_count();
        let start = self.mark_glyph_set_count_byte_range().end;
        start..start + (mark_glyph_set_count as usize).saturating_mul(Offset32::RAW_BYTE_LEN)
    }
}

const _: () = assert!(FontData::default_data_long_enough(MarkGlyphSets::MIN_SIZE));

impl Default for MarkGlyphSets<'_> {
    fn default() -> Self {
        Self {
            data: FontData::default_format_1_u16_table_data(),
        }
    }
}

#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for MarkGlyphSets<'a> {
    fn type_name(&self) -> &str {
        "MarkGlyphSets"
    }
    fn get_field(&self, idx: usize) -> Option<Field<'a>> {
        match idx {
            0usize => Some(Field::new("format", self.format())),
            1usize => Some(Field::new(
                "mark_glyph_set_count",
                self.mark_glyph_set_count(),
            )),
            2usize => Some(Field::new(
                "coverage_offsets",
                FieldType::from(self.coverages()),
            )),
            _ => None,
        }
    }
}

#[cfg(feature = "experimental_traverse")]
#[allow(clippy::needless_lifetimes)]
impl<'a> std::fmt::Debug for MarkGlyphSets<'a> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        (self as &dyn SomeTable<'a>).fmt(f)
    }
}
