//! Bounded decoder for the simulator's binary BVH animation asset format.

#![allow(
    clippy::needless_pass_by_value,
    clippy::too_many_lines,
    clippy::unused_self
)] // Mapped C# signatures and the source catalog are fixed.

use libremetaverse_types::compat::Object;
use libremetaverse_types::{Error, UUID, Vector3};
use std::hash::{Hash, Hasher};

const MAX_ANIMATION_BYTES: usize = 32 * 1024 * 1024;
const MAX_JOINTS: usize = 512;
const MAX_KEYS_PER_JOINT: usize = 10_000;
const MAX_JOINT_NAME_BYTES: usize = 255;

pub(crate) fn dance1() -> UUID {
    UUID::new_with_string("b68a3d7c-de9e-fc87-eec8-543d787e5b0d".into())
        .expect("built-in DANCE1 UUID must be valid")
}

/// Returns the complete built-in viewer animation catalog from the pinned
/// `LibreMetaverse` source snapshot.
pub(crate) fn builtin_animations() -> std::collections::HashMap<UUID, String> {
    const ENTRIES: &[(&str, &str)] = &[
        ("AFRAID", "6b61c8e8-4747-0d75-12d7-e49ff207a4ca"),
        ("AIM_BAZOOKA_R", "b5b4a67d-0aee-30d2-72cd-77b333e932ef"),
        ("AIM_BOW_L", "46bb4359-de38-4ed8-6a22-f1f52fe8f506"),
        ("AIM_HANDGUN_R", "3147d815-6338-b932-f011-16b56d9ac18b"),
        ("AIM_RIFLE_R", "ea633413-8006-180a-c3ba-96dd1d756720"),
        ("ANGRY", "5747a48e-073e-c331-f6f3-7c2149613d3e"),
        ("AWAY", "fd037134-85d4-f241-72c6-4f42164fedee"),
        ("BACKFLIP", "c4ca6188-9127-4f31-0158-23c4e2f93304"),
        ("BELLY_LAUGH", "18b3a4b5-b463-bd48-e4b6-71eaac76c515"),
        ("BLOW_KISS", "db84829b-462c-ee83-1e27-9bbee66bd624"),
        ("BORED", "b906c4ba-703b-1940-32a3-0c7f7d791510"),
        ("BOW", "82e99230-c906-1403-4d9c-3889dd98daba"),
        ("BRUSH", "349a3801-54f9-bf2c-3bd0-1ac89772af01"),
        ("BUSY", "efcf670c-2d18-8128-973a-034ebc806b67"),
        ("CLAP", "9b0c1c4e-8ac7-7969-1494-28c874c4f668"),
        ("COURTBOW", "9ba1c942-08be-e43a-fb29-16ad440efc50"),
        ("CROUCH", "201f3fdf-cb1f-dbec-201f-7333e328ae7c"),
        ("CROUCHWALK", "47f5f6fb-22e5-ae44-f871-73aaaf4a6022"),
        ("CRY", "92624d3e-1068-f1aa-a5ec-8244585193ed"),
        ("CUSTOMIZE", "038fcec9-5ebd-8a8e-0e2e-6e71a0a1ac53"),
        ("CUSTOMIZE_DONE", "6883a61a-b27b-5914-a61e-dda118a9ee2c"),
        ("DANCE1", "b68a3d7c-de9e-fc87-eec8-543d787e5b0d"),
        ("DANCE2", "928cae18-e31d-76fd-9cc9-2f55160ff818"),
        ("DANCE3", "30047778-10ea-1af7-6881-4db7a3a5a114"),
        ("DANCE4", "951469f4-c7b2-c818-9dee-ad7eea8c30b7"),
        ("DANCE5", "4bd69a1d-1114-a0b4-625f-84e0a5237155"),
        ("DANCE6", "cd28b69b-9c95-bb78-3f94-8d605ff1bb12"),
        ("DANCE7", "a54d8ee2-28bb-80a9-7f0c-7afbbe24a5d6"),
        ("DANCE8", "b0dc417c-1f11-af36-2e80-7e7489fa7cdc"),
        ("DEAD", "57abaae6-1d17-7b1b-5f98-6d11a6411276"),
        ("DRINK", "0f86e355-dd31-a61c-fdb0-3a96b9aad05f"),
        ("EMBARRASSED", "514af488-9051-044a-b3fc-d4dbf76377c6"),
        ("EXPRESS_AFRAID", "aa2df84d-cf8f-7218-527b-424a52de766e"),
        ("EXPRESS_ANGER", "1a03b575-9634-b62a-5767-3a679e81f4de"),
        ("EXPRESS_BORED", "214aa6c1-ba6a-4578-f27c-ce7688f61d0d"),
        ("EXPRESS_CRY", "d535471b-85bf-3b4d-a542-93bea4f59d33"),
        ("EXPRESS_DISDAIN", "d4416ff1-09d3-300f-4183-1b68a19b9fc1"),
        (
            "EXPRESS_EMBARRASSED",
            "0b8c8211-d78c-33e8-fa28-c51a9594e424",
        ),
        ("EXPRESS_FROWN", "fee3df48-fa3d-1015-1e26-a205810e3001"),
        ("EXPRESS_KISS", "1e8d90cc-a84e-e135-884c-7c82c8b03a14"),
        ("EXPRESS_LAUGH", "62570842-0950-96f8-341c-809e65110823"),
        ("EXPRESS_OPEN_MOUTH", "d63bc1f9-fc81-9625-a0c6-007176d82eb7"),
        ("EXPRESS_REPULSED", "f76cda94-41d4-a229-2872-e0296e58afe1"),
        ("EXPRESS_SAD", "eb6ebfb2-a4b3-a19c-d388-4dd5c03823f7"),
        ("EXPRESS_SHRUG", "a351b1bc-cc94-aac2-7bea-a7e6ebad15ef"),
        ("EXPRESS_SMILE", "b7c7c833-e3d3-c4e3-9fc0-131237446312"),
        ("EXPRESS_SURPRISE", "728646d9-cc79-08b2-32d6-937f0a835c24"),
        ("EXPRESS_TONGUE_OUT", "835965c6-7f2f-bda2-5deb-2478737f91bf"),
        ("EXPRESS_TOOTHSMILE", "b92ec1a5-e7ce-a76b-2b05-bcdb9311417e"),
        ("EXPRESS_WINK", "da020525-4d94-59d6-23d7-81fdebf33148"),
        ("EXPRESS_WORRY", "9c05e5c7-6f07-6ca4-ed5a-b230390c3950"),
        ("FALLDOWN", "666307d9-a860-572d-6fd4-c3ab8865c094"),
        ("FEMALE_WALK", "f5fc7433-043d-e819-8298-f519a119b688"),
        ("FINGER_WAG", "c1bc7f36-3ba0-d844-f93c-93be945d644f"),
        ("FIST_PUMP", "7db00ccd-f380-f3ee-439d-61968ec69c8a"),
        ("FLY", "aec4610c-757f-bc4e-c092-c6e9caf18daf"),
        ("FLYSLOW", "2b5a38b2-5e00-3a97-a495-4c826bc443e6"),
        ("HELLO", "9b29cd61-c45b-5689-ded2-91756b8d76a9"),
        ("HOLD_BAZOOKA_R", "ef62d355-c815-4816-2474-b1acc21094a6"),
        ("HOLD_BOW_L", "8b102617-bcba-037b-86c1-b76219f90c88"),
        ("HOLD_HANDGUN_R", "efdc1727-8b8a-c800-4077-975fc27ee2f2"),
        ("HOLD_RIFLE_R", "3d94bad0-c55b-7dcc-8763-033c59405d33"),
        ("HOLD_THROW_R", "7570c7b5-1f22-56dd-56ef-a9168241bbb6"),
        ("HOVER", "4ae8016b-31b9-03bb-c401-b1ea941db41d"),
        ("HOVER_DOWN", "20f063ea-8306-2562-0b07-5c853b37b31e"),
        ("HOVER_UP", "62c5de58-cb33-5743-3d07-9e4cd4352864"),
        ("IMPATIENT", "5ea3991f-c293-392e-6860-91dfa01278a3"),
        ("JUMP", "2305bd75-1ca9-b03b-1faa-b176b8a8c49e"),
        ("JUMP_FOR_JOY", "709ea28e-1573-c023-8bf8-520c8bc637fa"),
        ("KISS_MY_BUTT", "19999406-3a3a-d58c-a2ac-d72e555dcf51"),
        ("LAND", "7a17b059-12b2-41b1-570a-186368b6aa6f"),
        ("LAUGH_SHORT", "ca5b3f14-3194-7a2b-c894-aa699b718d1f"),
        ("MEDIUM_LAND", "f4f00d6e-b9fe-9292-f4cb-0ae06ea58d57"),
        ("MOTORCYCLE_SIT", "08464f78-3a8e-2944-cba5-0c94aff3af29"),
        ("MUSCLE_BEACH", "315c3a41-a5f3-0ba4-27da-f893f769e69b"),
        ("NO", "5a977ed9-7f72-44e9-4c4c-6e913df8ae74"),
        ("NO_UNHAPPY", "d83fa0e5-97ed-7eb2-e798-7bd006215cb4"),
        ("NYAH_NYAH", "f061723d-0a18-754f-66ee-29a44795a32f"),
        ("ONETWO_PUNCH", "eefc79be-daae-a239-8c04-890f5d23654a"),
        ("PEACE", "b312b10e-65ab-a0a4-8b3c-1326ea8e3ed9"),
        ("POINT_ME", "17c024cc-eef2-f6a0-3527-9869876d7752"),
        ("POINT_YOU", "ec952cca-61ef-aa3b-2789-4d1344f016de"),
        ("PRE_JUMP", "7a4e87fe-de39-6fcb-6223-024b00893244"),
        ("PUNCH_LEFT", "f3300ad9-3462-1d07-2044-0fef80062da0"),
        ("PUNCH_RIGHT", "c8e42d32-7310-6906-c903-cab5d4a34656"),
        ("REPULSED", "36f81a92-f076-5893-dc4b-7c3795e487cf"),
        ("ROUNDHOUSE_KICK", "49aea43b-5ac3-8a44-b595-96100af0beda"),
        ("RPS_COUNTDOWN", "35db4f7e-28c2-6679-cea9-3ee108f7fc7f"),
        ("RPS_PAPER", "0836b67f-7f7b-f37b-c00a-460dc1521f5a"),
        ("RPS_ROCK", "42dd95d5-0bc6-6392-f650-777304946c0f"),
        ("RPS_SCISSORS", "16803a9f-5140-e042-4d7b-d28ba247c325"),
        ("RUN", "05ddbff8-aaa9-92a1-2b74-8fe77a29b445"),
        ("SAD", "0eb702e2-cc5a-9a88-56a5-661a55c0676a"),
        ("SALUTE", "cd7668a6-7011-d7e2-ead8-fc69eff1a104"),
        ("SHOOT_BOW_L", "e04d450d-fdb5-0432-fd68-818aaf5935f8"),
        ("SHOUT", "6bd01860-4ebd-127a-bb3d-d1427e8e0c42"),
        ("SHRUG", "70ea714f-3a97-d742-1b01-590a8fcd1db5"),
        ("SIT", "1a5fe8ac-a804-8a5d-7cbd-56bd83184568"),
        ("SIT_FEMALE", "b1709c8d-ecd3-54a1-4f28-d55ac0840782"),
        ("SIT_GENERIC", "245f3c54-f1c0-bf2e-811f-46d8eeb386e7"),
        ("SIT_GROUND", "1c7600d6-661f-b87b-efe2-d7421eb93c86"),
        (
            "SIT_GROUND_staticRAINED",
            "1a2bd58e-87ff-0df8-0b4c-53e047b0bb6e",
        ),
        ("SIT_TO_STAND", "a8dee56f-2eae-9e7a-05a2-6fb92b97e21e"),
        ("SLEEP", "f2bed5f9-9d44-39af-b0cd-257b2a17fe40"),
        ("SMOKE_IDLE", "d2f2ee58-8ad1-06c9-d8d3-3827ba31567a"),
        ("SMOKE_INHALE", "6802d553-49da-0778-9f85-1599a2266526"),
        ("SMOKE_THROW_DOWN", "0a9fb970-8b44-9114-d3a9-bf69cfe804d6"),
        ("SNAPSHOT", "eae8905b-271a-99e2-4c0e-31106afd100c"),
        ("STAND", "2408fe9e-df1d-1d7d-f4ff-1384fa7b350f"),
        ("STANDUP", "3da1d753-028a-5446-24f3-9c9b856d9422"),
        ("STAND_1", "15468e00-3400-bb66-cecc-646d7c14458e"),
        ("STAND_2", "370f3a20-6ca6-9971-848c-9a01bc42ae3c"),
        ("STAND_3", "42b46214-4b44-79ae-deb8-0df61424ff4b"),
        ("STAND_4", "f22fed8b-a5ed-2c93-64d5-bdd8b93c889f"),
        ("STRETCH", "80700431-74ec-a008-14f8-77575e73693f"),
        ("STRIDE", "1cb562b0-ba21-2202-efb3-30f82cdf9595"),
        ("SURF", "41426836-7437-7e89-025d-0aa4d10f1d69"),
        ("SURPRISE", "313b9881-4302-73c0-c7d0-0e7a36b6c224"),
        ("SWORD_STRIKE", "85428680-6bf9-3e64-b489-6f81087c24bd"),
        ("TALK", "5c682a95-6da4-a463-0bf6-0f5b7be129d1"),
        ("TANTRUM", "11000694-3f41-adc2-606b-eee1d66f3724"),
        ("THROW_R", "aa134404-7dac-7aca-2cba-435f9db875ca"),
        ("TRYON_SHIRT", "83ff59fe-2346-f236-9009-4e3608af64c1"),
        ("TURNLEFT", "56e0ba0d-4a9f-7f27-6117-32f2ebbf6135"),
        ("TURNRIGHT", "2d6daa51-3192-6794-8e2e-a15f8338ec30"),
        ("TYPE", "c541c47f-e0c0-058b-ad1a-d6ae3a4584d9"),
        ("WALK", "6ed24bd8-91aa-4b12-ccc7-c97c857ab4e0"),
        ("WHISPER", "7693f268-06c7-ea71-fa21-2b30d6533f8f"),
        ("WHISTLE", "b1ed7982-c68e-a982-7561-52a88a5298c0"),
        ("WINK", "869ecdad-a44b-671e-3266-56aef2e3ac2e"),
        ("WINK_HOLLYWOOD", "c0c4030f-c02b-49de-24ba-2331f43fe41c"),
        ("WORRY", "9f496bd2-589a-709f-16cc-69bf7df1d36c"),
        ("YES", "15dd911d-be82-2856-26db-27659b142875"),
        ("YES_HAPPY", "b8c8b2a3-9008-1771-3bfc-90924955ab2d"),
        ("YOGA_FLOAT", "42ecd00b-9947-a97c-400a-bbc9174c7aeb"),
    ];
    ENTRIES
        .iter()
        .map(|(name, id)| {
            (
                UUID::new_with_string((*id).to_owned()).expect("built-in animation UUID is valid"),
                (*name).to_owned(),
            )
        })
        .collect()
}

