aboutsummaryrefslogtreecommitdiff
path: root/common/object/src/tag.rs
blob: c937d4364b23e425c172a38c980ef2270d30e90c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/*
    This file is part of jellything (https://codeberg.org/metamuffin/jellything)
    which is licensed under the GNU Affero General Public License (version 3); see /COPYING.
    Copyright (C) 2026 metamuffin <metamuffin.org>
*/

use core::marker::{PhantomData, Sized};
use std::fmt::Display;

#[repr(transparent)]
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Tag(pub u32);

impl Default for Tag {
    fn default() -> Self {
        Self::new(b"1111")
    }
}
impl Tag {
    pub const fn new(fourcc: &[u8; 4]) -> Self {
        Self(u32::from_le_bytes(*fourcc))
    }
}
impl Display for Tag {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(str::from_utf8(&self.0.to_le_bytes()).unwrap())
    }
}

#[derive(PartialEq, Eq, PartialOrd, Ord)]
pub struct TypedTag<T: ?Sized>(pub Tag, pub PhantomData<T>);
impl<T: ?Sized> Display for TypedTag<T> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.0.fmt(f)
    }
}
#[allow(clippy::non_canonical_clone_impl)]
impl<T: ?Sized> Clone for TypedTag<T> {
    fn clone(&self) -> Self {
        Self(self.0, PhantomData)
    }
}
impl<T: ?Sized> Copy for TypedTag<T> {}
impl<T: ?Sized> TypedTag<T> {
    pub const fn new(tag: Tag) -> Self {
        Self(tag, PhantomData)
    }
}

pub mod types {
    use crate::Object;
    use std::any::TypeId;

    pub const OBJECT: TypeId = TypeId::of::<Object>();
    pub const STR: TypeId = TypeId::of::<&str>();
    pub const BINARY: TypeId = TypeId::of::<&[u8]>();
    pub const U32: TypeId = TypeId::of::<u32>();
    pub const U64: TypeId = TypeId::of::<u64>();
    pub const I64: TypeId = TypeId::of::<i64>();
    pub const F64: TypeId = TypeId::of::<f64>();
}

#[macro_export]
macro_rules! fields {
    ($($id:ident: $type:ty = $tag:literal;)*) => {
        $(pub const $id: $crate::TypedTag<$type> = $crate::TypedTag::new($crate::Tag::new($tag));)*
    };
}
#[macro_export]
macro_rules! enums {
    ($($id:ident = $tag:literal;)*) => {
        $(pub const $id: $crate::Tag = $crate::Tag::new($tag);)*
    };
}