Skip to main content

co_primitives/types/
mapped_cid.rs

1// SPDX-License-Identifier: AGPL-3.0-only
2// Copyright (C) 2026 1io BRANDGUARDIAN GmbH
3
4use anyhow::anyhow;
5use cid::Cid;
6use derive_more::From;
7use serde::{Deserialize, Serialize};
8
9/// Simple type to make mapped Cid's clear.
10#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord, From, Serialize, Deserialize)]
11#[serde(untagged)]
12pub enum OptionMappedCid {
13	/// Unmapped Cid (Internal/Mapped is the same as External/Plain).
14	Unmapped(Cid),
15
16	/// Mapped Cid (Internal/Mapped, External/Plain).
17	Mapped(MappedCid),
18}
19impl OptionMappedCid {
20	pub fn new(internal: Cid, external: Cid) -> OptionMappedCid {
21		MappedCid(internal, external).into()
22	}
23
24	pub fn new_unmapped(internal: Cid) -> OptionMappedCid {
25		internal.into()
26	}
27
28	pub fn mapped(&self) -> Option<MappedCid> {
29		match self {
30			OptionMappedCid::Unmapped(_cid) => None,
31			OptionMappedCid::Mapped(mapped_cid) => Some(*mapped_cid),
32		}
33	}
34
35	pub fn external(&self) -> Cid {
36		match self {
37			OptionMappedCid::Unmapped(cid) => *cid,
38			OptionMappedCid::Mapped(MappedCid(_internal, external)) => *external,
39		}
40	}
41
42	pub fn force_external(&self) -> Result<Cid, anyhow::Error> {
43		match self {
44			OptionMappedCid::Unmapped(cid) => Err(anyhow!("failed to map: {:?}", cid)),
45			OptionMappedCid::Mapped(MappedCid(_internal, external)) => Ok(*external),
46		}
47	}
48
49	pub fn internal(&self) -> Cid {
50		match self {
51			OptionMappedCid::Unmapped(cid) => *cid,
52			OptionMappedCid::Mapped(MappedCid(internal, _external)) => *internal,
53		}
54	}
55}
56
57/// Mapped Cid.
58///
59/// # Args
60/// - 0: Internal/Mapped.
61/// - 1: External/Plain.
62#[derive(Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
63pub struct MappedCid(pub Cid, pub Cid);
64impl MappedCid {
65	pub fn new(internal: Cid, external: Cid) -> Self {
66		Self(internal, external)
67	}
68
69	pub fn external(&self) -> Cid {
70		self.1
71	}
72
73	pub fn internal(&self) -> Cid {
74		self.0
75	}
76}
77impl From<(Cid, Cid)> for MappedCid {
78	fn from((internal, external): (Cid, Cid)) -> Self {
79		Self(internal, external)
80	}
81}