pub(crate) fn builtin_animation(name: &str) -> UUID {
    builtin_animations()
        .into_iter()
        .find_map(|(id, candidate)| (candidate == name).then_some(id))
        .unwrap_or_else(|| panic!("unknown built-in animation {name}"))
}

#[derive(Clone, Debug)]
pub struct BinBVHJointKey {
    pub key_element: Vector3,
    pub time: f32,
}

#[derive(Clone, Debug)]
pub struct BinBVHJoint {
    pub name: String,
    pub priority: i32,
    pub tag: Object,
    pub positionkeys: Vec<BinBVHJointKey>,
    pub rotationkeys: Vec<BinBVHJointKey>,
}

impl BinBVHJoint {
    pub(crate) fn native_equals(&self, other: &Self) -> bool {
        self.priority == other.priority
            && self.name == other.name
            && keys_equal(&self.rotationkeys, &other.rotationkeys)
            && keys_equal(&self.positionkeys, &other.positionkeys)
    }

    pub(crate) fn native_get_hash_code(&self) -> i32 {
        let mut hasher = std::collections::hash_map::DefaultHasher::new();
        self.priority.hash(&mut hasher);
        self.name.hash(&mut hasher);
        for key in self.rotationkeys.iter().chain(&self.positionkeys) {
            key.time.to_bits().hash(&mut hasher);
            key.key_element.x.to_bits().hash(&mut hasher);
            key.key_element.y.to_bits().hash(&mut hasher);
            key.key_element.z.to_bits().hash(&mut hasher);
        }
        fold_hash(hasher.finish())
    }
}

