// 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::*;

/// [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(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct VarcMarker {}

impl VarcMarker {
    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
    }
}

impl MinByteRange for VarcMarker {
    fn min_byte_range(&self) -> Range<usize> {
        0..self.var_composite_glyphs_offset_byte_range().end
    }
}

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> {
        let mut cursor = data.cursor();
        cursor.advance::<MajorMinor>();
        cursor.advance::<Offset32>();
        cursor.advance::<Offset32>();
        cursor.advance::<Offset32>();
        cursor.advance::<Offset32>();
        cursor.advance::<Offset32>();
        cursor.finish(VarcMarker {})
    }
}

/// [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)
pub type Varc<'a> = TableRef<'a, VarcMarker>;

#[allow(clippy::needless_lifetimes)]
impl<'a> Varc<'a> {
    /// Major/minor version number. Set to 1.0.
    pub fn version(&self) -> MajorMinor {
        let range = self.shape.version_byte_range();
        self.data.read_at(range.start).unwrap()
    }

    pub fn coverage_offset(&self) -> Offset32 {
        let range = self.shape.coverage_offset_byte_range();
        self.data.read_at(range.start).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.shape.multi_var_store_offset_byte_range();
        self.data.read_at(range.start).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.shape.condition_list_offset_byte_range();
        self.data.read_at(range.start).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.shape.axis_indices_list_offset_byte_range();
        self.data.read_at(range.start).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.shape.var_composite_glyphs_offset_byte_range();
        self.data.read_at(range.start).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)
    }
}

#[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 MultiItemVariationStoreMarker {
    const FORMAT: u16 = 1;
}

/// * <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(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct MultiItemVariationStoreMarker {
    variation_data_offsets_byte_len: usize,
}

impl MultiItemVariationStoreMarker {
    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 start = self.variation_data_count_byte_range().end;
        start..start + self.variation_data_offsets_byte_len
    }
}

impl MinByteRange for MultiItemVariationStoreMarker {
    fn min_byte_range(&self) -> Range<usize> {
        0..self.variation_data_offsets_byte_range().end
    }
}

impl<'a> FontRead<'a> for MultiItemVariationStore<'a> {
    fn read(data: FontData<'a>) -> Result<Self, ReadError> {
        let mut cursor = data.cursor();
        cursor.advance::<u16>();
        cursor.advance::<Offset32>();
        let variation_data_count: u16 = cursor.read()?;
        let variation_data_offsets_byte_len = (variation_data_count as usize)
            .checked_mul(Offset32::RAW_BYTE_LEN)
            .ok_or(ReadError::OutOfBounds)?;
        cursor.advance_by(variation_data_offsets_byte_len);
        cursor.finish(MultiItemVariationStoreMarker {
            variation_data_offsets_byte_len,
        })
    }
}

/// * <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>
pub type MultiItemVariationStore<'a> = TableRef<'a, MultiItemVariationStoreMarker>;

#[allow(clippy::needless_lifetimes)]
impl<'a> MultiItemVariationStore<'a> {
    pub fn format(&self) -> u16 {
        let range = self.shape.format_byte_range();
        self.data.read_at(range.start).unwrap()
    }

    pub fn region_list_offset(&self) -> Offset32 {
        let range = self.shape.region_list_offset_byte_range();
        self.data.read_at(range.start).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.shape.variation_data_count_byte_range();
        self.data.read_at(range.start).unwrap()
    }

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

    /// 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, ())
    }
}

#[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({
                let data = self.data;
                Field::new(
                    "variation_data_offsets",
                    FieldType::array_of_offsets(
                        better_type_name::<MultiItemVariationData>(),
                        self.variation_data_offsets(),
                        move |off| {
                            let target = off.get().resolve::<MultiItemVariationData>(data);
                            FieldType::offset(off.get(), target)
                        },
                    ),
                )
            }),
            _ => 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)
    }
}

#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct SparseVariationRegionListMarker {
    region_offsets_byte_len: usize,
}

impl SparseVariationRegionListMarker {
    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 start = self.region_count_byte_range().end;
        start..start + self.region_offsets_byte_len
    }
}

impl MinByteRange for SparseVariationRegionListMarker {
    fn min_byte_range(&self) -> Range<usize> {
        0..self.region_offsets_byte_range().end
    }
}

impl<'a> FontRead<'a> for SparseVariationRegionList<'a> {
    fn read(data: FontData<'a>) -> Result<Self, ReadError> {
        let mut cursor = data.cursor();
        let region_count: u16 = cursor.read()?;
        let region_offsets_byte_len = (region_count as usize)
            .checked_mul(Offset32::RAW_BYTE_LEN)
            .ok_or(ReadError::OutOfBounds)?;
        cursor.advance_by(region_offsets_byte_len);
        cursor.finish(SparseVariationRegionListMarker {
            region_offsets_byte_len,
        })
    }
}

pub type SparseVariationRegionList<'a> = TableRef<'a, SparseVariationRegionListMarker>;

#[allow(clippy::needless_lifetimes)]
impl<'a> SparseVariationRegionList<'a> {
    pub fn region_count(&self) -> u16 {
        let range = self.shape.region_count_byte_range();
        self.data.read_at(range.start).unwrap()
    }

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

    /// 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, ())
    }
}

#[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({
                let data = self.data;
                Field::new(
                    "region_offsets",
                    FieldType::array_of_offsets(
                        better_type_name::<SparseVariationRegion>(),
                        self.region_offsets(),
                        move |off| {
                            let target = off.get().resolve::<SparseVariationRegion>(data);
                            FieldType::offset(off.get(), target)
                        },
                    ),
                )
            }),
            _ => 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)
    }
}

