// 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 Varc<'a> {
    fn min_byte_range(&self) -> Range<usize> {
        0..self.var_composite_glyphs_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 Varc<'_> {
    /// `VARC`
    const TAG: Tag = Tag::new(b"VARC");
}

impl<'a> FontRead<'a> for Varc<'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 })
    }
}

/// [VARC](https://github.com/harfbuzz/boring-expansion-spec/blob/main/VARC.md) (Variable Composites / Components Table)
///
/// [FontTools VARC](https://github.com/fonttools/fonttools/blob/5e6b12d12fa08abafbeb7570f47707fbedf69a45/Lib/fontTools/ttLib/tables/otData.py#L3459-L3476)
#[derive(Clone)]
pub struct Varc<'a> {
    data: FontData<'a>,
}

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

    /// Major/minor version number. Set to 1.0.
    pub fn version(&self) -> MajorMinor {
        let range = self.version_byte_range();
        self.data.read_at(range.start).ok().unwrap()
    }

    pub fn coverage_offset(&self) -> Offset32 {
        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)
    }

    pub fn multi_var_store_offset(&self) -> Nullable<Offset32> {
        let range = self.multi_var_store_offset_byte_range();
        self.data.read_at(range.start).ok().unwrap()
    }

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

    pub fn condition_list_offset(&self) -> Nullable<Offset32> {
        let range = self.condition_list_offset_byte_range();
        self.data.read_at(range.start).ok().unwrap()
    }

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

    pub fn axis_indices_list_offset(&self) -> Nullable<Offset32> {
        let range = self.axis_indices_list_offset_byte_range();
        self.data.read_at(range.start).ok().unwrap()
    }

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

    pub fn var_composite_glyphs_offset(&self) -> Offset32 {
        let range = self.var_composite_glyphs_offset_byte_range();
        self.data.read_at(range.start).ok().unwrap()
    }

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

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

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

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

    pub fn condition_list_offset_byte_range(&self) -> Range<usize> {
        let start = self.multi_var_store_offset_byte_range().end;
        start..start + Offset32::RAW_BYTE_LEN
    }

    pub fn axis_indices_list_offset_byte_range(&self) -> Range<usize> {
        let start = self.condition_list_offset_byte_range().end;
        start..start + Offset32::RAW_BYTE_LEN
    }

    pub fn var_composite_glyphs_offset_byte_range(&self) -> Range<usize> {
        let start = self.axis_indices_list_offset_byte_range().end;
        start..start + Offset32::RAW_BYTE_LEN
    }
}

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

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

#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for Varc<'a> {
    fn type_name(&self) -> &str {
        "Varc"
    }
    fn get_field(&self, idx: usize) -> Option<Field<'a>> {
        match idx {
            0usize => Some(Field::new("version", self.version())),
            1usize => Some(Field::new(
                "coverage_offset",
                FieldType::offset(self.coverage_offset(), self.coverage()),
            )),
            2usize => Some(Field::new(
                "multi_var_store_offset",
                FieldType::offset(self.multi_var_store_offset(), self.multi_var_store()),
            )),
            3usize => Some(Field::new(
                "condition_list_offset",
                FieldType::offset(self.condition_list_offset(), self.condition_list()),
            )),
            4usize => Some(Field::new(
                "axis_indices_list_offset",
                FieldType::offset(self.axis_indices_list_offset(), self.axis_indices_list()),
            )),
            5usize => Some(Field::new(
                "var_composite_glyphs_offset",
                FieldType::offset(
                    self.var_composite_glyphs_offset(),
                    self.var_composite_glyphs(),
                ),
            )),
            _ => None,
        }
    }
}

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

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

impl<'a> MinByteRange<'a> for MultiItemVariationStore<'a> {
    fn min_byte_range(&self) -> Range<usize> {
        0..self.variation_data_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 MultiItemVariationStore<'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 })
    }
}