pub(crate) fn key_equal(left: &BinBVHJointKey, right: &BinBVHJointKey) -> bool {
    left.time.to_bits() == right.time.to_bits() && Vector3::eq(left.key_element, right.key_element)
}

pub(crate) fn keys_equal(left: &[BinBVHJointKey], right: &[BinBVHJointKey]) -> bool {
    left.len() == right.len()
        && left
            .iter()
            .zip(right)
            .all(|(left, right)| key_equal(left, right))
}

pub(crate) fn joints_equal(left: &[BinBVHJoint], right: &[BinBVHJoint]) -> bool {
    left.len() == right.len()
        && left
            .iter()
            .zip(right)
            .all(|(left, right)| left.native_equals(right))
}

#[derive(Clone, Debug)]
pub struct BinBVHAnimationReader {
    pub ease_in_time: f32,
    pub ease_out_time: f32,
    pub expression_name: String,
    pub hand_pose: u32,
    pub in_point: f32,
    pub joint_count: u32,
    pub length: f32,
    pub loop_: bool,
    pub out_point: f32,
    pub priority: i32,
    pub joints: Vec<BinBVHJoint>,
    pub unknown0: u16,
    pub unknown1: u16,
}

impl BinBVHAnimationReader {
    pub(crate) fn native_new(data: Vec<u8>) -> Result<Self, Error> {
        if data.len() > MAX_ANIMATION_BYTES {
            return Err(Error::Argument);
        }
        let mut cursor = Cursor::new(&data);
        let unknown0 = cursor.u16()?;
        let unknown1 = cursor.u16()?;
        let priority = cursor.i32()?;
        let length = cursor.f32()?;
        let expression_name = cursor.string(MAX_JOINT_NAME_BYTES)?;
        let in_point = cursor.f32()?;
        let out_point = cursor.f32()?;
        let loop_ = cursor.i32()? != 0;
        let ease_in_time = cursor.f32()?;
        let ease_out_time = cursor.f32()?;
        let hand_pose = cursor.u32()?;
        let joint_count = cursor.u32()?;
        if length < 0.0
            || in_point < 0.0
            || out_point < in_point
            || ease_in_time < 0.0
            || ease_out_time < 0.0
        {
            return Err(Error::Argument);
        }
        let count = usize::try_from(joint_count).map_err(|_| Error::Argument)?;
        if count > MAX_JOINTS {
            return Err(Error::Argument);
        }
        let mut result = Self {
            ease_in_time,
            ease_out_time,
            expression_name,
            hand_pose,
            in_point,
            joint_count,
            length,
            loop_,
            out_point,
            priority,
            joints: Vec::with_capacity(count),
            unknown0,
            unknown1,
        };
        for _ in 0..count {
            result.joints.push(result.read_joint_cursor(&mut cursor)?);
        }
        Ok(result)
    }

