use facet::Facet;
use facet_json::{from_str, to_string};
use facet_testhelpers::test;
#[derive(Debug, PartialEq, Facet)]
#[facet(cow)]
#[repr(u8)]
pub enum Stem<'a> {
Borrowed(&'a str),
Owned(String),
}
#[derive(Debug, PartialEq, Facet)]
pub struct Document<'a> {
pub title: Stem<'a>,
pub content: Stem<'a>,
}
#[test]
fn test_cow_enum_serialize_transparent() {
let stem = Stem::Owned("hello".to_string());
let json = to_string(&stem).expect("should serialize");
assert_eq!(json, r#""hello""#);
}
#[test]
fn test_cow_enum_serialize_borrowed_transparent() {
let stem = Stem::Borrowed("world");
let json = to_string(&stem).expect("should serialize");
assert_eq!(json, r#""world""#);
}
#[test]
fn test_cow_enum_deserialize_transparent() {
let json = r#""hello""#;
let result: Stem<'static> = from_str(json).expect("should deserialize");
assert_eq!(result, Stem::Owned("hello".to_string()));
}
#[test]
fn test_cow_enum_in_struct() {
let json = r#"{"title": "My Title", "content": "Some content"}"#;
let result: Document<'static> = from_str(json).expect("should deserialize");
assert_eq!(result.title, Stem::Owned("My Title".to_string()));
assert_eq!(result.content, Stem::Owned("Some content".to_string()));
}
#[test]
fn test_cow_enum_roundtrip() {
let doc = Document {
title: Stem::Owned("Test".to_string()),
content: Stem::Owned("Content".to_string()),
};
let json = to_string(&doc).expect("should serialize");
assert_eq!(json, r#"{"title":"Test","content":"Content"}"#);
let parsed: Document<'static> = from_str(&json).expect("should deserialize");
assert_eq!(parsed, doc);
}
#[test]
fn test_cow_enum_roundtrip_borrowed() {
let stem = Stem::Borrowed("borrowed");
let json = to_string(&stem).expect("should serialize");
assert_eq!(json, r#""borrowed""#);
let parsed: Stem<'static> = from_str(&json).expect("should deserialize");
assert_eq!(parsed, Stem::Owned("borrowed".to_string()));
}