/// * <https://github.com/fonttools/fonttools/blob/5e6b12d12fa08abafbeb7570f47707fbedf69a45/Lib/fontTools/ttLib/tables/otData.py#L3451-L3457>
/// * <https://github.com/harfbuzz/harfbuzz/blob/7be12b33e3f07067c159d8f516eb31df58c75876/src/hb-ot-layout-common.hh#L3517-L3520C3>
#[derive(Clone)]
pub struct MultiItemVariationStore<'a> {
    data: FontData<'a>,
}

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

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

    pub fn region_list_offset(&self) -> Offset32 {
        let range = self.region_list_offset_byte_range();
        self.data.read_at(range.start).ok().unwrap()
    }

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

    pub fn variation_data_count(&self) -> u16 {
        let range = self.variation_data_count_byte_range();
        self.data.read_at(range.start).ok().unwrap()
    }

    pub fn variation_data_offsets(&self) -> &'a [BigEndian<Offset32>] {
        let range = self.variation_data_offsets_byte_range();
        self.data.read_array(range).ok().unwrap_or_default()
    }

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

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

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

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

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

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

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

#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for MultiItemVariationStore<'a> {
    fn type_name(&self) -> &str {
        "MultiItemVariationStore"
    }
    fn get_field(&self, idx: usize) -> Option<Field<'a>> {
        match idx {
            0usize => Some(Field::new("format", self.format())),
            1usize => Some(Field::new(
                "region_list_offset",
                FieldType::offset(self.region_list_offset(), self.region_list()),
            )),
            2usize => Some(Field::new(
                "variation_data_count",
                self.variation_data_count(),
            )),
            3usize => Some(Field::new(
                "variation_data_offsets",
                FieldType::from(self.variation_data()),
            )),
            _ => None,
        }
    }
}

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

impl<'a> MinByteRange<'a> for SparseVariationRegionList<'a> {
    fn min_byte_range(&self) -> Range<usize> {
        0..self.region_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 SparseVariationRegionList<'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 })
    }
}

#[derive(Clone)]
pub struct SparseVariationRegionList<'a> {
    data: FontData<'a>,
}

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

    pub fn region_count(&self) -> u16 {
        let range = self.region_count_byte_range();
        self.data.read_at(range.start).ok().unwrap()
    }

    pub fn region_offsets(&self) -> &'a [BigEndian<Offset32>] {
        let range = self.region_offsets_byte_range();
        self.data.read_array(range).ok().unwrap_or_default()
    }

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

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

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

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

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

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

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

impl<'a> MinByteRange<'a> for SparseVariationRegion<'a> {
    fn min_byte_range(&self) -> Range<usize> {
        0..self.region_axes_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 SparseVariationRegion<'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 })
    }
}

#[derive(Clone)]
pub struct SparseVariationRegion<'a> {
    data: FontData<'a>,
}

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

    pub fn region_axis_count(&self) -> u16 {
        let range = self.region_axis_count_byte_range();
        self.data.read_at(range.start).ok().unwrap()
    }

    pub fn region_axes(&self) -> &'a [SparseRegionAxisCoordinates] {
        let range = self.region_axes_byte_range();
        self.data.read_array(range).ok().unwrap_or_default()
    }

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

    pub fn region_axes_byte_range(&self) -> Range<usize> {
        let region_axis_count = self.region_axis_count();
        let start = self.region_axis_count_byte_range().end;
        start
            ..start
                + (region_axis_count as usize)
                    .saturating_mul(SparseRegionAxisCoordinates::RAW_BYTE_LEN)
    }
}

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

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

#[cfg(feature = "experimental_traverse")]
impl<'a> SomeTable<'a> for SparseVariationRegion<'a> {
    fn type_name(&self) -> &str {
        "SparseVariationRegion"
    }
    fn get_field(&self, idx: usize) -> Option<Field<'a>> {
        match idx {
            0usize => Some(Field::new("region_axis_count", self.region_axis_count())),
            1usize => Some(Field::new(
                "region_axes",
                traversal::FieldType::array_of_records(
                    stringify!(SparseRegionAxisCoordinates),
                    self.region_axes(),
                    self.offset_data(),
                ),
            )),
            _ => None,
        }
    }
}

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

