hydrate_base/
artifact_id.rs

1use serde::{de, ser};
2use serde::{Deserialize, Serialize};
3use std::fmt;
4use std::str::FromStr;
5use uuid::Uuid;
6
7/// ID of a built piece of data. A build job can produce any number of artifacts, usually reading
8/// import data and/or asset data. Different platforms may have different artifacts for the same
9/// conceptual piece of data
10#[derive(Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd, Default)]
11pub struct ArtifactId(pub Uuid);
12impl ArtifactId {
13    pub const fn null() -> Self {
14        ArtifactId(Uuid::nil())
15    }
16
17    pub fn parse_str(input: &str) -> Result<Self, uuid::Error> {
18        Ok(ArtifactId(Uuid::parse_str(input)?))
19    }
20
21    pub fn is_null(&self) -> bool {
22        self.0.is_nil()
23    }
24
25    pub fn from_uuid(uuid: Uuid) -> Self {
26        ArtifactId(uuid)
27    }
28
29    pub fn as_uuid(&self) -> Uuid {
30        self.0
31    }
32
33    pub fn from_u128(u: u128) -> Self {
34        Self(Uuid::from_u128(u))
35    }
36
37    pub fn as_u128(&self) -> u128 {
38        self.0.as_u128()
39    }
40
41    pub fn from_bytes(bytes: uuid::Bytes) -> Self {
42        ArtifactId(Uuid::from_bytes(bytes))
43    }
44
45    pub fn as_bytes(&self) -> &uuid::Bytes {
46        self.0.as_bytes()
47    }
48}
49
50impl fmt::Debug for ArtifactId {
51    fn fmt(
52        &self,
53        f: &mut fmt::Formatter<'_>,
54    ) -> fmt::Result {
55        f.debug_tuple("ArtifactId").field(&self.0).finish()
56    }
57}
58
59impl fmt::Display for ArtifactId {
60    fn fmt(
61        &self,
62        f: &mut fmt::Formatter<'_>,
63    ) -> fmt::Result {
64        self.0.fmt(f)
65    }
66}
67
68impl Serialize for ArtifactId {
69    fn serialize<S: ser::Serializer>(
70        &self,
71        serializer: S,
72    ) -> Result<S::Ok, S::Error> {
73        if serializer.is_human_readable() {
74            serializer.serialize_str(&self.to_string())
75        } else {
76            self.0.serialize(serializer)
77        }
78    }
79}
80
81struct ArtifactIdVisitor;
82
83impl<'a> de::Visitor<'a> for ArtifactIdVisitor {
84    type Value = ArtifactId;
85
86    fn expecting(
87        &self,
88        fmt: &mut fmt::Formatter<'_>,
89    ) -> fmt::Result {
90        write!(fmt, "a UUID-formatted string")
91    }
92
93    fn visit_str<E: de::Error>(
94        self,
95        s: &str,
96    ) -> Result<Self::Value, E> {
97        Uuid::from_str(s)
98            .map(|id| ArtifactId(id))
99            .map_err(|_| de::Error::invalid_value(de::Unexpected::Str(s), &self))
100    }
101}
102
103impl<'de> Deserialize<'de> for ArtifactId {
104    fn deserialize<D: de::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
105        if deserializer.is_human_readable() {
106            deserializer.deserialize_string(ArtifactIdVisitor)
107        } else {
108            Ok(ArtifactId(Uuid::deserialize(deserializer)?))
109        }
110    }
111}