solomon_gremlin/structure/
gid.rs

1use crate::{GremlinError, GremlinResult};
2use uuid::Uuid;
3
4#[derive(Debug, Clone)]
5pub struct GIDs(pub(crate) Vec<GID>);
6
7impl<T: Into<GID>> From<T> for GIDs {
8	fn from(val: T) -> GIDs {
9		GIDs(vec![val.into()])
10	}
11}
12
13impl<T: Into<GID>> From<Vec<T>> for GIDs {
14	fn from(val: Vec<T>) -> GIDs {
15		GIDs(val.into_iter().map(|gid| gid.into()).collect())
16	}
17}
18
19impl From<()> for GIDs {
20	fn from(_val: ()) -> GIDs {
21		GIDs(vec![])
22	}
23}
24
25#[derive(Debug, PartialEq, Eq, Hash, Clone)]
26pub enum GID {
27	String(String),
28	Int32(i32),
29	Int64(i64),
30	Bytes(Vec<u8>),
31}
32
33impl GID {
34	pub fn bytes(&self) -> Vec<u8> {
35		match self {
36			GID::String(v) => v.as_bytes().to_vec(),
37			GID::Int32(v) => i32::to_be_bytes(*v).to_vec(),
38			GID::Int64(v) => i64::to_be_bytes(*v).to_vec(),
39			GID::Bytes(v) => v.to_vec(),
40		}
41	}
42
43	pub fn bytes_len(&self) -> usize {
44		self.bytes().len()
45	}
46
47	pub fn get<'a, T>(&'a self) -> GremlinResult<&'a T>
48	where
49		T: BorrowFromGID,
50	{
51		T::from_gid(self)
52	}
53}
54
55impl From<&'static str> for GID {
56	fn from(val: &str) -> Self {
57		GID::String(String::from(val))
58	}
59}
60
61impl From<String> for GID {
62	fn from(val: String) -> Self {
63		GID::String(val)
64	}
65}
66
67impl From<i32> for GID {
68	fn from(val: i32) -> Self {
69		GID::Int32(val)
70	}
71}
72
73impl From<i64> for GID {
74	fn from(val: i64) -> Self {
75		GID::Int64(val)
76	}
77}
78
79impl From<&GID> for GID {
80	fn from(val: &GID) -> Self {
81		val.clone()
82	}
83}
84
85impl From<Uuid> for GID {
86	fn from(val: Uuid) -> Self {
87		GID::String(val.to_string())
88	}
89}
90
91// Borrow from GID
92
93#[doc(hidden)]
94pub trait BorrowFromGID: Sized {
95	fn from_gid<'a>(v: &'a GID) -> GremlinResult<&'a Self>;
96}
97
98macro_rules! impl_borrow_from_gid {
99	($t:ty, $v:path) => {
100		impl BorrowFromGID for $t {
101			fn from_gid<'a>(v: &'a GID) -> GremlinResult<&'a $t> {
102				match v {
103					$v(e) => Ok(e),
104					_ => Err(GremlinError::Cast(format!(
105						"Cannot convert {:?} to {}",
106						v,
107						stringify!($t)
108					))),
109				}
110			}
111		}
112	};
113}
114
115impl_borrow_from_gid!(String, GID::String);
116impl_borrow_from_gid!(Vec<u8>, GID::Bytes);
117impl_borrow_from_gid!(i32, GID::Int32);
118impl_borrow_from_gid!(i64, GID::Int64);