#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Copy, bytemuck :: AnyBitPattern)]
#[repr(C)]
#[repr(packed)]
pub struct SparseRegionAxisCoordinates {
    pub axis_index: BigEndian<u16>,
    pub start: BigEndian<F2Dot14>,
    pub peak: BigEndian<F2Dot14>,
    pub end: BigEndian<F2Dot14>,
}

impl SparseRegionAxisCoordinates {
    pub fn axis_index(&self) -> u16 {
        self.axis_index.get()
    }

    pub fn start(&self) -> F2Dot14 {
        self.start.get()
    }

    pub fn peak(&self) -> F2Dot14 {
        self.peak.get()
    }

    pub fn end(&self) -> F2Dot14 {
        self.end.get()
    }
}

impl FixedSize for SparseRegionAxisCoordinates {
    const RAW_BYTE_LEN: usize =
        u16::RAW_BYTE_LEN + F2Dot14::RAW_BYTE_LEN + F2Dot14::RAW_BYTE_LEN + F2Dot14::RAW_BYTE_LEN;
}

#[cfg(feature = "experimental_traverse")]
impl<'a> SomeRecord<'a> for SparseRegionAxisCoordinates {
    fn traverse(self, data: FontData<'a>) -> RecordResolver<'a> {
        RecordResolver {
            name: "SparseRegionAxisCoordinates",
            get_field: Box::new(move |idx, _data| match idx {
                0usize => Some(Field::new("axis_index", self.axis_index())),
                1usize => Some(Field::new("start", self.start())),
                2usize => Some(Field::new("peak", self.peak())),
                3usize => Some(Field::new("end", self.end())),
                _ => None,
            }),
            data,
        }
    }
}

impl Format<u8> for MultiItemVariationData<'_> {
    const FORMAT: u8 = 1;
}

impl<'a> MinByteRange<'a> for MultiItemVariationData<'a> {
    fn min_byte_range(&self) -> Range<usize> {
        0..self.raw_delta_sets_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 MultiItemVariationData<'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 })
    }
}

#[derive(Clone)]
pub struct MultiItemVariationData<'a> {
    data: FontData<'a>,
}

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

    pub fn format(&self) -> u8 {
        let range = self.format_byte_range();
        self.data.read_at(range.start).ok().unwrap()
    }

    pub fn region_index_count(&self) -> u16 {
        let range = self.region_index_count_byte_range();
        self.data.read_at(range.start).ok().unwrap()
    }

    pub fn region_indices(&self) -> &'a [BigEndian<u16>] {
        let range = self.region_indices_byte_range();
        self.data.read_array(range).ok().unwrap_or_default()
    }

    pub fn raw_delta_sets(&self) -> &'a [u8] {
        let range = self.raw_delta_sets_byte_range();
        self.data.read_array(range).ok().unwrap_or_default()
    }

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

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

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

    pub fn raw_delta_sets_byte_range(&self) -> Range<usize> {
        let start = self.region_indices_byte_range().end;
        start..start + self.data.len().saturating_sub(start) / u8::RAW_BYTE_LEN * u8::RAW_BYTE_LEN
    }
}

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

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

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

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

impl<'a> MinByteRange<'a> for ConditionList<'a> {
    fn min_byte_range(&self) -> Range<usize> {
        0..self.condition_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 ConditionList<'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 })
    }
}

#[derive(Clone)]
pub struct ConditionList<'a> {
    data: FontData<'a>,
}

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

    pub fn condition_count(&self) -> u32 {
        let range = self.condition_count_byte_range();
        self.data.read_at(range.start).ok().unwrap()
    }

    pub fn condition_offsets(&self) -> &'a [BigEndian<Offset32>] {
        let range = self.condition_offsets_byte_range();
        self.data.read_array(range).ok().unwrap_or_default()
    }

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

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

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

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

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

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

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

