small_len 1.1.2

A small library for storing the length in the smallest internal type.
Documentation
use std::num::ParseIntError;
use std::str::FromStr;
use crate::{from_primitive, Length, SmallLength, to_primitive};

impl From<usize> for Length {
    #[inline]
    fn from(value: usize) -> Self {
        Length::new(value)
    }
}

impl From<Length> for SmallLength {
    #[inline]
    fn from(value: Length) -> Self {
        value.index().into()
    }
}

impl From<SmallLength> for Length {
    #[inline]
    fn from(value: SmallLength) -> Self {
        Length {
            index: value.index()
        }
    }
}

impl From<u8> for SmallLength {
    #[inline]
    fn from(v: u8) -> Self {
        SmallLength::Byte(v)
    }
}

impl From<u16> for SmallLength {
    #[inline]
    fn from(v: u16) -> Self {
        if v <= u8::MAX as u16 {
            SmallLength::Byte(v as u8)
        } else {
            SmallLength::Word(v)
        }
    }
}

impl From<u32> for SmallLength {
    #[inline]
    fn from(v: u32) -> Self {
        if v <= u16::MAX as u32 {
            (v as u16).into()
        } else {
            SmallLength::Double(v)
        }
    }
}

impl From<u64> for SmallLength {
    #[inline]
    fn from(v: u64) -> Self {
        if v <= u32::MAX as u64 {
            (v as u32).into()
        } else {
            SmallLength::Quad(v)
        }
    }
}

impl From<usize> for SmallLength {
    #[inline]
    fn from(v: usize) -> Self {
        // Optimize for smaller values, probably should benchmark this
        if v <= u8::MAX as usize {
            return SmallLength::Byte(v as u8)
        }

        if v <= u16::MAX as usize {
            return SmallLength::Word(v as u16)
        }

        (v as u64).into()
    }
}

to_primitive! { usize u8 u16 u32 u64 u128 }

from_primitive! { i8{u8} i16{u16} i32{u32} i64{u64} isize{usize} }

impl FromStr for SmallLength {
    type Err = ParseIntError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let u: usize = s.parse()?;
        Ok(u.into())
    }
}

impl FromStr for Length {
    type Err = ParseIntError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let u: usize = s.parse()?;
        Ok(u.into())
    }
}