use std::{
fmt,
error,
str::Utf8Error,
cmp::{Ord, Ordering},
};
#[cfg(feature = "serde")]
use serde::{
Serialize,
Serializer,
Deserialize,
Deserializer,
de::{Visitor, Error as DeError}
};
pub trait CopystrComparable {
fn relevant_bytes(&self) -> &[u8];
}
impl CopystrComparable for String {
fn relevant_bytes(&self) -> &[u8] {
self.as_bytes()
}
}
impl CopystrComparable for &str {
fn relevant_bytes(&self) -> &[u8] {
self.as_bytes()
}
}
#[macro_export]
macro_rules! csstruct {
($css:ident, $asize:expr) => {
#[allow(non_camel_case_types)]
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct $css {
raw: [u8; $asize],
len: usize,
}
impl $css {
pub fn new(string: &str) -> Result<Self, Error> {
$css::from_slice(string.as_bytes())
}
pub fn from_slice(raw: &[u8]) -> Result<Self, Error> {
let len = raw.len();
if len > $asize {
return Err(Error::TooBig($asize, len));
}
let mut writeable: [u8; $asize] = [0; $asize];
let (writearea, _) = writeable.split_at_mut(len);
writearea.copy_from_slice(&raw);
Ok($css { raw: writeable, len })
}
pub const fn assume_from_array(arr: [u8; $asize]) -> Self {
$css { raw: arr, len: $asize }
}
pub fn capacity() -> usize {
$asize
}
pub fn len(&self) -> usize {
self.len
}
pub fn is_empty(&self) -> bool {
self.len == 0
}
pub fn as_str(&self) -> &str {
let (s, _) = self.raw.split_at(self.len);
std::str::from_utf8(s).expect("Invalid UTF8.")
}
pub fn try_as_str(&self) -> Result<&str, Error> {
let (s, _) = self.raw.split_at(self.len);
std::str::from_utf8(s).map_err(|e| Error::from(e))
}
pub fn as_bytes(&self) -> &[u8] {
let (b, _) = self.raw.split_at(self.len);
b
}
pub fn as_all_bytes(&self) -> &[u8] {
&self.raw
}
}
impl std::convert::TryFrom<&str> for $css {
type Error = Error;
fn try_from(value: &str) -> Result<Self, Self::Error> {
$css::new(value)
}
}
impl fmt::Display for $css {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.as_str())
}
}
impl Default for $css {
fn default() -> Self {
$css {
raw: [0; $asize],
len: 0,
}
}
}
impl<T: CopystrComparable> PartialEq<T> for $css {
#[inline]
fn eq(&self, other: &T) -> bool {
self.as_bytes() == other.relevant_bytes()
}
#[inline]
fn ne(&self, other: &T) -> bool {
!(self).eq(other)
}
}
impl<T: CopystrComparable> PartialOrd<T> for $css {
#[inline]
fn partial_cmp(&self, other: &T) -> Option<Ordering> {
Some(self.as_bytes().cmp(other.relevant_bytes()))
}
}
#[cfg(feature = "serde")]
impl Serialize for $css {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(self.as_str())
}
}
#[cfg(feature = "serde")]
impl<'de> Deserialize<'de> for $css {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'de>
{
struct CSSVisitor;
impl<'de> Visitor<'de> for CSSVisitor {
type Value = $css;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
let msg = format!("a UTF-8 string no bigger than {} bytes", $asize);
formatter.write_str(msg.as_str())
}
fn visit_str<E: DeError>(self, v: &str) -> Result<Self::Value, E> {
$css::new(v).map_err(|e| E::custom(e))
}
fn visit_borrowed_str<E>(self, v: &'de str) -> Result<Self::Value, E>
where E: DeError,
{
$css::new(v).map_err(|e| E::custom(e))
}
fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
where E: DeError,
{
$css::new(v.as_str()).map_err(|e| E::custom(e))
}
}
deserializer.deserialize_str(CSSVisitor)
}
}
};
}
csstruct!(s3, 3);
csstruct!(s4, 4);
csstruct!(s5, 5);
csstruct!(s6, 6);
csstruct!(s7, 7);
csstruct!(s8, 8);
csstruct!(s9, 9);
csstruct!(s10, 10);
csstruct!(s11, 11);
csstruct!(s12, 12);
csstruct!(s13, 13);
csstruct!(s14, 14);
csstruct!(s15, 15);
csstruct!(s16, 16);
csstruct!(s17, 17);
csstruct!(s18, 18);
csstruct!(s19, 19);
csstruct!(s20, 20);
csstruct!(s21, 21);
csstruct!(s22, 22);
csstruct!(s23, 23);
csstruct!(s24, 24);
csstruct!(s25, 25);
csstruct!(s26, 26);
csstruct!(s27, 27);
csstruct!(s28, 28);
csstruct!(s29, 29);
csstruct!(s30, 30);
csstruct!(s31, 31);
csstruct!(s32, 32);
macro_rules! impl_copystr_comp {
($css:ident, $ ($o:ident),+ ) => {
$(
impl PartialEq<$o> for $css {
#[inline]
fn eq(&self, other: &$o) -> bool {
self.as_bytes() == other.as_bytes()
}
#[inline]
fn ne(&self, other: &$o) -> bool {
!(self).eq(other)
}
}
impl PartialOrd<$o> for $css {
#[inline]
fn partial_cmp(&self, other: &$o) -> Option<Ordering> {
Some(self.as_bytes().cmp(other.as_bytes()))
}
}
)*
};
}
impl_copystr_comp!(s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14, s15, s16, s17, s18,
s19, s20, s21, s22, s23, s24, s25, s26, s27, s28, s29, s30, s31, s32);
impl_copystr_comp!(s4, s3, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14, s15, s16, s17, s18,
s19, s20, s21, s22, s23, s24, s25, s26, s27, s28, s29, s30, s31, s32);
impl_copystr_comp!(s5, s3, s4, s6, s7, s8, s9, s10, s11, s12, s13, s14, s15, s16, s17, s18,
s19, s20, s21, s22, s23, s24, s25, s26, s27, s28, s29, s30, s31, s32);
impl_copystr_comp!(s6, s3, s4, s5, s7, s8, s9, s10, s11, s12, s13, s14, s15, s16, s17, s18,
s19, s20, s21, s22, s23, s24, s25, s26, s27, s28, s29, s30, s31, s32);
impl_copystr_comp!(s7, s3, s4, s5, s6, s8, s9, s10, s11, s12, s13, s14, s15, s16, s17, s18,
s19, s20, s21, s22, s23, s24, s25, s26, s27, s28, s29, s30, s31, s32);
impl_copystr_comp!(s8, s3, s4, s5, s6, s7, s9, s10, s11, s12, s13, s14, s15, s16, s17, s18,
s19, s20, s21, s22, s23, s24, s25, s26, s27, s28, s29, s30, s31, s32);
impl_copystr_comp!(s9, s3, s4, s5, s6, s7, s8, s10, s11, s12, s13, s14, s15, s16, s17, s18,
s19, s20, s21, s22, s23, s24, s25, s26, s27, s28, s29, s30, s31, s32);
impl_copystr_comp!(s10, s3, s4, s5, s6, s7, s8, s9, s11, s12, s13, s14, s15, s16, s17, s18,
s19, s20, s21, s22, s23, s24, s25, s26, s27, s28, s29, s30, s31, s32);
impl_copystr_comp!(s11, s3, s4, s5, s6, s7, s8, s9, s10, s12, s13, s14, s15, s16, s17, s18,
s19, s20, s21, s22, s23, s24, s25, s26, s27, s28, s29, s30, s31, s32);
impl_copystr_comp!(s12, s3, s4, s5, s6, s7, s8, s9, s10, s11, s13, s14, s15, s16, s17, s18,
s19, s20, s21, s22, s23, s24, s25, s26, s27, s28, s29, s30, s31, s32);
impl_copystr_comp!(s13, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s14, s15, s16, s17, s18,
s19, s20, s21, s22, s23, s24, s25, s26, s27, s28, s29, s30, s31, s32);
impl_copystr_comp!(s14, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s15, s16, s17, s18,
s19, s20, s21, s22, s23, s24, s25, s26, s27, s28, s29, s30, s31, s32);
impl_copystr_comp!(s15, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14, s16, s17, s18,
s19, s20, s21, s22, s23, s24, s25, s26, s27, s28, s29, s30, s31, s32);
impl_copystr_comp!(s16, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14, s15, s17, s18,
s19, s20, s21, s22, s23, s24, s25, s26, s27, s28, s29, s30, s31, s32);
impl_copystr_comp!(s17, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14, s15, s16, s18,
s19, s20, s21, s22, s23, s24, s25, s26, s27, s28, s29, s30, s31, s32);
impl_copystr_comp!(s18, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14, s15, s16, s17,
s19, s20, s21, s22, s23, s24, s25, s26, s27, s28, s29, s30, s31, s32);
impl_copystr_comp!(s19, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14, s15, s16, s17,
s18, s20, s21, s22, s23, s24, s25, s26, s27, s28, s29, s30, s31, s32);
impl_copystr_comp!(s20, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14, s15, s16, s17,
s18, s19, s21, s22, s23, s24, s25, s26, s27, s28, s29, s30, s31, s32);
impl_copystr_comp!(s21, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14, s15, s16, s17,
s18, s19, s20, s22, s23, s24, s25, s26, s27, s28, s29, s30, s31, s32);
impl_copystr_comp!(s22, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14, s15, s16, s17,
s18, s19, s20, s21, s23, s24, s25, s26, s27, s28, s29, s30, s31, s32);
impl_copystr_comp!(s23, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14, s15, s16, s17,
s18, s19, s20, s21, s22, s24, s25, s26, s27, s28, s29, s30, s31, s32);
impl_copystr_comp!(s24, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14, s15, s16, s17,
s18, s19, s20, s21, s22, s23, s25, s26, s27, s28, s29, s30, s31, s32);
impl_copystr_comp!(s25, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14, s15, s16, s17,
s18, s19, s20, s21, s22, s23, s24, s26, s27, s28, s29, s30, s31, s32);
impl_copystr_comp!(s26, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14, s15, s16, s17,
s18, s19, s20, s21, s22, s23, s24, s25, s27, s28, s29, s30, s31, s32);
impl_copystr_comp!(s27, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14, s15, s16, s17,
s18, s19, s20, s21, s22, s23, s24, s25, s26, s28, s29, s30, s31, s32);
impl_copystr_comp!(s28, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14, s15, s16, s17,
s18, s19, s20, s21, s22, s23, s24, s25, s26, s27, s29, s30, s31, s32);
impl_copystr_comp!(s29, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14, s15, s16, s17,
s18, s19, s20, s21, s22, s23, s24, s25, s26, s27, s28, s30, s31, s32);
impl_copystr_comp!(s30, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14, s15, s16, s17,
s18, s19, s20, s21, s22, s23, s24, s25, s26, s27, s28, s29, s31, s32);
impl_copystr_comp!(s31, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14, s15, s16, s17,
s18, s19, s20, s21, s22, s23, s24, s25, s26, s27, s28, s29, s30, s32);
impl_copystr_comp!(s32, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14, s15, s16, s17,
s18, s19, s20, s21, s22, s23, s24, s25, s26, s27, s28, s29, s30, s31);
pub type CopyStringCapacity = usize;
pub type StringLength = usize;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Error {
InvalidUtf8(Utf8Error),
TooBig(CopyStringCapacity, StringLength),
Msg(String),
}
impl Error {
pub fn into_msg(self) -> Self {
let msg = self.to_string();
Error::Msg(msg)
}
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Self::InvalidUtf8(e) => write!(f, "{}", &e),
Self::TooBig(mlen, slen) => write!(
f,
"String length {} larger than internal array len {}.",
&mlen,
&slen,
),
Self::Msg(m) => write!(f, "{}", &m),
}
}
}
impl error::Error for Error {
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
match self {
Self::InvalidUtf8(e) => Some(e),
_ => None,
}
}
}
#[cfg(feature = "serde")]
impl DeError for Error {
fn custom<T: fmt::Display>(msg: T) -> Self {
Error::Msg(msg.to_string())
}
}
impl From<Utf8Error> for Error {
fn from(e: Utf8Error) -> Self {
Error::InvalidUtf8(e)
}
}
#[cfg(test)]
mod tests {
use std::{
convert::TryFrom,
error,
};
#[cfg(feature = "serde")]
use serde::{Serialize, Deserialize};
use super::*;
#[cfg(feature = "serde")]
#[derive(Serialize, Deserialize)]
struct Msg {
val: usize,
txt: s4,
}
#[test]
fn copy_string_struct() {
let cs = s4::try_from("ABC").unwrap();
assert_eq!(cs.as_str(), "ABC");
}
#[test]
fn new_string_struct() {
let cs = s8::new("It's me!").unwrap();
assert_eq!(cs.as_str(), "It's me!");
}
#[test]
fn default_ok() {
let cs = s16::default();
assert!(cs.len() == 0);
assert_eq!(cs.as_str(), "");
}
#[test]
fn display() {
let cs = s4::try_from("XYZ").unwrap();
assert_eq!(cs.to_string(), "XYZ");
}
#[cfg(feature = "serde")]
#[test]
fn serialize_to_json() -> Result<(), Box<dyn error::Error>> {
let cs = s4::new("Yo!")?;
let msg = Msg {
val: 10,
txt: cs,
};
let json = serde_json::to_string(&msg)?;
assert_eq!(r##"{"val":10,"txt":"Yo!"}"##, &json);
Ok(())
}
#[cfg(feature = "serde")]
#[test]
fn deserialize_from_json() -> Result<(), Box<dyn error::Error>> {
let json = r##"{"val":45,"txt":"Hey!"}"##;
let cs = s4::new("Hey!")?;
let msg: Msg = serde_json::from_str(json)?;
assert!(msg.val == 45);
assert!(msg.txt == cs);
Ok(())
}
#[cfg(feature = "serde")]
#[test]
fn deserialize_from_json_too_big() -> Result<(), Box<dyn error::Error>> {
let json = r##"{"val":45,"txt":"HUGE!"}"##;
let maybie_msg: Result<Msg, serde_json::Error> = serde_json::from_str(json);
assert!(maybie_msg.is_err());
Ok(())
}
#[test]
fn str_comparison_works() -> Result<(), Box<dyn error::Error>> {
let cs = s6::new("Yeah")?;
assert!(cs == "Yeah");
assert!(cs != "Alright");
Ok(())
}
#[test]
fn string_comparison_works() -> Result<(), Box<dyn error::Error>> {
let cs = s6::new("Yeah")?;
assert!(cs == "Yeah".to_string());
assert!(cs != "Alright".to_string());
Ok(())
}
#[test]
fn const_construction_should_work() {
const CS: s5 = s5::assume_from_array([b's', b'm', b'i', b'l', b'e']);
assert!(CS == "smile");
}
#[test]
fn str_ordering_works() -> Result<(), Box<dyn error::Error>> {
let cs = s6::new("bcd")?;
assert!(cs < "cde");
assert!(cs > "abc");
assert!(cs > "a");
assert!(cs >= "bcd");
assert!(cs <= "bcd");
Ok(())
}
#[test]
fn string_ordering_works() -> Result<(), Box<dyn error::Error>> {
let cs = s6::new("bcd")?;
assert!(cs < "cde".to_string());
assert!(cs > "abc".to_string());
assert!(cs > "a".to_string());
assert!(cs >= "bcd".to_string());
assert!(cs <= "bcd".to_string());
Ok(())
}
#[test]
fn same_sized_copystr_comparison_works() -> Result<(), Box<dyn error::Error>> {
let cs1 = s6::new("bcd")?;
let cs2 = s6::new("bcd")?;
assert!(cs1 == cs2);
Ok(())
}
#[test]
fn different_sized_copystr_comparison_works() -> Result<(), Box<dyn error::Error>> {
let cs1 = s6::new("bcd")?;
let cs2 = s5::new("bcd")?;
assert!(cs1 == cs2);
Ok(())
}
const MT1: s3 = s3::assume_from_array([b'b', b'c', b'a']);
const MT2: s3 = s3::assume_from_array([b'b', b'c', b'd']);
#[test]
fn same_size_copystr_match_works() -> Result<(), Box<dyn error::Error>> {
let val = s3::new("bca")?;
match val {
MT1 => Ok(()),
MT2 => panic!("Matched wrong copystr"),
_ => panic!("Didn't match copystr"),
}
}
}