/// Flags used in the [VarcComponent] byte stream
///
/// <https://github.com/harfbuzz/boring-expansion-spec/blob/main/VARC.md#variable-component-flags>
#[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash, bytemuck :: AnyBitPattern)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[repr(transparent)]
pub struct VarcFlags {
    bits: u32,
}

impl VarcFlags {
    pub const RESET_UNSPECIFIED_AXES: Self = Self {
        bits: 0b0000_0000_0000_0001,
    };

    pub const HAVE_AXES: Self = Self {
        bits: 0b0000_0000_0000_0010,
    };

    pub const AXIS_VALUES_HAVE_VARIATION: Self = Self {
        bits: 0b0000_0000_0000_0100,
    };

    pub const TRANSFORM_HAS_VARIATION: Self = Self {
        bits: 0b0000_0000_0000_1000,
    };

    pub const HAVE_TRANSLATE_X: Self = Self {
        bits: 0b0000_0000_0001_0000,
    };

    pub const HAVE_TRANSLATE_Y: Self = Self {
        bits: 0b0000_0000_0010_0000,
    };

    pub const HAVE_ROTATION: Self = Self {
        bits: 0b0000_0000_0100_0000,
    };

    pub const HAVE_CONDITION: Self = Self {
        bits: 0b0000_0000_1000_0000,
    };

    pub const HAVE_SCALE_X: Self = Self {
        bits: 0b0000_0001_0000_0000,
    };

    pub const HAVE_SCALE_Y: Self = Self {
        bits: 0b0000_0010_0000_0000,
    };

    pub const HAVE_TCENTER_X: Self = Self {
        bits: 0b0000_0100_0000_0000,
    };

    pub const HAVE_TCENTER_Y: Self = Self {
        bits: 0b0000_1000_0000_0000,
    };

    pub const GID_IS_24BIT: Self = Self {
        bits: 0b0001_0000_0000_0000,
    };

    pub const HAVE_SKEW_X: Self = Self {
        bits: 0b0010_0000_0000_0000,
    };

    pub const HAVE_SKEW_Y: Self = Self {
        bits: 0b0100_0000_0000_0000,
    };

    pub const RESERVED_MASK: Self = Self { bits: 0xFFFF8000 };
}

impl VarcFlags {
    ///  Returns an empty set of flags.
    #[inline]
    pub const fn empty() -> Self {
        Self { bits: 0 }
    }

    /// Returns the set containing all flags.
    #[inline]
    pub const fn all() -> Self {
        Self {
            bits: Self::RESET_UNSPECIFIED_AXES.bits
                | Self::HAVE_AXES.bits
                | Self::AXIS_VALUES_HAVE_VARIATION.bits
                | Self::TRANSFORM_HAS_VARIATION.bits
                | Self::HAVE_TRANSLATE_X.bits
                | Self::HAVE_TRANSLATE_Y.bits
                | Self::HAVE_ROTATION.bits
                | Self::HAVE_CONDITION.bits
                | Self::HAVE_SCALE_X.bits
                | Self::HAVE_SCALE_Y.bits
                | Self::HAVE_TCENTER_X.bits
                | Self::HAVE_TCENTER_Y.bits
                | Self::GID_IS_24BIT.bits
                | Self::HAVE_SKEW_X.bits
                | Self::HAVE_SKEW_Y.bits
                | Self::RESERVED_MASK.bits,
        }
    }

    /// Returns the raw value of the flags currently stored.
    #[inline]
    pub const fn bits(&self) -> u32 {
        self.bits
    }

    /// Convert from underlying bit representation, unless that
    /// representation contains bits that do not correspond to a flag.
    #[inline]
    pub const fn from_bits(bits: u32) -> Option<Self> {
        if (bits & !Self::all().bits()) == 0 {
            Some(Self { bits })
        } else {
            None
        }
    }

