1use crate::error::{Error, ErrorKind};
2use crate::{Meta, Validator};
3use tanzim_value::{Value, ValueType};
4
5#[derive(Debug, Clone, Default)]
7pub struct Uuid {
8 meta: Meta,
9}
10
11impl Uuid {
12 pub fn new() -> Self {
13 Self {
14 meta: Meta::default(),
15 }
16 }
17
18 pub fn with_meta(mut self, meta: Meta) -> Self {
20 self.meta = meta;
21 self
22 }
23}
24
25crate::impl_meta_methods!(Uuid);
26
27impl Validator for Uuid {
28 fn meta(&self) -> &Meta {
29 &self.meta
30 }
31
32 fn meta_mut(&mut self) -> &mut Meta {
33 &mut self.meta
34 }
35
36 fn check(&self, value: &mut Value) -> Result<(), Error> {
37 let text = match value {
38 Value::String(text) => text,
39 other => {
40 return Err(Error::new(ErrorKind::Type {
41 expected: ValueType::String,
42 found: other.type_name(),
43 }));
44 }
45 };
46 match uuid::Uuid::parse_str(text) {
47 Ok(_) => Ok(()),
48 Err(_) => Err(Error::new(ErrorKind::Format { expected: "uuid" })),
49 }
50 }
51}
52
53#[cfg(test)]
54mod tests {
55 use super::*;
56
57 #[test]
58 fn accepts_and_rejects() {
59 assert!(
60 Uuid::new()
61 .validate(&mut Value::String(
62 "67e55044-10b1-426f-9247-bb680e5fe0c8".into()
63 ))
64 .is_ok()
65 );
66 assert!(
67 Uuid::new()
68 .validate(&mut Value::String("nope".into()))
69 .is_err()
70 );
71 }
72}