    fn read_joint_cursor(&self, cursor: &mut Cursor<'_>) -> Result<BinBVHJoint, Error> {
        let name = cursor.string(MAX_JOINT_NAME_BYTES)?;
        let priority = cursor.i32()?;
        let rotation_count = cursor.count(MAX_KEYS_PER_JOINT)?;
        let rotationkeys = self.read_keys_cursor(cursor, rotation_count, -1.0, 1.0)?;
        let position_count = cursor.count(MAX_KEYS_PER_JOINT)?;
        let positionkeys = self.read_keys_cursor(cursor, position_count, -0.5, 1.5)?;
        Ok(BinBVHJoint {
            name,
            priority,
            tag: Object::Undefined,
            positionkeys,
            rotationkeys,
        })
    }

    fn read_keys_cursor(
        &self,
        cursor: &mut Cursor<'_>,
        count: usize,
        min: f32,
        max: f32,
    ) -> Result<Vec<BinBVHJointKey>, Error> {
        let mut keys = Vec::with_capacity(count);
        for _ in 0..count {
            keys.push(BinBVHJointKey {
                time: decode_u16(cursor.u16()?, self.in_point, self.out_point),
                key_element: Vector3 {
                    x: decode_u16(cursor.u16()?, min, max),
                    y: decode_u16(cursor.u16()?, min, max),
                    z: decode_u16(cursor.u16()?, min, max),
                },
            });
        }
        Ok(keys)
    }