    /// Convert from underlying bit representation, dropping any bits
    /// that do not correspond to flags.
    #[inline]
    pub const fn from_bits_truncate(bits: u32) -> Self {
        Self {
            bits: bits & Self::all().bits,
        }
    }

    /// Returns `true` if no flags are currently stored.
    #[inline]
    pub const fn is_empty(&self) -> bool {
        self.bits() == Self::empty().bits()
    }

    /// Returns `true` if there are flags common to both `self` and `other`.
    #[inline]
    pub const fn intersects(&self, other: Self) -> bool {
        !(Self {
            bits: self.bits & other.bits,
        })
        .is_empty()
    }

    /// Returns `true` if all of the flags in `other` are contained within `self`.
    #[inline]
    pub const fn contains(&self, other: Self) -> bool {
        (self.bits & other.bits) == other.bits
    }

    /// Inserts the specified flags in-place.
    #[inline]
    pub fn insert(&mut self, other: Self) {
        self.bits |= other.bits;
    }

    /// Removes the specified flags in-place.
    #[inline]
    pub fn remove(&mut self, other: Self) {
        self.bits &= !other.bits;
    }

    /// Toggles the specified flags in-place.
    #[inline]
    pub fn toggle(&mut self, other: Self) {
        self.bits ^= other.bits;
    }

    /// Returns the intersection between the flags in `self` and
    /// `other`.
    ///
    /// Specifically, the returned set contains only the flags which are
    /// present in *both* `self` *and* `other`.
    ///
    /// This is equivalent to using the `&` operator (e.g.
    /// [`ops::BitAnd`]), as in `flags & other`.
    ///
    /// [`ops::BitAnd`]: https://doc.rust-lang.org/std/ops/trait.BitAnd.html
    #[inline]
    #[must_use]
    pub const fn intersection(self, other: Self) -> Self {
        Self {
            bits: self.bits & other.bits,
        }
    }

    /// Returns the union of between the flags in `self` and `other`.
    ///
    /// Specifically, the returned set contains all flags which are
    /// present in *either* `self` *or* `other`, including any which are
    /// present in both.
    ///
    /// This is equivalent to using the `|` operator (e.g.
    /// [`ops::BitOr`]), as in `flags | other`.
    ///
    /// [`ops::BitOr`]: https://doc.rust-lang.org/std/ops/trait.BitOr.html
    #[inline]
    #[must_use]
    pub const fn union(self, other: Self) -> Self {
        Self {
            bits: self.bits | other.bits,
        }
    }

    /// Returns the difference between the flags in `self` and `other`.
    ///
    /// Specifically, the returned set contains all flags present in
    /// `self`, except for the ones present in `other`.
    ///
    /// It is also conceptually equivalent to the "bit-clear" operation:
    /// `flags & !other` (and this syntax is also supported).
    ///
    /// This is equivalent to using the `-` operator (e.g.
    /// [`ops::Sub`]), as in `flags - other`.
    ///
    /// [`ops::Sub`]: https://doc.rust-lang.org/std/ops/trait.Sub.html
    #[inline]
    #[must_use]
    pub const fn difference(self, other: Self) -> Self {
        Self {
            bits: self.bits & !other.bits,
        }
    }
}

impl std::ops::BitOr for VarcFlags {
    type Output = Self;

    /// Returns the union of the two sets of flags.
    #[inline]
    fn bitor(self, other: VarcFlags) -> Self {
        Self {
            bits: self.bits | other.bits,
        }
    }
}

impl std::ops::BitOrAssign for VarcFlags {
    /// Adds the set of flags.
    #[inline]
    fn bitor_assign(&mut self, other: Self) {
        self.bits |= other.bits;
    }
}

impl std::ops::BitXor for VarcFlags {
    type Output = Self;

    /// Returns the left flags, but with all the right flags toggled.
    #[inline]
    fn bitxor(self, other: Self) -> Self {
        Self {
            bits: self.bits ^ other.bits,
        }
    }
}

