use std::cmp::Ordering;
use std::fmt;
use std::hash::{Hash, Hasher};
use crate::value::Value;
const CORE_PREFIX: &str = "tag:yaml.org,2002:";
#[derive(Clone, Debug)]
struct TagInner {
handle: String,
suffix: String,
}
#[derive(Clone)]
pub struct Tag {
inner: Box<TagInner>,
}
impl fmt::Debug for Tag {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("Tag")
.field("handle", &self.inner.handle)
.field("suffix", &self.inner.suffix)
.finish()
}
}
impl Tag {
fn from_parts(handle: String, suffix: String) -> Self {
Self {
inner: Box::new(TagInner { handle, suffix }),
}
}
#[must_use]
pub fn new(handle: impl Into<String>, suffix: impl Into<String>) -> Self {
let handle = handle.into();
let suffix = suffix.into();
if handle != CORE_PREFIX
&& (CORE_PREFIX.starts_with(handle.as_str()) || handle.starts_with(CORE_PREFIX))
{
let full = format!("{handle}{suffix}");
if let Some(rest) = full.strip_prefix(CORE_PREFIX) {
return Self::from_parts(CORE_PREFIX.to_owned(), rest.to_owned());
}
}
if handle.is_empty()
&& let Some(rest) = suffix.strip_prefix('!')
{
return Self::from_parts("!".to_owned(), rest.to_owned());
}
if handle.is_empty()
&& let Some((last, _)) = suffix.char_indices().next_back()
&& last > 0
{
let cut = suffix[..last]
.rfind([':', '/', '#'])
.map_or(last, |index| index + 1);
if cut < suffix.len() {
return Self::from_parts(suffix[..cut].to_owned(), suffix[cut..].to_owned());
}
}
Self::from_parts(handle, suffix)
}
pub(crate) fn is_core_collection(&self) -> bool {
self.is_core() && matches!(self.suffix(), "seq" | "map" | "set" | "omap" | "pairs")
}
pub(crate) fn is_core_scalar(&self) -> bool {
self.is_core() && matches!(self.suffix(), "str" | "int" | "float" | "bool" | "null")
}
pub(crate) fn serde_name(&self) -> String {
if let Some(prefix) = self.inner.handle.strip_prefix('!') {
let name = format!("{prefix}{}", self.inner.suffix);
if bare_serde_name(&name) {
return name;
}
}
format!("<{}{}>", self.inner.handle, self.inner.suffix)
}
pub(crate) fn variant_name(&self) -> String {
match self.inner.handle.strip_prefix('!') {
Some(prefix) => format!("{prefix}{}", self.inner.suffix),
None => format!("<{}{}>", self.inner.handle, self.inner.suffix),
}
}
pub(crate) fn is_non_specific(&self) -> bool {
self.inner.handle == "!" && self.inner.suffix.is_empty()
}
pub(crate) fn is_local(&self) -> bool {
self.inner.handle.starts_with('!')
|| (self.inner.handle.is_empty() && self.inner.suffix.starts_with('!'))
}
pub(crate) fn is_non_core_global(&self) -> bool {
!self.is_local() && !self.is_core_scalar() && !self.is_core_collection()
}
pub(crate) fn into_variant_name(self) -> String {
if self.inner.handle == "!" {
self.inner.suffix
} else {
self.variant_name()
}
}
pub(crate) fn from_serde_name(name: &str) -> Self {
match name
.strip_prefix('<')
.and_then(|rest| rest.strip_suffix('>'))
{
Some(full) => Self::new("", full),
None if name.starts_with('!') => Self::new("", name),
None => Self::local(name),
}
}
fn full(&self) -> impl Iterator<Item = u8> + '_ {
self.inner.handle.bytes().chain(self.inner.suffix.bytes())
}
#[must_use]
pub fn core(suffix: impl Into<String>) -> Self {
Self::new(CORE_PREFIX, suffix)
}
#[must_use]
pub fn local(suffix: impl Into<String>) -> Self {
Self::new("!", suffix)
}
#[must_use]
pub fn handle(&self) -> &str {
&self.inner.handle
}
pub(crate) fn text_len(&self) -> usize {
self.inner
.handle
.len()
.saturating_add(self.inner.suffix.len())
}
#[must_use]
pub fn suffix(&self) -> &str {
&self.inner.suffix
}
#[must_use]
pub fn is_core(&self) -> bool {
self.inner.handle == CORE_PREFIX
}
}
impl PartialEq for Tag {
fn eq(&self, other: &Self) -> bool {
self.inner.handle.len() + self.inner.suffix.len()
== other.inner.handle.len() + other.inner.suffix.len()
&& self.full().eq(other.full())
}
}
impl Eq for Tag {}
impl Hash for Tag {
fn hash<H: Hasher>(&self, state: &mut H) {
for byte in self.full() {
state.write_u8(byte);
}
state.write_u8(0xff);
}
}
impl PartialOrd for Tag {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for Tag {
fn cmp(&self, other: &Self) -> Ordering {
self.full().cmp(other.full())
}
}
impl fmt::Display for Tag {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.inner.handle == "!" {
write!(formatter, "!{}", self.inner.suffix)
} else if self.inner.handle == CORE_PREFIX {
write!(formatter, "!!{}", self.inner.suffix)
} else {
write!(formatter, "{}{}", self.inner.handle, self.inner.suffix)
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct TaggedValue {
pub tag: Tag,
pub value: Value,
}
impl TaggedValue {
#[must_use]
pub fn new(tag: Tag, value: Value) -> Self {
Self { tag, value }
}
}
fn bare_serde_name(name: &str) -> bool {
!name.is_empty() && !name.starts_with(['!', '<'])
}
pub(crate) fn verbatim_reads_back(handle: &str, suffix: &str) -> bool {
let mut bytes = handle.bytes().chain(suffix.bytes());
let mut first = true;
let mut scheme = true;
let mut has_scheme = false;
let mut local = false;
while let Some(byte) = bytes.next() {
if first {
first = false;
local = byte == b'!';
scheme = byte.is_ascii_alphabetic();
} else if scheme && !has_scheme {
if byte == b':' {
has_scheme = true;
} else if !(byte.is_ascii_alphanumeric() || matches!(byte, b'+' | b'-' | b'.')) {
scheme = false;
}
}
if byte == b'%' {
for _ in 0..2 {
if !bytes.next().is_some_and(|digit| digit.is_ascii_hexdigit()) {
return false;
}
}
} else if !(is_uri_byte(byte) || matches!(byte, b'!' | b',' | b'[' | b']')) {
return false;
}
}
local || has_scheme
}
pub(crate) fn is_uri_byte(byte: u8) -> bool {
byte.is_ascii_alphanumeric()
|| matches!(
byte,
b'-' | b'#'
| b';'
| b'/'
| b'?'
| b':'
| b'@'
| b'&'
| b'='
| b'+'
| b'$'
| b'_'
| b'.'
| b'~'
| b'*'
| b'\''
| b'('
| b')'
)
}
#[cfg(test)]
mod tests {
use super::{Tag, TaggedValue};
use crate::value::Value;
#[test]
fn a_tags_hash_does_not_show_where_its_text_splits() {
use std::hash::{Hash, Hasher};
#[derive(Default)]
struct Writes(Vec<Vec<u8>>);
impl Hasher for Writes {
fn write(&mut self, bytes: &[u8]) {
self.0.push(bytes.to_vec());
}
fn finish(&self) -> u64 {
0
}
}
let writes = |tag: Tag| {
let mut writes = Writes::default();
tag.hash(&mut writes);
writes.0
};
let (split, other) = (Tag::new("!ab", "c"), Tag::new("!", "abc"));
assert_eq!(split, other);
assert_eq!(writes(split), writes(other));
}
#[test]
fn local_and_core_tags_display_canonically() {
assert_eq!(Tag::local("Custom").to_string(), "!Custom");
assert_eq!(Tag::core("str").to_string(), "!!str");
assert_eq!(
Tag::new("tag:example.com,2026:", "foo").to_string(),
"tag:example.com,2026:foo"
);
}
#[test]
fn serde_names_read_back() {
for tag in [
Tag::local("Foo"),
Tag::local(""),
Tag::local("!"),
Tag::local("<x>"),
Tag::local("a:b"),
Tag::core("set"),
Tag::new("tag:example.com,2000:", "foo"),
Tag::new("", "tag:x"),
Tag::new("!a-", "b"),
Tag::new("!", ""),
Tag::new("!!", "x"),
] {
assert_eq!(Tag::from_serde_name(&tag.serde_name()), tag, "{tag}");
}
assert_eq!(Tag::local("Foo").serde_name(), "Foo");
assert_eq!(Tag::new("!a-", "b").serde_name(), "a-b");
assert_eq!(Tag::core("set").serde_name(), "<tag:yaml.org,2002:set>");
}
#[test]
fn variant_names_read_back() {
for (tag, name) in [
(Tag::local("B"), "B"),
(Tag::new("!a-", "b"), "a-b"),
(Tag::new("", "!!x"), "!x"),
(Tag::new("!!", "x"), "!x"),
(Tag::local("<!x>"), "<!x>"),
(Tag::local(""), ""),
(Tag::new("tag:x:", "B"), "<tag:x:B>"),
(Tag::core("C"), "<tag:yaml.org,2002:C>"),
] {
assert_eq!(tag.variant_name(), name, "{tag}");
assert_eq!(tag.clone().into_variant_name(), name, "{tag}");
assert_eq!(Tag::local(name).variant_name(), name, "{tag}");
}
}
#[test]
fn tags_compare_by_full_name() {
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
fn hash(tag: &Tag) -> u64 {
let mut hasher = DefaultHasher::new();
tag.hash(&mut hasher);
hasher.finish()
}
let verbatim = Tag::new("", "tag:yaml.org,2002:str");
assert_eq!(verbatim, Tag::core("str"));
assert!(verbatim.is_core());
assert_eq!(verbatim.suffix(), "str");
assert_eq!(Tag::new("", "!x"), Tag::local("x"));
let handle = Tag::new("tag:example.com,2000:app/", "foo");
let full = Tag::new("", "tag:example.com,2000:app/foo");
assert_eq!(handle, full);
assert_eq!(hash(&handle), hash(&full));
assert_eq!(handle.cmp(&full), std::cmp::Ordering::Equal);
assert_ne!(Tag::local("a"), Tag::local("b"));
assert!(Tag::local("a") < Tag::local("b"));
}
#[test]
fn core_tag_is_recognized() {
assert!(Tag::core("int").is_core());
assert!(!Tag::local("int").is_core());
}
#[test]
fn tagged_value_keeps_its_tag_and_payload() {
let tagged = TaggedValue::new(Tag::local("Custom"), Value::from(1_u64));
assert_eq!(tagged.tag.to_string(), "!Custom");
assert_eq!(tagged.value, Value::from(1_u64));
}
#[cfg(target_pointer_width = "64")]
#[test]
fn tag_is_pointer_sized() {
assert_eq!(size_of::<Tag>(), 8);
assert_eq!(size_of::<Option<Tag>>(), 8);
assert_eq!(
format!("{:?}", Tag::local("Custom")),
"Tag { handle: \"!\", suffix: \"Custom\" }"
);
}
}