Skip to main content

provenant/models/
dependency_uid.rs

1// SPDX-FileCopyrightText: Provenant contributors
2// SPDX-License-Identifier: Apache-2.0
3
4use std::borrow::Borrow;
5use std::fmt;
6use std::ops::Deref;
7
8use serde::{Deserialize, Serialize};
9use uuid::Uuid;
10
11#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Hash)]
12#[serde(transparent)]
13pub struct DependencyUid(String);
14
15impl DependencyUid {
16    /// Creates a new `DependencyUid` by appending a UUID to the given purl.
17    pub fn new(purl: &str) -> Self {
18        let uuid = Uuid::new_v4();
19        DependencyUid(crate::models::purl::append_uuid_qualifier(
20            purl,
21            &uuid.to_string(),
22        ))
23    }
24
25    /// Wraps an existing UID string without validation or UUID generation.
26    ///
27    /// Use this for deserialization boundaries and round-trip conversions
28    /// where the UID string is already well-formed.
29    pub fn from_raw(s: String) -> Self {
30        DependencyUid(s)
31    }
32
33    /// Returns the empty-string sentinel representing "no purl".
34    pub fn empty() -> Self {
35        DependencyUid(String::new())
36    }
37
38    /// Returns a new `DependencyUid` with the purl base replaced, preserving the UUID.
39    pub fn replace_base(&self, new_purl: &str) -> Self {
40        let Some(uuid) = crate::models::purl::uuid_qualifier_value(&self.0) else {
41            return DependencyUid(self.0.clone());
42        };
43        DependencyUid(crate::models::purl::append_uuid_qualifier(new_purl, uuid))
44    }
45}
46
47impl fmt::Display for DependencyUid {
48    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
49        self.0.fmt(f)
50    }
51}
52
53impl AsRef<str> for DependencyUid {
54    fn as_ref(&self) -> &str {
55        &self.0
56    }
57}
58
59impl Borrow<str> for DependencyUid {
60    fn borrow(&self) -> &str {
61        &self.0
62    }
63}
64
65impl Deref for DependencyUid {
66    type Target = str;
67
68    fn deref(&self) -> &Self::Target {
69        &self.0
70    }
71}