impl std::ops::BitXorAssign for VarcFlags {
    /// Toggles the set of flags.
    #[inline]
    fn bitxor_assign(&mut self, other: Self) {
        self.bits ^= other.bits;
    }
}

impl std::ops::BitAnd for VarcFlags {
    type Output = Self;

    /// Returns the intersection between the two sets of flags.
    #[inline]
    fn bitand(self, other: Self) -> Self {
        Self {
            bits: self.bits & other.bits,
        }
    }
}

impl std::ops::BitAndAssign for VarcFlags {
    /// Disables all flags disabled in the set.
    #[inline]
    fn bitand_assign(&mut self, other: Self) {
        self.bits &= other.bits;
    }
}

impl std::ops::Sub for VarcFlags {
    type Output = Self;

    /// Returns the set difference of the two sets of flags.
    #[inline]
    fn sub(self, other: Self) -> Self {
        Self {
            bits: self.bits & !other.bits,
        }
    }
}

impl std::ops::SubAssign for VarcFlags {
    /// Disables all flags enabled in the set.
    #[inline]
    fn sub_assign(&mut self, other: Self) {
        self.bits &= !other.bits;
    }
}

impl std::ops::Not for VarcFlags {
    type Output = Self;

    /// Returns the complement of this set of flags.
    #[inline]
    fn not(self) -> Self {
        Self { bits: !self.bits } & Self::all()
    }
}

impl std::fmt::Debug for VarcFlags {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        let members: &[(&str, Self)] = &[
            ("RESET_UNSPECIFIED_AXES", Self::RESET_UNSPECIFIED_AXES),
            ("HAVE_AXES", Self::HAVE_AXES),
            (
                "AXIS_VALUES_HAVE_VARIATION",
                Self::AXIS_VALUES_HAVE_VARIATION,
            ),
            ("TRANSFORM_HAS_VARIATION", Self::TRANSFORM_HAS_VARIATION),
            ("HAVE_TRANSLATE_X", Self::HAVE_TRANSLATE_X),
            ("HAVE_TRANSLATE_Y", Self::HAVE_TRANSLATE_Y),
            ("HAVE_ROTATION", Self::HAVE_ROTATION),
            ("HAVE_CONDITION", Self::HAVE_CONDITION),
            ("HAVE_SCALE_X", Self::HAVE_SCALE_X),
            ("HAVE_SCALE_Y", Self::HAVE_SCALE_Y),
            ("HAVE_TCENTER_X", Self::HAVE_TCENTER_X),
            ("HAVE_TCENTER_Y", Self::HAVE_TCENTER_Y),
            ("GID_IS_24BIT", Self::GID_IS_24BIT),
            ("HAVE_SKEW_X", Self::HAVE_SKEW_X),
            ("HAVE_SKEW_Y", Self::HAVE_SKEW_Y),
            ("RESERVED_MASK", Self::RESERVED_MASK),
        ];
        let mut first = true;
        for (name, value) in members {
            if self.contains(*value) {
                if !first {
                    f.write_str(" | ")?;
                }
                first = false;
                f.write_str(name)?;
            }
        }
        if first {
            f.write_str("(empty)")?;
        }
        Ok(())
    }
}

impl std::fmt::Binary for VarcFlags {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        std::fmt::Binary::fmt(&self.bits, f)
    }
}

impl std::fmt::Octal for VarcFlags {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        std::fmt::Octal::fmt(&self.bits, f)
    }
}

impl std::fmt::LowerHex for VarcFlags {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        std::fmt::LowerHex::fmt(&self.bits, f)
    }
}

impl std::fmt::UpperHex for VarcFlags {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        std::fmt::UpperHex::fmt(&self.bits, f)
    }
}

impl font_types::Scalar for VarcFlags {
    type Raw = <u32 as font_types::Scalar>::Raw;
    fn to_raw(self) -> Self::Raw {
        self.bits().to_raw()
    }
    fn from_raw(raw: Self::Raw) -> Self {
        let t = <u32>::from_raw(raw);
        Self::from_bits_truncate(t)
    }
}

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