    pub(crate) fn native_read_bytes_until_null(
        &self,
        data: Vec<u8>,
        offset: &mut i32,
    ) -> Result<String, Error> {
        let start = usize::try_from(*offset).map_err(|_| Error::Argument)?;
        let mut cursor = Cursor::at(&data, start)?;
        let value = cursor.string(MAX_JOINT_NAME_BYTES)?;
        *offset = i32::try_from(cursor.position).map_err(|_| Error::Argument)?;
        Ok(value)
    }

    pub(crate) fn native_read_joint(
        &self,
        data: Vec<u8>,
        offset: &mut i32,
    ) -> Result<BinBVHJoint, Error> {
        let start = usize::try_from(*offset).map_err(|_| Error::Argument)?;
        let mut cursor = Cursor::at(&data, start)?;
        let joint = self.read_joint_cursor(&mut cursor)?;
        *offset = i32::try_from(cursor.position).map_err(|_| Error::Argument)?;
        Ok(joint)
    }

    pub(crate) fn native_read_keys(
        &self,
        data: Vec<u8>,
        offset: &mut i32,
        key_count: i32,
        min: f32,
        max: f32,
    ) -> Result<Vec<BinBVHJointKey>, Error> {
        let count = usize::try_from(key_count).map_err(|_| Error::Argument)?;
        if count > MAX_KEYS_PER_JOINT || !min.is_finite() || !max.is_finite() || min > max {
            return Err(Error::Argument);
        }
        let start = usize::try_from(*offset).map_err(|_| Error::Argument)?;
        let mut cursor = Cursor::at(&data, start)?;
        let keys = self.read_keys_cursor(&mut cursor, count, min, max)?;
        *offset = i32::try_from(cursor.position).map_err(|_| Error::Argument)?;
        Ok(keys)
    }

