use alloc::{borrow::Cow, string::String};
use core::fmt;
use crate::text;
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Id<'a> {
Number(i64),
String(Cow<'a, str>),
}
impl Id<'_> {
#[inline]
#[must_use]
pub const fn as_i64(&self) -> Option<i64> {
match self {
Id::Number(n) => Some(*n),
Id::String(_) => None,
}
}
#[inline]
#[must_use]
pub fn as_str(&self) -> Option<&str> {
match self {
Id::Number(_) => None,
Id::String(s) => Some(s),
}
}
#[must_use]
pub fn into_owned(self) -> Id<'static> {
match self {
Id::Number(n) => Id::Number(n),
Id::String(s) => Id::String(Cow::Owned(s.into_owned())),
}
}
pub(crate) fn write(&self, out: &mut String) {
match self {
Id::Number(n) => text::push_i64(out, *n),
Id::String(s) => jsonx_lib::write_string(out, s),
}
}
}
impl fmt::Display for Id<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut out = String::new();
self.write(&mut out);
f.write_str(&out)
}
}
impl From<i64> for Id<'_> {
#[inline]
fn from(n: i64) -> Self {
Id::Number(n)
}
}
impl From<i32> for Id<'_> {
#[inline]
fn from(n: i32) -> Self {
Id::Number(i64::from(n))
}
}
impl From<u32> for Id<'_> {
#[inline]
fn from(n: u32) -> Self {
Id::Number(i64::from(n))
}
}
impl<'a> From<&'a str> for Id<'a> {
#[inline]
fn from(s: &'a str) -> Self {
Id::String(Cow::Borrowed(s))
}
}
impl From<String> for Id<'_> {
#[inline]
fn from(s: String) -> Self {
Id::String(Cow::Owned(s))
}
}
impl<'a> From<Cow<'a, str>> for Id<'a> {
#[inline]
fn from(s: Cow<'a, str>) -> Self {
Id::String(s)
}
}
#[cfg(test)]
#[allow(clippy::panic)]
mod tests {
use alloc::string::ToString;
use super::*;
#[test]
fn test_display_writes_json() {
assert_eq!(Id::from(i64::MIN).to_string(), "-9223372036854775808");
assert_eq!(Id::from("a\"b").to_string(), r#""a\"b""#);
}
#[test]
fn test_ids_order_numbers_before_strings() {
assert!(Id::from(5) < Id::from("0"));
assert!(Id::from(-1) < Id::from(0));
}
}