#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct SparseVariationRegionMarker {
    region_axis_offsets_byte_len: usize,
}

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

    pub fn region_axis_offsets_byte_range(&self) -> Range<usize> {
        let start = self.region_axis_count_byte_range().end;
        start..start + self.region_axis_offsets_byte_len
    }
}

impl MinByteRange for SparseVariationRegionMarker {
    fn min_byte_range(&self) -> Range<usize> {
        0..self.region_axis_offsets_byte_range().end
    }
}

impl<'a> FontRead<'a> for SparseVariationRegion<'a> {
    fn read(data: FontData<'a>) -> Result<Self, ReadError> {
        let mut cursor = data.cursor();
        let region_axis_count: u16 = cursor.read()?;
        let region_axis_offsets_byte_len = (region_axis_count as usize)
            .checked_mul(SparseRegionAxisCoordinates::RAW_BYTE_LEN)
            .ok_or(ReadError::OutOfBounds)?;
        cursor.advance_by(region_axis_offsets_byte_len);
        cursor.finish(SparseVariationRegionMarker {
            region_axis_offsets_byte_len,
        })
    }
}

pub type SparseVariationRegion<'a> = TableRef<'a, SparseVariationRegionMarker>;

#[allow(clippy::needless_lifetimes)]
impl<'a> SparseVariationRegion<'a> {
    pub fn region_axis_count(&self) -> u16 {
        let range = self.shape.region_axis_count_byte_range();
        self.data.read_at(range.start).unwrap()
    }

    pub fn region_axis_offsets(&self) -> &'a [SparseRegionAxisCoordinates] {
        let range = self.shape.region_axis_offsets_byte_range();
        self.data.read_array(range).unwrap()
    }
}

#[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_axis_offsets",
                traversal::FieldType::array_of_records(
                    stringify!(SparseRegionAxisCoordinates),
                    self.region_axis_offsets(),
                    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 MultiItemVariationDataMarker {
    const FORMAT: u8 = 1;
}

#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct MultiItemVariationDataMarker {
    region_indices_byte_len: usize,
    raw_delta_sets_byte_len: usize,
}

impl MultiItemVariationDataMarker {
    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 start = self.region_index_count_byte_range().end;
        start..start + self.region_indices_byte_len
    }

    pub fn raw_delta_sets_byte_range(&self) -> Range<usize> {
        let start = self.region_indices_byte_range().end;
        start..start + self.raw_delta_sets_byte_len
    }
}

impl MinByteRange for MultiItemVariationDataMarker {
    fn min_byte_range(&self) -> Range<usize> {
        0..self.raw_delta_sets_byte_range().end
    }
}

impl<'a> FontRead<'a> for MultiItemVariationData<'a> {
    fn read(data: FontData<'a>) -> Result<Self, ReadError> {
        let mut cursor = data.cursor();
        cursor.advance::<u8>();
        let region_index_count: u16 = cursor.read()?;
        let region_indices_byte_len = (region_index_count as usize)
            .checked_mul(u16::RAW_BYTE_LEN)
            .ok_or(ReadError::OutOfBounds)?;
        cursor.advance_by(region_indices_byte_len);
        let raw_delta_sets_byte_len =
            cursor.remaining_bytes() / u8::RAW_BYTE_LEN * u8::RAW_BYTE_LEN;
        cursor.advance_by(raw_delta_sets_byte_len);
        cursor.finish(MultiItemVariationDataMarker {
            region_indices_byte_len,
            raw_delta_sets_byte_len,
        })
    }
}

pub type MultiItemVariationData<'a> = TableRef<'a, MultiItemVariationDataMarker>;

#[allow(clippy::needless_lifetimes)]
impl<'a> MultiItemVariationData<'a> {
    pub fn format(&self) -> u8 {
        let range = self.shape.format_byte_range();
        self.data.read_at(range.start).unwrap()
    }

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

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

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

#[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)
    }
}

#[derive(Debug, Clone, Copy)]
#[doc(hidden)]
pub struct ConditionListMarker {
    condition_offsets_byte_len: usize,
}

impl ConditionListMarker {
    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 start = self.condition_count_byte_range().end;
        start..start + self.condition_offsets_byte_len
    }
}

impl MinByteRange for ConditionListMarker {
    fn min_byte_range(&self) -> Range<usize> {
        0..self.condition_offsets_byte_range().end
    }
}

impl<'a> FontRead<'a> for ConditionList<'a> {
    fn read(data: FontData<'a>) -> Result<Self, ReadError> {
        let mut cursor = data.cursor();
        let condition_count: u32 = cursor.read()?;
        let condition_offsets_byte_len = (condition_count as usize)
            .checked_mul(Offset32::RAW_BYTE_LEN)
            .ok_or(ReadError::OutOfBounds)?;
        cursor.advance_by(condition_offsets_byte_len);
        cursor.finish(ConditionListMarker {
            condition_offsets_byte_len,
        })
    }
}

pub type ConditionList<'a> = TableRef<'a, ConditionListMarker>;

#[allow(clippy::needless_lifetimes)]
impl<'a> ConditionList<'a> {
    pub fn condition_count(&self) -> u32 {
        let range = self.shape.condition_count_byte_range();
        self.data.read_at(range.start).unwrap()
    }

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

    /// 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, ())
    }
}

#[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({
                let data = self.data;
                Field::new(
                    "condition_offsets",
                    FieldType::array_of_offsets(
                        better_type_name::<Condition>(),
                        self.condition_offsets(),
                        move |off| {
                            let target = off.get().resolve::<Condition>(data);
                            FieldType::offset(off.get(), target)
                        },
                    ),
                )
            }),
            _ => 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()
    }
}