    pub(crate) fn native_equals(&self, other: Option<&Self>) -> bool {
        let Some(other) = other else { return false };
        self.loop_ == other.loop_
            && self.out_point.to_bits() == other.out_point.to_bits()
            && self.in_point.to_bits() == other.in_point.to_bits()
            && self.length.to_bits() == other.length.to_bits()
            && self.hand_pose == other.hand_pose
            && self.joint_count == other.joint_count
            && self.ease_in_time.to_bits() == other.ease_in_time.to_bits()
            && self.ease_out_time.to_bits() == other.ease_out_time.to_bits()
            && self.priority == other.priority
            && self.unknown0 == other.unknown0
            && self.unknown1 == other.unknown1
            && self.joints.len() == other.joints.len()
            && self
                .joints
                .iter()
                .zip(&other.joints)
                .all(|(left, right)| left.native_equals(right))
    }

    pub(crate) fn native_get_hash_code(&self) -> i32 {
        let mut hasher = std::collections::hash_map::DefaultHasher::new();
        self.loop_.hash(&mut hasher);
        self.out_point.to_bits().hash(&mut hasher);
        self.in_point.to_bits().hash(&mut hasher);
        self.length.to_bits().hash(&mut hasher);
        self.hand_pose.hash(&mut hasher);
        self.priority.hash(&mut hasher);
        for joint in &self.joints {
            joint.native_get_hash_code().hash(&mut hasher);
        }
        fold_hash(hasher.finish())
    }
}

