use std::fmt;
use ciborium::tag::Captured;
use ciborium::value::Value as CborValue;
use serde::de::Error as DeError;
use serde::ser::Error as SerError;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
fn cbor_to_json(v: CborValue) -> serde_json::Value {
match v {
CborValue::Null => serde_json::Value::Null,
CborValue::Bool(b) => serde_json::Value::Bool(b),
CborValue::Integer(i) => serde_json::Value::Number(
i64::try_from(i).map(Into::into).unwrap_or_else(|_| {
u64::try_from(i).map(Into::into).unwrap_or_else(|_| 0.into())
}),
),
CborValue::Float(f) => serde_json::Number::from_f64(f)
.map(serde_json::Value::Number)
.unwrap_or(serde_json::Value::Null),
CborValue::Text(s) => serde_json::Value::String(s),
CborValue::Bytes(b) => serde_json::Value::String(format!(
"0x{}",
b.iter().map(|x| format!("{x:02x}")).collect::<String>()
)),
CborValue::Array(a) => serde_json::Value::Array(a.into_iter().map(cbor_to_json).collect()),
CborValue::Map(m) => {
let mut obj = serde_json::Map::new();
for (k, v) in m {
let ks = match k {
CborValue::Text(s) => s,
CborValue::Integer(i) => i128::from(i).to_string(),
_ => continue,
};
obj.insert(ks, cbor_to_json(v));
}
serde_json::Value::Object(obj)
}
CborValue::Tag(_, inner) => cbor_to_json(*inner),
_ => serde_json::Value::Null,
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct RecordId(pub String, pub RecordIdKey);
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum RecordIdKey {
String(String),
Number(i64),
Object(serde_json::Value),
Array(serde_json::Value),
}
impl RecordId {
pub fn new(table: impl Into<String>, key: impl Into<String>) -> Self {
Self(table.into(), RecordIdKey::String(key.into()))
}
pub fn as_str(&self) -> String {
match &self.1 {
RecordIdKey::String(k) => format!("{}:{}", self.0, k),
RecordIdKey::Number(n) => format!("{}:{}", self.0, n),
_ => format!("{}:<complex>", self.0),
}
}
}
impl fmt::Display for RecordId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.as_str())
}
}
impl Serialize for RecordId {
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
s.serialize_str(&self.as_str())
}
}
pub mod cbor_record_id {
use super::*;
pub fn deserialize<'de, D>(d: D) -> Result<RecordId, D::Error>
where
D: Deserializer<'de>,
{
let c: Captured<CborValue> = Captured::deserialize(d)?;
match c.0 {
Some(8) => parse_record_id(c.1).map_err(DeError::custom),
Some(t) => Err(DeError::custom(format!("expected Tag 8 RecordId, got Tag {t}"))),
None => Err(DeError::custom("expected Tag 8 RecordId, got untagged")),
}
}
pub fn serialize<S>(_r: &RecordId, _s: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
Err(SerError::custom("RecordId serialize not supported; use .query().bind()"))
}
}
pub(crate) fn parse_record_id(v: CborValue) -> Result<RecordId, String> {
match v {
CborValue::Text(s) => {
let (t, k) = s
.split_once(':')
.ok_or_else(|| format!("invalid RecordId text: {s}"))?;
Ok(RecordId(t.into(), RecordIdKey::String(k.into())))
}
CborValue::Array(mut a) if a.len() == 2 => {
let table = match a.remove(0) {
CborValue::Text(t) => t,
other => return Err(format!("RecordId table must be text, got {other:?}")),
};
let key = match a.remove(0) {
CborValue::Integer(i) => match i64::try_from(i) {
Ok(n) => RecordIdKey::Number(n),
Err(_) => RecordIdKey::String(i128::from(i).to_string()),
},
CborValue::Text(s) => RecordIdKey::String(s),
CborValue::Map(m) => RecordIdKey::Object(serde_json::Value::Object({
let mut obj = serde_json::Map::new();
for (k, v) in m {
let ks = match k {
CborValue::Text(s) => s,
CborValue::Integer(i) => i128::from(i).to_string(),
_ => continue,
};
obj.insert(ks, cbor_to_json(v));
}
obj
})),
CborValue::Array(inner) => RecordIdKey::Array(serde_json::Value::Array(
inner.into_iter().map(cbor_to_json).collect(),
)),
other => return Err(format!("RecordId key type unsupported: {other:?}")),
};
Ok(RecordId(table, key))
}
other => Err(format!("RecordId expects Text or Array[2], got {other:?}")),
}
}
pub mod cbor_datetime {
use super::*;
pub fn deserialize<'de, D>(d: D) -> Result<chrono::DateTime<chrono::Utc>, D::Error>
where
D: Deserializer<'de>,
{
let c: Captured<CborValue> = Captured::deserialize(d)?;
match c.0 {
Some(0) => parse_dt_str(c.1).map_err(DeError::custom),
Some(12) => parse_dt_struct(&c.1).map_err(DeError::custom),
Some(t) => Err(D::Error::custom(format!(
"expected Tag 0/12 Datetime, got Tag {t}"
))),
None => Err(D::Error::custom("expected Datetime Tag, got untagged")),
}
}
}
fn parse_dt_str(s: CborValue) -> Result<chrono::DateTime<chrono::Utc>, String> {
let CborValue::Text(s) = s else {
return Err(format!("Datetime Tag 0 expects Text, got {s:?}"));
};
chrono::DateTime::parse_from_rfc3339(&s)
.map(|dt| dt.with_timezone(&chrono::Utc))
.map_err(|e| format!("invalid RFC3339: {e}"))
}
fn parse_dt_struct(v: &CborValue) -> Result<chrono::DateTime<chrono::Utc>, String> {
let CborValue::Array(a) = v else {
return Err(format!("Datetime Tag 12 expects Array, got {v:?}"));
};
if a.len() != 2 {
return Err(format!("Datetime Array must have 2 elements, got {}", a.len()));
}
let secs = match &a[0] {
CborValue::Integer(i) => i64::try_from(*i).map_err(|e| format!("secs overflow: {e}"))?,
other => return Err(format!("Datetime[0] expects Integer, got {other:?}")),
};
let nanos = match &a[1] {
CborValue::Integer(i) => u32::try_from(*i).map_err(|e| format!("nanos overflow: {e}"))?,
other => return Err(format!("Datetime[1] expects Integer, got {other:?}")),
};
chrono::DateTime::<chrono::Utc>::from_timestamp(secs, nanos)
.ok_or_else(|| format!("invalid Datetime: secs={secs} nanos={nanos}"))
}
pub mod cbor_uuid {
use super::*;
pub fn deserialize<'de, D>(d: D) -> Result<uuid::Uuid, D::Error>
where
D: Deserializer<'de>,
{
let c: Captured<CborValue> = Captured::deserialize(d)?;
match c.0 {
Some(9) => {
let CborValue::Text(s) = c.1 else {
return Err(DeError::custom("UUID Tag 9 expects Text"));
};
uuid::Uuid::parse_str(&s).map_err(DeError::custom)
}
Some(37) => {
let CborValue::Bytes(b) = c.1 else {
return Err(DeError::custom("UUID Tag 37 expects Bytes"));
};
if b.len() != 16 {
return Err(DeError::custom(format!("UUID must be 16 bytes, got {}", b.len())));
}
let mut a = [0u8; 16];
a.copy_from_slice(&b);
Ok(uuid::Uuid::from_bytes(a))
}
Some(t) => Err(DeError::custom(format!("expected Tag 9/37 UUID, got Tag {t}"))),
None => Err(DeError::custom("expected UUID Tag, got untagged")),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Hash)]
pub struct CborNone;
impl Serialize for CborNone {
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
s.serialize_unit()
}
}
impl<'de> Deserialize<'de> for CborNone {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
let c: Captured<CborValue> = Captured::deserialize(d)?;
match c.0 {
Some(6) if matches!(c.1, CborValue::Null) => Ok(CborNone),
Some(6) => Err(D::Error::custom("expected Tag 6 wrapping Null, got non-null inner")),
Some(t) => Err(D::Error::custom(format!("expected Tag 6 None, got Tag {t}"))),
None if matches!(c.1, CborValue::Null) => Ok(CborNone),
None => Err(D::Error::custom("expected Tag 6 None, got untagged non-null")),
}
}
}
pub mod cbor_none {
use super::*;
pub fn deserialize<'de, D>(d: D) -> Result<CborNone, D::Error>
where
D: Deserializer<'de>,
{
CborNone::deserialize(d)
}
pub fn serialize<S>(n: &CborNone, s: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
n.serialize(s)
}
}
#[cfg(test)]
mod tests {
use super::*;
use ciborium::value::Integer;
fn text(s: &str) -> CborValue { CborValue::Text(s.into()) }
fn int(n: i64) -> CborValue { CborValue::Integer(Integer::from(n)) }
fn tag(n: u64, inner: CborValue) -> CborValue {
CborValue::Tag(n, Box::new(inner))
}
fn de_capture<T, F>(v: CborValue, expected: u64, parse: F) -> Result<T, String>
where
F: FnOnce(CborValue) -> Result<T, String>,
{
let mut buf = Vec::new();
ciborium::into_writer(&v, &mut buf).unwrap();
let mut scratch = [0u8; 4096];
let cap: Captured<CborValue> = ciborium::from_reader_with_buffer(&buf[..], &mut scratch)
.map_err(|e| format!("{e:?}"))?;
match cap.0 {
Some(t) if t == expected => parse(cap.1),
Some(t) => Err(format!("expected Tag {expected}, got Tag {t}")),
None => Err(format!("expected Tag {expected}, got untagged")),
}
}
#[test]
fn record_id_via_parse() {
let r = de_capture(tag(8, text("user:alice")), 8, parse_record_id).unwrap();
assert_eq!(r, RecordId::new("user", "alice"));
let r = de_capture(
tag(8, CborValue::Array(vec![text("user"), text("bob")])),
8,
parse_record_id,
)
.unwrap();
assert_eq!(r, RecordId::new("user", "bob"));
let r = de_capture(
tag(8, CborValue::Array(vec![text("user"), int(42)])),
8,
parse_record_id,
)
.unwrap();
assert_eq!(r, RecordId("user".into(), RecordIdKey::Number(42)));
assert!(parse_record_id(text("no_colon")).is_err());
assert!(parse_record_id(int(123)).is_err());
}
#[test]
fn datetime_via_capture() {
let v = tag(12, CborValue::Array(vec![int(1_752_600_000), int(0)]));
let dt = de_capture(v, 12, |inner| parse_dt_struct(&inner)).unwrap();
assert_eq!(dt.timestamp(), 1_752_600_000);
let v = tag(0, text("2026-07-16T10:00:00Z"));
let dt = de_capture(v, 0, parse_dt_str).unwrap();
assert_eq!(dt.to_rfc3339(), "2026-07-16T10:00:00+00:00");
}
#[test]
fn uuid_via_capture() {
let s = "550e8400-e29b-41d4-a716-446655440000";
let v = tag(9, text(s));
let u = de_capture(v, 9, |inner| {
let CborValue::Text(s) = inner else {
return Err("not text".into());
};
uuid::Uuid::parse_str(&s).map_err(|e| e.to_string())
}).unwrap();
assert_eq!(u.to_string(), s);
let bytes = b"\x55\x0e\x84\x00\xe2\x9b\x41\xd4\xa7\x16\x44\x66\x55\x44\x00\x00";
let v = tag(37, CborValue::Bytes(bytes.to_vec()));
let u = de_capture(v, 37, |inner| {
let CborValue::Bytes(b) = inner else {
return Err("not bytes".into());
};
if b.len() != 16 { return Err("not 16".into()); }
let mut a = [0u8; 16];
a.copy_from_slice(&b);
Ok(uuid::Uuid::from_bytes(a))
}).unwrap();
assert_eq!(u.to_string(), s);
}
#[test]
fn none_via_capture() {
let mut buf = Vec::new();
ciborium::into_writer(&tag(6, CborValue::Null), &mut buf).unwrap();
let mut scratch = [0u8; 256];
let n: CborNone = ciborium::from_reader_with_buffer(&buf[..], &mut scratch).unwrap();
assert_eq!(n, CborNone);
let mut buf = Vec::new();
ciborium::into_writer(&CborValue::Null, &mut buf).unwrap();
let mut scratch = [0u8; 256];
let n: CborNone = ciborium::from_reader_with_buffer(&buf[..], &mut scratch).unwrap();
assert_eq!(n, CborNone);
}
}