fn fold_hash(hash: u64) -> i32 {
    let folded = hash ^ (hash >> 32);
    u32::try_from(folded & u64::from(u32::MAX))
        .unwrap_or_default()
        .cast_signed()
}

fn decode_u16(value: u16, min: f32, max: f32) -> f32 {
    min + (f32::from(value) / f32::from(u16::MAX)) * (max - min)
}

struct Cursor<'a> {
    data: &'a [u8],
    position: usize,
}

impl<'a> Cursor<'a> {
    const fn new(data: &'a [u8]) -> Self {
        Self { data, position: 0 }
    }

    fn at(data: &'a [u8], position: usize) -> Result<Self, Error> {
        if position > data.len() {
            return Err(Error::IndexOutOfRange);
        }
        Ok(Self { data, position })
    }

    fn take<const N: usize>(&mut self) -> Result<[u8; N], Error> {
        let end = self.position.checked_add(N).ok_or(Error::IndexOutOfRange)?;
        let bytes = self
            .data
            .get(self.position..end)
            .ok_or(Error::IndexOutOfRange)?;
        self.position = end;
        bytes.try_into().map_err(|_| Error::IndexOutOfRange)
    }

    fn u16(&mut self) -> Result<u16, Error> {
        Ok(u16::from_le_bytes(self.take()?))
    }

    fn u32(&mut self) -> Result<u32, Error> {
        Ok(u32::from_le_bytes(self.take()?))
    }

    fn i32(&mut self) -> Result<i32, Error> {
        Ok(i32::from_le_bytes(self.take()?))
    }

    fn f32(&mut self) -> Result<f32, Error> {
        let value = f32::from_le_bytes(self.take()?);
        value.is_finite().then_some(value).ok_or(Error::Argument)
    }

    fn count(&mut self, maximum: usize) -> Result<usize, Error> {
        let value = usize::try_from(self.i32()?).map_err(|_| Error::Argument)?;
        (value <= maximum).then_some(value).ok_or(Error::Argument)
    }

    fn string(&mut self, maximum: usize) -> Result<String, Error> {
        let remaining = self
            .data
            .get(self.position..)
            .ok_or(Error::IndexOutOfRange)?;
        let length = remaining
            .iter()
            .take(maximum.saturating_add(1))
            .position(|byte| *byte == 0)
            .ok_or(Error::Argument)?;
        if length > maximum {
            return Err(Error::Argument);
        }
        let bytes = &remaining[..length];
        self.position = self
            .position
            .checked_add(length + 1)
            .ok_or(Error::IndexOutOfRange)?;
        String::from_utf8(bytes.to_vec()).map_err(|_| Error::Argument)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn built_in_catalog_contains_every_pinned_animation_once() {
        let catalog = builtin_animations();
        assert_eq!(catalog.len(), 135);
        assert_eq!(catalog.get(&dance1()).map(String::as_str), Some("DANCE1"));
        let yoga = UUID::new_with_string("42ecd00b-9947-a97c-400a-bbc9174c7aeb".into())
            .expect("YOGA_FLOAT UUID");
        assert_eq!(catalog.get(&yoga).map(String::as_str), Some("YOGA_FLOAT"));
    }
}
