{"repo_name": "facet", "file_name": "/facet/facet-macros-parse/src/function/func_body.rs", "inference_info": {"prefix_code": "use crate::VerbatimUntil;\n#[cfg(test)]\nuse proc_macro2::TokenStream;\nuse unsynn::*;\n\nunsynn! {\n /// A function signature followed by its body\n pub struct FunctionWithBody {\n /// Everything before the function body (return type, etc.) - optional\n pub prefix: Option>,\n /// The function body in braces\n pub body: BraceGroup,\n }\n}\n\n/// Parse function body from tokens using declarative parsing\n/// Returns the function body as TokenStream\n#[cfg(test)]\npub fn parse_function_body(tokens: &[TokenTree]) -> TokenStream {\n // Convert tokens to TokenStream for parsing\n let mut token_stream = TokenStream::new();\n for token in tokens {\n token_stream.extend(core::iter::once(token.clone()));\n }\n\n let mut it = token_stream.to_token_iter();\n\n match it.parse::() {\n Ok(func_with_body) => func_with_body.body.to_token_stream(),\n Err(_) => {\n // No function body found, return empty braces\n quote::quote! { {} }\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use quote::quote;\n\n #[test]\n fn test_simple_function_body() {\n let input: Vec = quote! { { x + y } }.into_iter().collect();\n let body = parse_function_body(&input);\n assert_eq!(body.to_string().trim(), \"{ x + y }\");\n }\n\n #[test]\n fn test_complex_function_body() {\n let input: Vec = quote! { {\n let result = x + y;\n println!(\"Result: {}\", result);\n result\n } }\n .into_iter()\n .collect();\n let body = parse_function_body(&input);\n let body_str = body.to_string();\n assert!(body_str.contains(\"let result\"));\n assert!(body_str.contains(\"println !\"));\n assert!(body_str.starts_with('{'));\n assert!(body_str.ends_with('}'));\n }\n\n #[test]\n fn test_function_with_trailing_tokens() {\n // Simulate tokens like: -> i32 { x + y }\n let input: Vec = quote! { -> i32 { x + y } }.into_iter().collect();\n let body = parse_function_body(&input);\n assert_eq!(body.to_string().trim(), \"{ x + y }\");\n }\n\n #[test]\n fn test_no_function_body() {\n let input: Vec = quote! { -> i32 }.into_iter().collect();\n let body = parse_function_body(&input);\n assert_eq!(body.to_string().trim(), \"{ }\");\n }\n\n #[test]\n ", "suffix_code": "\n}\n", "middle_code": "fn test_nested_braces() {\n let input: Vec = quote! { {\n if condition {\n inner_block();\n }\n } }\n .into_iter()\n .collect();\n let body = parse_function_body(&input);\n let body_str = body.to_string();\n assert!(body_str.contains(\"if condition\"));\n assert!(body_str.contains(\"inner_block\"));\n }", "code_description": null, "fill_type": "FUNCTION_TYPE", "language_type": "rust", "sub_task_type": null}, "context_code": [["/facet/facet-macros-parse/src/function/func_sig.rs", "use proc_macro2::TokenStream;\nuse unsynn::*;\n\n// Re-use the types from our other modules\nuse crate::func_params::Parameter;\nuse crate::generics::GenericParams;\nuse crate::ret_type::ReturnType;\nuse crate::{Attribute, AttributeInner};\n\nkeyword! {\n /// The \"fn\" keyword.\n pub KFn = \"fn\";\n}\n\n// We need to define how to parse different types of attributes\nunsynn! {\n /// A complete function signature with optional attributes\n pub struct FnSignature {\n /// Zero or more attributes (including doc comments)\n pub attributes: Option>,\n /// The \"fn\" keyword\n pub _fn_keyword: KFn,\n /// Function name\n pub name: Ident,\n /// Optional generic parameters\n pub generics: Option,\n /// Parameter list in parentheses\n pub params: ParenthesisGroup,\n /// Optional return type\n pub return_type: Option,\n /// Function body\n pub body: BraceGroup,\n }\n}\n\n/// Parsed function signature with extracted components including documentation\npub struct FunctionSignature {\n /// Function name\n pub name: Ident,\n /// Optional generic parameters\n pub generics: Option,\n /// Function parameters\n pub parameters: Vec,\n /// Optional return type\n pub return_type: TokenStream,\n /// Function body\n pub body: TokenStream,\n /// Extracted documentation from doc comments as separate lines\n pub documentation: Vec,\n}\n\n/// Extract documentation from attributes\npub fn extract_documentation(attributes: &Option>) -> Vec {\n let attrs = match attributes {\n Some(many_attrs) => &many_attrs.0,\n None => return Vec::new(),\n };\n\n let mut doc_lines = Vec::new();\n\n for attr in attrs.iter() {\n // Pattern match on the AttributeInner enum\n match &attr.value.body.content {\n AttributeInner::Doc(doc_attr) => {\n // LiteralString lets you access the unquoted value, but must be unescaped\n let doc_str = doc_attr.value.as_str().replace(\"\\\\\\\"\", \"\\\"\");\n doc_lines.push(doc_str);\n }\n AttributeInner::Facet(_) | AttributeInner::Repr(_) | AttributeInner::Any(_) => {\n // Not a doc attribute, skipping\n }\n }\n }\n\n doc_lines\n}\n\n/// Parse a complete function signature from TokenStream\npub fn parse_function_signature(input: TokenStream) -> FunctionSignature {\n let mut it = input.to_token_iter();\n\n match it.parse::() {\n Ok(sig) => {\n // Extract parameters from the parenthesis group\n let params_content = {\n let params_tokens = sig.params.to_token_stream();\n let mut it = params_tokens.to_token_iter();\n if let Ok(TokenTree::Group(group)) = it.parse::() {\n group.stream()\n } else {\n TokenStream::new()\n }\n };\n let parameters = crate::func_params::parse_fn_parameters(params_content);\n\n // Extract generics if present\n let generics = sig.generics.map(|g| g.to_token_stream());\n\n // Extract return type if present\n let return_type = sig\n .return_type\n .map(|rt| rt.return_type.to_token_stream())\n .unwrap_or_else(|| quote::quote! { () });\n\n // Extract body\n let body = sig.body.to_token_stream();\n\n // Extract documentation from attributes\n let documentation = extract_documentation(&sig.attributes);\n\n FunctionSignature {\n name: sig.name,\n generics,\n parameters,\n return_type,\n body,\n documentation,\n }\n }\n Err(err) => {\n panic!(\"Failed to parse function signature: {err}\");\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use quote::quote;\n\n #[test]\n fn test_simple_function() {\n let input = quote! {\n fn add(x: i32, y: i32) -> i32 {\n x + y\n }\n };\n\n let parsed = parse_function_signature(input);\n assert_eq!(parsed.name.to_string(), \"add\");\n assert!(parsed.generics.is_none());\n assert_eq!(parsed.parameters.len(), 2);\n assert_eq!(parsed.parameters[0].name.to_string(), \"x\");\n assert_eq!(parsed.parameters[1].name.to_string(), \"y\");\n assert_eq!(parsed.return_type.to_string().trim(), \"i32\");\n }\n\n #[test]\n fn test_generic_function() {\n let input = quote! {\n fn generic_add(x: T, y: T) -> T {\n x + y\n }\n };\n\n let parsed = parse_function_signature(input);\n assert_eq!(parsed.name.to_string(), \"generic_add\");\n assert!(parsed.generics.is_some());\n assert_eq!(parsed.parameters.len(), 2);\n assert_eq!(parsed.return_type.to_string().trim(), \"T\");\n }\n\n #[test]\n fn test_no_params_function() {\n let input = quote! {\n fn no_params() -> &'static str {\n \"hello\"\n }\n };\n\n let parsed = parse_function_signature(input);\n assert_eq!(parsed.name.to_string(), \"no_params\");\n assert_eq!(parsed.parameters.len(), 0);\n assert_eq!(parsed.return_type.to_string().trim(), \"& 'static str\");\n }\n\n #[test]\n fn test_no_return_type() {\n let input = quote! {\n fn no_return(x: i32) {\n println!(\"{}\", x);\n }\n };\n\n let parsed = parse_function_signature(input);\n assert_eq!(parsed.name.to_string(), \"no_return\");\n assert_eq!(parsed.parameters.len(), 1);\n assert_eq!(parsed.return_type.to_string().trim(), \"()\");\n }\n\n #[test]\n fn test_function_with_doc_comments() {\n let input = quote! {\n #[doc = \" This is a test function\"]\n #[doc = \" that does addition of two numbers\"]\n fn add(x: i32, y: i32) -> i32 {\n x + y\n }\n };\n\n let parsed = parse_function_signature(input);\n assert_eq!(parsed.name.to_string(), \"add\");\n assert!(parsed.generics.is_none());\n assert_eq!(parsed.parameters.len(), 2);\n assert_eq!(parsed.parameters[0].name.to_string(), \"x\");\n assert_eq!(parsed.parameters[1].name.to_string(), \"y\");\n assert_eq!(parsed.return_type.to_string().trim(), \"i32\");\n\n // Check documentation\n assert!(!parsed.documentation.is_empty());\n assert_eq!(parsed.documentation.len(), 2); // Two doc lines\n assert_eq!(parsed.documentation[0], \" This is a test function\");\n assert_eq!(\n parsed.documentation[1],\n \" that does addition of two numbers\"\n );\n }\n\n #[test]\n fn test_function_with_single_doc_comment() {\n let input = quote! {\n #[doc = \" Single line documentation\"]\n fn greet(name: String) -> String {\n format!(\"Hello, {}!\", name)\n }\n };\n\n let parsed = parse_function_signature(input);\n assert!(!parsed.documentation.is_empty());\n assert_eq!(parsed.documentation.len(), 1);\n assert_eq!(parsed.documentation[0], \" Single line documentation\");\n }\n\n #[test]\n fn test_function_without_doc_comments() {\n let input = quote! {\n fn no_docs(x: i32) -> i32 {\n x * 2\n }\n };\n\n let parsed = parse_function_signature(input);\n assert_eq!(parsed.name.to_string(), \"no_docs\");\n assert!(parsed.documentation.is_empty());\n }\n\n #[test]\n fn test_function_with_mixed_attributes() {\n let input = quote! {\n #[doc = \" Documentation comment\"]\n #[derive(Debug)]\n #[doc = \" More documentation\"]\n fn mixed_attrs() {\n println!(\"test\");\n }\n };\n\n let parsed = parse_function_signature(input);\n assert_eq!(parsed.name.to_string(), \"mixed_attrs\");\n assert!(!parsed.documentation.is_empty());\n assert_eq!(parsed.documentation.len(), 2); // Two doc lines\n\n assert_eq!(parsed.documentation[0], \" Documentation comment\");\n assert_eq!(parsed.documentation[1], \" More documentation\");\n }\n\n #[test]\n fn test_generic_function_with_docs() {\n // Imitate `///d` with `#[doc = \"d\"]` because `quote!` gives `r\"d\"` not `\"d\"`\n // which `unsynn::LiteralString` will not match on when parsing.\n let input = quote! {\n #[doc = \" Generic function that adds two values\"]\n fn generic_add>(x: T, y: T) -> T {\n x + y\n }\n };\n\n let parsed = parse_function_signature(input);\n assert_eq!(parsed.name.to_string(), \"generic_add\");\n assert!(parsed.generics.is_some());\n assert!(!parsed.documentation.is_empty());\n assert_eq!(parsed.documentation.len(), 1);\n\n // Check the content\n assert_eq!(\n parsed.documentation[0],\n \" Generic function that adds two values\"\n );\n }\n}\n"], ["/facet/facet-macros-parse/src/function/ret_type.rs", "use crate::VerbatimUntil;\n#[cfg(test)]\nuse proc_macro2::TokenStream;\nuse unsynn::*;\n\nunsynn! {\n /// A return type annotation with arrow and type\n pub struct ReturnType {\n /// The \"->\" arrow\n pub _arrow: RArrow,\n /// Return type (everything until brace group)\n pub return_type: VerbatimUntil,\n }\n}\n\n/// Parse return type from tokens after parameters\n/// Returns the return type as TokenStream, or unit type () if no return type found\n#[cfg(test)]\npub fn parse_return_type(tokens: Vec) -> TokenStream {\n let mut token_stream = TokenStream::new();\n for token in &tokens {\n token_stream.extend(core::iter::once(token.clone()));\n }\n\n let mut it = token_stream.to_token_iter();\n\n match it.parse::() {\n Ok(ret_type) => ret_type.return_type.to_token_stream(),\n Err(_) => {\n // No return type found, default to unit type\n quote::quote! { () }\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use quote::quote;\n\n #[test]\n fn test_no_return_type() {\n let input = vec![];\n let ret_type = parse_return_type(input);\n assert_eq!(ret_type.to_string().trim(), \"()\");\n }\n\n #[test]\n fn test_simple_return_type() {\n let input: Vec = quote! { -> i32 }.into_iter().collect();\n let ret_type = parse_return_type(input);\n assert_eq!(ret_type.to_string().trim(), \"i32\");\n }\n\n #[test]\n fn test_complex_return_type() {\n let input: Vec = quote! { -> Result> }\n .into_iter()\n .collect();\n let ret_type = parse_return_type(input);\n assert_eq!(\n ret_type.to_string().trim(),\n \"Result < String , Box < dyn Error > >\"\n );\n }\n\n #[test]\n fn test_reference_return_type() {\n let input: Vec = quote! { -> &'static str }.into_iter().collect();\n let ret_type = parse_return_type(input);\n assert_eq!(ret_type.to_string().trim(), \"& 'static str\");\n }\n}\n"], ["/facet/facet-macros-parse/src/function/func_params.rs", "use crate::VerbatimUntil;\nuse proc_macro2::TokenStream;\nuse unsynn::*;\n\nunsynn! {\n /// A function parameter with name and type\n pub struct Parameter {\n /// Parameter name\n pub name: Ident,\n /// Colon separator\n pub _colon: Colon,\n /// Parameter type (everything until comma or end)\n pub param_type: VerbatimUntil,\n }\n}\n\nimpl Parameter {\n /// Convert the parameter type to TokenStream for use with quote!\n pub fn param_type_tokens(&self) -> TokenStream {\n self.param_type.to_token_stream()\n }\n}\n\n/// Parse function parameters from a TokenStream (content of parentheses)\n/// Returns a Vec of Parameter structs\npub fn parse_fn_parameters(params_ts: TokenStream) -> Vec {\n let mut it = params_ts.to_token_iter();\n\n // Parse as comma-delimited list of parameters\n match it.parse::>() {\n Ok(params) => params.0.into_iter().map(|delim| delim.value).collect(),\n Err(_) => Vec::new(), // Empty parameter list\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use quote::quote;\n\n #[test]\n fn test_empty_parameters() {\n let input = quote! {};\n let params = parse_fn_parameters(input);\n assert_eq!(params.len(), 0);\n }\n\n #[test]\n fn test_single_parameter() {\n let input = quote! { x: i32 };\n let params = parse_fn_parameters(input);\n assert_eq!(params.len(), 1);\n assert_eq!(params[0].name.to_string(), \"x\");\n assert_eq!(params[0].param_type.tokens_to_string().trim(), \"i32\");\n }\n\n #[test]\n fn test_multiple_parameters() {\n let input = quote! { x: i32, y: String };\n let params = parse_fn_parameters(input);\n assert_eq!(params.len(), 2);\n assert_eq!(params[0].name.to_string(), \"x\");\n assert_eq!(params[0].param_type.tokens_to_string().trim(), \"i32\");\n assert_eq!(params[1].name.to_string(), \"y\");\n assert_eq!(params[1].param_type.tokens_to_string().trim(), \"String\");\n }\n\n #[test]\n fn test_complex_types() {\n let input = quote! { callback: fn(i32) -> String, data: Vec> };\n let params = parse_fn_parameters(input);\n assert_eq!(params.len(), 2);\n assert_eq!(params[0].name.to_string(), \"callback\");\n assert_eq!(\n params[0].param_type.tokens_to_string().trim(),\n \"fn (i32) -> String\"\n );\n assert_eq!(params[1].name.to_string(), \"data\");\n assert_eq!(\n params[1].param_type.tokens_to_string().trim(),\n \"Vec < Option < u64 > >\"\n );\n }\n}\n"], ["/facet/facet-testhelpers-macros/src/lib.rs", "use unsynn::*;\n\nkeyword! {\n KFn = \"fn\";\n}\n\nunsynn! {\n struct UntilFn {\n items: Any, TokenTree>>,\n }\n\n struct UntilBody {\n items: Any, TokenTree>>,\n }\n\n struct Body {\n items: BraceGroup,\n }\n\n struct FunctionDecl {\n until_fn: UntilFn, _fn: KFn, name: Ident,\n until_body: UntilBody, body: Body\n }\n}\n\nimpl quote::ToTokens for UntilFn {\n fn to_tokens(&self, tokens: &mut unsynn::TokenStream) {\n self.items.to_tokens(tokens)\n }\n}\n\nimpl quote::ToTokens for UntilBody {\n fn to_tokens(&self, tokens: &mut unsynn::TokenStream) {\n self.items.to_tokens(tokens)\n }\n}\n\nimpl quote::ToTokens for Body {\n fn to_tokens(&self, tokens: &mut unsynn::TokenStream) {\n tokens.extend(self.items.0.stream())\n }\n}\n\n#[proc_macro_attribute]\npub fn test(\n _attr: proc_macro::TokenStream,\n item: proc_macro::TokenStream,\n) -> proc_macro::TokenStream {\n let item = TokenStream::from(item);\n let mut i = item.to_token_iter();\n let fdecl = i.parse::().unwrap();\n\n let FunctionDecl {\n until_fn,\n _fn,\n name,\n until_body,\n body,\n } = fdecl;\n\n quote::quote! {\n #[::core::prelude::rust_2024::test]\n #until_fn fn #name #until_body {\n ::facet_testhelpers::setup();\n\n #body\n }\n }\n .into()\n}\n"], ["/facet/facet-macros-parse/src/function/fn_shape_input.rs", "use proc_macro2::TokenStream;\nuse unsynn::*;\n\n// Re-use the generics parser from our other module\nuse crate::generics::GenericParams;\n\nunsynn! {\n /// Input to fn_shape! macro: function_name or function_name\n pub struct FnShapeInput {\n /// Function name\n pub name: Ident,\n /// Optional generic parameters\n pub generics: Option,\n }\n}\n\n/// Parsed fn_shape input with extracted components\npub struct ParsedFnShapeInput {\n /// Function name\n pub name: Ident,\n /// Optional generic type parameters\n pub generics: Option,\n}\n\n/// Parse fn_shape! macro input from TokenStream\npub fn parse_fn_shape_input(input: TokenStream) -> ParsedFnShapeInput {\n let mut it = input.to_token_iter();\n\n match it.parse::() {\n Ok(shape_input) => {\n let name = shape_input.name;\n let generics = shape_input.generics.map(|g| g.to_token_stream());\n\n ParsedFnShapeInput { name, generics }\n }\n Err(err) => {\n panic!(\"Failed to parse fn_shape input: {err}\");\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use quote::quote;\n\n #[test]\n fn test_simple_function_name() {\n let input = quote! { add };\n let parsed = parse_fn_shape_input(input);\n assert_eq!(parsed.name.to_string(), \"add\");\n assert!(parsed.generics.is_none());\n }\n\n #[test]\n fn test_function_with_single_generic() {\n let input = quote! { generic_add };\n let parsed = parse_fn_shape_input(input);\n assert_eq!(parsed.name.to_string(), \"generic_add\");\n assert!(parsed.generics.is_some());\n assert_eq!(parsed.generics.unwrap().to_string().trim(), \"< T >\");\n }\n\n #[test]\n fn test_function_with_multiple_generics() {\n let input = quote! { multi_ty_param_fn };\n let parsed = parse_fn_shape_input(input);\n assert_eq!(parsed.name.to_string(), \"multi_ty_param_fn\");\n assert!(parsed.generics.is_some());\n assert_eq!(parsed.generics.unwrap().to_string().trim(), \"< T , U >\");\n }\n\n #[test]\n fn test_function_with_bounded_generics() {\n let input = quote! { bounded_fn };\n let parsed = parse_fn_shape_input(input);\n assert_eq!(parsed.name.to_string(), \"bounded_fn\");\n assert!(parsed.generics.is_some());\n assert_eq!(parsed.generics.unwrap().to_string().trim(), \"< U : Clone >\");\n }\n\n #[test]\n fn test_function_with_complex_generics() {\n let input = quote! { nested_fn> };\n let parsed = parse_fn_shape_input(input);\n assert_eq!(parsed.name.to_string(), \"nested_fn\");\n assert!(parsed.generics.is_some());\n assert_eq!(\n parsed.generics.unwrap().to_string().trim(),\n \"< T : Add < Output = T > >\"\n );\n }\n}\n"], ["/facet/facet-macros-emit/src/function/emit.rs", "use facet_macros_parse::function::*;\nuse facet_macros_parse::{FunctionSignature, Ident, Span, TokenStream, extract_type_params};\nuse quote::quote;\n\n/// Entry point for the facet_fn attribute macro\npub fn facet_fn(_attr: TokenStream, item: TokenStream) -> TokenStream {\n // Convert to proc_macro2 for parsing (quote requires it)\n let parsed = parse_function_signature(item);\n let result = generate_function_shape(parsed);\n\n // Convert back\n result.to_string().parse().unwrap()\n}\n\n/// Entry point for the fn_shape procedural macro\npub fn fn_shape(input: TokenStream) -> TokenStream {\n let parsed = parse_fn_shape_input(input);\n let result = generate_fn_shape_call(parsed);\n\n result.to_string().parse().unwrap()\n}\n\npub fn generate_function_shape(parsed: FunctionSignature) -> TokenStream {\n let fn_name = parsed.name;\n let generics = parsed.generics;\n let params = parsed.parameters;\n let return_type = parsed.return_type;\n let body = parsed.body;\n\n let hidden_mod = Ident::new(&format!(\"__fn_shape_{fn_name}\"), Span::call_site());\n let shape_name = Ident::new(\n &format!(\"{}_SHAPE\", fn_name.to_string().to_uppercase()),\n Span::call_site(),\n );\n let defs: Vec<_> = params\n .iter()\n .map(|p| {\n let name = &p.name;\n let ty = &p.param_type_tokens();\n quote! { #name: #ty }\n })\n .collect();\n let idents: Vec<_> = params\n .iter()\n .map(|p| {\n let name = &p.name;\n quote! { #name }\n })\n .collect();\n let types: Vec<_> = params\n .iter()\n .map(|p| {\n let ty = &p.param_type_tokens();\n quote! { #ty }\n })\n .collect();\n let names: Vec<_> = params\n .iter()\n .map(|p| p.name.to_string())\n .collect::>();\n let arity = params.len();\n let fn_name_str = fn_name.to_string();\n\n // Extract type parameters for PhantomData using unsynn parsing\n let generics_type = if let Some(ref generics_ts) = generics {\n extract_type_params(generics_ts.clone())\n } else {\n quote! { () }\n };\n\n let documentation_lines: Vec<_> = parsed\n .documentation\n .iter()\n .map(|doc| quote! { #doc })\n .collect();\n\n let shape_definition = quote! {\n pub fn shape #generics () -> FunctionShape<( #( #types ),* ), #return_type, #generics_type> {\n FunctionShape::new(\n #fn_name_str,\n #arity,\n &[ #( #names ),* ],\n &[ #( #documentation_lines ),* ]\n )\n }\n };\n\n let out = quote! {\n // 1) Move the real implementation into a private module\n #[allow(non_snake_case)]\n mod #hidden_mod {\n use super::*;\n pub(super) fn inner #generics ( #( #defs ),* ) -> #return_type #body\n\n #[derive(Debug, Clone)]\n pub struct FunctionShape {\n pub name: &'static str,\n pub param_count: usize,\n pub param_names: &'static [&'static str],\n pub documentation: &'static [&'static str],\n _args: core::marker::PhantomData,\n _ret: core::marker::PhantomData,\n _generics: core::marker::PhantomData,\n }\n\n impl FunctionShape {\n pub const fn new(\n name: &'static str,\n param_count: usize,\n param_names: &'static [&'static str],\n documentation: &'static [&'static str],\n ) -> Self {\n Self {\n name,\n param_count,\n param_names,\n documentation,\n _args: core::marker::PhantomData,\n _ret: core::marker::PhantomData,\n _generics: core::marker::PhantomData,\n }\n }\n }\n\n #shape_definition\n }\n\n // 2) Public wrapper retains the exact original signature\n pub fn #fn_name #generics ( #( #defs ),* ) -> #return_type {\n #hidden_mod::inner( #( #idents ),* )\n }\n\n // 3) Re-export the shape function with function name\n pub use #hidden_mod::shape as #shape_name;\n };\n\n out\n}\n\nfn generate_fn_shape_call(parsed: ParsedFnShapeInput) -> TokenStream {\n let fn_name = parsed.name;\n let generic_args = parsed.generics;\n\n // Generate the shape function name\n let shape_name = Ident::new(\n &format!(\"{}_SHAPE\", fn_name.to_string().to_uppercase()),\n Span::call_site(),\n );\n\n if let Some(generics) = generic_args {\n quote! { #shape_name::#generics() }\n } else {\n quote! { #shape_name() }\n }\n}\n"], ["/facet/facet-macros-parse/src/function/generics.rs", "use crate::VerbatimUntil;\n#[cfg(test)]\nuse proc_macro2::TokenStream;\nuse unsynn::*;\n\nunsynn! {\n /// Parses either a `TokenTree` or `<...>` grouping (which is not a [`Group`] as far as proc-macros\n /// are concerned).\n #[derive(Clone)]\n pub struct AngleTokenTree(\n #[allow(clippy::type_complexity)] // look,\n pub Either, AngleTokenTree>>, Gt>, TokenTree>,\n );\n\n /// A generic type parameter with name and optional bounds\n pub struct TypeParam {\n /// Type parameter name\n pub name: Ident,\n /// Optional colon and bounds (e.g., \": Clone + Send\")\n pub bounds: Option>>>,\n }\n\n /// Generic parameters with angle brackets\n pub struct GenericParams {\n /// Opening angle bracket\n pub _lt: Lt,\n /// Comma-delimited list of generic parameters\n pub params: CommaDelimitedVec,\n /// Closing angle bracket\n pub _gt: Gt,\n }\n}\n\n/// Parse generics from TokenStream\n#[cfg(test)]\npub fn parse_generics_for_test(input: TokenStream) -> Option {\n let mut it = input.to_token_iter();\n it.parse::().ok()\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use quote::quote;\n\n #[test]\n fn test_no_generics() {\n let input = quote! { fn_name() };\n let generics = parse_generics_for_test(input);\n assert!(generics.is_none());\n }\n\n #[test]\n fn test_simple_generics() {\n let input = quote! { };\n let generics = parse_generics_for_test(input).expect(\"should parse\");\n assert_eq!(generics.params.0.len(), 1);\n assert_eq!(generics.params.0[0].value.name.to_string(), \"T\");\n assert!(generics.params.0[0].value.bounds.is_none());\n }\n\n #[test]\n fn test_multiple_generics() {\n let input = quote! { };\n let generics = parse_generics_for_test(input).expect(\"should parse\");\n assert_eq!(generics.params.0.len(), 3);\n assert_eq!(generics.params.0[0].value.name.to_string(), \"T\");\n assert_eq!(generics.params.0[1].value.name.to_string(), \"U\");\n assert_eq!(generics.params.0[2].value.name.to_string(), \"V\");\n }\n\n #[test]\n fn test_generics_with_bounds() {\n let input = quote! { };\n let generics = parse_generics_for_test(input).expect(\"should parse\");\n assert_eq!(generics.params.0.len(), 2);\n assert_eq!(generics.params.0[0].value.name.to_string(), \"T\");\n assert!(generics.params.0[0].value.bounds.is_some());\n assert_eq!(generics.params.0[1].value.name.to_string(), \"U\");\n assert!(generics.params.0[1].value.bounds.is_some());\n }\n\n #[test]\n fn test_complex_generics() {\n let input = quote! { , U: Iterator> };\n let generics = parse_generics_for_test(input).expect(\"should parse\");\n assert_eq!(generics.params.0.len(), 2);\n assert_eq!(generics.params.0[0].value.name.to_string(), \"T\");\n assert_eq!(generics.params.0[1].value.name.to_string(), \"U\");\n assert!(generics.params.0[0].value.bounds.is_some());\n assert!(generics.params.0[1].value.bounds.is_some());\n }\n\n #[test]\n fn test_empty_generics() {\n let input = quote! { <> };\n let generics = parse_generics_for_test(input).expect(\"should parse\");\n assert_eq!(generics.params.0.len(), 0);\n }\n}\n"], ["/facet/facet-macros-parse/src/function/type_params.rs", "use proc_macro2::TokenStream;\nuse unsynn::*;\n\n// Re-use the generics parser\nuse crate::generics::GenericParams;\n\n/// Extract just the type parameter names from generic parameters\n/// Returns a TokenStream suitable for PhantomData<(A, B, C)>\npub fn extract_type_params(generics_ts: TokenStream) -> TokenStream {\n let mut it = generics_ts.to_token_iter();\n\n match it.parse::() {\n Ok(generics) => {\n let type_param_names: Vec<_> = generics\n .params\n .0\n .into_iter()\n .map(|delim| delim.value.name)\n .collect();\n\n if type_param_names.is_empty() {\n quote::quote! { () }\n } else if type_param_names.len() == 1 {\n let param = &type_param_names[0];\n quote::quote! { #param }\n } else {\n quote::quote! { ( #( #type_param_names ),* ) }\n }\n }\n Err(_) => {\n // Fallback to unit type if parsing fails\n quote::quote! { () }\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use quote::quote;\n\n #[test]\n fn test_single_type_param() {\n let input = quote! { };\n let result = extract_type_params(input);\n assert_eq!(result.to_string().trim(), \"T\");\n }\n\n #[test]\n fn test_multiple_type_params() {\n let input = quote! { };\n let result = extract_type_params(input);\n assert_eq!(result.to_string().trim(), \"(A , B , C)\");\n }\n\n #[test]\n fn test_type_params_with_bounds() {\n let input = quote! { };\n let result = extract_type_params(input);\n assert_eq!(result.to_string().trim(), \"(T , U)\");\n }\n\n #[test]\n fn test_empty_generics() {\n let input = quote! { <> };\n let result = extract_type_params(input);\n assert_eq!(result.to_string().trim(), \"()\");\n }\n}\n"], ["/facet/facet-macros-parse/src/lib.rs", "#![warn(missing_docs)]\n#![doc = include_str!(\"../README.md\")]\n\n/// Parse function signature shape\n#[cfg(feature = \"function\")]\npub mod function;\n#[cfg(feature = \"function\")]\npub use function::*;\n\npub use unsynn::*;\n\nkeyword! {\n /// The \"pub\" keyword.\n pub KPub = \"pub\";\n /// The \"struct\" keyword.\n pub KStruct = \"struct\";\n /// The \"enum\" keyword.\n pub KEnum = \"enum\";\n /// The \"doc\" keyword.\n pub KDoc = \"doc\";\n /// The \"repr\" keyword.\n pub KRepr = \"repr\";\n /// The \"crate\" keyword.\n pub KCrate = \"crate\";\n /// The \"in\" keyword.\n pub KIn = \"in\";\n /// The \"const\" keyword.\n pub KConst = \"const\";\n /// The \"where\" keyword.\n pub KWhere = \"where\";\n /// The \"mut\" keyword.\n pub KMut = \"mut\";\n /// The \"facet\" keyword.\n pub KFacet = \"facet\";\n /// The \"sensitive\" keyword.\n pub KSensitive = \"sensitive\";\n /// The \"invariants\" keyword.\n pub KInvariants = \"invariants\";\n /// The \"opaque\" keyword.\n pub KOpaque = \"opaque\";\n /// The \"deny_unknown_fields\" keyword.\n pub KDenyUnknownFields = \"deny_unknown_fields\";\n /// The \"default\" keyword.\n pub KDefault = \"default\";\n /// The \"transparent\" keyword.\n pub KTransparent = \"transparent\";\n /// The \"rename\" keyword.\n pub KRename = \"rename\";\n /// The \"rename_all\" keyword.\n pub KRenameAll = \"rename_all\";\n /// The \"flatten\" keyword\n pub KFlatten = \"flatten\";\n /// The \"child\" keyword\n pub KChild = \"child\";\n /// The \"skip_serializing\" keyword.\n pub KSkipSerializing = \"skip_serializing\";\n /// The \"skip_serializing_if\" keyword.\n pub KSkipSerializingIf = \"skip_serializing_if\";\n /// The \"type_tag\" keyword.\n pub KTypeTag = \"type_tag\";\n}\n\noperator! {\n /// Represents the '=' operator.\n pub Eq = \"=\";\n /// Represents the ';' operator.\n pub Semi = \";\";\n /// Represents the apostrophe '\\'' operator.\n pub Apostrophe = \"'\";\n /// Represents the double semicolon '::' operator.\n pub DoubleSemicolon = \"::\";\n}\n\n/// Parses tokens and groups until `C` is found on the current token tree level.\npub type VerbatimUntil = Many, AngleTokenTree>>;\n\n/// Represents a module path, consisting of an optional path separator followed by\n/// a path-separator-delimited sequence of identifiers.\npub type ModPath = Cons, PathSepDelimited>;\n\n/// Represents type bounds, consisting of a colon followed by tokens until\n/// a comma, equals sign, or closing angle bracket is encountered.\npub type Bounds = Cons>>;\n\nunsynn! {\n /// Parses either a `TokenTree` or `<...>` grouping (which is not a [`Group`] as far as proc-macros\n /// are concerned).\n #[derive(Clone)]\n pub struct AngleTokenTree(\n #[allow(clippy::type_complexity)] // look,\n pub Either, AngleTokenTree>>, Gt>, TokenTree>,\n );\n\n /// Represents an algebraic data type (ADT) declaration, which can be either a struct or enum.\n pub enum AdtDecl {\n /// A struct ADT variant.\n Struct(Struct),\n /// An enum ADT variant.\n Enum(Enum),\n }\n\n /// Represents visibility modifiers for items.\n pub enum Vis {\n /// `pub(in? crate::foo::bar)`/`pub(in? ::foo::bar)`\n PubIn(Cons, ModPath>>>),\n /// Public visibility, indicated by the \"pub\" keyword.\n Pub(KPub),\n }\n\n /// Represents an attribute annotation on a field, typically in the form `#[attr]`.\n pub struct Attribute {\n /// The pound sign preceding the attribute.\n pub _pound: Pound,\n /// The content of the attribute enclosed in square brackets.\n pub body: BracketGroupContaining,\n }\n\n /// Represents the inner content of an attribute annotation.\n pub enum AttributeInner {\n /// A facet attribute that can contain specialized metadata.\n Facet(FacetAttr),\n /// A documentation attribute typically used for generating documentation.\n Doc(DocInner),\n /// A representation attribute that specifies how data should be laid out.\n Repr(ReprInner),\n /// Any other attribute represented as a sequence of token trees.\n Any(Vec),\n }\n\n /// Represents a facet attribute that can contain specialized metadata.\n pub struct FacetAttr {\n /// The keyword for the facet attribute.\n pub _facet: KFacet,\n /// The inner content of the facet attribute.\n pub inner: ParenthesisGroupContaining>,\n }\n\n /// Represents the inner content of a facet attribute.\n pub enum FacetInner {\n /// A sensitive attribute that specifies sensitivity information.\n Sensitive(KSensitive),\n /// An invariants attribute that specifies invariants for the type.\n Invariants(InvariantInner),\n /// An opaque attribute that specifies opaque information.\n Opaque(KOpaque),\n /// A deny_unknown_fields attribute that specifies whether unknown fields are allowed.\n DenyUnknownFields(KDenyUnknownFields),\n /// A default attribute with an explicit value (#[facet(default = \"myfunc\")])\n DefaultEquals(DefaultEqualsInner),\n /// A default attribute with no explicit value (#[facet(default)])\n Default(KDefault),\n /// A transparent attribute for containers\n Transparent(KTransparent),\n /// A rename_all attribute that specifies a case conversion for all fields/variants (#[facet(rename_all = \"camelCase\")])\n RenameAll(RenameAllInner),\n /// A rename attribute that specifies a custom name for a field/variant (#[facet(rename = \"custom_name\")])\n Rename(RenameInner),\n /// A flatten attribute that marks a field to be flattened into the parent structure\n Flatten(FlattenInner),\n /// A child attribute that marks a field as a child node\n Child(ChildInner),\n /// A skip_serializing attribute that specifies whether a field should be skipped during serialization.\n SkipSerializing(SkipSerializingInner),\n /// A skip_serializing_if attribute that specifies a condition for skipping serialization.\n SkipSerializingIf(SkipSerializingIfInner),\n /// A type_tag attribute that specifies the identifying tag for self describing formats\n TypeTag(TypeTagInner),\n /// Any other attribute represented as a sequence of token trees.\n Arbitrary(VerbatimUntil),\n }\n\n /// Inner value for #[facet(flatten)]\n pub struct FlattenInner {\n /// The \"flatten\" keyword.\n pub _kw_flatten: KFlatten,\n }\n\n /// Inner value for #[facet(child)]\n pub struct ChildInner {\n /// The \"child\" keyword.\n pub _kw_child: KChild,\n }\n\n /// Inner value for #[facet(skip_serializing)]\n pub struct SkipSerializingInner {\n /// The \"skip_serializing\" keyword.\n pub _kw_skip_serializing: KSkipSerializing,\n }\n\n /// Inner value for #[facet(skip_serializing_if = ...)]\n pub struct SkipSerializingIfInner {\n /// The \"skip_serializing_if\" keyword.\n pub _kw_skip_serializing_if: KSkipSerializingIf,\n /// The equals sign '='.\n pub _eq: Eq,\n /// The conditional expression as verbatim until comma.\n pub expr: VerbatimUntil,\n }\n\n /// Inner value for #[facet(type_tag = ...)]\n pub struct TypeTagInner {\n /// The \"type_tag\" keyword.\n pub _kw_type_tag: KTypeTag,\n /// The equals sign '='.\n pub _eq: Eq,\n /// The value assigned, as a literal string.\n pub expr: LiteralString,\n }\n\n /// Inner value for #[facet(default = ...)]\n pub struct DefaultEqualsInner {\n /// The \"default\" keyword.\n pub _kw_default: KDefault,\n /// The equals sign '='.\n pub _eq: Eq,\n /// The value assigned, as verbatim until comma.\n pub expr: VerbatimUntil,\n }\n\n /// Inner value for #[facet(rename = ...)]\n pub struct RenameInner {\n /// The \"rename\" keyword.\n pub _kw_rename: KRename,\n /// The equals sign '='.\n pub _eq: Eq,\n /// The value assigned, as a literal string.\n pub value: LiteralString,\n }\n\n /// Inner value for #[facet(rename_all = ...)]\n pub struct RenameAllInner {\n /// The \"rename_all\" keyword.\n pub _kw_rename_all: KRenameAll,\n /// The equals sign '='.\n pub _eq: Eq,\n /// The value assigned, as a literal string.\n pub value: LiteralString,\n }\n\n /// Represents invariants for a type.\n pub struct InvariantInner {\n /// The \"invariants\" keyword.\n pub _kw_invariants: KInvariants,\n /// The equality operator.\n pub _eq: Eq,\n /// The invariant value\n pub expr: VerbatimUntil,\n }\n\n /// Represents documentation for an item.\n pub struct DocInner {\n /// The \"doc\" keyword.\n pub _kw_doc: KDoc,\n /// The equality operator.\n pub _eq: Eq,\n /// The documentation content as a literal string.\n pub value: LiteralString,\n }\n\n /// Represents the inner content of a `repr` attribute, typically used for specifying\n /// memory layout or representation hints.\n pub struct ReprInner {\n /// The \"repr\" keyword.\n pub _kw_repr: KRepr,\n /// The representation attributes enclosed in parentheses.\n pub attr: ParenthesisGroupContaining>,\n }\n\n /// Represents a struct definition.\n pub struct Struct {\n /// Attributes applied to the struct.\n pub attributes: Vec,\n /// The visibility modifier of the struct (e.g., `pub`).\n pub _vis: Option,\n /// The \"struct\" keyword.\n pub _kw_struct: KStruct,\n /// The name of the struct.\n pub name: Ident,\n /// Generic parameters for the struct, if any.\n pub generics: Option,\n /// The variant of struct (unit, tuple, or regular struct with named fields).\n pub kind: StructKind,\n }\n\n /// Represents the generic parameters of a struct or enum definition, enclosed in angle brackets.\n /// e.g., `<'a, T: Trait, const N: usize>`.\n pub struct GenericParams {\n /// The opening angle bracket `<`.\n pub _lt: Lt,\n /// The comma-delimited list of generic parameters.\n pub params: CommaDelimitedVec,\n /// The closing angle bracket `>`.\n pub _gt: Gt,\n }\n\n /// Represents a single generic parameter within a `GenericParams` list.\n pub enum GenericParam {\n /// A lifetime parameter, e.g., `'a` or `'a: 'b + 'c`.\n Lifetime {\n /// The lifetime identifier (e.g., `'a`).\n name: Lifetime,\n /// Optional lifetime bounds (e.g., `: 'b + 'c`).\n bounds: Option>>>,\n },\n /// A const generic parameter, e.g., `const N: usize = 10`.\n Const {\n /// The `const` keyword.\n _const: KConst,\n /// The name of the const parameter (e.g., `N`).\n name: Ident,\n /// The colon separating the name and type.\n _colon: Colon,\n /// The type of the const parameter (e.g., `usize`).\n typ: VerbatimUntil>,\n /// An optional default value (e.g., `= 10`).\n default: Option>>>,\n },\n /// A type parameter, e.g., `T: Trait = DefaultType`.\n Type {\n /// The name of the type parameter (e.g., `T`).\n name: Ident,\n /// Optional type bounds (e.g., `: Trait`).\n bounds: Option,\n /// An optional default type (e.g., `= DefaultType`).\n default: Option>>>,\n },\n }\n\n /// Represents a `where` clause attached to a definition.\n /// e.g., `where T: Trait, 'a: 'b`.\n #[derive(Clone)]\n pub struct WhereClauses {\n /// The `where` keyword.\n pub _kw_where: KWhere,\n /// The comma-delimited list of where clause predicates.\n pub clauses: CommaDelimitedVec,\n }\n\n /// Represents a single predicate within a `where` clause.\n /// e.g., `T: Trait` or `'a: 'b`.\n #[derive(Clone)]\n pub struct WhereClause {\n // FIXME: This likely breaks for absolute `::` paths\n /// The type or lifetime being constrained (e.g., `T` or `'a`).\n pub _pred: VerbatimUntil,\n /// The colon separating the constrained item and its bounds.\n pub _colon: Colon,\n /// The bounds applied to the type or lifetime (e.g., `Trait` or `'b`).\n pub bounds: VerbatimUntil>,\n }\n\n /// Represents the kind of a struct definition.\n pub enum StructKind {\n /// A regular struct with named fields, e.g., `struct Foo { bar: u32 }`.\n Struct {\n /// Optional where clauses.\n clauses: Option,\n /// The fields enclosed in braces `{}`.\n fields: BraceGroupContaining>,\n },\n /// A tuple struct, e.g., `struct Foo(u32, String);`.\n TupleStruct {\n /// The fields enclosed in parentheses `()`.\n fields: ParenthesisGroupContaining>,\n /// Optional where clauses.\n clauses: Option,\n /// The trailing semicolon `;`.\n semi: Semi,\n },\n /// A unit struct, e.g., `struct Foo;`.\n UnitStruct {\n /// Optional where clauses.\n clauses: Option,\n /// The trailing semicolon `;`.\n semi: Semi,\n },\n }\n\n /// Represents a lifetime annotation, like `'a`.\n pub struct Lifetime {\n /// The apostrophe `'` starting the lifetime.\n pub _apostrophe: PunctJoint<'\\''>,\n /// The identifier name of the lifetime (e.g., `a`).\n pub name: Ident,\n }\n\n /// Represents a simple expression, currently only integer literals.\n /// Used potentially for const generic default values.\n pub enum Expr {\n /// An integer literal expression.\n Integer(LiteralInteger),\n }\n\n /// Represents either the `const` or `mut` keyword, often used with pointers.\n pub enum ConstOrMut {\n /// The `const` keyword.\n Const(KConst),\n /// The `mut` keyword.\n Mut(KMut),\n }\n\n /// Represents a field within a regular struct definition.\n /// e.g., `pub name: String`.\n pub struct StructField {\n /// Attributes applied to the field (e.g., `#[doc = \"...\"]`).\n pub attributes: Vec,\n /// Optional visibility modifier (e.g., `pub`).\n pub _vis: Option,\n /// The name of the field.\n pub name: Ident,\n /// The colon separating the name and type.\n pub _colon: Colon,\n /// The type of the field.\n pub typ: VerbatimUntil,\n }\n\n /// Represents a field within a tuple struct definition.\n /// e.g., `pub String`.\n pub struct TupleField {\n /// Attributes applied to the field (e.g., `#[doc = \"...\"]`).\n pub attributes: Vec,\n /// Optional visibility modifier (e.g., `pub`).\n pub vis: Option,\n /// The type of the field.\n pub typ: VerbatimUntil,\n }\n\n /// Represents an enum definition.\n /// e.g., `#[repr(u8)] pub enum MyEnum where T: Clone { Variant1, Variant2(T) }`.\n pub struct Enum {\n /// Attributes applied to the enum (e.g., `#[repr(...)]`).\n pub attributes: Vec,\n /// Optional visibility modifier (e.g., `pub`, `pub(crate)`, etc.).\n pub _vis: Option,\n /// The `enum` keyword.\n pub _kw_enum: KEnum,\n /// The name of the enum.\n pub name: Ident,\n /// Optional generic parameters.\n pub generics: Option,\n /// Optional where clauses.\n pub clauses: Option,\n /// The enum variants enclosed in braces `{}`.\n pub body: BraceGroupContaining>,\n }\n\n /// Represents a variant of an enum, including the optional discriminant value\n pub struct EnumVariantLike {\n /// The actual variant\n pub variant: EnumVariantData,\n /// The optional discriminant value\n pub discriminant: Option>>\n }\n\n /// Represents the different kinds of variants an enum can have.\n pub enum EnumVariantData {\n /// A tuple-like variant, e.g., `Variant(u32, String)`.\n Tuple(TupleVariant),\n /// A struct-like variant, e.g., `Variant { field1: u32, field2: String }`.\n Struct(StructEnumVariant),\n /// A unit-like variant, e.g., `Variant`.\n Unit(UnitVariant),\n }\n\n /// Represents a unit-like enum variant.\n /// e.g., `MyVariant`.\n pub struct UnitVariant {\n /// Attributes applied to the variant.\n pub attributes: Vec,\n /// The name of the variant.\n pub name: Ident,\n }\n\n /// Represents a tuple-like enum variant.\n /// e.g., `MyVariant(u32, String)`.\n pub struct TupleVariant {\n /// Attributes applied to the variant.\n pub attributes: Vec,\n /// The name of the variant.\n pub name: Ident,\n /// The fields enclosed in parentheses `()`.\n pub fields: ParenthesisGroupContaining>,\n }\n\n /// Represents a struct-like enum variant.\n /// e.g., `MyVariant { field1: u32, field2: String }`.\n pub struct StructEnumVariant {\n /// Attributes applied to the variant.\n pub attributes: Vec,\n /// The name of the variant.\n pub name: Ident,\n /// The fields enclosed in braces `{}`.\n pub fields: BraceGroupContaining>,\n }\n\n /// A lifetime or a tokentree, used to gather lifetimes in type definitions\n pub enum LifetimeOrTt {\n /// A lifetime annotation.\n Lifetime(Lifetime),\n /// A single token tree.\n TokenTree(TokenTree),\n }\n}\n\nimpl core::fmt::Display for AngleTokenTree {\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n match &self.0 {\n Either::First(it) => {\n write!(f, \"<\")?;\n for it in it.second.iter() {\n write!(f, \"{}\", it.second)?;\n }\n write!(f, \">\")?;\n }\n Either::Second(it) => write!(f, \"{it}\")?,\n Either::Third(Invalid) => unreachable!(),\n Either::Fourth(Invalid) => unreachable!(),\n };\n Ok(())\n }\n}\n\n/// Display the verbatim tokens until the given token.\npub struct VerbatimDisplay<'a, C>(pub &'a VerbatimUntil);\n\nimpl core::fmt::Display for VerbatimDisplay<'_, C> {\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n for tt in self.0.0.iter() {\n write!(f, \"{}\", tt.value.second)?;\n }\n Ok(())\n }\n}\n\nimpl core::fmt::Display for ConstOrMut {\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n match self {\n ConstOrMut::Const(_) => write!(f, \"const\"),\n ConstOrMut::Mut(_) => write!(f, \"mut\"),\n }\n }\n}\n\nimpl core::fmt::Display for Lifetime {\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n write!(f, \"'{}\", self.name)\n }\n}\n\nimpl core::fmt::Display for WhereClauses {\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n write!(f, \"where \")?;\n for clause in self.clauses.0.iter() {\n write!(f, \"{},\", clause.value)?;\n }\n Ok(())\n }\n}\n\nimpl core::fmt::Display for WhereClause {\n fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n write!(\n f,\n \"{}: {}\",\n VerbatimDisplay(&self._pred),\n VerbatimDisplay(&self.bounds)\n )\n }\n}\n\nimpl core::fmt::Display for Expr {\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n match self {\n Expr::Integer(int) => write!(f, \"{}\", int.value()),\n }\n }\n}\n\nimpl Struct {\n /// Returns an iterator over the `FacetInner` content of `#[facet(...)]` attributes\n /// applied to this struct.\n pub fn facet_attributes(&self) -> impl Iterator {\n self.attributes\n .iter()\n .filter_map(|attr| match &attr.body.content {\n AttributeInner::Facet(f) => Some(&f.inner.content.0),\n _ => None,\n })\n .flatten()\n .map(|d| &d.value)\n }\n\n /// Returns `true` if the struct is marked `#[facet(transparent)]`.\n pub fn is_transparent(&self) -> bool {\n self.facet_attributes()\n .any(|inner| matches!(inner, FacetInner::Transparent(_)))\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n use quote::quote;\n\n #[test]\n fn test_struct_with_field_doc_comments() {\n let input = quote! {\n #[derive(Facet)]\n pub struct User {\n #[doc = \" The user's unique identifier\"]\n pub id: u64,\n }\n };\n\n let mut it = input.to_token_iter();\n let parsed = it.parse::().expect(\"Failed to parse struct\");\n\n // Check that we parsed the struct correctly\n assert_eq!(parsed.name.to_string(), \"User\");\n\n // Extract fields from the struct\n if let StructKind::Struct { fields, .. } = &parsed.kind {\n let field_list = &fields.content.0;\n assert_eq!(field_list.len(), 1);\n\n // Check first field (id)\n let id_field = &field_list[0].value;\n assert_eq!(id_field.name.to_string(), \"id\");\n\n // Extract doc comments from id field\n let mut doc_found = false;\n for attr in &id_field.attributes {\n match &attr.body.content {\n AttributeInner::Doc(doc_inner) => {\n // This should work with LiteralString\n assert_eq!(doc_inner.value, \" The user's unique identifier\");\n doc_found = true;\n }\n _ => {\n // Skip non-doc attributes\n }\n }\n }\n assert!(doc_found, \"Should have found a doc comment\");\n } else {\n panic!(\"Expected a regular struct with named fields\");\n }\n }\n}\n"], ["/facet/facet-macros-emit/src/parsed.rs", "use crate::{BoundedGenericParams, RenameRule};\nuse facet_macros_parse::{Ident, ReprInner, ToTokens, TokenStream};\nuse quote::quote;\n\n/// For struct fields, they can either be identifiers (`my_struct.foo`)\n/// or literals (`my_struct.2`) — for tuple structs.\n#[derive(Clone)]\npub enum IdentOrLiteral {\n Ident(Ident),\n Literal(usize),\n}\n\nimpl quote::ToTokens for IdentOrLiteral {\n fn to_tokens(&self, tokens: &mut TokenStream) {\n match self {\n IdentOrLiteral::Ident(ident) => tokens.extend(quote::quote! { #ident }),\n IdentOrLiteral::Literal(lit) => {\n let unsuffixed = facet_macros_parse::Literal::usize_unsuffixed(*lit);\n tokens.extend(quote! { #unsuffixed })\n }\n }\n }\n}\n\n/// All the supported facet attributes, e.g. `#[facet(sensitive)]` `#[facet(rename_all)]`, etc.\n///\n/// Stands for `parsed facet attr`\n#[derive(Clone)]\npub enum PFacetAttr {\n /// Valid in field\n /// `#[facet(sensitive)]` — must be censored in debug outputs\n Sensitive,\n\n /// Valid in container\n /// `#[facet(opaque)]` — the inner field does not have to implement\n /// `Facet`\n Opaque,\n\n /// Valid in container\n /// `#[facet(transparent)]` — applied on things like `NonZero`, `Utf8PathBuf`,\n /// etc. — when you're doing the newtype pattern. `de/ser` is forwarded.\n Transparent,\n\n /// Valid in field\n /// `#[facet(flatten)]` — flattens a field's contents\n /// into the parent structure.\n Flatten,\n\n /// Valid in field\n /// `#[facet(child)]` — marks a field as child node in a hierarchy\n Child,\n\n /// Valid in container\n /// `#[facet(invariants = \"Self::invariants_func\")]` — returns a bool, is called\n /// when doing `Partial::build`\n Invariants { expr: TokenStream },\n\n /// Valid in container\n /// `#[facet(deny_unknown_fields)]`\n DenyUnknownFields,\n\n /// Valid in field\n /// `#[facet(default = expr)]` — when deserializing and missing, use `fn_name` to provide a default value\n DefaultEquals { expr: TokenStream },\n\n /// Valid in field\n /// `#[facet(default)]` — when deserializing and missing, use the field's value from\n /// the container's `Default::default()`\n Default,\n\n /// Valid in field, enum variant, container\n /// An arbitrary/unknown string, like,\n /// `#[facet(bleh)]`\n Arbitrary { content: String },\n\n /// Valid in container\n /// `#[facet(rename_all = \"rule\")]` — rename all fields following a rule\n RenameAll { rule: RenameRule },\n\n /// Valid in field, enum variant, or container\n /// `#[facet(skip_serializing)]` — skip serializing this field. Like serde.\n SkipSerializing,\n\n /// Valid in field, enum variant, or container\n /// `#[facet(skip_serializing_if = \"func\")]` — skip serializing if the function returns true.\n SkipSerializingIf { expr: TokenStream },\n\n /// Valid in container\n /// `#[facet(type_tag = \"com.example.MyType\")]` — identify type by tag and serialize with this tag\n TypeTag { content: String },\n}\n\nimpl PFacetAttr {\n /// Parse a `FacetAttr` attribute into a `PFacetAttr`.\n /// Pushes to `dest` for each parsed attribute.\n pub fn parse(\n facet_attr: &facet_macros_parse::FacetAttr,\n display_name: &mut String,\n dest: &mut Vec,\n ) {\n use facet_macros_parse::FacetInner;\n\n for attr in facet_attr.inner.content.0.iter().map(|d| &d.value) {\n match attr {\n FacetInner::Sensitive(_) => dest.push(PFacetAttr::Sensitive),\n FacetInner::Opaque(_) => dest.push(PFacetAttr::Opaque),\n FacetInner::Flatten(_) => dest.push(PFacetAttr::Flatten),\n FacetInner::Child(_) => dest.push(PFacetAttr::Child),\n FacetInner::Transparent(_) => dest.push(PFacetAttr::Transparent),\n\n FacetInner::Invariants(invariant) => {\n let expr = invariant.expr.to_token_stream();\n dest.push(PFacetAttr::Invariants { expr });\n }\n FacetInner::DenyUnknownFields(_) => dest.push(PFacetAttr::DenyUnknownFields),\n FacetInner::DefaultEquals(default_equals) => dest.push(PFacetAttr::DefaultEquals {\n expr: default_equals.expr.to_token_stream(),\n }),\n FacetInner::Default(_) => dest.push(PFacetAttr::Default),\n FacetInner::Rename(rename) => {\n *display_name = rename.value.as_str().to_string();\n }\n FacetInner::RenameAll(rename_all) => {\n let rule_str = rename_all.value.as_str();\n if let Some(rule) = RenameRule::from_str(rule_str) {\n dest.push(PFacetAttr::RenameAll { rule });\n } else {\n panic!(\"Unknown #[facet(rename_all = ...)] rule: {rule_str}\");\n }\n }\n FacetInner::Arbitrary(tt) => {\n dest.push(PFacetAttr::Arbitrary {\n content: tt.tokens_to_string(),\n });\n }\n FacetInner::SkipSerializing(_) => {\n dest.push(PFacetAttr::SkipSerializing);\n }\n FacetInner::SkipSerializingIf(skip_if) => {\n dest.push(PFacetAttr::SkipSerializingIf {\n expr: skip_if.expr.to_token_stream(),\n });\n }\n FacetInner::TypeTag(type_tag) => {\n dest.push(PFacetAttr::TypeTag {\n content: type_tag.expr.as_str().to_string(),\n });\n }\n }\n }\n }\n}\n\n/// Parsed attr\npub enum PAttr {\n /// A single line of doc comments\n /// `#[doc = \"Some doc\"], or `/// Some doc`, same thing\n Doc { line: String },\n\n /// A representation attribute\n Repr { repr: PRepr },\n\n /// A facet attribute\n Facet { name: String },\n}\n\n/// A parsed name, which includes the raw name and the\n/// effective name.\n///\n/// Examples:\n///\n/// raw = \"foo_bar\", no rename rule, effective = \"foo_bar\"\n/// raw = \"foo_bar\", #[facet(rename = \"kiki\")], effective = \"kiki\"\n/// raw = \"foo_bar\", #[facet(rename_all = camelCase)], effective = \"fooBar\"\n/// raw = \"r#type\", no rename rule, effective = \"type\"\n///\n#[derive(Clone)]\npub struct PName {\n /// The raw identifier, as we found it in the source code. It might\n /// be _actually_ raw, as in \"r#keyword\".\n pub raw: IdentOrLiteral,\n\n /// The name after applying rename rules, which might not be a valid identifier in Rust.\n /// It could be a number. It could be a kebab-case thing.\n pub effective: String,\n}\n\nimpl PName {\n /// Constructs a new `PName` with the given raw name, an optional container-level rename rule,\n /// an optional field-level rename rule, and a raw identifier.\n ///\n /// Precedence:\n /// - If field_rename_rule is Some, use it on raw for effective name\n /// - Else if container_rename_rule is Some, use it on raw for effective name\n /// - Else, strip raw (\"r#\" if present) for effective name\n pub fn new(container_rename_rule: Option, raw: IdentOrLiteral) -> Self {\n // Remove Rust's raw identifier prefix, e.g. r#type -> type\n let norm_raw_str = match &raw {\n IdentOrLiteral::Ident(ident) => ident\n .tokens_to_string()\n .trim_start_matches(\"r#\")\n .to_string(),\n IdentOrLiteral::Literal(l) => l.to_string(),\n };\n\n let effective = if let Some(container_rule) = container_rename_rule {\n container_rule.apply(&norm_raw_str)\n } else {\n norm_raw_str // Use the normalized string (without r#)\n };\n\n Self {\n raw: raw.clone(), // Keep the original raw identifier\n effective,\n }\n }\n}\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]\npub enum PRepr {\n Transparent,\n Rust(Option),\n C(Option),\n}\n\nimpl PRepr {\n /// Parse a `&str` (for example a value coming from #[repr(...)] attribute)\n /// into a `PRepr` variant.\n pub fn parse(s: &ReprInner) -> Option {\n enum ReprKind {\n Rust,\n C,\n }\n\n let items = s.attr.content.0.as_slice();\n let mut repr_kind: Option = None;\n let mut primitive_repr: Option = None;\n let mut is_transparent = false;\n\n for token_delimited in items {\n let token_str = token_delimited.value.to_string();\n match token_str.as_str() {\n \"C\" | \"c\" => {\n if repr_kind.is_some() && !matches!(repr_kind, Some(ReprKind::C)) {\n panic!(\n \"Conflicting repr kinds found in #[repr(...)]. Cannot mix C/c and Rust/rust.\"\n );\n }\n if is_transparent {\n panic!(\n \"Conflicting repr kinds found in #[repr(...)]. Cannot mix C/c and transparent.\"\n );\n }\n // If primitive is already set, and kind is not already C, ensure kind becomes C.\n // Example: #[repr(u8, C)] is valid.\n repr_kind = Some(ReprKind::C);\n }\n \"Rust\" | \"rust\" => {\n if repr_kind.is_some() && !matches!(repr_kind, Some(ReprKind::Rust)) {\n panic!(\n \"Conflicting repr kinds found in #[repr(...)]. Cannot mix Rust/rust and C/c.\"\n );\n }\n if is_transparent {\n panic!(\n \"Conflicting repr kinds found in #[repr(...)]. Cannot mix Rust/rust and transparent.\"\n );\n }\n // If primitive is already set, and kind is not already Rust, ensure kind becomes Rust.\n // Example: #[repr(i32, Rust)] is valid.\n repr_kind = Some(ReprKind::Rust);\n }\n \"transparent\" => {\n if repr_kind.is_some() || primitive_repr.is_some() {\n panic!(\n \"Conflicting repr kinds found in #[repr(...)]. Cannot mix transparent with C/c, Rust/rust, or primitive types.\"\n );\n }\n // Allow duplicate \"transparent\", although weird.\n is_transparent = true;\n }\n prim_str @ (\"u8\" | \"u16\" | \"u32\" | \"u64\" | \"u128\" | \"i8\" | \"i16\" | \"i32\"\n | \"i64\" | \"i128\" | \"usize\" | \"isize\") => {\n let current_prim = match prim_str {\n \"u8\" => PrimitiveRepr::U8,\n \"u16\" => PrimitiveRepr::U16,\n \"u32\" => PrimitiveRepr::U32,\n \"u64\" => PrimitiveRepr::U64,\n \"u128\" => PrimitiveRepr::U128,\n \"i8\" => PrimitiveRepr::I8,\n \"i16\" => PrimitiveRepr::I16,\n \"i32\" => PrimitiveRepr::I32,\n \"i64\" => PrimitiveRepr::I64,\n \"i128\" => PrimitiveRepr::I128,\n \"usize\" => PrimitiveRepr::Usize,\n \"isize\" => PrimitiveRepr::Isize,\n _ => unreachable!(), // Already matched by outer pattern\n };\n if is_transparent {\n panic!(\n \"Conflicting repr kinds found in #[repr(...)]. Cannot mix primitive types and transparent.\"\n );\n }\n if primitive_repr.is_some() {\n panic!(\"Multiple primitive types specified in #[repr(...)].\");\n }\n primitive_repr = Some(current_prim);\n }\n unknown => {\n // Standard #[repr] only allows specific identifiers.\n panic!(\n \"Unknown token '{unknown}' in #[repr(...)]. Only C, Rust, transparent, or primitive integer types allowed.\"\n );\n }\n }\n }\n\n // Final construction\n if is_transparent {\n if repr_kind.is_some() || primitive_repr.is_some() {\n // This check should be redundant due to checks inside the loop, but added for safety.\n panic!(\"Internal error: transparent repr mixed with other kinds after parsing.\");\n }\n Some(PRepr::Transparent)\n } else {\n // Default to Rust if only a primitive type is provided (e.g., #[repr(u8)]) or if nothing is specified.\n // If C/c or Rust/rust was specified, use that.\n let final_kind = repr_kind.unwrap_or(ReprKind::Rust);\n match final_kind {\n ReprKind::Rust => Some(PRepr::Rust(primitive_repr)),\n ReprKind::C => Some(PRepr::C(primitive_repr)),\n }\n }\n }\n}\n\n#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]\npub enum PrimitiveRepr {\n U8,\n U16,\n U32,\n U64,\n U128,\n I8,\n I16,\n I32,\n I64,\n I128,\n Isize,\n Usize,\n}\n\nimpl PrimitiveRepr {\n pub fn type_name(&self) -> TokenStream {\n match self {\n PrimitiveRepr::U8 => quote! { u8 },\n PrimitiveRepr::U16 => quote! { u16 },\n PrimitiveRepr::U32 => quote! { u32 },\n PrimitiveRepr::U64 => quote! { u64 },\n PrimitiveRepr::U128 => quote! { u128 },\n PrimitiveRepr::I8 => quote! { i8 },\n PrimitiveRepr::I16 => quote! { i16 },\n PrimitiveRepr::I32 => quote! { i32 },\n PrimitiveRepr::I64 => quote! { i64 },\n PrimitiveRepr::I128 => quote! { i128 },\n PrimitiveRepr::Isize => quote! { isize },\n PrimitiveRepr::Usize => quote! { usize },\n }\n }\n}\n\n/// Parsed attributes\n#[derive(Clone)]\npub struct PAttrs {\n /// An array of doc lines\n pub doc: Vec,\n\n /// Facet attributes specifically\n pub facet: Vec,\n\n /// Representation of the facet\n pub repr: PRepr,\n\n /// rename_all rule (if any)\n pub rename_all: Option,\n}\n\nimpl PAttrs {\n fn parse(attrs: &[facet_macros_parse::Attribute], display_name: &mut String) -> Self {\n let mut doc_lines: Vec = Vec::new();\n let mut facet_attrs: Vec = Vec::new();\n let mut repr: Option = None;\n let mut rename_all: Option = None;\n\n for attr in attrs {\n match &attr.body.content {\n facet_macros_parse::AttributeInner::Doc(doc_attr) => {\n // Handle doc comments\n doc_lines.push(doc_attr.value.as_str().replace(\"\\\\\\\"\", \"\\\"\"));\n }\n facet_macros_parse::AttributeInner::Repr(repr_attr) => {\n if repr.is_some() {\n panic!(\"Multiple #[repr] attributes found\");\n }\n\n // Parse repr attribute, e.g. #[repr(C)], #[repr(transparent)], #[repr(u8)]\n // repr_attr.attr.content is a Vec>>\n // which represents something like [\"C\"], or [\"u8\"], or [\"transparent\"]\n //\n // We should parse each possible repr kind. But usually there's only one item.\n //\n // We'll take the first one and parse it, ignoring the rest.\n repr = match PRepr::parse(repr_attr) {\n Some(parsed) => Some(parsed),\n None => {\n panic!(\n \"Unknown #[repr] attribute: {}\",\n repr_attr.tokens_to_string()\n );\n }\n };\n }\n facet_macros_parse::AttributeInner::Facet(facet_attr) => {\n PFacetAttr::parse(facet_attr, display_name, &mut facet_attrs);\n }\n _ => {\n // Ignore unknown AttributeInner types\n }\n }\n }\n\n for attr in &facet_attrs {\n if let PFacetAttr::RenameAll { rule } = attr {\n rename_all = Some(*rule);\n }\n }\n\n Self {\n doc: doc_lines,\n facet: facet_attrs,\n repr: repr.unwrap_or(PRepr::Rust(None)),\n rename_all,\n }\n }\n\n pub(crate) fn is_transparent(&self) -> bool {\n self.facet\n .iter()\n .any(|attr| matches!(attr, PFacetAttr::Transparent))\n }\n\n pub(crate) fn type_tag(&self) -> Option<&str> {\n for attr in &self.facet {\n if let PFacetAttr::TypeTag { content } = attr {\n return Some(content);\n }\n }\n None\n }\n}\n\n/// Parsed container\npub struct PContainer {\n /// Name of the container (could be a struct, an enum variant, etc.)\n pub name: Ident,\n\n /// Attributes of the container\n pub attrs: PAttrs,\n\n /// Generic parameters of the container\n pub bgp: BoundedGenericParams,\n}\n\n/// Parse struct\npub struct PStruct {\n /// Container information\n pub container: PContainer,\n\n /// Kind of struct\n pub kind: PStructKind,\n}\n\n/// Parsed enum (given attributes etc.)\npub struct PEnum {\n /// Container information\n pub container: PContainer,\n /// The variants of the enum, in parsed form\n pub variants: Vec,\n /// The representation (repr) for the enum (e.g., C, u8, etc.)\n pub repr: PRepr,\n}\n\nimpl PEnum {\n /// Parse a `facet_macros_parse::Enum` into a `PEnum`.\n pub fn parse(e: &facet_macros_parse::Enum) -> Self {\n let mut container_display_name = e.name.to_string();\n\n // Parse container-level attributes\n let attrs = PAttrs::parse(&e.attributes, &mut container_display_name);\n\n // Get the container-level rename_all rule\n let container_rename_all_rule = attrs.rename_all;\n\n // Build PContainer\n let container = PContainer {\n name: e.name.clone(),\n attrs,\n bgp: BoundedGenericParams::parse(e.generics.as_ref()),\n };\n\n // Parse variants, passing the container's rename_all rule\n let variants = e\n .body\n .content\n .0\n .iter()\n .map(|delim| PVariant::parse(&delim.value, container_rename_all_rule))\n .collect();\n\n // Get the repr attribute if present, or default to Rust(None)\n let mut repr = None;\n for attr in &e.attributes {\n if let facet_macros_parse::AttributeInner::Repr(repr_attr) = &attr.body.content {\n // Parse repr attribute, will panic if invalid, just like struct repr parser\n repr = match PRepr::parse(repr_attr) {\n Some(parsed) => Some(parsed),\n None => panic!(\n \"Unknown #[repr] attribute: {}\",\n repr_attr.tokens_to_string()\n ),\n };\n break; // Only use the first #[repr] attribute\n }\n }\n // Default to Rust(None) if not present, to match previous behavior, but enums will typically require repr(C) or a primitive in process_enum\n let repr = repr.unwrap_or(PRepr::Rust(None));\n\n PEnum {\n container,\n variants,\n repr,\n }\n }\n}\n\n/// Parsed field\n#[derive(Clone)]\npub struct PStructField {\n /// The field's name (with rename rules applied)\n pub name: PName,\n\n /// The field's type\n pub ty: TokenStream,\n\n /// The field's offset (can be an expression, like `offset_of!(self, field)`)\n pub offset: TokenStream,\n\n /// The field's attributes\n pub attrs: PAttrs,\n}\n\nimpl PStructField {\n /// Parse a named struct field (usual struct).\n pub(crate) fn from_struct_field(\n f: &facet_macros_parse::StructField,\n rename_all_rule: Option,\n ) -> Self {\n use facet_macros_parse::ToTokens;\n Self::parse(\n &f.attributes,\n IdentOrLiteral::Ident(f.name.clone()),\n f.typ.to_token_stream(),\n rename_all_rule,\n )\n }\n\n /// Parse a tuple (unnamed) field for tuple structs or enum tuple variants.\n /// The index is converted to an identifier like `_0`, `_1`, etc.\n pub(crate) fn from_enum_field(\n attrs: &[facet_macros_parse::Attribute],\n idx: usize,\n typ: &facet_macros_parse::VerbatimUntil,\n rename_all_rule: Option,\n ) -> Self {\n use facet_macros_parse::ToTokens;\n // Create an Ident from the index, using `_` prefix convention for tuple fields\n let ty = typ.to_token_stream(); // Convert to TokenStream\n Self::parse(attrs, IdentOrLiteral::Literal(idx), ty, rename_all_rule)\n }\n\n /// Central parse function used by both `from_struct_field` and `from_enum_field`.\n fn parse(\n attrs: &[facet_macros_parse::Attribute],\n name: IdentOrLiteral,\n ty: TokenStream,\n rename_all_rule: Option,\n ) -> Self {\n let initial_display_name = quote::ToTokens::to_token_stream(&name).tokens_to_string();\n let mut display_name = initial_display_name.clone();\n\n // Parse attributes for the field\n let attrs = PAttrs::parse(attrs, &mut display_name);\n\n // Name resolution:\n // Precedence:\n // 1. Field-level #[facet(rename = \"...\")]\n // 2. rename_all_rule argument (container-level rename_all, passed in)\n // 3. Raw field name (after stripping \"r#\")\n let raw = name.clone();\n\n let p_name = if display_name != initial_display_name {\n // If #[facet(rename = \"...\")] is present, use it directly as the effective name.\n // Preserve the span of the original identifier.\n PName {\n raw: raw.clone(),\n effective: display_name,\n }\n } else {\n // Use PName::new logic with container_rename_rule as the rename_all_rule argument.\n // PName::new handles the case where rename_all_rule is None.\n PName::new(rename_all_rule, raw)\n };\n\n // Field type as TokenStream (already provided as argument)\n let ty = ty.clone();\n\n // Offset string -- we don't know the offset here in generic parsing, so just default to empty\n let offset = quote! {};\n\n PStructField {\n name: p_name,\n ty,\n offset,\n attrs,\n }\n }\n}\n/// Parsed struct kind, modeled after `StructKind`.\npub enum PStructKind {\n /// A regular struct with named fields.\n Struct { fields: Vec },\n /// A tuple struct.\n TupleStruct { fields: Vec },\n /// A unit struct.\n UnitStruct,\n}\n\nimpl PStructKind {\n /// Parse a `facet_macros_parse::StructKind` into a `PStructKind`.\n /// Passes rename_all_rule through to all PStructField parsing.\n pub fn parse(\n kind: &facet_macros_parse::StructKind,\n rename_all_rule: Option,\n ) -> Self {\n match kind {\n facet_macros_parse::StructKind::Struct { clauses: _, fields } => {\n let parsed_fields = fields\n .content\n .0\n .iter()\n .map(|delim| PStructField::from_struct_field(&delim.value, rename_all_rule))\n .collect();\n PStructKind::Struct {\n fields: parsed_fields,\n }\n }\n facet_macros_parse::StructKind::TupleStruct {\n fields,\n clauses: _,\n semi: _,\n } => {\n let parsed_fields = fields\n .content\n .0\n .iter()\n .enumerate()\n .map(|(idx, delim)| {\n PStructField::from_enum_field(\n &delim.value.attributes,\n idx,\n &delim.value.typ,\n rename_all_rule,\n )\n })\n .collect();\n PStructKind::TupleStruct {\n fields: parsed_fields,\n }\n }\n facet_macros_parse::StructKind::UnitStruct {\n clauses: _,\n semi: _,\n } => PStructKind::UnitStruct,\n }\n }\n}\n\nimpl PStruct {\n pub fn parse(s: &facet_macros_parse::Struct) -> Self {\n // Create a mutable string to pass to PAttrs::parse.\n // While #[facet(rename = \"...\")] isn't typically used directly on the struct\n // definition itself in the same way as fields, the parse function expects\n // a mutable string to potentially modify if such an attribute is found.\n // We initialize it with the struct's name, although its value isn't\n // directly used for the container's name after parsing attributes.\n let mut container_display_name = s.name.to_string();\n\n // Parse top-level (container) attributes for the struct.\n let attrs = PAttrs::parse(&s.attributes, &mut container_display_name);\n\n // Extract the rename_all rule *after* parsing all attributes.\n let rename_all_rule = attrs.rename_all;\n\n // Build PContainer from struct's name and attributes.\n let container = PContainer {\n name: s.name.clone(),\n attrs, // Use the parsed attributes (which includes rename_all implicitly)\n bgp: BoundedGenericParams::parse(s.generics.as_ref()),\n };\n\n // Pass the container's rename_all rule (extracted above) as argument to PStructKind::parse\n let kind = PStructKind::parse(&s.kind, rename_all_rule);\n\n PStruct { container, kind }\n }\n}\n\n/// Parsed enum variant kind\npub enum PVariantKind {\n /// Unit variant, e.g., `Variant`.\n Unit,\n /// Tuple variant, e.g., `Variant(u32, String)`.\n Tuple { fields: Vec },\n /// Struct variant, e.g., `Variant { field1: u32, field2: String }`.\n Struct { fields: Vec },\n}\n\n/// Parsed enum variant\npub struct PVariant {\n /// Name of the variant (with rename rules applied)\n pub name: PName,\n /// Attributes of the variant\n pub attrs: PAttrs,\n /// Kind of the variant (unit, tuple, or struct)\n pub kind: PVariantKind,\n /// Optional explicit discriminant (`= literal`)\n pub discriminant: Option,\n}\n\nimpl PVariant {\n /// Parses an `EnumVariantLike` from `facet_macros_parse` into a `PVariant`.\n ///\n /// Requires the container-level `rename_all` rule to correctly determine the\n /// effective name of the variant itself. The variant's own `rename_all` rule\n /// (if present) will be stored in `attrs.rename_all` and used for its fields.\n fn parse(\n var_like: &facet_macros_parse::EnumVariantLike,\n container_rename_all_rule: Option,\n ) -> Self {\n use facet_macros_parse::{EnumVariantData, StructEnumVariant, TupleVariant, UnitVariant};\n\n let (raw_name_ident, attributes) = match &var_like.variant {\n // Fix: Changed var_like.value.variant to var_like.variant\n EnumVariantData::Unit(UnitVariant { name, attributes })\n | EnumVariantData::Tuple(TupleVariant {\n name, attributes, ..\n })\n | EnumVariantData::Struct(StructEnumVariant {\n name, attributes, ..\n }) => (name, attributes),\n };\n\n let initial_display_name = raw_name_ident.to_string();\n let mut display_name = initial_display_name.clone();\n\n // Parse variant attributes, potentially modifying display_name if #[facet(rename=...)] is found\n let attrs = PAttrs::parse(attributes.as_slice(), &mut display_name); // Fix: Pass attributes as a slice\n\n // Determine the variant's effective name\n let name = if display_name != initial_display_name {\n // #[facet(rename=...)] was present on the variant\n PName {\n raw: IdentOrLiteral::Ident(raw_name_ident.clone()),\n effective: display_name,\n }\n } else {\n // Use container's rename_all rule if no variant-specific rename found\n PName::new(\n container_rename_all_rule,\n IdentOrLiteral::Ident(raw_name_ident.clone()),\n )\n };\n\n // Extract the variant's own rename_all rule to apply to its fields\n let variant_field_rename_rule = attrs.rename_all;\n\n // Parse the variant kind and its fields\n let kind = match &var_like.variant {\n // Fix: Changed var_like.value.variant to var_like.variant\n EnumVariantData::Unit(_) => PVariantKind::Unit,\n EnumVariantData::Tuple(TupleVariant { fields, .. }) => {\n let parsed_fields = fields\n .content\n .0\n .iter()\n .enumerate()\n .map(|(idx, delim)| {\n PStructField::from_enum_field(\n &delim.value.attributes,\n idx,\n &delim.value.typ,\n variant_field_rename_rule, // Use variant's rule for its fields\n )\n })\n .collect();\n PVariantKind::Tuple {\n fields: parsed_fields,\n }\n }\n EnumVariantData::Struct(StructEnumVariant { fields, .. }) => {\n let parsed_fields = fields\n .content\n .0\n .iter()\n .map(|delim| {\n PStructField::from_struct_field(\n &delim.value,\n variant_field_rename_rule, // Use variant's rule for its fields\n )\n })\n .collect();\n PVariantKind::Struct {\n fields: parsed_fields,\n }\n }\n };\n\n // Extract the discriminant literal if present\n let discriminant = var_like\n .discriminant\n .as_ref()\n .map(|d| d.second.to_token_stream());\n\n PVariant {\n name,\n attrs,\n kind,\n discriminant,\n }\n }\n}\n"], ["/facet/facet-macros-emit/src/generics.rs", "use facet_macros_parse::{GenericParam, GenericParams, ToTokens, TokenStream};\nuse quote::quote;\n\nuse crate::LifetimeName;\n\n/// The name of a generic parameter\n#[derive(Clone)]\npub enum GenericParamName {\n /// \"a\" but formatted as \"'a\"\n Lifetime(LifetimeName),\n\n /// \"T\", formatted as \"T\"\n Type(TokenStream),\n\n /// \"N\", formatted as \"N\"\n Const(TokenStream),\n}\n\n/// The name of a generic parameter with bounds\n#[derive(Clone)]\npub struct BoundedGenericParam {\n /// the parameter name\n pub param: GenericParamName,\n\n /// bounds like `'static`, or `Send + Sync`, etc. — None if no bounds\n pub bounds: Option,\n}\n\n/// Stores different representations of generic parameters for implementing traits.\n///\n/// This structure separates generic parameters into different formats needed when\n/// generating trait implementations.\n#[derive(Clone)]\npub struct BoundedGenericParams {\n /// Collection of generic parameters with their bounds\n pub params: Vec,\n}\n\n/// Display wrapper that shows generic parameters with their bounds\n///\n/// This is used to format generic parameters for display purposes,\n/// including both the parameter names and their bounds (if any).\n///\n/// # Example\n///\n/// For a parameter like `T: Clone`, this will display ``.\npub struct WithBounds<'a>(&'a BoundedGenericParams);\n\n/// Display wrapper that shows generic parameters without their bounds\n///\n/// This is used to format just the parameter names for display purposes,\n/// omitting any bounds information.\n///\n/// # Example\n///\n/// For a parameter like `T: Clone`, this will display just ``.\npub struct WithoutBounds<'a>(&'a BoundedGenericParams);\n\n/// Display wrapper that outputs generic parameters as a PhantomData\n///\n/// This is used to format generic parameters as a PhantomData type\n/// for use in trait implementations.\n///\n/// # Example\n///\n/// For parameters `<'a, T, const N: usize>`, this will display\n/// `::core::marker::PhantomData<(*mut &'__facet (), T, [u32; N])>`.\npub struct AsPhantomData<'a>(&'a BoundedGenericParams);\n\nimpl quote::ToTokens for AsPhantomData<'_> {\n fn to_tokens(&self, tokens: &mut TokenStream) {\n let mut temp = TokenStream::new();\n\n {\n #[expect(unused)]\n let tokens = ();\n\n // Track if we've written anything to handle commas correctly\n let mut first_param = true;\n\n // Generate all parameters in the tuple\n for param in &self.0.params {\n if !first_param {\n temp.extend(quote! { , });\n }\n\n match ¶m.param {\n GenericParamName::Lifetime(name) => {\n temp.extend(quote! { *mut &#name () });\n }\n GenericParamName::Type(name) => {\n temp.extend(quote! { #name });\n }\n GenericParamName::Const(name) => {\n temp.extend(quote! { [u32; #name] });\n }\n }\n\n first_param = false;\n }\n\n // If no parameters at all, add a unit type to make the PhantomData valid\n if first_param {\n temp.extend(quote! { () });\n }\n }\n tokens.extend(quote! {\n ::core::marker::PhantomData<(#temp)>\n })\n }\n}\n\nimpl BoundedGenericParams {\n pub fn as_phantom_data(&self) -> AsPhantomData<'_> {\n AsPhantomData(self)\n }\n}\n\nimpl quote::ToTokens for WithBounds<'_> {\n fn to_tokens(&self, tokens: &mut TokenStream) {\n if self.0.params.is_empty() {\n return;\n }\n\n tokens.extend(quote! {\n <\n });\n\n for (i, param) in self.0.params.iter().enumerate() {\n if i > 0 {\n tokens.extend(quote! { , });\n }\n\n match ¶m.param {\n GenericParamName::Lifetime(name) => {\n tokens.extend(quote! { #name });\n }\n GenericParamName::Type(name) => {\n tokens.extend(quote! { #name });\n }\n GenericParamName::Const(name) => {\n tokens.extend(quote! { const #name });\n }\n }\n\n // Add bounds if they exist\n if let Some(bounds) = ¶m.bounds {\n tokens.extend(quote! { : #bounds });\n }\n }\n\n tokens.extend(quote! {\n >\n });\n }\n}\n\nimpl quote::ToTokens for WithoutBounds<'_> {\n fn to_tokens(&self, tokens: &mut TokenStream) {\n if self.0.params.is_empty() {\n return;\n }\n\n tokens.extend(quote! {\n <\n });\n\n for (i, param) in self.0.params.iter().enumerate() {\n if i > 0 {\n tokens.extend(quote! { , });\n }\n\n match ¶m.param {\n GenericParamName::Lifetime(name) => {\n tokens.extend(quote! { #name });\n }\n GenericParamName::Type(name) => {\n tokens.extend(quote! { #name });\n }\n GenericParamName::Const(name) => {\n tokens.extend(quote! { #name });\n }\n }\n }\n\n tokens.extend(quote! {\n >\n });\n }\n}\n\nimpl BoundedGenericParams {\n pub fn display_with_bounds(&self) -> WithBounds<'_> {\n WithBounds(self)\n }\n\n pub fn display_without_bounds(&self) -> WithoutBounds<'_> {\n WithoutBounds(self)\n }\n\n /// Returns a display wrapper that formats generic parameters as a PhantomData\n ///\n /// This is a convenience method for generating PhantomData expressions\n /// for use in trait implementations.\n ///\n /// # Example\n ///\n /// For generic parameters `<'a, T, const N: usize>`, this returns a wrapper that\n /// when displayed produces:\n /// `::core::marker::PhantomData<(*mut &'a (), T, [u32; N])>`\n pub fn display_as_phantom_data(&self) -> AsPhantomData<'_> {\n AsPhantomData(self)\n }\n\n pub fn with(&self, param: BoundedGenericParam) -> Self {\n let mut params = self.params.clone();\n\n match ¶m.param {\n GenericParamName::Lifetime(_) => {\n // Find the position after the last lifetime parameter\n let insert_position = params\n .iter()\n .position(|p| !matches!(p.param, GenericParamName::Lifetime(_)))\n .unwrap_or(params.len());\n\n params.insert(insert_position, param);\n }\n GenericParamName::Type(_) => {\n // Find the position after the last type parameter but before any const parameters\n let after_lifetimes = params\n .iter()\n .position(|p| !matches!(p.param, GenericParamName::Lifetime(_)))\n .unwrap_or(params.len());\n\n let insert_position = params[after_lifetimes..]\n .iter()\n .position(|p| matches!(p.param, GenericParamName::Const(_)))\n .map(|pos| pos + after_lifetimes)\n .unwrap_or(params.len());\n\n params.insert(insert_position, param);\n }\n GenericParamName::Const(_) => {\n // Constants go at the end\n params.push(param);\n }\n }\n\n Self { params }\n }\n\n /// Adds a new lifetime parameter with the given name without bounds\n ///\n /// This is a convenience method for adding a lifetime parameter\n /// that's commonly used in trait implementations.\n pub fn with_lifetime(&self, name: LifetimeName) -> Self {\n self.with(BoundedGenericParam {\n param: GenericParamName::Lifetime(name),\n bounds: None,\n })\n }\n\n /// Adds a new type parameter with the given name without bounds\n ///\n /// This is a convenience method for adding a type parameter\n /// that's commonly used in trait implementations.\n pub fn with_type(&self, name: TokenStream) -> Self {\n self.with(BoundedGenericParam {\n param: GenericParamName::Type(name),\n bounds: None,\n })\n }\n}\n\nimpl BoundedGenericParams {\n /// Parses generic parameters into separate components for implementing traits.\n ///\n /// This method takes a generic parameter declaration and populates the BoundedGenericParams struct\n /// with different representations of the generic parameters needed for code generation.\n ///\n /// # Examples\n ///\n /// For a type like `struct Example`, this would populate:\n /// params with entries for each parameter and their bounds.\n pub fn parse(generics: Option<&GenericParams>) -> Self {\n let Some(generics) = generics else {\n return Self { params: Vec::new() };\n };\n\n let mut params = Vec::new();\n\n for param in generics.params.0.iter() {\n match ¶m.value {\n GenericParam::Type {\n name,\n bounds,\n default: _,\n } => {\n params.push(BoundedGenericParam {\n param: GenericParamName::Type(name.to_token_stream()),\n bounds: bounds\n .as_ref()\n .map(|bounds| bounds.second.to_token_stream()),\n });\n }\n GenericParam::Lifetime { name, bounds } => {\n params.push(BoundedGenericParam {\n param: GenericParamName::Lifetime(LifetimeName(name.name.clone())),\n bounds: bounds\n .as_ref()\n .map(|bounds| bounds.second.to_token_stream()),\n });\n }\n GenericParam::Const {\n _const: _,\n name,\n _colon: _,\n typ,\n default: _,\n } => {\n params.push(BoundedGenericParam {\n param: GenericParamName::Const(name.to_token_stream()),\n bounds: Some(typ.to_token_stream()),\n });\n }\n }\n }\n\n Self { params }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::{BoundedGenericParam, BoundedGenericParams, GenericParamName};\n use crate::LifetimeName;\n use quote::{ToTokens as _, quote};\n\n // Helper to render ToTokens implementors to string for comparison\n fn render_to_string(t: T) -> String {\n quote!(#t).to_string()\n }\n\n #[test]\n fn test_empty_generic_params() {\n let p = BoundedGenericParams { params: vec![] };\n assert_eq!(render_to_string(p.display_with_bounds()), \"\");\n assert_eq!(render_to_string(p.display_without_bounds()), \"\");\n }\n\n #[test]\n fn print_multiple_generic_params() {\n let p = BoundedGenericParams {\n params: vec![\n BoundedGenericParam {\n bounds: Some(quote! { 'static }),\n param: GenericParamName::Lifetime(LifetimeName(quote::format_ident!(\"a\"))),\n },\n BoundedGenericParam {\n bounds: Some(quote! { Clone + Debug }),\n param: GenericParamName::Type(quote! { T }),\n },\n BoundedGenericParam {\n bounds: None,\n param: GenericParamName::Type(quote! { U }),\n },\n BoundedGenericParam {\n bounds: Some(quote! { usize }), // Const params bounds are types\n param: GenericParamName::Const(quote! { N }),\n },\n ],\n };\n // Check display with bounds\n let expected_with_bounds = quote! { <'a : 'static, T : Clone + Debug, U, const N : usize> };\n assert_eq!(\n p.display_with_bounds().to_token_stream().to_string(),\n expected_with_bounds.to_string()\n );\n\n // Check display without bounds\n let expected_without_bounds = quote! { <'a, T, U, N> }; // Note: const param N doesn't show `const` or type here\n assert_eq!(\n p.display_without_bounds().to_token_stream().to_string(),\n expected_without_bounds.to_string()\n );\n }\n\n #[test]\n fn test_add_mixed_parameters() {\n // Create a complex example with all parameter types\n let mut params = BoundedGenericParams { params: vec![] };\n\n // Add parameters in different order to test sorting\n params = params.with(BoundedGenericParam {\n bounds: None,\n param: GenericParamName::Type(quote! { T }),\n });\n\n params = params.with(BoundedGenericParam {\n bounds: Some(quote! { usize }), // Const bounds are types\n param: GenericParamName::Const(quote! { N }),\n });\n\n params = params.with(BoundedGenericParam {\n bounds: None,\n param: GenericParamName::Lifetime(LifetimeName(quote::format_ident!(\"a\"))),\n });\n\n params = params.with(BoundedGenericParam {\n bounds: Some(quote! { Clone }),\n param: GenericParamName::Type(quote! { U }),\n });\n\n params = params.with(BoundedGenericParam {\n bounds: Some(quote! { 'static }),\n param: GenericParamName::Lifetime(LifetimeName(quote::format_ident!(\"b\"))),\n });\n\n params = params.with(BoundedGenericParam {\n bounds: Some(quote! { u8 }), // Const bounds are types\n param: GenericParamName::Const(quote! { M }),\n });\n\n // Expected order: lifetimes first, then types, then consts\n let expected_without_bounds = quote! { <'a, 'b, T, U, N, M> };\n // Compare string representations for robust assertion\n assert_eq!(\n params\n .display_without_bounds()\n .to_token_stream()\n .to_string(),\n expected_without_bounds.to_string()\n );\n\n let expected_with_bounds =\n quote! { <'a, 'b : 'static, T, U : Clone, const N : usize, const M : u8> };\n // Compare string representations for robust assertion\n assert_eq!(\n params.display_with_bounds().to_token_stream().to_string(),\n expected_with_bounds.to_string()\n );\n }\n\n #[test]\n fn test_phantom_data_formatting() {\n // Empty params should have PhantomData with a unit type\n let empty = BoundedGenericParams { params: vec![] };\n assert_eq!(\n render_to_string(empty.display_as_phantom_data()),\n \":: core :: marker :: PhantomData < (()) >\"\n );\n\n // Single lifetime\n let lifetime = BoundedGenericParams {\n params: vec![BoundedGenericParam {\n param: GenericParamName::Lifetime(LifetimeName(quote::format_ident!(\"a\"))),\n bounds: None,\n }],\n };\n assert_eq!(\n render_to_string(lifetime.display_as_phantom_data()),\n \":: core :: marker :: PhantomData < (* mut & 'a ()) >\"\n );\n\n // Single type\n let type_param = BoundedGenericParams {\n params: vec![BoundedGenericParam {\n param: GenericParamName::Type(quote! { T }),\n bounds: None,\n }],\n };\n assert_eq!(\n render_to_string(type_param.display_as_phantom_data()),\n \":: core :: marker :: PhantomData < (T) >\"\n );\n\n // Single const\n let const_param = BoundedGenericParams {\n params: vec![BoundedGenericParam {\n param: GenericParamName::Const(quote! { N }),\n bounds: None, // Bounds are irrelevant for PhantomData formatting\n }],\n };\n assert_eq!(\n render_to_string(const_param.display_as_phantom_data()),\n \":: core :: marker :: PhantomData < ([u32 ; N]) >\"\n );\n\n // Complex mix of params\n let mixed = BoundedGenericParams {\n params: vec![\n BoundedGenericParam {\n param: GenericParamName::Lifetime(LifetimeName(quote::format_ident!(\"a\"))),\n bounds: None,\n },\n BoundedGenericParam {\n param: GenericParamName::Type(quote! { T }),\n bounds: Some(quote! { Clone }), // Bounds irrelevant here\n },\n BoundedGenericParam {\n param: GenericParamName::Const(quote! { N }),\n bounds: Some(quote! { usize }), // Bounds irrelevant here\n },\n ],\n };\n let actual_tokens = mixed.display_as_phantom_data();\n let expected_tokens = quote! {\n ::core::marker::PhantomData<(*mut &'a (), T, [u32; N])>\n };\n assert_eq!(\n actual_tokens.to_token_stream().to_string(),\n expected_tokens.to_string()\n );\n }\n}\n"], ["/facet/facet-macros-emit/src/derive.rs", "use facet_macros_parse::{ToTokens, *};\nuse quote::{TokenStreamExt as _, quote};\n\nuse crate::{LifetimeName, RenameRule, process_enum, process_struct};\n\npub fn facet_macros(input: TokenStream) -> TokenStream {\n let mut i = input.to_token_iter();\n\n // Parse as TypeDecl\n match i.parse::>() {\n Ok(it) => match it.first {\n AdtDecl::Struct(parsed) => process_struct::process_struct(parsed),\n AdtDecl::Enum(parsed) => process_enum::process_enum(parsed),\n },\n Err(err) => {\n panic!(\"Could not parse type declaration: {input}\\nError: {err}\");\n }\n }\n}\n\n/// Generate a static declaration that exports the crate\npub(crate) fn generate_static_decl(type_name: &Ident) -> TokenStream {\n let type_name_str = type_name.to_string();\n let screaming_snake_name = RenameRule::ScreamingSnakeCase.apply(&type_name_str);\n\n let static_name_ident = quote::format_ident!(\"{}_SHAPE\", screaming_snake_name);\n\n quote! {\n static #static_name_ident: &'static ::facet::Shape = <#type_name as ::facet::Facet>::SHAPE;\n }\n}\n\npub(crate) fn build_where_clauses(\n where_clauses: Option<&WhereClauses>,\n generics: Option<&GenericParams>,\n) -> TokenStream {\n let mut where_clause_tokens = TokenStream::new();\n let mut has_clauses = false;\n\n if let Some(wc) = where_clauses {\n for c in &wc.clauses.0 {\n if has_clauses {\n where_clause_tokens.extend(quote! { , });\n }\n where_clause_tokens.extend(c.value.to_token_stream());\n has_clauses = true;\n }\n }\n\n if let Some(generics) = generics {\n for p in &generics.params.0 {\n match &p.value {\n GenericParam::Lifetime { name, .. } => {\n let facet_lifetime = LifetimeName(quote::format_ident!(\"{}\", \"__facet\"));\n let lifetime = LifetimeName(name.name.clone());\n if has_clauses {\n where_clause_tokens.extend(quote! { , });\n }\n where_clause_tokens\n .extend(quote! { #lifetime: #facet_lifetime, #facet_lifetime: #lifetime });\n\n has_clauses = true;\n }\n GenericParam::Const { .. } => {\n // ignore for now\n }\n GenericParam::Type { name, .. } => {\n if has_clauses {\n where_clause_tokens.extend(quote! { , });\n }\n where_clause_tokens.extend(quote! { #name: ::facet::Facet<'__facet> });\n has_clauses = true;\n }\n }\n }\n }\n\n if !has_clauses {\n quote! {}\n } else {\n quote! { where #where_clause_tokens }\n }\n}\n\npub(crate) fn build_type_params(generics: Option<&GenericParams>) -> TokenStream {\n let mut type_params = Vec::new();\n if let Some(generics) = generics {\n for p in &generics.params.0 {\n match &p.value {\n GenericParam::Lifetime { .. } => {\n // ignore for now\n }\n GenericParam::Const { .. } => {\n // ignore for now\n }\n GenericParam::Type { name, .. } => {\n let name_str = name.to_string();\n type_params.push(quote! {\n ::facet::TypeParam {\n name: #name_str,\n shape: || <#name as ::facet::Facet>::SHAPE\n }\n });\n }\n }\n }\n }\n\n if type_params.is_empty() {\n quote! {}\n } else {\n quote! { .type_params(&[#(#type_params),*]) }\n }\n}\n\n/// Generate the `type_name` function for the `ValueVTable`,\n/// displaying realized generics if present.\npub(crate) fn generate_type_name_fn(\n type_name: &Ident,\n generics: Option<&GenericParams>,\n) -> TokenStream {\n let type_name_str = type_name.to_string();\n\n let write_generics = generics.and_then(|generics| {\n let params = generics.params.0.iter();\n let write_each = params.filter_map(|param| match ¶m.value {\n // Lifetimes not shown by `std::any::type_name`, this is parity.\n GenericParam::Lifetime { .. } => None,\n GenericParam::Const { name, .. } => Some(quote! {\n write!(f, \"{:?}\", #name)?;\n }),\n GenericParam::Type { name, .. } => Some(quote! {\n <#name as ::facet::Facet>::SHAPE.vtable.type_name()(f, opts)?;\n }),\n });\n // TODO: is there a way to construct a DelimitedVec from an iterator?\n let mut tokens = TokenStream::new();\n tokens.append_separated(write_each, quote! { write!(f, \", \")?; });\n if tokens.is_empty() {\n None\n } else {\n Some(tokens)\n }\n });\n\n if let Some(write_generics) = write_generics {\n quote! {\n |f, opts| {\n write!(f, #type_name_str)?;\n if let Some(opts) = opts.for_children() {\n write!(f, \"<\")?;\n #write_generics\n write!(f, \">\")?;\n } else {\n write!(f, \"<…>\")?;\n }\n Ok(())\n }\n }\n } else {\n quote! {\n |f, _opts| ::core::fmt::Write::write_str(f, #type_name_str)\n }\n }\n}\n"], ["/facet/facet-macros-emit/src/process_enum.rs", "use super::*;\n// Import PRepr, PrimitiveRepr, PStructField, etc. from parsed module\nuse crate::{\n parsed::{IdentOrLiteral, PFacetAttr, PRepr, PVariantKind, PrimitiveRepr},\n process_struct::gen_field_from_pfield,\n};\nuse quote::{format_ident, quote};\n\n/// Processes an enum to implement Facet\npub(crate) fn process_enum(parsed: Enum) -> TokenStream {\n // Use already-parsed PEnum, including container/variant/field attributes and rename rules\n let pe = PEnum::parse(&parsed);\n\n let enum_name = &pe.container.name;\n let enum_name_str = enum_name.to_string();\n\n let type_name_fn = generate_type_name_fn(enum_name, parsed.generics.as_ref());\n\n let bgp = pe.container.bgp.clone();\n // Use the AST directly for where clauses and generics, as PContainer/PEnum doesn't store them\n let where_clauses_tokens =\n build_where_clauses(parsed.clauses.as_ref(), parsed.generics.as_ref());\n let type_params = build_type_params(parsed.generics.as_ref());\n\n // Container-level docs from PAttrs\n let maybe_container_doc = match &pe.container.attrs.doc[..] {\n [] => quote! {},\n doc_lines => quote! { .doc(&[#(#doc_lines),*]) },\n };\n\n let container_attributes_tokens = {\n let mut attribute_tokens: Vec = Vec::new();\n for attr in &pe.container.attrs.facet {\n match attr {\n PFacetAttr::DenyUnknownFields => {\n attribute_tokens.push(quote! { ::facet::ShapeAttribute::DenyUnknownFields });\n }\n PFacetAttr::Arbitrary { content } => {\n attribute_tokens.push(quote! { ::facet::ShapeAttribute::Arbitrary(#content) });\n }\n PFacetAttr::RenameAll { rule } => {\n // RenameAll is handled by PName logic, but add it as ShapeAttribute too\n let rule_str = rule.apply(\"\"); // Hack to get str - improve RenameRule display\n attribute_tokens.push(quote! { ::facet::ShapeAttribute::RenameAll(#rule_str) });\n }\n PFacetAttr::Invariants { .. } => {\n // Note: Facet vtable does not currently support invariants directly on enums\n // Maybe panic or warn here? For now, ignoring.\n panic!(\"Invariants are not supported on enums\")\n }\n // Opaque, Transparent, SkipSerializing/If, Default/Equals are not relevant/valid for enum containers.\n _ => {}\n }\n }\n\n if attribute_tokens.is_empty() {\n quote! {}\n } else {\n quote! { .attributes(&const { [#(#attribute_tokens),*] }) }\n }\n };\n\n let type_tag_maybe = {\n if let Some(type_tag) = pe.container.attrs.type_tag() {\n quote! { .type_tag(#type_tag) }\n } else {\n quote! {}\n }\n };\n\n // Determine enum repr (already resolved by PEnum::parse())\n let valid_repr = &pe.repr;\n\n // Are these relevant for enums? Or is it always `repr(C)` if a `PrimitiveRepr` is present?\n let repr = match &valid_repr {\n PRepr::Transparent => unreachable!(\"this should be caught by PRepr::parse\"),\n PRepr::Rust(_) => quote! { ::facet::Repr::default() },\n PRepr::C(_) => quote! { ::facet::Repr::c() },\n };\n\n // Helper for EnumRepr TS (token stream) generation for primitives\n fn enum_repr_ts_from_primitive(primitive_repr: PrimitiveRepr) -> TokenStream {\n let type_name_str = primitive_repr.type_name().to_string();\n let enum_repr_variant_ident = format_ident!(\"{}\", type_name_str.to_uppercase());\n quote! { ::facet::EnumRepr::#enum_repr_variant_ident }\n }\n\n // --- Processing code for shadow struct/fields/variant_expressions ---\n // A. C-style enums have shadow-discriminant, shadow-union, shadow-struct\n // B. Primitive enums have simpler layout.\n let (shadow_struct_defs, variant_expressions, enum_repr_type_tokenstream) = match valid_repr {\n PRepr::C(prim_opt) => {\n // Shadow discriminant\n let shadow_discriminant_name =\n quote::format_ident!(\"__Shadow_CRepr_Discriminant_for_{}\", enum_name_str);\n let all_variant_names: Vec = pe\n .variants\n .iter()\n .map(|pv| match &pv.name.raw {\n IdentOrLiteral::Ident(id) => id.clone(),\n IdentOrLiteral::Literal(n) => format_ident!(\"_{}\", n), // Should not happen for enums\n })\n .collect();\n\n let repr_attr_content = match prim_opt {\n Some(p) => p.type_name(),\n None => quote! { C },\n };\n let mut shadow_defs = vec![quote! {\n #[repr(#repr_attr_content)]\n #[allow(dead_code)]\n enum #shadow_discriminant_name { #(#all_variant_names),* }\n }];\n\n // Shadow union\n let shadow_union_name =\n quote::format_ident!(\"__Shadow_CRepr_Fields_Union_for_{}\", enum_name_str);\n let facet_bgp = bgp.with_lifetime(LifetimeName(format_ident!(\"__facet\")));\n let bgp_with_bounds = facet_bgp.display_with_bounds();\n let bgp_without_bounds = facet_bgp.display_without_bounds();\n let phantom_data = facet_bgp.display_as_phantom_data();\n let all_union_fields: Vec = pe.variants.iter().map(|pv| {\n // Each field is named after the variant, struct for its fields.\n let variant_ident = match &pv.name.raw {\n IdentOrLiteral::Ident(id) => id.clone(),\n IdentOrLiteral::Literal(idx) => format_ident!(\"_{}\", idx), // Should not happen\n };\n let shadow_field_name_ident = quote::format_ident!(\"__Shadow_CRepr_Field{}_{}\", enum_name_str, variant_ident);\n quote! {\n #variant_ident: ::core::mem::ManuallyDrop<#shadow_field_name_ident #bgp_without_bounds>\n }\n }).collect();\n\n shadow_defs.push(quote! {\n #[repr(C)]\n #[allow(non_snake_case, dead_code)]\n union #shadow_union_name #bgp_with_bounds #where_clauses_tokens { #(#all_union_fields),* }\n });\n\n // Shadow repr struct for enum as a whole\n let shadow_repr_name =\n quote::format_ident!(\"__Shadow_CRepr_Struct_for_{}\", enum_name_str);\n shadow_defs.push(quote! {\n #[repr(C)]\n #[allow(non_snake_case)]\n #[allow(dead_code)]\n struct #shadow_repr_name #bgp_with_bounds #where_clauses_tokens {\n _discriminant: #shadow_discriminant_name,\n _phantom: #phantom_data,\n _fields: #shadow_union_name #bgp_without_bounds,\n }\n });\n\n // Generate variant_expressions\n let mut discriminant: Option<&TokenStream> = None;\n let mut discriminant_offset: i64 = 0;\n let mut exprs = Vec::new();\n\n for pv in pe.variants.iter() {\n if let Some(dis) = &pv.discriminant {\n discriminant = Some(dis);\n discriminant_offset = 0;\n }\n\n let discriminant_ts = if let Some(discriminant) = discriminant {\n if discriminant_offset > 0 {\n quote! { #discriminant + #discriminant_offset }\n } else {\n quote! { #discriminant }\n }\n } else {\n quote! { #discriminant_offset }\n };\n\n let display_name = pv.name.effective.clone();\n let variant_attrs_tokens = {\n let mut tokens = Vec::new();\n let name_token = TokenTree::Literal(Literal::string(&display_name));\n // Attributes from PAttrs\n if pv.attrs.facet.is_empty() {\n tokens.push(quote! { .name(#name_token) });\n } else {\n let mut attrs_list = Vec::new();\n for attr in &pv.attrs.facet {\n if let PFacetAttr::Arbitrary { content } = attr {\n attrs_list.push(\n quote! { ::facet::VariantAttribute::Arbitrary(#content) },\n );\n }\n }\n if attrs_list.is_empty() {\n tokens.push(quote! { .name(#name_token) });\n } else {\n tokens.push(\n quote! { .name(#name_token).attributes(&[#(#attrs_list),*]) },\n );\n }\n }\n quote! { #(#tokens)* }\n };\n\n let maybe_doc = match &pv.attrs.doc[..] {\n [] => quote! {},\n doc_lines => quote! { .doc(&[#(#doc_lines),*]) },\n };\n\n let shadow_struct_name = match &pv.name.raw {\n IdentOrLiteral::Ident(id) => {\n // Use the same naming convention as in the union definition\n quote::format_ident!(\"__Shadow_CRepr_Field{}_{}\", enum_name_str, id)\n }\n IdentOrLiteral::Literal(idx) => {\n // Use the same naming convention as in the union definition\n quote::format_ident!(\n \"__Shadow_CRepr_Field{}_{}\",\n enum_name_str,\n format_ident!(\"_{}\", idx) // Should not happen\n )\n }\n };\n\n let variant_offset = quote! {\n ::core::mem::offset_of!(#shadow_repr_name #bgp_without_bounds, _fields)\n };\n\n // Determine field structure for the variant\n match &pv.kind {\n PVariantKind::Unit => {\n // Generate unit shadow struct for the variant\n shadow_defs.push(quote! {\n #[repr(C)]\n #[allow(non_snake_case, dead_code)]\n struct #shadow_struct_name #bgp_with_bounds #where_clauses_tokens { _phantom: #phantom_data }\n });\n exprs.push(quote! {\n ::facet::Variant::builder()\n #variant_attrs_tokens\n .discriminant(#discriminant_ts as i64)\n .data(::facet::StructType::builder().repr(::facet::Repr::c()).unit().build())\n #maybe_doc\n .build()\n });\n }\n PVariantKind::Tuple { fields } => {\n // Tuple shadow struct\n let fields_with_types: Vec = fields\n .iter()\n .enumerate()\n .map(|(idx, pf)| {\n let field_ident = format_ident!(\"_{}\", idx);\n let typ = &pf.ty;\n quote! { #field_ident: #typ }\n })\n .collect();\n shadow_defs.push(quote! {\n #[repr(C)]\n #[allow(non_snake_case, dead_code)]\n struct #shadow_struct_name #bgp_with_bounds #where_clauses_tokens {\n #(#fields_with_types),* ,\n _phantom: #phantom_data\n }\n });\n let field_defs: Vec = fields\n .iter()\n .enumerate()\n .map(|(idx, pf)| {\n let mut pfield = pf.clone();\n let field_ident = format_ident!(\"_{}\", idx);\n pfield.name.raw = IdentOrLiteral::Ident(field_ident);\n gen_field_from_pfield(\n &pfield,\n &shadow_struct_name,\n &facet_bgp,\n Some(variant_offset.clone()),\n )\n })\n .collect();\n exprs.push(quote! {{\n let fields: &'static [::facet::Field] = &const {[\n #(#field_defs),*\n ]};\n ::facet::Variant::builder()\n #variant_attrs_tokens\n .discriminant(#discriminant_ts as i64)\n .data(::facet::StructType::builder().repr(::facet::Repr::c()).tuple().fields(fields).build())\n #maybe_doc\n .build()\n }});\n }\n PVariantKind::Struct { fields } => {\n let fields_with_types: Vec = fields\n .iter()\n .map(|pf| {\n // Use raw name for struct field definition\n let field_name = match &pf.name.raw {\n IdentOrLiteral::Ident(id) => quote! { #id },\n IdentOrLiteral::Literal(_) => {\n panic!(\"Struct variant cannot have literal field names\")\n }\n };\n let typ = &pf.ty;\n quote! { #field_name: #typ }\n })\n .collect();\n\n // Handle empty fields case explicitly\n let struct_fields = if fields_with_types.is_empty() {\n // Only add phantom data for empty struct variants\n quote! { _phantom: #phantom_data }\n } else {\n // Add fields plus phantom data for non-empty struct variants\n quote! { #(#fields_with_types),*, _phantom: #phantom_data }\n };\n shadow_defs.push(quote! {\n #[repr(C)]\n #[allow(non_snake_case, dead_code)]\n struct #shadow_struct_name #bgp_with_bounds #where_clauses_tokens {\n #struct_fields\n }\n });\n\n let field_defs: Vec = fields\n .iter()\n .map(|pf| {\n gen_field_from_pfield(\n pf,\n &shadow_struct_name,\n &facet_bgp,\n Some(variant_offset.clone()),\n )\n })\n .collect();\n\n exprs.push(quote! {{\n let fields: &'static [::facet::Field] = &const {[\n #(#field_defs),*\n ]};\n ::facet::Variant::builder()\n #variant_attrs_tokens\n .discriminant(#discriminant_ts as i64)\n .data(::facet::StructType::builder().repr(::facet::Repr::c()).struct_().fields(fields).build())\n #maybe_doc\n .build()\n }});\n }\n };\n\n // C-style enums increment discriminant unless explicitly set\n discriminant_offset += 1;\n }\n\n // Generate the EnumRepr token stream\n let repr_type_ts = match prim_opt {\n None => {\n quote! { ::facet::EnumRepr::from_discriminant_size::<#shadow_discriminant_name>() }\n }\n Some(p) => enum_repr_ts_from_primitive(*p),\n };\n\n (shadow_defs, exprs, repr_type_ts)\n }\n PRepr::Rust(Some(prim)) => {\n // Treat as primitive repr\n let facet_bgp = bgp.with_lifetime(LifetimeName(format_ident!(\"__facet\")));\n let bgp_with_bounds = facet_bgp.display_with_bounds();\n let phantom_data = facet_bgp.display_as_phantom_data();\n let discriminant_rust_type = prim.type_name();\n let mut shadow_defs = Vec::new();\n\n // Generate variant_expressions\n let mut discriminant: Option<&TokenStream> = None;\n let mut discriminant_offset: i64 = 0;\n\n let mut exprs = Vec::new();\n\n for pv in pe.variants.iter() {\n if let Some(dis) = &pv.discriminant {\n discriminant = Some(dis);\n discriminant_offset = 0;\n }\n\n let discriminant_ts = if let Some(discriminant) = discriminant {\n if discriminant_offset > 0 {\n quote! { #discriminant + #discriminant_offset }\n } else {\n quote! { #discriminant }\n }\n } else {\n quote! { #discriminant_offset }\n };\n\n let display_name = pv.name.effective.clone();\n let variant_attrs_tokens = {\n let mut tokens = Vec::new();\n let name_token = TokenTree::Literal(Literal::string(&display_name));\n if pv.attrs.facet.is_empty() {\n tokens.push(quote! { .name(#name_token) });\n } else {\n let mut attrs_list = Vec::new();\n for attr in &pv.attrs.facet {\n if let PFacetAttr::Arbitrary { content } = attr {\n attrs_list.push(\n quote! { ::facet::VariantAttribute::Arbitrary(#content) },\n );\n }\n }\n if attrs_list.is_empty() {\n tokens.push(quote! { .name(#name_token) });\n } else {\n tokens.push(\n quote! { .name(#name_token).attributes(&[#(#attrs_list),*]) },\n );\n }\n }\n quote! { #(#tokens)* }\n };\n\n let maybe_doc = match &pv.attrs.doc[..] {\n [] => quote! {},\n doc_lines => quote! { .doc(&[#(#doc_lines),*]) },\n };\n\n match &pv.kind {\n PVariantKind::Unit => {\n exprs.push(quote! {\n ::facet::Variant::builder()\n #variant_attrs_tokens\n .discriminant(#discriminant_ts as i64)\n .data(::facet::StructType::builder().repr(::facet::Repr::c()).unit().build())\n #maybe_doc\n .build()\n });\n }\n PVariantKind::Tuple { fields } => {\n let shadow_struct_name = match &pv.name.raw {\n IdentOrLiteral::Ident(id) => {\n quote::format_ident!(\n \"__Shadow_RustRepr_Tuple_for_{}_{}\",\n enum_name_str,\n id\n )\n }\n IdentOrLiteral::Literal(_) => {\n panic!(\n \"Enum variant names cannot be literals for tuple variants in #[repr(Rust)]\"\n )\n }\n };\n let fields_with_types: Vec = fields\n .iter()\n .enumerate()\n .map(|(idx, pf)| {\n let field_ident = format_ident!(\"_{}\", idx);\n let typ = &pf.ty;\n quote! { #field_ident: #typ }\n })\n .collect();\n shadow_defs.push(quote! {\n #[repr(C)] // Layout variants like C structs\n #[allow(non_snake_case, dead_code)]\n struct #shadow_struct_name #bgp_with_bounds #where_clauses_tokens {\n _discriminant: #discriminant_rust_type,\n _phantom: #phantom_data,\n #(#fields_with_types),*\n }\n });\n let field_defs: Vec = fields\n .iter()\n .enumerate()\n .map(|(idx, pf)| {\n let mut pf = pf.clone();\n let field_ident = format_ident!(\"_{}\", idx);\n pf.name.raw = IdentOrLiteral::Ident(field_ident);\n gen_field_from_pfield(&pf, &shadow_struct_name, &facet_bgp, None)\n })\n .collect();\n exprs.push(quote! {{\n let fields: &'static [::facet::Field] = &const {[\n #(#field_defs),*\n ]};\n ::facet::Variant::builder()\n #variant_attrs_tokens\n .discriminant(#discriminant_ts as i64)\n .data(::facet::StructType::builder().repr(::facet::Repr::c()).tuple().fields(fields).build())\n #maybe_doc\n .build()\n }});\n }\n PVariantKind::Struct { fields } => {\n let shadow_struct_name = match &pv.name.raw {\n IdentOrLiteral::Ident(id) => {\n // Use a more descriptive name, similar to the Tuple variant case\n quote::format_ident!(\n \"__Shadow_RustRepr_Struct_for_{}_{}\",\n enum_name_str,\n id\n )\n }\n IdentOrLiteral::Literal(_) => {\n // This case should ideally not happen for named struct variants\n panic!(\n \"Enum variant names cannot be literals for struct variants in #[repr(Rust)]\"\n )\n }\n };\n let fields_with_types: Vec = fields\n .iter()\n .map(|pf| {\n let field_name = match &pf.name.raw {\n IdentOrLiteral::Ident(id) => quote! { #id },\n IdentOrLiteral::Literal(_) => {\n panic!(\"Struct variant cannot have literal field names\")\n }\n };\n let typ = &pf.ty;\n quote! { #field_name: #typ }\n })\n .collect();\n shadow_defs.push(quote! {\n #[repr(C)] // Layout variants like C structs\n #[allow(non_snake_case, dead_code)]\n struct #shadow_struct_name #bgp_with_bounds #where_clauses_tokens {\n _discriminant: #discriminant_rust_type,\n _phantom: #phantom_data,\n #(#fields_with_types),*\n }\n });\n let field_defs: Vec = fields\n .iter()\n .map(|pf| {\n gen_field_from_pfield(pf, &shadow_struct_name, &facet_bgp, None)\n })\n .collect();\n exprs.push(quote! {{\n let fields: &'static [::facet::Field] = &const {[\n #(#field_defs),*\n ]};\n ::facet::Variant::builder()\n #variant_attrs_tokens\n .discriminant(#discriminant_ts as i64)\n .data(::facet::StructType::builder().repr(::facet::Repr::c()).struct_().fields(fields).build())\n #maybe_doc\n .build()\n }});\n }\n }\n // Rust-style enums increment discriminant unless explicitly set\n discriminant_offset += 1;\n }\n let repr_type_ts = enum_repr_ts_from_primitive(*prim);\n (shadow_defs, exprs, repr_type_ts)\n }\n PRepr::Transparent => {\n return quote! {\n compile_error!(\"#[repr(transparent)] is not supported on enums by Facet\");\n };\n }\n PRepr::Rust(None) => {\n return quote! {\n compile_error!(\"Facet requires enums to have an explicit representation (e.g., #[repr(C)], #[repr(u8)])\");\n };\n }\n };\n\n // Only make static_decl for non-generic enums\n let static_decl = if parsed.generics.is_none() {\n generate_static_decl(enum_name)\n } else {\n quote! {}\n };\n\n // Set up generics for impl blocks\n let facet_bgp = bgp.with_lifetime(LifetimeName(format_ident!(\"__facet\")));\n let bgp_def = facet_bgp.display_with_bounds();\n let bgp_without_bounds = bgp.display_without_bounds();\n\n // Generate the impl\n quote! {\n #static_decl\n\n #[automatically_derived]\n #[allow(non_camel_case_types)]\n unsafe impl #bgp_def ::facet::Facet<'__facet> for #enum_name #bgp_without_bounds #where_clauses_tokens {\n const VTABLE: &'static ::facet::ValueVTable = &const {\n ::facet::value_vtable!(Self, #type_name_fn)\n };\n\n const SHAPE: &'static ::facet::Shape = &const {\n #(#shadow_struct_defs)*\n\n let __facet_variants: &'static [::facet::Variant] = &const {[\n #(#variant_expressions),*\n ]};\n\n ::facet::Shape::builder_for_sized::()\n .type_identifier(#enum_name_str)\n #type_params\n .ty(::facet::Type::User(::facet::UserType::Enum(::facet::EnumType::builder()\n // Use variant expressions that just reference the shadow structs\n // which are now defined above\n .variants(__facet_variants)\n .repr(#repr)\n .enum_repr(#enum_repr_type_tokenstream)\n .build())\n ))\n #maybe_container_doc\n #container_attributes_tokens\n #type_tag_maybe\n .build()\n };\n }\n }\n}\n"], ["/facet/facet-macros-emit/src/process_struct.rs", "use quote::{format_ident, quote};\n\nuse super::*;\n\n/// Generates the `::facet::Field` definition `TokenStream` from a `PStructField`.\npub(crate) fn gen_field_from_pfield(\n field: &PStructField,\n struct_name: &Ident,\n bgp: &BoundedGenericParams,\n base_offset: Option,\n) -> TokenStream {\n let field_name_effective = &field.name.effective;\n let field_name_raw = &field.name.raw;\n let field_type = &field.ty; // TokenStream of the type\n\n let tts: facet_macros_parse::TokenStream = field_type.clone();\n let field_type_static = tts\n .to_token_iter()\n .parse::>()\n .unwrap()\n .into_iter()\n .map(|lott| match lott {\n LifetimeOrTt::TokenTree(tt) => quote! { #tt },\n LifetimeOrTt::Lifetime(_) => quote! { 'static },\n })\n .collect::();\n\n let bgp_without_bounds = bgp.display_without_bounds();\n\n // Determine field flags and other attributes from field.attrs\n let mut flags = quote! {};\n let mut flags_empty = true;\n\n let mut vtable_items: Vec = vec![];\n let mut attribute_list: Vec = vec![];\n let doc_lines: Vec = field\n .attrs\n .doc\n .iter()\n .map(|doc| doc.as_str().replace(\"\\\\\\\"\", \"\\\"\"))\n .collect();\n let mut shape_of = quote! { shape_of };\n let mut asserts: Vec = vec![];\n\n // Process attributes other than rename rules, which are handled by PName\n for attr in &field.attrs.facet {\n match attr {\n PFacetAttr::Sensitive => {\n if flags_empty {\n flags_empty = false;\n flags = quote! { ::facet::FieldFlags::SENSITIVE };\n } else {\n flags = quote! { #flags.union(::facet::FieldFlags::SENSITIVE) };\n }\n }\n PFacetAttr::Default => {\n if flags_empty {\n flags_empty = false;\n flags = quote! { ::facet::FieldFlags::DEFAULT };\n } else {\n flags = quote! { #flags.union(::facet::FieldFlags::DEFAULT) };\n }\n asserts.push(quote! {\n ::facet::static_assertions::assert_impl_all!(#field_type_static: ::core::default::Default);\n })\n }\n PFacetAttr::DefaultEquals { expr } => {\n if flags_empty {\n flags_empty = false;\n flags = quote! { ::facet::FieldFlags::DEFAULT };\n } else {\n flags = quote! { #flags.union(::facet::FieldFlags::DEFAULT) };\n }\n\n vtable_items.push(quote! {\n .default_fn(|ptr| {\n unsafe { ptr.put::<#field_type>(#expr) }\n })\n });\n }\n PFacetAttr::Child => {\n if flags_empty {\n flags_empty = false;\n flags = quote! { ::facet::FieldFlags::CHILD };\n } else {\n flags = quote! { #flags.union(::facet::FieldFlags::CHILD) };\n }\n }\n PFacetAttr::Flatten => {\n if flags_empty {\n flags_empty = false;\n flags = quote! { ::facet::FieldFlags::FLATTEN };\n } else {\n flags = quote! { #flags.union(::facet::FieldFlags::FLATTEN) };\n }\n }\n PFacetAttr::Opaque => {\n shape_of = quote! { shape_of_opaque };\n }\n PFacetAttr::Arbitrary { content } => {\n attribute_list.push(quote! { ::facet::FieldAttribute::Arbitrary(#content) });\n }\n PFacetAttr::SkipSerializing => {\n if flags_empty {\n flags_empty = false;\n flags = quote! { ::facet::FieldFlags::SKIP_SERIALIZING };\n } else {\n flags = quote! { #flags.union(::facet::FieldFlags::SKIP_SERIALIZING) };\n }\n }\n PFacetAttr::SkipSerializingIf { expr } => {\n let predicate = expr;\n let field_ty = field_type;\n vtable_items.push(quote! {\n .skip_serializing_if(unsafe { ::core::mem::transmute((#predicate) as fn(&#field_ty) -> bool) })\n });\n }\n // These are handled by PName or are container-level, so ignore them for field attributes.\n PFacetAttr::RenameAll { .. } => {} // Explicitly ignore rename attributes here\n PFacetAttr::Transparent\n | PFacetAttr::Invariants { .. }\n | PFacetAttr::DenyUnknownFields\n | PFacetAttr::TypeTag { .. } => {}\n }\n }\n\n let maybe_attributes = if attribute_list.is_empty() {\n quote! {}\n } else {\n quote! { .attributes(&const { [#(#attribute_list),*] }) }\n };\n\n let maybe_field_doc = if doc_lines.is_empty() {\n quote! {}\n } else {\n quote! { .doc(&[#(#doc_lines),*]) }\n };\n\n let maybe_vtable = if vtable_items.is_empty() {\n quote! {}\n } else {\n quote! {\n .vtable(&const {\n ::facet::FieldVTable::builder()\n #(#vtable_items)*\n .build()\n })\n }\n };\n\n let maybe_flags = if flags_empty {\n quote! {}\n } else {\n quote! { .flags(#flags) }\n };\n\n // Calculate the final offset, incorporating the base_offset if present\n let final_offset = match base_offset {\n Some(base) => {\n quote! { #base + ::core::mem::offset_of!(#struct_name #bgp_without_bounds, #field_name_raw) }\n }\n None => {\n quote! { ::core::mem::offset_of!(#struct_name #bgp_without_bounds, #field_name_raw) }\n }\n };\n\n quote! {\n {\n #(#asserts)*;\n ::facet::Field::builder()\n // Use the effective name (after rename rules) for metadata\n .name(#field_name_effective)\n // Use the raw field name/index TokenStream for shape_of and offset_of\n .shape(::facet::#shape_of(&|s: &#struct_name #bgp_without_bounds| &s.#field_name_raw))\n .offset(#final_offset)\n #maybe_flags\n #maybe_attributes\n #maybe_field_doc\n #maybe_vtable\n .build()\n }\n }\n}\n\n/// Processes a regular struct to implement Facet\n///\n/// Example input:\n/// ```rust\n/// struct Blah {\n/// foo: u32,\n/// bar: String,\n/// }\n/// ```\npub(crate) fn process_struct(parsed: Struct) -> TokenStream {\n let ps = PStruct::parse(&parsed); // Use the parsed representation\n\n let struct_name_ident = format_ident!(\"{}\", ps.container.name);\n let struct_name = &ps.container.name;\n let struct_name_str = struct_name.to_string();\n\n let type_name_fn = generate_type_name_fn(struct_name, parsed.generics.as_ref());\n\n // TODO: I assume the `PrimitiveRepr` is only relevant for enums, and does not need to be preserved?\n let repr = match &ps.container.attrs.repr {\n PRepr::Transparent => quote! { ::facet::Repr::transparent() },\n PRepr::Rust(_) => quote! { ::facet::Repr::default() },\n PRepr::C(_) => quote! { ::facet::Repr::c() },\n };\n\n // Use PStruct for kind and fields\n let (kind, fields_vec) = match &ps.kind {\n PStructKind::Struct { fields } => {\n let kind = quote!(::facet::StructKind::Struct);\n let fields_vec = fields\n .iter()\n .map(|field| gen_field_from_pfield(field, struct_name, &ps.container.bgp, None))\n .collect::>();\n (kind, fields_vec)\n }\n PStructKind::TupleStruct { fields } => {\n let kind = quote!(::facet::StructKind::TupleStruct);\n let fields_vec = fields\n .iter()\n .map(|field| gen_field_from_pfield(field, struct_name, &ps.container.bgp, None))\n .collect::>();\n (kind, fields_vec)\n }\n PStructKind::UnitStruct => {\n let kind = quote!(::facet::StructKind::Unit);\n (kind, vec![])\n }\n };\n\n // Still need original AST for where clauses and type params for build_ helpers\n let where_clauses_ast = match &parsed.kind {\n StructKind::Struct { clauses, .. } => clauses.as_ref(),\n StructKind::TupleStruct { clauses, .. } => clauses.as_ref(),\n StructKind::UnitStruct { clauses, .. } => clauses.as_ref(),\n };\n let where_clauses = build_where_clauses(where_clauses_ast, parsed.generics.as_ref());\n let type_params = build_type_params(parsed.generics.as_ref());\n\n // Static decl using PStruct BGP\n let static_decl = if ps.container.bgp.params.is_empty() {\n generate_static_decl(struct_name)\n } else {\n TokenStream::new()\n };\n\n // Doc comments from PStruct\n let maybe_container_doc = if ps.container.attrs.doc.is_empty() {\n quote! {}\n } else {\n let doc_lines = ps.container.attrs.doc.iter().map(|s| quote!(#s));\n quote! { .doc(&[#(#doc_lines),*]) }\n };\n\n // Container attributes from PStruct\n let container_attributes_tokens = {\n let mut items = Vec::new();\n for attr in &ps.container.attrs.facet {\n match attr {\n PFacetAttr::DenyUnknownFields => {\n items.push(quote! { ::facet::ShapeAttribute::DenyUnknownFields });\n }\n PFacetAttr::Default | PFacetAttr::DefaultEquals { .. } => {\n // Corresponds to `#[facet(default)]` on container\n items.push(quote! { ::facet::ShapeAttribute::Default });\n }\n PFacetAttr::Transparent => {\n items.push(quote! { ::facet::ShapeAttribute::Transparent });\n }\n PFacetAttr::RenameAll { .. } => {}\n PFacetAttr::Arbitrary { content } => {\n items.push(quote! { ::facet::ShapeAttribute::Arbitrary(#content) });\n }\n // Others not applicable at container level or handled elsewhere\n PFacetAttr::Sensitive\n | PFacetAttr::Opaque\n | PFacetAttr::Invariants { .. }\n | PFacetAttr::SkipSerializing\n | PFacetAttr::SkipSerializingIf { .. }\n | PFacetAttr::Flatten\n | PFacetAttr::Child\n | PFacetAttr::TypeTag { .. } => {}\n }\n }\n if items.is_empty() {\n quote! {}\n } else {\n quote! { .attributes(&[#(#items),*]) }\n }\n };\n\n // Type tag from PStruct\n let type_tag_maybe = {\n if let Some(type_tag) = ps.container.attrs.type_tag() {\n quote! { .type_tag(#type_tag) }\n } else {\n quote! {}\n }\n };\n\n // Invariants from PStruct\n let invariant_maybe = {\n let mut invariant_fns = Vec::new();\n for attr in &ps.container.attrs.facet {\n if let PFacetAttr::Invariants { expr } = attr {\n invariant_fns.push(expr);\n }\n }\n\n if !invariant_fns.is_empty() {\n let tests = invariant_fns.iter().map(|expr| {\n quote! {\n if !#expr(value) {\n return false;\n }\n }\n });\n\n let bgp_display = ps.container.bgp.display_without_bounds(); // Use the BGP from PStruct\n quote! {\n unsafe fn invariants<'mem>(value: ::facet::PtrConst<'mem>) -> bool {\n let value = value.get::<#struct_name_ident #bgp_display>();\n #(#tests)*\n true\n }\n\n {\n let vtable_sized = vtable.sized_mut().unwrap();\n vtable_sized.invariants = || Some(invariants);\n }\n }\n } else {\n quote! {}\n }\n };\n\n // Transparent logic using PStruct\n let inner_field = if ps.container.attrs.is_transparent() {\n match &ps.kind {\n PStructKind::TupleStruct { fields } => {\n if fields.len() > 1 {\n return quote! {\n compile_error!(\"Transparent structs must be tuple structs with zero or one field\");\n };\n }\n fields.first().cloned() // Use first field if it exists, None otherwise (ZST case)\n }\n _ => {\n return quote! {\n compile_error!(\"Transparent structs must be tuple structs\");\n };\n }\n }\n } else {\n None\n };\n\n // Add try_from_inner implementation for transparent types\n let try_from_inner_code = if ps.container.attrs.is_transparent() {\n if let Some(inner_field) = &inner_field {\n // Transparent struct with one field\n let inner_field_type = &inner_field.ty;\n let bgp_without_bounds = ps.container.bgp.display_without_bounds();\n\n quote! {\n // Define the try_from function for the value vtable\n unsafe fn try_from<'src, 'dst>(\n src_ptr: ::facet::PtrConst<'src>,\n src_shape: &'static ::facet::Shape,\n dst: ::facet::PtrUninit<'dst>\n ) -> Result<::facet::PtrMut<'dst>, ::facet::TryFromError> {\n // Try the inner type's try_from function if it exists\n let inner_result = match (<#inner_field_type as ::facet::Facet>::SHAPE.vtable.sized().and_then(|v| (v.try_from)())) {\n Some(inner_try) => unsafe { (inner_try)(src_ptr, src_shape, dst) },\n None => Err(::facet::TryFromError::UnsupportedSourceShape {\n src_shape,\n expected: const { &[ &<#inner_field_type as ::facet::Facet>::SHAPE ] },\n })\n };\n\n match inner_result {\n Ok(result) => Ok(result),\n Err(_) => {\n // If inner_try failed, check if source shape is exactly the inner shape\n if src_shape != <#inner_field_type as ::facet::Facet>::SHAPE {\n return Err(::facet::TryFromError::UnsupportedSourceShape {\n src_shape,\n expected: const { &[ &<#inner_field_type as ::facet::Facet>::SHAPE ] },\n });\n }\n // Read the inner value and construct the wrapper.\n let inner: #inner_field_type = unsafe { src_ptr.read() };\n Ok(unsafe { dst.put(inner) }) // Construct wrapper\n }\n }\n }\n\n // Define the try_into_inner function for the value vtable\n unsafe fn try_into_inner<'src, 'dst>(\n src_ptr: ::facet::PtrMut<'src>,\n dst: ::facet::PtrUninit<'dst>\n ) -> Result<::facet::PtrMut<'dst>, ::facet::TryIntoInnerError> {\n let wrapper = unsafe { src_ptr.get::<#struct_name_ident #bgp_without_bounds>() };\n Ok(unsafe { dst.put(wrapper.0.clone()) }) // Assume tuple struct field 0\n }\n\n // Define the try_borrow_inner function for the value vtable\n unsafe fn try_borrow_inner<'src>(\n src_ptr: ::facet::PtrConst<'src>\n ) -> Result<::facet::PtrConst<'src>, ::facet::TryBorrowInnerError> {\n let wrapper = unsafe { src_ptr.get::<#struct_name_ident #bgp_without_bounds>() };\n // Return a pointer to the inner field (field 0 for tuple struct)\n Ok(::facet::PtrConst::new(&wrapper.0 as *const _ as *const u8))\n }\n\n {\n let vtable_sized = vtable.sized_mut().unwrap();\n vtable_sized.try_from = || Some(try_from);\n vtable_sized.try_into_inner = || Some(try_into_inner);\n vtable_sized.try_borrow_inner = || Some(try_borrow_inner);\n }\n }\n } else {\n // Transparent ZST struct (like struct Unit;)\n quote! {\n // Define the try_from function for the value vtable (ZST case)\n unsafe fn try_from<'src, 'dst>(\n src_ptr: ::facet::PtrConst<'src>,\n src_shape: &'static ::facet::Shape,\n dst: ::facet::PtrUninit<'dst>\n ) -> Result<::facet::PtrMut<'dst>, ::facet::TryFromError> {\n if src_shape.layout.size() == 0 {\n Ok(unsafe { dst.put(#struct_name_ident) }) // Construct ZST\n } else {\n Err(::facet::TryFromError::UnsupportedSourceShape {\n src_shape,\n expected: const { &[ <() as ::facet::Facet>::SHAPE ] }, // Expect unit-like shape\n })\n }\n }\n\n {\n let vtable_sized = vtable.sized_mut().unwrap();\n vtable_sized.try_from = || Some(try_from);\n }\n\n // ZSTs cannot be meaningfully borrowed or converted *into* an inner value\n // try_into_inner and try_borrow_inner remain None\n }\n }\n } else {\n quote! {} // Not transparent\n };\n\n // Generate the inner shape function for transparent types\n let inner_shape_fn = if ps.container.attrs.is_transparent() {\n if let Some(inner_field) = &inner_field {\n let ty = &inner_field.ty;\n quote! {\n // Function to return inner type's shape\n fn inner_shape() -> &'static ::facet::Shape {\n <#ty as ::facet::Facet>::SHAPE\n }\n }\n } else {\n // Transparent ZST case\n quote! {\n fn inner_shape() -> &'static ::facet::Shape {\n <() as ::facet::Facet>::SHAPE // Inner shape is unit\n }\n }\n }\n } else {\n quote! {}\n };\n\n let inner_setter = if ps.container.attrs.is_transparent() {\n quote! { .inner(inner_shape) }\n } else {\n quote! {}\n };\n\n // Generics from PStruct\n let facet_bgp = ps\n .container\n .bgp\n .with_lifetime(LifetimeName(format_ident!(\"__facet\")));\n let bgp_def = facet_bgp.display_with_bounds();\n let bgp_without_bounds = ps.container.bgp.display_without_bounds();\n\n // Final quote block using refactored parts\n let result = quote! {\n #static_decl\n\n #[automatically_derived]\n unsafe impl #bgp_def ::facet::Facet<'__facet> for #struct_name_ident #bgp_without_bounds #where_clauses {\n const VTABLE: &'static ::facet::ValueVTable = &const {\n let mut vtable = ::facet::value_vtable!(Self, #type_name_fn);\n #invariant_maybe\n #try_from_inner_code // Use the generated code for transparent types\n vtable\n };\n\n const SHAPE: &'static ::facet::Shape = &const {\n let fields: &'static [::facet::Field] = &const {[#(#fields_vec),*]};\n\n #inner_shape_fn // Include inner_shape function if needed\n\n ::facet::Shape::builder_for_sized::()\n .type_identifier(#struct_name_str)\n #type_params // Still from parsed.generics\n .ty(::facet::Type::User(::facet::UserType::Struct(::facet::StructType::builder()\n .repr(#repr)\n .kind(#kind)\n .fields(fields)\n .build()\n )))\n #inner_setter // Use transparency flag from PStruct\n #maybe_container_doc // From ps.container.attrs.doc\n #container_attributes_tokens // From ps.container.attrs.facet\n #type_tag_maybe\n .build()\n };\n }\n };\n\n result\n}\n"], ["/facet/facet-macros-emit/src/renamerule.rs", "/// Represents different case conversion strategies for renaming.\n/// All strategies assume an initial input of `snake_case` (e.g., `foo_bar`).\n#[derive(Clone, Copy, Debug, PartialEq, Eq)]\npub enum RenameRule {\n /// Rename to PascalCase: `foo_bar` -> `FooBar`\n PascalCase,\n /// Rename to camelCase: `foo_bar` -> `fooBar`\n CamelCase,\n /// Rename to snake_case: `foo_bar` -> `foo_bar`\n SnakeCase,\n /// Rename to SCREAMING_SNAKE_CASE: `foo_bar` -> `FOO_BAR`\n ScreamingSnakeCase,\n /// Rename to kebab-case: `foo_bar` -> `foo-bar`\n KebabCase,\n /// Rename to SCREAMING-KEBAB-CASE: `foo_bar` -> `FOO-BAR`\n ScreamingKebabCase,\n}\n\nimpl RenameRule {\n /// Parse a string into a `RenameRule`\n pub(crate) fn from_str(rule: &str) -> Option {\n match rule {\n \"PascalCase\" => Some(RenameRule::PascalCase),\n \"camelCase\" => Some(RenameRule::CamelCase),\n \"snake_case\" => Some(RenameRule::SnakeCase),\n \"SCREAMING_SNAKE_CASE\" => Some(RenameRule::ScreamingSnakeCase),\n \"kebab-case\" => Some(RenameRule::KebabCase),\n \"SCREAMING-KEBAB-CASE\" => Some(RenameRule::ScreamingKebabCase),\n _ => None,\n }\n }\n\n /// Apply this renaming rule to a string\n pub(crate) fn apply(self, input: &str) -> String {\n match self {\n RenameRule::PascalCase => to_pascal_case(input),\n RenameRule::CamelCase => to_camel_case(input),\n RenameRule::SnakeCase => to_snake_case(input),\n RenameRule::ScreamingSnakeCase => to_screaming_snake_case(input),\n RenameRule::KebabCase => to_kebab_case(input),\n RenameRule::ScreamingKebabCase => to_screaming_kebab_case(input),\n }\n }\n}\n\n/// Converts a string to PascalCase: `foo_bar` -> `FooBar`\nfn to_pascal_case(input: &str) -> String {\n split_into_words(input)\n .iter()\n .map(|word| {\n let mut chars = word.chars();\n match chars.next() {\n None => String::new(),\n Some(c) => {\n c.to_uppercase().collect::() + &chars.collect::().to_lowercase()\n }\n }\n })\n .collect()\n}\n\n/// Converts a string to camelCase: `foo_bar` -> `fooBar`\nfn to_camel_case(input: &str) -> String {\n let pascal = to_pascal_case(input);\n if pascal.is_empty() {\n return String::new();\n }\n\n let mut result = String::new();\n let mut chars = pascal.chars();\n if let Some(first_char) = chars.next() {\n result.push(first_char.to_lowercase().next().unwrap());\n }\n result.extend(chars);\n result\n}\n\n/// Converts a string to snake_case: `FooBar` -> `foo_bar`\nfn to_snake_case(input: &str) -> String {\n let words = split_into_words(input);\n words\n .iter()\n .map(|word| word.to_lowercase())\n .collect::>()\n .join(\"_\")\n}\n\n/// Converts a string to SCREAMING_SNAKE_CASE: `FooBar` -> `FOO_BAR`\nfn to_screaming_snake_case(input: &str) -> String {\n let words = split_into_words(input);\n words\n .iter()\n .map(|word| word.to_uppercase())\n .collect::>()\n .join(\"_\")\n}\n\n/// Converts a string to kebab-case: `FooBar` -> `foo-bar`\nfn to_kebab_case(input: &str) -> String {\n let words = split_into_words(input);\n words\n .iter()\n .map(|word| word.to_lowercase())\n .collect::>()\n .join(\"-\")\n}\n\n/// Converts a string to SCREAMING-KEBAB-CASE: `FooBar` -> `FOO-BAR`\nfn to_screaming_kebab_case(input: &str) -> String {\n let words = split_into_words(input);\n words\n .iter()\n .map(|word| word.to_uppercase())\n .collect::>()\n .join(\"-\")\n}\n\n/// Splits a string into words based on case and separators\n///\n/// Logic:\n/// - Iterates through characters in the input string.\n/// - Splits at underscores, hyphens, or whitespace.\n/// - Starts a new word on case boundaries, e.g. between lowercase and uppercase (as in \"fooBar\").\n/// - Handles consecutive uppercase letters correctly (e.g. \"HTTPServer\").\n/// - Aggregates non-separator characters into words.\n/// - Returns a vector of non-empty words as Strings.\nfn split_into_words(input: &str) -> Vec {\n if input.is_empty() {\n return vec![];\n }\n\n let mut words = Vec::new();\n let mut current_word = String::new();\n let mut chars = input.chars().peekable();\n\n while let Some(c) = chars.next() {\n // If separator, start new word\n if c == '_' || c == '-' || c.is_whitespace() {\n if !current_word.is_empty() {\n words.push(std::mem::take(&mut current_word));\n }\n continue;\n }\n\n // Peek at next character for deciding about word boundaries\n let next = chars.peek().copied();\n\n if c.is_uppercase() {\n if !current_word.is_empty() {\n let prev = current_word.chars().last().unwrap();\n // Both cases should take the same action, so fold them together.\n // Case 1: previous is lowercase or digit, now uppercase (e.g. fooBar, foo1Bar)\n // Case 2: end of consecutive uppercase group, e.g. \"BARBaz\"\n // (prev is uppercase and next char is lowercase)\n if prev.is_lowercase()\n || prev.is_ascii_digit()\n || (prev.is_uppercase() && next.map(|n| n.is_lowercase()).unwrap_or(false))\n {\n words.push(std::mem::take(&mut current_word));\n }\n }\n current_word.push(c);\n } else {\n // Lowercase or digit, just append\n // If previous is uppercase and next is lowercase, need to split, but handled above\n current_word.push(c);\n }\n }\n\n if !current_word.is_empty() {\n words.push(current_word);\n }\n\n words.into_iter().filter(|s| !s.is_empty()).collect()\n}\n\n#[cfg(test)]\nmod tests {\n use super::split_into_words;\n\n #[test]\n fn test_split_into_words_simple_snake_case() {\n assert_eq!(split_into_words(\"foo_bar_baz\"), vec![\"foo\", \"bar\", \"baz\"]);\n }\n\n #[test]\n fn test_split_into_words_single_word() {\n assert_eq!(split_into_words(\"foo\"), vec![\"foo\"]);\n assert_eq!(split_into_words(\"Foo\"), vec![\"Foo\"]);\n }\n\n #[test]\n fn test_split_into_words_empty_string() {\n assert_eq!(split_into_words(\"\"), Vec::::new());\n }\n\n #[test]\n fn test_split_into_words_multiple_underscores() {\n assert_eq!(split_into_words(\"foo__bar\"), vec![\"foo\", \"bar\"]);\n assert_eq!(split_into_words(\"_foo_bar_\"), vec![\"foo\", \"bar\"]);\n }\n\n #[test]\n fn test_split_into_words_kebab_case() {\n assert_eq!(split_into_words(\"foo-bar-baz\"), vec![\"foo\", \"bar\", \"baz\"]);\n }\n\n #[test]\n fn test_split_into_words_mixed_separators_and_space() {\n assert_eq!(split_into_words(\"foo_ bar-baz\"), vec![\"foo\", \"bar\", \"baz\"]);\n assert_eq!(split_into_words(\"a_b-c d\"), vec![\"a\", \"b\", \"c\", \"d\"]);\n }\n\n #[test]\n fn test_split_into_words_camel_case() {\n assert_eq!(split_into_words(\"fooBarBaz\"), vec![\"foo\", \"Bar\", \"Baz\"]);\n assert_eq!(split_into_words(\"fooBar\"), vec![\"foo\", \"Bar\"]);\n assert_eq!(\n split_into_words(\"fooBar_BazQuux\"),\n vec![\"foo\", \"Bar\", \"Baz\", \"Quux\"]\n );\n }\n\n #[test]\n fn test_split_into_words_pascal_case() {\n assert_eq!(split_into_words(\"FooBarBaz\"), vec![\"Foo\", \"Bar\", \"Baz\"]);\n assert_eq!(split_into_words(\"FooBar\"), vec![\"Foo\", \"Bar\"]);\n }\n\n #[test]\n fn test_split_into_words_http_server() {\n assert_eq!(split_into_words(\"HTTPServer\"), vec![\"HTTP\", \"Server\"]);\n assert_eq!(\n split_into_words(\"theHTTPServer\"),\n vec![\"the\", \"HTTP\", \"Server\"]\n );\n }\n\n #[test]\n fn test_split_into_words_consecutive_uppercase_at_end() {\n assert_eq!(split_into_words(\"FooBAR\"), vec![\"Foo\", \"BAR\"]);\n assert_eq!(split_into_words(\"FooBARBaz\"), vec![\"Foo\", \"BAR\", \"Baz\"]);\n }\n\n #[test]\n fn test_split_into_words_separators_and_case_boundaries() {\n assert_eq!(split_into_words(\"foo_barBaz\"), vec![\"foo\", \"bar\", \"Baz\"]);\n assert_eq!(\n split_into_words(\"fooBar_bazQux\"),\n vec![\"foo\", \"Bar\", \"baz\", \"Qux\"]\n );\n }\n\n #[test]\n fn test_rename_rule_snake_case() {\n use super::RenameRule;\n // Snake case input should remain unchanged\n assert_eq!(RenameRule::SnakeCase.apply(\"foo_bar_baz\"), \"foo_bar_baz\");\n // CamelCase input becomes snake_case\n assert_eq!(RenameRule::SnakeCase.apply(\"fooBarBaz\"), \"foo_bar_baz\");\n // PascalCase input becomes snake_case\n assert_eq!(RenameRule::SnakeCase.apply(\"FooBarBaz\"), \"foo_bar_baz\");\n // SCREAMING_SNAKE_CASE input becomes snake_case\n assert_eq!(RenameRule::SnakeCase.apply(\"FOO_BAR_BAZ\"), \"foo_bar_baz\");\n // kebab-case input becomes snake_case\n assert_eq!(RenameRule::SnakeCase.apply(\"foo-bar-baz\"), \"foo_bar_baz\");\n assert_eq!(\n RenameRule::SnakeCase.apply(\"Foo_Bar-Baz quux\"),\n \"foo_bar_baz_quux\"\n );\n // Mixed case and separator input\n assert_eq!(\n RenameRule::SnakeCase.apply(\"theHTTPServer\"),\n \"the_http_server\"\n );\n assert_eq!(RenameRule::SnakeCase.apply(\"FooBARBaz\"), \"foo_bar_baz\");\n // Empty input keeps empty\n assert_eq!(RenameRule::SnakeCase.apply(\"\"), \"\");\n }\n}\n"], ["/facet/facet-core/src/impls_alloc/btreeset.rs", "use alloc::boxed::Box;\nuse alloc::collections::BTreeSet;\n\nuse crate::ptr::{PtrConst, PtrMut};\n\nuse crate::{\n Def, Facet, IterVTable, MarkerTraits, SetDef, SetVTable, Shape, Type, TypeParam, UserType,\n ValueVTable,\n};\n\ntype BTreeSetIterator<'mem, T> = alloc::collections::btree_set::Iter<'mem, T>;\n\nunsafe impl<'a, T> Facet<'a> for BTreeSet\nwhere\n T: Facet<'a> + core::cmp::Eq + core::cmp::Ord,\n{\n const VTABLE: &'static ValueVTable = &const {\n ValueVTable::builder::()\n .marker_traits(|| {\n MarkerTraits::SEND\n .union(MarkerTraits::SYNC)\n .union(MarkerTraits::EQ)\n .union(MarkerTraits::UNPIN)\n .intersection(T::SHAPE.vtable.marker_traits())\n })\n .type_name(|f, opts| {\n if let Some(opts) = opts.for_children() {\n write!(f, \"{}<\", Self::SHAPE.type_identifier)?;\n T::SHAPE.vtable.type_name()(f, opts)?;\n write!(f, \">\")\n } else {\n write!(f, \"{}<⋯>\", Self::SHAPE.type_identifier)\n }\n })\n .default_in_place(|| Some(|target| unsafe { target.put(Self::default()) }))\n .build()\n };\n\n const SHAPE: &'static Shape = &const {\n Shape::builder_for_sized::()\n .type_identifier(\"BTreeSet\")\n .type_params(&[TypeParam {\n name: \"T\",\n shape: || T::SHAPE,\n }])\n .ty(Type::User(UserType::Opaque))\n .def(Def::Set(\n SetDef::builder()\n .t(|| T::SHAPE)\n .vtable(\n &const {\n SetVTable::builder()\n .init_in_place_with_capacity(|uninit, _capacity| unsafe {\n uninit.put(Self::new())\n })\n .insert(|ptr, item| unsafe {\n let set = ptr.as_mut::>();\n let item = item.read::();\n set.insert(item)\n })\n .len(|ptr| unsafe {\n let set = ptr.get::>();\n set.len()\n })\n .contains(|ptr, item| unsafe {\n let set = ptr.get::>();\n set.contains(item.get())\n })\n .iter_vtable(\n IterVTable::builder()\n .init_with_value(|ptr| {\n let set = unsafe { ptr.get::>() };\n let iter: BTreeSetIterator<'_, T> = set.iter();\n let iter_state = Box::new(iter);\n PtrMut::new(Box::into_raw(iter_state) as *mut u8)\n })\n .next(|iter_ptr| {\n let state = unsafe {\n iter_ptr.as_mut::>()\n };\n state\n .next()\n .map(|value| PtrConst::new(value as *const T))\n })\n .next_back(|iter_ptr| {\n let state = unsafe {\n iter_ptr.as_mut::>()\n };\n state\n .next_back()\n .map(|value| PtrConst::new(value as *const T))\n })\n .dealloc(|iter_ptr| unsafe {\n drop(Box::from_raw(\n iter_ptr.as_ptr::>()\n as *mut BTreeSetIterator<'_, T>,\n ));\n })\n .build(),\n )\n .build()\n },\n )\n .build(),\n ))\n .build()\n };\n}\n\n#[cfg(test)]\nmod tests {\n use alloc::collections::BTreeSet;\n use alloc::string::String;\n use alloc::vec::Vec;\n\n use super::*;\n\n #[test]\n fn test_btreesetset_type_params() {\n let [type_param_1] = >::SHAPE.type_params else {\n panic!(\"BTreeSet should have 1 type param\")\n };\n assert_eq!(type_param_1.shape(), i32::SHAPE);\n }\n\n #[test]\n fn test_btreeset_vtable_1_new_insert_iter_drop() {\n facet_testhelpers::setup();\n\n let btreeset_shape = >::SHAPE;\n let btreeset_def = btreeset_shape\n .def\n .into_set()\n .expect(\"BTreeSet should have a set definition\");\n\n // Allocate memory for the BTreeSet\n let btreeset_uninit_ptr = btreeset_shape.allocate().unwrap();\n\n // Create the BTreeSet\n let btreeset_ptr =\n unsafe { (btreeset_def.vtable.init_in_place_with_capacity_fn)(btreeset_uninit_ptr, 0) };\n\n // The BTreeSet is empty, so ensure its length is 0\n let btreeset_actual_length =\n unsafe { (btreeset_def.vtable.len_fn)(btreeset_ptr.as_const()) };\n assert_eq!(btreeset_actual_length, 0);\n\n // 5 sample values to insert\n let strings = [\"foo\", \"bar\", \"bazz\", \"fizzbuzz\", \"fifth thing\"];\n\n // Insert the 5 values into the BTreeSet\n let mut btreeset_length = 0;\n for string in strings {\n // Create the value\n let mut new_value = string.to_string();\n\n // Insert the value\n let did_insert = unsafe {\n (btreeset_def.vtable.insert_fn)(btreeset_ptr, PtrMut::new(&raw mut new_value))\n };\n\n // The value now belongs to the BTreeSet, so forget it\n core::mem::forget(new_value);\n\n assert!(did_insert, \"expected value to be inserted in the BTreeSet\");\n\n // Ensure the BTreeSet's length increased by 1\n btreeset_length += 1;\n let btreeset_actual_length =\n unsafe { (btreeset_def.vtable.len_fn)(btreeset_ptr.as_const()) };\n assert_eq!(btreeset_actual_length, btreeset_length);\n }\n\n // Insert the same 5 values again, ensuring they are deduplicated\n for string in strings {\n // Create the value\n let mut new_value = string.to_string();\n\n // Try to insert the value\n let did_insert = unsafe {\n (btreeset_def.vtable.insert_fn)(btreeset_ptr, PtrMut::new(&raw mut new_value))\n };\n\n // The value now belongs to the BTreeSet, so forget it\n core::mem::forget(new_value);\n\n assert!(\n !did_insert,\n \"expected value to not be inserted in the BTreeSet\"\n );\n\n // Ensure the BTreeSet's length did not increase\n let btreeset_actual_length =\n unsafe { (btreeset_def.vtable.len_fn)(btreeset_ptr.as_const()) };\n assert_eq!(btreeset_actual_length, btreeset_length);\n }\n\n // Create a new iterator over the BTreeSet\n let iter_init_with_value_fn = btreeset_def.vtable.iter_vtable.init_with_value.unwrap();\n let btreeset_iter_ptr = unsafe { iter_init_with_value_fn(btreeset_ptr.as_const()) };\n\n // Collect all the items from the BTreeSet's iterator\n let mut iter_items = Vec::<&str>::new();\n loop {\n // Get the next item from the iterator\n let item_ptr = unsafe { (btreeset_def.vtable.iter_vtable.next)(btreeset_iter_ptr) };\n let Some(item_ptr) = item_ptr else {\n break;\n };\n\n let item = unsafe { item_ptr.get::() };\n\n // Add the item into the list of items returned from the iterator\n iter_items.push(&**item);\n }\n\n // Deallocate the iterator\n unsafe {\n (btreeset_def.vtable.iter_vtable.dealloc)(btreeset_iter_ptr);\n }\n\n // BTrees iterate in sorted order, so ensure the iterator returned\n // each item in order\n let mut strings_sorted = strings.to_vec();\n strings_sorted.sort();\n assert_eq!(iter_items, strings_sorted);\n\n // Get the function pointer for dropping the BTreeSet\n let drop_fn = (btreeset_shape.vtable.sized().unwrap().drop_in_place)()\n .expect(\"BTreeSet should have drop_in_place\");\n\n // Drop the BTreeSet in place\n unsafe { drop_fn(btreeset_ptr) };\n\n // Deallocate the memory\n unsafe { btreeset_shape.deallocate_mut(btreeset_ptr).unwrap() };\n }\n}\n"], ["/facet/facet-reflect/src/partial/tests.rs", "use facet::Facet;\nuse facet_testhelpers::test;\n\nuse super::Partial;\n\n#[cfg(not(miri))]\nmacro_rules! assert_snapshot {\n ($($tt:tt)*) => {\n insta::assert_snapshot!($($tt)*);\n };\n}\n#[cfg(miri)]\nmacro_rules! assert_snapshot {\n ($($tt:tt)*) => {\n /* no-op under miri */\n };\n}\n\n#[test]\nfn f64_uninit() {\n assert_snapshot!(Partial::alloc::().unwrap().build().unwrap_err());\n}\n\n#[test]\nfn f64_init() {\n let hv = Partial::alloc::()\n .unwrap()\n .set::(6.241)\n .unwrap()\n .build()\n .unwrap();\n assert_eq!(*hv, 6.241);\n}\n\n#[test]\nfn option_uninit() {\n assert_snapshot!(\n Partial::alloc::>()\n .unwrap()\n .build()\n .unwrap_err()\n );\n}\n\n#[test]\nfn option_init() {\n let hv = Partial::alloc::>()\n .unwrap()\n .set::>(Some(6.241))\n .unwrap()\n .build()\n .unwrap();\n assert_eq!(*hv, Some(6.241));\n}\n\n#[test]\nfn struct_fully_uninit() {\n #[derive(Facet, Debug)]\n struct FooBar {\n foo: u64,\n bar: bool,\n }\n\n assert_snapshot!(Partial::alloc::().unwrap().build().unwrap_err());\n}\n\n#[test]\nfn struct_partially_uninit() {\n #[derive(Facet, Debug)]\n struct FooBar {\n foo: u64,\n bar: bool,\n }\n\n let mut partial = Partial::alloc::().unwrap();\n assert_snapshot!(\n partial\n .set_field(\"foo\", 42_u64)\n .unwrap()\n .build()\n .unwrap_err()\n );\n}\n\n#[test]\nfn struct_fully_init() {\n #[derive(Facet, Debug, PartialEq)]\n struct FooBar {\n foo: u64,\n bar: bool,\n }\n\n let hv = Partial::alloc::()\n .unwrap()\n .set_field(\"foo\", 42u64)\n .unwrap()\n .set_field(\"bar\", true)\n .unwrap()\n .build()\n .unwrap();\n assert_eq!(hv.foo, 42u64);\n assert_eq!(hv.bar, true);\n}\n\n#[test]\nfn struct_field_set_twice() {\n use core::sync::atomic::{AtomicUsize, Ordering};\n static DROP_COUNT: AtomicUsize = AtomicUsize::new(0);\n\n #[derive(Facet, Debug)]\n struct DropTracker {\n id: u64,\n }\n\n impl Drop for DropTracker {\n fn drop(&mut self) {\n DROP_COUNT.fetch_add(1, Ordering::SeqCst);\n println!(\"Dropping DropTracker with id: {}\", self.id);\n }\n }\n\n #[derive(Facet, Debug)]\n struct Container {\n tracker: DropTracker,\n value: u64,\n }\n\n DROP_COUNT.store(0, Ordering::SeqCst);\n\n let mut partial = Partial::alloc::().unwrap();\n\n // Set tracker field first time\n partial.set_field(\"tracker\", DropTracker { id: 1 }).unwrap();\n\n assert_eq!(DROP_COUNT.load(Ordering::SeqCst), 0, \"No drops yet\");\n\n // Set tracker field second time (should drop the previous value)\n partial.set_field(\"tracker\", DropTracker { id: 2 }).unwrap();\n\n assert_eq!(\n DROP_COUNT.load(Ordering::SeqCst),\n 1,\n \"First DropTracker should have been dropped\"\n );\n\n // Set value field\n partial.set_field(\"value\", 100u64).unwrap();\n\n let container = partial.build().unwrap();\n\n assert_eq!(container.tracker.id, 2); // Should have the second value\n assert_eq!(container.value, 100);\n\n // Drop the container\n drop(container);\n\n assert_eq!(\n DROP_COUNT.load(Ordering::SeqCst),\n 2,\n \"Both DropTrackers should have been dropped\"\n );\n}\n\n#[test]\nfn array_element_set_twice() {\n use core::sync::atomic::{AtomicUsize, Ordering};\n static DROP_COUNT: AtomicUsize = AtomicUsize::new(0);\n\n #[derive(Facet, Debug)]\n struct DropTracker {\n id: u64,\n }\n\n impl Drop for DropTracker {\n fn drop(&mut self) {\n DROP_COUNT.fetch_add(1, Ordering::SeqCst);\n println!(\"Dropping DropTracker with id: {}\", self.id);\n }\n }\n\n DROP_COUNT.store(0, Ordering::SeqCst);\n\n let array = Partial::alloc::<[DropTracker; 3]>()\n .unwrap()\n // Set element 0\n .set_nth_element(0, DropTracker { id: 1 })\n .unwrap()\n // Set element 0 again - drops old value\n .set_nth_element(0, DropTracker { id: 2 })\n .unwrap()\n // Set element 1\n .set_nth_element(1, DropTracker { id: 3 })\n .unwrap()\n // Set element 2\n .set_nth_element(2, DropTracker { id: 4 })\n .unwrap()\n .build()\n .unwrap();\n\n // Verify the final array has the expected values\n assert_eq!(array[0].id, 2); // Re-initialized value\n assert_eq!(array[1].id, 3);\n assert_eq!(array[2].id, 4);\n\n // The first value (id: 1) should have been dropped when we re-initialized\n assert_eq!(\n DROP_COUNT.load(Ordering::SeqCst),\n 1,\n \"First array element should have been dropped during re-initialization\"\n );\n}\n\n#[test]\nfn set_default() {\n #[derive(Facet, Debug, PartialEq, Default)]\n struct Sample {\n x: u32,\n y: String,\n }\n\n let sample = Partial::alloc::()\n .unwrap()\n .set_default()\n .unwrap()\n .build()\n .unwrap();\n assert_eq!(*sample, Sample::default());\n assert_eq!(sample.x, 0);\n assert_eq!(sample.y, \"\");\n}\n\n#[test]\nfn set_default_no_default_impl() {\n #[derive(Facet, Debug)]\n struct NoDefault {\n value: u32,\n }\n\n let result = Partial::alloc::()\n .unwrap()\n .set_default()\n .map(|_| ());\n assert!(\n result\n .unwrap_err()\n .to_string()\n .contains(\"does not implement Default\")\n );\n}\n\n#[test]\nfn set_default_drops_previous() {\n use core::sync::atomic::{AtomicUsize, Ordering};\n static DROP_COUNT: AtomicUsize = AtomicUsize::new(0);\n\n #[derive(Facet, Debug)]\n struct DropTracker {\n id: u64,\n }\n\n impl Drop for DropTracker {\n fn drop(&mut self) {\n DROP_COUNT.fetch_add(1, Ordering::SeqCst);\n }\n }\n\n impl Default for DropTracker {\n fn default() -> Self {\n Self { id: 999 }\n }\n }\n\n DROP_COUNT.store(0, Ordering::SeqCst);\n\n let mut partial = Partial::alloc::().unwrap();\n\n // Set initial value\n partial.set(DropTracker { id: 1 }).unwrap();\n assert_eq!(DROP_COUNT.load(Ordering::SeqCst), 0);\n\n // Set default (should drop the previous value)\n partial.set_default().unwrap();\n assert_eq!(DROP_COUNT.load(Ordering::SeqCst), 1);\n\n let tracker = partial.build().unwrap();\n assert_eq!(tracker.id, 999); // Default value\n\n drop(tracker);\n assert_eq!(DROP_COUNT.load(Ordering::SeqCst), 2);\n}\n\n#[test]\nfn drop_partially_initialized_struct() {\n use core::sync::atomic::{AtomicUsize, Ordering};\n\n static DROP_COUNT: AtomicUsize = AtomicUsize::new(0);\n\n #[derive(Facet, Debug)]\n struct NoisyDrop {\n value: u64,\n }\n\n impl Drop for NoisyDrop {\n fn drop(&mut self) {\n DROP_COUNT.fetch_add(1, Ordering::SeqCst);\n println!(\"Dropping NoisyDrop with value: {}\", self.value);\n }\n }\n\n #[derive(Facet, Debug)]\n struct Container {\n first: NoisyDrop,\n second: NoisyDrop,\n third: bool,\n }\n\n // Reset counter\n DROP_COUNT.store(0, Ordering::SeqCst);\n\n // Create a partially initialized struct and drop it\n {\n let mut partial = Partial::alloc::().unwrap();\n\n // Initialize first field\n partial.begin_field(\"first\").unwrap();\n assert_eq!(DROP_COUNT.load(Ordering::SeqCst), 0, \"No drops yet\");\n\n partial.set(NoisyDrop { value: 1 }).unwrap();\n assert_eq!(\n DROP_COUNT.load(Ordering::SeqCst),\n 0,\n \"After set, the value should NOT be dropped yet\"\n );\n\n partial.end().unwrap();\n assert_eq!(\n DROP_COUNT.load(Ordering::SeqCst),\n 0,\n \"Still no drops after end\"\n );\n\n // Initialize second field\n partial.begin_field(\"second\").unwrap();\n partial.set(NoisyDrop { value: 2 }).unwrap();\n assert_eq!(\n DROP_COUNT.load(Ordering::SeqCst),\n 0,\n \"After second set, still should have no drops\"\n );\n\n partial.end().unwrap();\n\n // Don't initialize third field - just drop the partial\n // This should call drop on the two NoisyDrop instances we created\n }\n\n let final_drops = DROP_COUNT.load(Ordering::SeqCst);\n assert_eq!(\n final_drops, 2,\n \"Expected 2 drops total for the two initialized NoisyDrop fields, but got {}\",\n final_drops\n );\n}\n\n#[test]\nfn drop_nested_partially_initialized() {\n use core::sync::atomic::{AtomicUsize, Ordering};\n\n static DROP_COUNT: AtomicUsize = AtomicUsize::new(0);\n\n #[derive(Facet, Debug)]\n struct NoisyDrop {\n id: u64,\n }\n\n impl Drop for NoisyDrop {\n fn drop(&mut self) {\n DROP_COUNT.fetch_add(1, Ordering::SeqCst);\n println!(\"Dropping NoisyDrop with id: {}\", self.id);\n }\n }\n\n #[derive(Facet, Debug)]\n struct Inner {\n a: NoisyDrop,\n b: NoisyDrop,\n }\n\n #[derive(Facet, Debug)]\n struct Outer {\n inner: Inner,\n extra: NoisyDrop,\n }\n\n DROP_COUNT.store(0, Ordering::SeqCst);\n\n {\n let mut partial = Partial::alloc::().unwrap();\n\n // Start initializing inner struct\n partial.begin_field(\"inner\").unwrap();\n partial.set_field(\"a\", NoisyDrop { id: 1 }).unwrap();\n\n // Only initialize one field of inner, leave 'b' uninitialized\n // Don't end from inner\n\n // Drop without finishing initialization\n }\n\n assert_eq!(\n DROP_COUNT.load(Ordering::SeqCst),\n 1,\n \"Should drop only the one initialized NoisyDrop in the nested struct\"\n );\n}\n\n#[test]\nfn drop_with_copy_types() {\n // Test that Copy types don't cause double-drops or other issues\n #[derive(Facet, Debug)]\n struct MixedTypes {\n copyable: u64,\n droppable: String,\n more_copy: bool,\n }\n\n let mut partial = Partial::alloc::().unwrap();\n\n partial.set_field(\"copyable\", 42u64).unwrap();\n\n partial.set_field(\"droppable\", \"Hello\".to_string()).unwrap();\n\n // Drop without initializing 'more_copy'\n drop(partial);\n\n // If this doesn't panic or segfault, we're good\n}\n\n#[test]\nfn drop_fully_uninitialized() {\n use core::sync::atomic::{AtomicUsize, Ordering};\n\n static DROP_COUNT: AtomicUsize = AtomicUsize::new(0);\n\n #[derive(Facet, Debug)]\n struct NoisyDrop {\n value: u64,\n }\n\n impl Drop for NoisyDrop {\n fn drop(&mut self) {\n DROP_COUNT.fetch_add(1, Ordering::SeqCst);\n }\n }\n\n #[derive(Facet, Debug)]\n struct Container {\n a: NoisyDrop,\n b: NoisyDrop,\n }\n\n DROP_COUNT.store(0, Ordering::SeqCst);\n\n {\n let _partial = Partial::alloc::().unwrap();\n // Drop immediately without initializing anything\n }\n\n assert_eq!(\n DROP_COUNT.load(Ordering::SeqCst),\n 0,\n \"No drops should occur for completely uninitialized struct\"\n );\n}\n\n#[test]\nfn drop_after_successful_build() {\n use core::sync::atomic::{AtomicUsize, Ordering};\n\n static DROP_COUNT: AtomicUsize = AtomicUsize::new(0);\n\n #[derive(Facet, Debug)]\n struct NoisyDrop {\n value: u64,\n }\n\n impl Drop for NoisyDrop {\n fn drop(&mut self) {\n DROP_COUNT.fetch_add(1, Ordering::SeqCst);\n }\n }\n\n DROP_COUNT.store(0, Ordering::SeqCst);\n\n let hv = Partial::alloc::()\n .unwrap()\n .set(NoisyDrop { value: 42 })\n .unwrap()\n .build()\n .unwrap();\n\n assert_eq!(\n DROP_COUNT.load(Ordering::SeqCst),\n 0,\n \"No drops yet after build\"\n );\n\n drop(hv);\n\n assert_eq!(\n DROP_COUNT.load(Ordering::SeqCst),\n 1,\n \"One drop after dropping HeapValue\"\n );\n}\n\n#[test]\nfn array_init() {\n let hv = Partial::alloc::<[u32; 3]>()\n .unwrap()\n // Initialize in order\n .set_nth_element(0, 42u32)\n .unwrap()\n .set_nth_element(1, 43u32)\n .unwrap()\n .set_nth_element(2, 44u32)\n .unwrap()\n .build()\n .unwrap();\n assert_eq!(*hv, [42, 43, 44]);\n}\n\n#[test]\nfn array_init_out_of_order() {\n let hv = Partial::alloc::<[u32; 3]>()\n .unwrap()\n // Initialize out of order\n .set_nth_element(2, 44u32)\n .unwrap()\n .set_nth_element(0, 42u32)\n .unwrap()\n .set_nth_element(1, 43u32)\n .unwrap()\n .build()\n .unwrap();\n assert_eq!(*hv, [42, 43, 44]);\n}\n\n#[test]\nfn array_partial_init() {\n // Should fail to build\n assert_snapshot!(\n Partial::alloc::<[u32; 3]>()\n .unwrap()\n // Initialize only two elements\n .set_nth_element(0, 42u32)\n .unwrap()\n .set_nth_element(2, 44u32)\n .unwrap()\n .build()\n .unwrap_err()\n );\n}\n\n#[test]\nfn drop_array_partially_initialized() {\n use core::sync::atomic::{AtomicUsize, Ordering};\n\n static DROP_COUNT: AtomicUsize = AtomicUsize::new(0);\n\n #[derive(Facet, Debug)]\n struct NoisyDrop {\n value: u64,\n }\n\n impl Drop for NoisyDrop {\n fn drop(&mut self) {\n DROP_COUNT.fetch_add(1, Ordering::SeqCst);\n println!(\"Dropping NoisyDrop with value: {}\", self.value);\n }\n }\n\n DROP_COUNT.store(0, Ordering::SeqCst);\n\n {\n let mut partial = Partial::alloc::<[NoisyDrop; 4]>().unwrap();\n\n // Initialize elements 0 and 2\n partial.set_nth_element(0, NoisyDrop { value: 10 }).unwrap();\n partial.set_nth_element(2, NoisyDrop { value: 30 }).unwrap();\n\n // Drop without initializing elements 1 and 3\n }\n\n assert_eq!(\n DROP_COUNT.load(Ordering::SeqCst),\n 2,\n \"Should drop only the two initialized array elements\"\n );\n}\n\n#[test]\nfn box_init() {\n let hv = Partial::alloc::>()\n .unwrap()\n // Push into the Box to build its inner value\n .begin_smart_ptr()\n .unwrap()\n .set(42u32)\n .unwrap()\n .end()\n .unwrap()\n .build()\n .unwrap();\n assert_eq!(**hv, 42);\n}\n\n#[test]\nfn box_partial_init() {\n // Don't initialize the Box at all\n assert_snapshot!(Partial::alloc::>().unwrap().build().unwrap_err());\n}\n\n#[test]\nfn box_struct() {\n #[derive(Facet, Debug, PartialEq)]\n struct Point {\n x: f64,\n y: f64,\n }\n\n let hv = Partial::alloc::>()\n .unwrap()\n // Push into the Box\n .begin_smart_ptr()\n .unwrap()\n // Build the Point inside the Box using set_field shorthand\n .set_field(\"x\", 1.0)\n .unwrap()\n .set_field(\"y\", 2.0)\n .unwrap()\n // end from Box\n .end()\n .unwrap()\n .build()\n .unwrap();\n assert_eq!(**hv, Point { x: 1.0, y: 2.0 });\n}\n\n#[test]\nfn drop_box_partially_initialized() {\n use core::sync::atomic::{AtomicUsize, Ordering};\n static BOX_DROP_COUNT: AtomicUsize = AtomicUsize::new(0);\n static INNER_DROP_COUNT: AtomicUsize = AtomicUsize::new(0);\n\n #[derive(Facet, Debug)]\n struct DropCounter {\n value: u32,\n }\n\n impl Drop for DropCounter {\n fn drop(&mut self) {\n INNER_DROP_COUNT.fetch_add(1, Ordering::SeqCst);\n println!(\"Dropping DropCounter with value: {}\", self.value);\n }\n }\n\n BOX_DROP_COUNT.store(0, Ordering::SeqCst);\n INNER_DROP_COUNT.store(0, Ordering::SeqCst);\n\n {\n let mut partial = Partial::alloc::>().unwrap();\n\n // Initialize the Box's inner value using set\n partial.begin_smart_ptr().unwrap();\n partial.set(DropCounter { value: 99 }).unwrap();\n partial.end().unwrap();\n\n // Drop the partial - should drop the Box which drops the inner value\n }\n\n assert_eq!(\n INNER_DROP_COUNT.load(Ordering::SeqCst),\n 1,\n \"Should drop the inner value through Box's drop\"\n );\n}\n\n#[test]\nfn arc_init() {\n use alloc::sync::Arc;\n\n let hv = Partial::alloc::>()\n .unwrap()\n // Push into the Arc to build its inner value\n .begin_smart_ptr()\n .unwrap()\n .set(42u32)\n .unwrap()\n .end()\n .unwrap()\n .build()\n .unwrap();\n assert_eq!(**hv, 42);\n}\n\n#[test]\nfn arc_partial_init() {\n use alloc::sync::Arc;\n\n // Don't initialize the Arc at all\n assert_snapshot!(Partial::alloc::>().unwrap().build().unwrap_err());\n}\n\n#[test]\nfn arc_struct() {\n use alloc::sync::Arc;\n\n #[derive(Facet, Debug, PartialEq)]\n struct Point {\n x: f64,\n y: f64,\n }\n\n let hv = Partial::alloc::>()\n .unwrap()\n // Push into the Arc\n .begin_smart_ptr()\n .unwrap()\n // Build the Point inside the Arc using set_field shorthand\n .set_field(\"x\", 3.0)\n .unwrap()\n .set_field(\"y\", 4.0)\n .unwrap()\n // end from Arc\n .end()\n .unwrap()\n .build()\n .unwrap();\n assert_eq!(**hv, Point { x: 3.0, y: 4.0 });\n}\n\n#[test]\nfn drop_arc_partially_initialized() {\n use alloc::sync::Arc;\n use core::sync::atomic::{AtomicUsize, Ordering};\n static INNER_DROP_COUNT: AtomicUsize = AtomicUsize::new(0);\n\n #[derive(Facet, Debug)]\n struct DropCounter {\n value: u32,\n }\n\n impl Drop for DropCounter {\n fn drop(&mut self) {\n INNER_DROP_COUNT.fetch_add(1, Ordering::SeqCst);\n println!(\"Dropping DropCounter with value: {}\", self.value);\n }\n }\n\n INNER_DROP_COUNT.store(0, Ordering::SeqCst);\n\n {\n let mut partial = Partial::alloc::>().unwrap();\n\n // Initialize the Arc's inner value\n partial.begin_smart_ptr().unwrap();\n partial.set(DropCounter { value: 123 }).unwrap();\n partial.end().unwrap();\n\n // Drop the partial - should drop the Arc which drops the inner value\n }\n\n assert_eq!(\n INNER_DROP_COUNT.load(Ordering::SeqCst),\n 1,\n \"Should drop the inner value through Arc's drop\"\n );\n}\n\n#[test]\nfn enum_unit_variant() {\n #[derive(Facet, Debug, PartialEq)]\n #[repr(u8)]\n #[allow(dead_code)]\n enum Status {\n Active = 0,\n Inactive = 1,\n Pending = 2,\n }\n\n let hv = Partial::alloc::()\n .unwrap()\n .select_variant(1)\n .unwrap() // Inactive\n .build()\n .unwrap();\n assert_eq!(*hv, Status::Inactive);\n}\n\n#[test]\nfn enum_struct_variant() {\n #[derive(Facet, Debug, PartialEq)]\n #[repr(u8)]\n #[allow(dead_code)]\n enum Message {\n Text { content: String } = 0,\n Number { value: i32 } = 1,\n Empty = 2,\n }\n\n let hv = Partial::alloc::()\n .unwrap()\n .select_variant(0)\n .unwrap() // Text variant\n .set_field(\"content\", \"Hello, world!\".to_string())\n .unwrap()\n .build()\n .unwrap();\n assert_eq!(\n *hv,\n Message::Text {\n content: \"Hello, world!\".to_string()\n }\n );\n}\n\n#[test]\nfn enum_tuple_variant() {\n #[derive(Facet, Debug, PartialEq)]\n #[repr(i32)]\n #[allow(dead_code)]\n enum Value {\n Int(i32) = 0,\n Float(f64) = 1,\n Pair(i32, String) = 2,\n }\n\n let hv = Partial::alloc::()\n .unwrap()\n .select_variant(2)\n .unwrap() // Pair variant\n .set_nth_enum_field(0, 42)\n .unwrap()\n .set_nth_enum_field(1, \"test\".to_string())\n .unwrap()\n .build()\n .unwrap();\n assert_eq!(*hv, Value::Pair(42, \"test\".to_string()));\n}\n\n#[test]\nfn enum_set_field_twice() {\n #[derive(Facet, Debug, PartialEq)]\n #[repr(u16)]\n enum Data {\n Point { x: f32, y: f32 } = 0,\n }\n\n let hv = Partial::alloc::()\n .unwrap()\n .select_variant(0)\n .unwrap() // Point variant\n // Set x field\n .set_field(\"x\", 1.0f32)\n .unwrap()\n // Set x field again (should drop previous value)\n .set_field(\"x\", 2.0f32)\n .unwrap()\n // Set y field\n .set_field(\"y\", 3.0f32)\n .unwrap()\n .build()\n .unwrap();\n assert_eq!(*hv, Data::Point { x: 2.0, y: 3.0 });\n}\n\n#[test]\nfn enum_partial_initialization_error() {\n #[derive(Facet, Debug)]\n #[repr(u8)]\n #[allow(dead_code)]\n enum Config {\n Settings { timeout: u32, retries: u8 } = 0,\n }\n\n // Should fail to build because retries is not initialized\n let result = Partial::alloc::()\n .unwrap()\n .select_variant(0)\n .unwrap() // Settings variant\n // Only initialize timeout, not retries\n .set_field(\"timeout\", 5000u32)\n .unwrap()\n .build();\n assert!(result.is_err());\n}\n\n#[test]\nfn enum_select_nth_variant() {\n #[derive(Facet, Debug, PartialEq)]\n #[repr(u8)]\n #[allow(dead_code)]\n enum Status {\n Active = 0,\n Inactive = 1,\n Pending = 2,\n }\n\n // Test selecting variant by index (0-based)\n let hv = Partial::alloc::()\n .unwrap()\n .select_nth_variant(1)\n .unwrap() // Inactive (index 1)\n .build()\n .unwrap();\n assert_eq!(*hv, Status::Inactive);\n\n // Test selecting different variant by index\n let hv2 = Partial::alloc::()\n .unwrap()\n .select_nth_variant(2)\n .unwrap() // Pending (index 2)\n .build()\n .unwrap();\n assert_eq!(*hv2, Status::Pending);\n}\n\n#[test]\nfn empty_struct_init() {\n #[derive(Facet, Debug, PartialEq)]\n struct EmptyStruct {}\n\n // Test that we can build an empty struct without setting any fields\n let hv = Partial::alloc::().unwrap().build().unwrap();\n assert_eq!(*hv, EmptyStruct {});\n}\n\n#[test]\nfn list_vec_basic() {\n let hv = Partial::alloc::>()\n .unwrap()\n .begin_list()\n .unwrap()\n .push(42)\n .unwrap()\n .push(84)\n .unwrap()\n .push(126)\n .unwrap()\n .build()\n .unwrap();\n let vec: &Vec = hv.as_ref();\n assert_eq!(vec, &vec![42, 84, 126]);\n}\n\n#[test]\nfn list_vec_complex() {\n #[derive(Debug, PartialEq, Clone, Facet)]\n struct Person {\n name: String,\n age: u32,\n }\n\n let hv = Partial::alloc::>()\n .unwrap()\n .begin_list()\n .unwrap()\n // Push first person\n .begin_list_item()\n .unwrap()\n .set_field(\"name\", \"Alice\".to_string())\n .unwrap()\n .set_field(\"age\", 30u32)\n .unwrap()\n .end()\n .unwrap() // Done with first person\n // Push second person\n .begin_list_item()\n .unwrap()\n .set_field(\"name\", \"Bob\".to_string())\n .unwrap()\n .set_field(\"age\", 25u32)\n .unwrap()\n .end()\n .unwrap() // Done with second person\n .build()\n .unwrap();\n let vec: &Vec = hv.as_ref();\n assert_eq!(\n vec,\n &vec![\n Person {\n name: \"Alice\".to_string(),\n age: 30\n },\n Person {\n name: \"Bob\".to_string(),\n age: 25\n }\n ]\n );\n}\n\n#[test]\nfn list_vec_empty() {\n let hv = Partial::alloc::>()\n .unwrap()\n .begin_list()\n .unwrap()\n // Don't push any elements\n .build()\n .unwrap();\n let vec: &Vec = hv.as_ref();\n assert_eq!(vec, &Vec::::new());\n}\n\n#[test]\nfn list_vec_nested() {\n let hv = Partial::alloc::>>()\n .unwrap()\n .begin_list()\n .unwrap()\n // Push first inner vec\n .begin_list_item()\n .unwrap()\n .begin_list()\n .unwrap()\n .push(1)\n .unwrap()\n .push(2)\n .unwrap()\n .end()\n .unwrap() // Done with first inner vec\n // Push second inner vec\n .begin_list_item()\n .unwrap()\n .begin_list()\n .unwrap()\n .push(3)\n .unwrap()\n .push(4)\n .unwrap()\n .push(5)\n .unwrap()\n .end()\n .unwrap() // Done with second inner vec\n .build()\n .unwrap();\n let vec: &Vec> = hv.as_ref();\n assert_eq!(vec, &vec![vec![1, 2], vec![3, 4, 5]]);\n}\n\n#[test]\nfn map_hashmap_simple() {\n use std::collections::HashMap;\n\n let hv = Partial::alloc::>()\n .unwrap()\n .begin_map()\n .unwrap()\n // Insert first pair: \"foo\" -> 42\n .begin_key()\n .unwrap()\n .set(\"foo\".to_string())\n .unwrap()\n .end()\n .unwrap()\n .begin_value()\n .unwrap()\n .set(42)\n .unwrap()\n .end()\n .unwrap()\n // Insert second pair: \"bar\" -> 123\n .begin_key()\n .unwrap()\n .set(\"bar\".to_string())\n .unwrap()\n .end()\n .unwrap()\n .begin_value()\n .unwrap()\n .set(123)\n .unwrap()\n .end()\n .unwrap()\n .build()\n .unwrap();\n let map: &HashMap = hv.as_ref();\n assert_eq!(map.len(), 2);\n assert_eq!(map.get(\"foo\"), Some(&42));\n assert_eq!(map.get(\"bar\"), Some(&123));\n}\n\n#[test]\nfn map_hashmap_empty() {\n use std::collections::HashMap;\n\n let hv = Partial::alloc::>()\n .unwrap()\n .begin_map()\n .unwrap()\n // Don't insert any pairs\n .build()\n .unwrap();\n let map: &HashMap = hv.as_ref();\n assert_eq!(map.len(), 0);\n}\n\n#[test]\nfn map_hashmap_complex_values() {\n use std::collections::HashMap;\n\n #[derive(Facet, Debug, PartialEq)]\n struct Person {\n name: String,\n age: u32,\n }\n\n let hv = Partial::alloc::>()\n .unwrap()\n .begin_map()\n .unwrap()\n // Insert \"alice\" -> Person { name: \"Alice\", age: 30 }\n .set_key(\"alice\".to_string())\n .unwrap()\n .begin_value()\n .unwrap()\n .set_field(\"name\", \"Alice\".to_string())\n .unwrap()\n .set_field(\"age\", 30u32)\n .unwrap()\n .end()\n .unwrap() // Done with value\n // Insert \"bob\" -> Person { name: \"Bob\", age: 25 }\n .set_key(\"bob\".to_string())\n .unwrap()\n .begin_value()\n .unwrap()\n .set_field(\"name\", \"Bob\".to_string())\n .unwrap()\n .set_field(\"age\", 25u32)\n .unwrap()\n .end()\n .unwrap() // Done with value\n .build()\n .unwrap();\n let map: &HashMap = hv.as_ref();\n assert_eq!(map.len(), 2);\n assert_eq!(\n map.get(\"alice\"),\n Some(&Person {\n name: \"Alice\".to_string(),\n age: 30\n })\n );\n assert_eq!(\n map.get(\"bob\"),\n Some(&Person {\n name: \"Bob\".to_string(),\n age: 25\n })\n );\n}\n\n#[test]\nfn variant_named() {\n #[derive(Facet, Debug, PartialEq)]\n #[repr(u8)]\n enum Animal {\n Dog { name: String, age: u8 } = 0,\n Cat { name: String, lives: u8 } = 1,\n Bird { species: String } = 2,\n }\n\n // Test Dog variant\n let animal = Partial::alloc::()\n .unwrap()\n .select_variant_named(\"Dog\")\n .unwrap()\n .set_field(\"name\", \"Buddy\".to_string())\n .unwrap()\n .set_field(\"age\", 5u8)\n .unwrap()\n .build()\n .unwrap();\n assert_eq!(\n *animal,\n Animal::Dog {\n name: \"Buddy\".to_string(),\n age: 5\n }\n );\n\n // Test Cat variant\n let animal = Partial::alloc::()\n .unwrap()\n .select_variant_named(\"Cat\")\n .unwrap()\n .set_field(\"name\", \"Whiskers\".to_string())\n .unwrap()\n .set_field(\"lives\", 9u8)\n .unwrap()\n .build()\n .unwrap();\n assert_eq!(\n *animal,\n Animal::Cat {\n name: \"Whiskers\".to_string(),\n lives: 9\n }\n );\n\n // Test Bird variant\n let animal = Partial::alloc::()\n .unwrap()\n .select_variant_named(\"Bird\")\n .unwrap()\n .set_field(\"species\", \"Parrot\".to_string())\n .unwrap()\n .build()\n .unwrap();\n assert_eq!(\n *animal,\n Animal::Bird {\n species: \"Parrot\".to_string()\n }\n );\n\n // Test invalid variant name\n let mut partial = Partial::alloc::().unwrap();\n let result = partial.select_variant_named(\"Fish\");\n assert!(result.is_err());\n assert!(\n result\n .unwrap_err()\n .to_string()\n .contains(\"No variant found with the given name\")\n );\n}\n\n#[test]\nfn field_named_on_struct() {\n #[derive(Facet, Debug, PartialEq)]\n struct Person {\n name: String,\n age: u32,\n email: String,\n }\n\n let person = Partial::alloc::()\n .unwrap()\n // Use field names instead of indices\n .begin_field(\"email\")\n .unwrap()\n .set(\"john@example.com\".to_string())\n .unwrap()\n .end()\n .unwrap()\n .begin_field(\"name\")\n .unwrap()\n .set(\"John Doe\".to_string())\n .unwrap()\n .end()\n .unwrap()\n .begin_field(\"age\")\n .unwrap()\n .set(30u32)\n .unwrap()\n .end()\n .unwrap()\n .build()\n .unwrap();\n assert_eq!(\n *person,\n Person {\n name: \"John Doe\".to_string(),\n age: 30,\n email: \"john@example.com\".to_string(),\n }\n );\n\n // Test invalid field name\n let mut partial = Partial::alloc::().unwrap();\n let result = partial.begin_field(\"invalid_field\");\n assert!(result.is_err());\n assert!(result.unwrap_err().to_string().contains(\"field not found\"));\n}\n\n#[test]\nfn field_named_on_enum() {\n #[derive(Facet, Debug, PartialEq)]\n #[repr(u8)]\n #[allow(dead_code)]\n enum Config {\n Server { host: String, port: u16, tls: bool } = 0,\n Client { url: String, timeout: u32 } = 1,\n }\n\n // Test field access on Server variant\n let config = Partial::alloc::()\n .unwrap()\n .select_variant_named(\"Server\")\n .unwrap()\n .set_field(\"port\", 8080u16)\n .unwrap()\n .set_field(\"host\", \"localhost\".to_string())\n .unwrap()\n .set_field(\"tls\", true)\n .unwrap()\n .build()\n .unwrap();\n assert_eq!(\n *config,\n Config::Server {\n host: \"localhost\".to_string(),\n port: 8080,\n tls: true,\n }\n );\n\n // Test invalid field name on enum variant\n\n let mut partial = Partial::alloc::().unwrap();\n partial.select_variant_named(\"Client\").unwrap();\n let result = partial.begin_field(\"port\"); // port doesn't exist on Client\n assert!(result.is_err());\n assert!(\n result\n .unwrap_err()\n .to_string()\n .contains(\"field not found in current enum variant\")\n );\n}\n\n#[test]\nfn map_partial_initialization_drop() {\n use core::sync::atomic::{AtomicUsize, Ordering};\n use std::collections::HashMap;\n static DROP_COUNT: AtomicUsize = AtomicUsize::new(0);\n\n #[derive(Facet, Debug)]\n struct DropTracker {\n id: u64,\n }\n\n impl Drop for DropTracker {\n fn drop(&mut self) {\n DROP_COUNT.fetch_add(1, Ordering::SeqCst);\n println!(\"Dropping DropTracker with id: {}\", self.id);\n }\n }\n\n DROP_COUNT.store(0, Ordering::SeqCst);\n\n {\n let mut partial = Partial::alloc::>().unwrap();\n partial\n .begin_map()\n .unwrap()\n // Insert a complete pair\n .begin_key()\n .unwrap()\n .set(\"first\".to_string())\n .unwrap()\n .end()\n .unwrap()\n .begin_value()\n .unwrap()\n .set(DropTracker { id: 1 })\n .unwrap()\n .end()\n .unwrap()\n // Start inserting another pair but only complete the key\n .begin_key()\n .unwrap()\n .set(\"second\".to_string())\n .unwrap()\n .end()\n .unwrap();\n // Don't set_value - leave incomplete\n\n // Drop the partial - should clean up properly\n }\n\n assert_eq!(\n DROP_COUNT.load(Ordering::SeqCst),\n 1,\n \"Should drop the one inserted value\"\n );\n}\n\n#[test]\nfn tuple_basic() {\n // Test building a simple tuple\n let boxed = Partial::alloc::<(i32, String)>()\n .unwrap()\n .set_nth_field(0, 42i32)\n .unwrap()\n .set_nth_field(1, \"hello\".to_string())\n .unwrap()\n .build()\n .unwrap();\n assert_eq!(*boxed, (42, \"hello\".to_string()));\n}\n\n#[test]\nfn tuple_mixed_types() {\n // Test building a tuple with more diverse types\n let boxed = Partial::alloc::<(u8, bool, f64, String)>()\n .unwrap()\n // Set fields in non-sequential order to test flexibility\n .set_nth_field(2, 56.124f64)\n .unwrap()\n .set_nth_field(0, 255u8)\n .unwrap()\n .set_nth_field(3, \"world\".to_string())\n .unwrap()\n .set_nth_field(1, true)\n .unwrap()\n .build()\n .unwrap();\n assert_eq!(*boxed, (255u8, true, 56.124f64, \"world\".to_string()));\n}\n\n#[test]\nfn tuple_nested() {\n // Test nested tuples\n let boxed = Partial::alloc::<((i32, i32), String)>()\n .unwrap()\n // Build the nested tuple first\n .begin_nth_field(0)\n .unwrap()\n .set_nth_field(0, 1i32)\n .unwrap()\n .set_nth_field(1, 2i32)\n .unwrap()\n .end()\n .unwrap() // Pop out of the nested tuple\n // Now set the string\n .set_nth_field(1, \"nested\".to_string())\n .unwrap()\n .build()\n .unwrap();\n assert_eq!(*boxed, ((1, 2), \"nested\".to_string()));\n}\n\n#[test]\nfn tuple_empty() {\n // Test empty tuple (unit type)\n let boxed = Partial::alloc::<()>()\n .unwrap()\n .set(())\n .unwrap()\n .build()\n .unwrap();\n assert_eq!(*boxed, ());\n}\n"], ["/facet/facet-core/src/impls_std/hashset.rs", "use core::hash::BuildHasher;\nuse std::collections::HashSet;\n\nuse crate::ptr::{PtrConst, PtrMut};\n\nuse crate::{\n Def, Facet, IterVTable, MarkerTraits, SetDef, SetVTable, Shape, Type, TypeParam, UserType,\n ValueVTable,\n};\n\ntype HashSetIterator<'mem, T> = std::collections::hash_set::Iter<'mem, T>;\n\nunsafe impl<'a, T, S> Facet<'a> for HashSet\nwhere\n T: Facet<'a> + core::cmp::Eq + core::hash::Hash,\n S: Facet<'a> + Default + BuildHasher,\n{\n const VTABLE: &'static ValueVTable = &const {\n ValueVTable::builder::()\n .marker_traits(|| {\n MarkerTraits::SEND\n .union(MarkerTraits::SYNC)\n .union(MarkerTraits::EQ)\n .union(MarkerTraits::UNPIN)\n .intersection(T::SHAPE.vtable.marker_traits())\n })\n .type_name(|f, opts| {\n if let Some(opts) = opts.for_children() {\n write!(f, \"{}<\", Self::SHAPE.type_identifier)?;\n (T::SHAPE.vtable.type_name())(f, opts)?;\n write!(f, \">\")\n } else {\n write!(f, \"HashSet<⋯>\")\n }\n })\n .default_in_place(|| Some(|target| unsafe { target.put(Self::default()) }))\n .build()\n };\n\n const SHAPE: &'static Shape = &const {\n Shape::builder_for_sized::()\n .type_identifier(\"HashSet\")\n .type_params(&[\n TypeParam {\n name: \"T\",\n shape: || T::SHAPE,\n },\n TypeParam {\n name: \"S\",\n shape: || S::SHAPE,\n },\n ])\n .ty(Type::User(UserType::Opaque))\n .def(Def::Set(\n SetDef::builder()\n .t(|| T::SHAPE)\n .vtable(\n &const {\n SetVTable::builder()\n .init_in_place_with_capacity(|uninit, capacity| unsafe {\n uninit\n .put(Self::with_capacity_and_hasher(capacity, S::default()))\n })\n .insert(|ptr, item| unsafe {\n let set = ptr.as_mut::>();\n let item = item.read::();\n set.insert(item)\n })\n .len(|ptr| unsafe {\n let set = ptr.get::>();\n set.len()\n })\n .contains(|ptr, item| unsafe {\n let set = ptr.get::>();\n set.contains(item.get())\n })\n .iter_vtable(\n IterVTable::builder()\n .init_with_value(|ptr| unsafe {\n let set = ptr.get::>();\n let iter: HashSetIterator<'_, T> = set.iter();\n let iter_state = Box::new(iter);\n PtrMut::new(Box::into_raw(iter_state) as *mut u8)\n })\n .next(|iter_ptr| unsafe {\n let state = iter_ptr.as_mut::>();\n state.next().map(|value| PtrConst::new(value))\n })\n .dealloc(|iter_ptr| unsafe {\n drop(Box::from_raw(\n iter_ptr.as_ptr::>()\n as *mut HashSetIterator<'_, T>,\n ));\n })\n .build(),\n )\n .build()\n },\n )\n .build(),\n ))\n .build()\n };\n}\n\n#[cfg(test)]\nmod tests {\n use alloc::string::String;\n use std::collections::HashSet;\n use std::hash::RandomState;\n\n use super::*;\n\n #[test]\n fn test_hashset_type_params() {\n // HashSet should have a type param for both its value type\n // and its hasher state\n let [type_param_1, type_param_2] = >::SHAPE.type_params else {\n panic!(\"HashSet should have 2 type params\")\n };\n assert_eq!(type_param_1.shape(), i32::SHAPE);\n assert_eq!(type_param_2.shape(), RandomState::SHAPE);\n }\n\n #[test]\n fn test_hashset_vtable_1_new_insert_iter_drop() {\n facet_testhelpers::setup();\n\n let hashset_shape = >::SHAPE;\n let hashset_def = hashset_shape\n .def\n .into_set()\n .expect(\"HashSet should have a set definition\");\n\n // Allocate memory for the HashSet\n let hashset_uninit_ptr = hashset_shape.allocate().unwrap();\n\n // Create the HashSet with a capacity of 3\n let hashset_ptr =\n unsafe { (hashset_def.vtable.init_in_place_with_capacity_fn)(hashset_uninit_ptr, 3) };\n\n // The HashSet is empty, so ensure its length is 0\n let hashset_actual_length = unsafe { (hashset_def.vtable.len_fn)(hashset_ptr.as_const()) };\n assert_eq!(hashset_actual_length, 0);\n\n // 5 sample values to insert\n let strings = [\"foo\", \"bar\", \"bazz\", \"fizzbuzz\", \"fifth thing\"];\n\n // Insert the 5 values into the HashSet\n let mut hashset_length = 0;\n for string in strings {\n // Create the value\n let mut new_value = string.to_string();\n\n // Insert the value\n let did_insert = unsafe {\n (hashset_def.vtable.insert_fn)(hashset_ptr, PtrMut::new(&raw mut new_value))\n };\n\n // The value now belongs to the HashSet, so forget it\n core::mem::forget(new_value);\n\n assert!(did_insert, \"expected value to be inserted in the HashSet\");\n\n // Ensure the HashSet's length increased by 1\n hashset_length += 1;\n let hashset_actual_length =\n unsafe { (hashset_def.vtable.len_fn)(hashset_ptr.as_const()) };\n assert_eq!(hashset_actual_length, hashset_length);\n }\n\n // Insert the same 5 values again, ensuring they are deduplicated\n for string in strings {\n // Create the value\n let mut new_value = string.to_string();\n\n // Try to insert the value\n let did_insert = unsafe {\n (hashset_def.vtable.insert_fn)(hashset_ptr, PtrMut::new(&raw mut new_value))\n };\n\n // The value now belongs to the HashSet, so forget it\n core::mem::forget(new_value);\n\n assert!(\n !did_insert,\n \"expected value to not be inserted in the HashSet\"\n );\n\n // Ensure the HashSet's length did not increase\n let hashset_actual_length =\n unsafe { (hashset_def.vtable.len_fn)(hashset_ptr.as_const()) };\n assert_eq!(hashset_actual_length, hashset_length);\n }\n\n // Create a new iterator over the HashSet\n let iter_init_with_value_fn = hashset_def.vtable.iter_vtable.init_with_value.unwrap();\n let hashset_iter_ptr = unsafe { iter_init_with_value_fn(hashset_ptr.as_const()) };\n\n // Collect all the items from the HashSet's iterator\n let mut iter_items = HashSet::<&str>::new();\n loop {\n // Get the next item from the iterator\n let item_ptr = unsafe { (hashset_def.vtable.iter_vtable.next)(hashset_iter_ptr) };\n let Some(item_ptr) = item_ptr else {\n break;\n };\n\n let item = unsafe { item_ptr.get::() };\n\n // Insert the item into the set of items returned from the iterator\n let did_insert = iter_items.insert(&**item);\n\n assert!(did_insert, \"HashSet iterator returned duplicate item\");\n }\n\n // Deallocate the iterator\n unsafe {\n (hashset_def.vtable.iter_vtable.dealloc)(hashset_iter_ptr);\n }\n\n // Ensure the iterator returned all of the strings\n assert_eq!(iter_items, strings.iter().copied().collect::>());\n\n // Get the function pointer for dropping the HashSet\n let drop_fn = (hashset_shape.vtable.sized().unwrap().drop_in_place)()\n .expect(\"HashSet should have drop_in_place\");\n\n // Drop the HashSet in place\n unsafe { drop_fn(hashset_ptr) };\n\n // Deallocate the memory\n unsafe { hashset_shape.deallocate_mut(hashset_ptr).unwrap() };\n }\n}\n"], ["/facet/facet-reflect/src/partial/mod.rs", "//! Partial value construction for dynamic reflection\n//!\n//! This module provides APIs for incrementally building values through reflection,\n//! particularly useful when deserializing data from external formats like JSON or YAML.\n//!\n//! # Overview\n//!\n//! The `Partial` type (formerly known as `Wip` - Work In Progress) allows you to:\n//! - Allocate memory for a value based on its `Shape`\n//! - Initialize fields incrementally in a type-safe manner\n//! - Handle complex nested structures including structs, enums, collections, and smart pointers\n//! - Build the final value once all required fields are initialized\n//!\n//! # Basic Usage\n//!\n//! ```no_run\n//! # use facet_reflect::Partial;\n//! # use facet_core::{Shape, Facet};\n//! # fn example>() -> Result<(), Box> {\n//! // Allocate memory for a struct\n//! let mut partial = Partial::alloc::()?;\n//!\n//! // Set simple fields\n//! partial.set_field(\"name\", \"Alice\")?;\n//! partial.set_field(\"age\", 30u32)?;\n//!\n//! // Work with nested structures\n//! partial.begin_field(\"address\")?;\n//! partial.set_field(\"street\", \"123 Main St\")?;\n//! partial.set_field(\"city\", \"Springfield\")?;\n//! partial.end()?;\n//!\n//! // Build the final value\n//! let value = partial.build()?;\n//! # Ok(())\n//! # }\n//! ```\n//!\n//! # Chaining Style\n//!\n//! The API supports method chaining for cleaner code:\n//!\n//! ```no_run\n//! # use facet_reflect::Partial;\n//! # use facet_core::{Shape, Facet};\n//! # fn example>() -> Result<(), Box> {\n//! let value = Partial::alloc::()?\n//! .set_field(\"name\", \"Bob\")?\n//! .begin_field(\"scores\")?\n//! .set(vec![95, 87, 92])?\n//! .end()?\n//! .build()?;\n//! # Ok(())\n//! # }\n//! ```\n//!\n//! # Working with Collections\n//!\n//! ```no_run\n//! # use facet_reflect::Partial;\n//! # use facet_core::{Shape, Facet};\n//! # fn example() -> Result<(), Box> {\n//! let mut partial = Partial::alloc::>()?;\n//!\n//! // Add items to a list\n//! partial.begin_list_item()?;\n//! partial.set(\"first\")?;\n//! partial.end()?;\n//!\n//! partial.begin_list_item()?;\n//! partial.set(\"second\")?;\n//! partial.end()?;\n//!\n//! let vec = partial.build()?;\n//! # Ok(())\n//! # }\n//! ```\n//!\n//! # Working with Maps\n//!\n//! ```no_run\n//! # use facet_reflect::Partial;\n//! # use facet_core::{Shape, Facet};\n//! # use std::collections::HashMap;\n//! # fn example() -> Result<(), Box> {\n//! let mut partial = Partial::alloc::>()?;\n//!\n//! // Insert key-value pairs\n//! partial.begin_key()?;\n//! partial.set(\"score\")?;\n//! partial.end()?;\n//! partial.begin_value()?;\n//! partial.set(100i32)?;\n//! partial.end()?;\n//!\n//! let map = partial.build()?;\n//! # Ok(())\n//! # }\n//! ```\n//!\n//! # Safety and Memory Management\n//!\n//! The `Partial` type ensures memory safety by:\n//! - Tracking initialization state of all fields\n//! - Preventing use-after-build through state tracking\n//! - Properly handling drop semantics for partially initialized values\n//! - Supporting both owned and borrowed values through lifetime parameters\n\n#[cfg(test)]\nmod tests;\n\nuse alloc::boxed::Box;\nuse alloc::format;\nuse alloc::string::{String, ToString};\nuse alloc::vec;\n\nmod iset;\n\nuse crate::{Peek, ReflectError, trace};\nuse facet_core::{DefaultInPlaceFn, SequenceType};\n\nuse core::marker::PhantomData;\n\nmod heap_value;\nuse alloc::vec::Vec;\npub use heap_value::*;\n\nuse facet_core::{\n Def, EnumRepr, Facet, KnownPointer, PtrConst, PtrMut, PtrUninit, Shape, SliceBuilderVTable,\n Type, UserType, Variant,\n};\nuse iset::ISet;\n\n/// State of a partial value\n#[derive(Debug, Clone, Copy, PartialEq, Eq)]\nenum PartialState {\n /// Partial is active and can be modified\n Active,\n /// Partial has been successfully built and cannot be reused\n Built,\n /// Building failed and Partial is poisoned\n BuildFailed,\n}\n\n/// A work-in-progress heap-allocated value\n///\n/// # Lifetimes\n///\n/// * `'facet`: The lifetime of borrowed values within the structure (or 'static if it's owned)\n/// * `'shape`: The lifetime of the Shape structure itself (often 'static)\npub struct Partial<'facet> {\n /// stack of frames to keep track of deeply nested initialization\n frames: Vec,\n\n /// current state of the Partial\n state: PartialState,\n\n invariant: PhantomData &'facet ()>,\n}\n\n#[derive(Clone, Copy, Debug)]\nenum MapInsertState {\n /// Not currently inserting\n Idle,\n /// Pushing key\n PushingKey {\n /// Temporary storage for the key being built\n key_ptr: Option>,\n },\n /// Pushing value after key is done\n PushingValue {\n /// Temporary storage for the key that was built\n key_ptr: PtrUninit<'static>,\n /// Temporary storage for the value being built\n value_ptr: Option>,\n },\n}\n\n#[derive(Debug)]\nenum FrameOwnership {\n /// This frame owns the allocation and should deallocate it on drop\n Owned,\n /// This frame is a field pointer into a parent allocation\n Field,\n /// This frame's allocation is managed elsewhere (e.g., in MapInsertState)\n ManagedElsewhere,\n}\n\nstruct Frame {\n /// Address of the value being initialized\n data: PtrUninit<'static>,\n\n /// Shape of the value being initialized\n shape: &'static Shape,\n\n /// Tracks initialized fields\n tracker: Tracker,\n\n /// Whether this frame owns the allocation or is just a field pointer\n ownership: FrameOwnership,\n}\n\n#[derive(Debug)]\nenum Tracker {\n /// Wholly uninitialized\n Uninit,\n\n /// Wholly initialized\n Init,\n\n /// Partially initialized array\n Array {\n /// Track which array elements are initialized (up to 63 elements)\n iset: ISet,\n /// If we're pushing another frame, this is set to the array index\n current_child: Option,\n },\n\n /// Partially initialized struct/tuple-struct etc.\n Struct {\n /// fields need to be individually tracked — we only\n /// support up to 63 fields.\n iset: ISet,\n\n /// if we're pushing another frame, this is set to the\n /// index of the struct field\n current_child: Option,\n },\n\n /// Smart pointer being initialized\n SmartPointer {\n /// Whether the inner value has been initialized\n is_initialized: bool,\n },\n\n /// We're initializing an `Arc`, `Box`, `Rc`, etc.\n ///\n /// We expect `set` with a `String`\n SmartPointerStr,\n\n /// We're initializing an `Arc<[T]>`, `Box<[T]>`, `Rc<[T]>`, etc.\n ///\n /// We're using the slice builder API to construct the slice\n SmartPointerSlice {\n /// The slice builder vtable\n vtable: &'static SliceBuilderVTable,\n /// Whether we're currently building an item to push\n building_item: bool,\n },\n\n /// Partially initialized enum (but we picked a variant)\n Enum {\n variant: &'static Variant,\n data: ISet,\n /// If we're pushing another frame, this is set to the field index\n current_child: Option,\n },\n\n /// Partially initialized list (Vec, etc.)\n List {\n /// The list has been initialized with capacity\n is_initialized: bool,\n /// If we're pushing another frame for an element\n current_child: bool,\n },\n\n /// Partially initialized map (HashMap, BTreeMap, etc.)\n Map {\n /// The map has been initialized with capacity\n is_initialized: bool,\n /// State of the current insertion operation\n insert_state: MapInsertState,\n },\n\n /// Option being initialized with Some(inner_value)\n Option {\n /// Whether we're currently building the inner value\n building_inner: bool,\n },\n}\n\nimpl Frame {\n fn new(data: PtrUninit<'static>, shape: &'static Shape, ownership: FrameOwnership) -> Self {\n // For empty structs (structs with 0 fields), start as Init since there's nothing to initialize\n // This includes empty tuples () which are zero-sized types with no fields to initialize\n let tracker = match shape.ty {\n Type::User(UserType::Struct(struct_type)) if struct_type.fields.is_empty() => {\n Tracker::Init\n }\n _ => Tracker::Uninit,\n };\n\n Self {\n data,\n shape,\n tracker,\n ownership,\n }\n }\n\n /// Returns an error if the value is not fully initialized\n fn require_full_initialization(&self) -> Result<(), ReflectError> {\n match self.tracker {\n Tracker::Uninit => Err(ReflectError::UninitializedValue { shape: self.shape }),\n Tracker::Init => Ok(()),\n Tracker::Array { iset, .. } => {\n match self.shape.ty {\n Type::Sequence(facet_core::SequenceType::Array(array_def)) => {\n // Check if all array elements are initialized\n if (0..array_def.n).all(|idx| iset.get(idx)) {\n Ok(())\n } else {\n Err(ReflectError::UninitializedValue { shape: self.shape })\n }\n }\n _ => Err(ReflectError::UninitializedValue { shape: self.shape }),\n }\n }\n Tracker::Struct { iset, .. } => {\n if iset.all_set() {\n Ok(())\n } else {\n // Attempt to find the first uninitialized field, if possible\n match self.shape.ty {\n Type::User(UserType::Struct(struct_type)) => {\n // Find index of the first bit not set\n let first_missing_idx =\n (0..struct_type.fields.len()).find(|&idx| !iset.get(idx));\n if let Some(missing_idx) = first_missing_idx {\n let field_name = struct_type.fields[missing_idx].name;\n Err(ReflectError::UninitializedField {\n shape: self.shape,\n field_name,\n })\n } else {\n // fallback, something went wrong\n Err(ReflectError::UninitializedValue { shape: self.shape })\n }\n }\n _ => Err(ReflectError::UninitializedValue { shape: self.shape }),\n }\n }\n }\n Tracker::Enum { variant, data, .. } => {\n // Check if all fields of the variant are initialized\n let num_fields = variant.data.fields.len();\n if num_fields == 0 {\n // Unit variant, always initialized\n Ok(())\n } else if (0..num_fields).all(|idx| data.get(idx)) {\n Ok(())\n } else {\n // Find the first uninitialized field\n let first_missing_idx = (0..num_fields).find(|&idx| !data.get(idx));\n if let Some(missing_idx) = first_missing_idx {\n let field_name = variant.data.fields[missing_idx].name;\n Err(ReflectError::UninitializedEnumField {\n shape: self.shape,\n field_name,\n variant_name: variant.name,\n })\n } else {\n Err(ReflectError::UninitializedValue { shape: self.shape })\n }\n }\n }\n Tracker::SmartPointer { is_initialized } => {\n if is_initialized {\n Ok(())\n } else {\n Err(ReflectError::UninitializedValue { shape: self.shape })\n }\n }\n Tracker::SmartPointerStr => {\n todo!()\n }\n Tracker::SmartPointerSlice { building_item, .. } => {\n if building_item {\n Err(ReflectError::UninitializedValue { shape: self.shape })\n } else {\n Ok(())\n }\n }\n Tracker::List { is_initialized, .. } => {\n if is_initialized {\n Ok(())\n } else {\n Err(ReflectError::UninitializedValue { shape: self.shape })\n }\n }\n Tracker::Map {\n is_initialized,\n insert_state,\n } => {\n if is_initialized && matches!(insert_state, MapInsertState::Idle) {\n Ok(())\n } else {\n Err(ReflectError::UninitializedValue { shape: self.shape })\n }\n }\n Tracker::Option { building_inner } => {\n if building_inner {\n Err(ReflectError::UninitializedValue { shape: self.shape })\n } else {\n Ok(())\n }\n }\n }\n }\n}\n\nimpl<'facet> Partial<'facet> {\n /// Allocates a new Partial instance with the given shape\n pub fn alloc_shape(shape: &'static Shape) -> Result {\n crate::trace!(\n \"alloc_shape({:?}), with layout {:?}\",\n shape,\n shape.layout.sized_layout()\n );\n\n let data = shape.allocate().map_err(|_| ReflectError::Unsized {\n shape,\n operation: \"alloc_shape\",\n })?;\n\n // Preallocate a couple of frames. The cost of allocating 4 frames is\n // basically identical to allocating 1 frame, so for every type that\n // has at least 1 level of nesting, this saves at least one guaranteed reallocation.\n let mut frames = Vec::with_capacity(4);\n frames.push(Frame::new(data, shape, FrameOwnership::Owned));\n\n Ok(Self {\n frames,\n state: PartialState::Active,\n invariant: PhantomData,\n })\n }\n\n /// Allocates a new TypedPartial instance with the given shape and type\n pub fn alloc() -> Result, ReflectError>\n where\n T: Facet<'facet>,\n {\n Ok(TypedPartial {\n inner: Self::alloc_shape(T::SHAPE)?,\n phantom: PhantomData,\n })\n }\n\n /// Creates a Partial from an existing pointer and shape (used for nested initialization)\n pub fn from_ptr(data: PtrUninit<'_>, shape: &'static Shape) -> Self {\n // We need to convert the lifetime, which is safe because we're storing it in a frame\n // that will manage the lifetime correctly\n let data_static = PtrUninit::new(data.as_mut_byte_ptr());\n Self {\n frames: vec![Frame::new(data_static, shape, FrameOwnership::Field)],\n state: PartialState::Active,\n invariant: PhantomData,\n }\n }\n\n /// Require that the partial is active\n fn require_active(&self) -> Result<(), ReflectError> {\n if self.state == PartialState::Active {\n Ok(())\n } else {\n Err(ReflectError::InvariantViolation {\n invariant: \"Cannot use Partial after it has been built or poisoned\",\n })\n }\n }\n\n /// Returns the current frame count (depth of nesting)\n #[inline]\n pub fn frame_count(&self) -> usize {\n self.frames.len()\n }\n\n /// Sets a value wholesale into the current frame\n pub fn set(&mut self, value: U) -> Result<&mut Self, ReflectError>\n where\n U: Facet<'facet>,\n {\n self.require_active()?;\n\n // For conversion frames, store the value in the conversion frame itself\n // The conversion will happen during end()\n let ptr_const = PtrConst::new(&raw const value);\n unsafe {\n // Safety: We are calling set_shape with a valid shape and a valid pointer\n self.set_shape(ptr_const, U::SHAPE)?\n };\n\n // Prevent the value from being dropped since we've copied it\n core::mem::forget(value);\n Ok(self)\n }\n\n /// Sets a value into the current frame by shape, for shape-based operations\n ///\n /// If this returns Ok, then `src_value` has been moved out of\n ///\n /// # Safety\n ///\n /// The caller must ensure that `src_value` points to a valid instance of a value\n /// whose memory layout and type matches `src_shape`, and that this value can be\n /// safely copied (bitwise) into the destination specified by the Partial's current frame.\n /// No automatic drop will be performed for any existing value, so calling this on an\n /// already-initialized destination may result in leaks or double drops if misused.\n /// After a successful call, the ownership of the value at `src_value` is effectively moved\n /// into the Partial (i.e., the destination), and the original value should not be used\n /// or dropped by the caller; consider using `core::mem::forget` on the passed value.\n /// If an error is returned, the destination remains unmodified and safe for future operations.\n #[inline]\n pub unsafe fn set_shape(\n &mut self,\n src_value: PtrConst<'_>,\n src_shape: &'static Shape,\n ) -> Result<&mut Self, ReflectError> {\n self.require_active()?;\n\n let fr = self.frames.last_mut().unwrap();\n crate::trace!(\"set_shape({src_shape:?})\");\n if !fr.shape.is_shape(src_shape) {\n let err = ReflectError::WrongShape {\n expected: fr.shape,\n actual: src_shape,\n };\n return Err(err);\n }\n\n if fr.shape.layout.sized_layout().is_err() {\n return Err(ReflectError::Unsized {\n shape: fr.shape,\n operation: \"set_shape\",\n });\n }\n\n unsafe {\n fr.data.copy_from(src_value, fr.shape).unwrap();\n }\n fr.tracker = Tracker::Init;\n Ok(self)\n }\n\n /// Sets the current frame to its default value\n #[inline]\n pub fn set_default(&mut self) -> Result<&mut Self, ReflectError> {\n let frame = self.frames.last().unwrap(); // Get frame to access vtable\n\n if let Some(default_fn) = frame\n .shape\n .vtable\n .sized()\n .and_then(|v| (v.default_in_place)())\n {\n // Initialize with default value using set_from_function\n // SAFETY: set_from_function handles the active check, dropping,\n // and setting tracker. The closure passes the correct pointer type\n // and casts to 'static which is safe within the context of calling\n // the vtable function. The closure returns Ok(()) because the\n // default_in_place function does not return errors.\n self.set_from_function(move |ptr: PtrUninit<'_>| {\n unsafe { default_fn(PtrUninit::new(ptr.as_mut_byte_ptr())) };\n Ok(())\n })\n } else {\n // Default function not available, set state and return error\n Err(ReflectError::OperationFailed {\n shape: frame.shape,\n operation: \"type does not implement Default\",\n })\n }\n }\n\n /// Sets the current frame using a field-level default function\n #[inline]\n pub fn set_field_default(\n &mut self,\n field_default_fn: DefaultInPlaceFn,\n ) -> Result<&mut Self, ReflectError> {\n // Use the field-level default function to initialize the value\n // SAFETY: set_from_function handles the active check, dropping,\n // and setting tracker. The closure passes the correct pointer type\n // and casts to 'static which is safe within the context of calling\n // the field vtable function. The closure returns Ok(()) because the\n // default function does not return errors.\n self.set_from_function(move |ptr: PtrUninit<'_>| {\n unsafe { field_default_fn(PtrUninit::new(ptr.as_mut_byte_ptr())) };\n Ok(())\n })\n }\n\n /// Sets the current frame using a function that initializes the value\n pub fn set_from_function(&mut self, f: F) -> Result<&mut Self, ReflectError>\n where\n F: FnOnce(PtrUninit<'_>) -> Result<(), ReflectError>,\n {\n self.require_active()?;\n\n let frame = self.frames.last_mut().unwrap();\n\n // Check if we need to drop an existing value\n if matches!(frame.tracker, Tracker::Init) {\n if let Some(drop_fn) = frame.shape.vtable.sized().and_then(|v| (v.drop_in_place)()) {\n unsafe { drop_fn(PtrMut::new(frame.data.as_mut_byte_ptr())) };\n }\n }\n\n // Don't allow overwriting when building an Option's inner value\n if matches!(\n frame.tracker,\n Tracker::Option {\n building_inner: true\n }\n ) {\n return Err(ReflectError::OperationFailed {\n shape: frame.shape,\n operation: \"Cannot overwrite while building Option inner value\",\n });\n }\n\n // Call the function to initialize the value\n match f(frame.data) {\n Ok(()) => {\n // FIXME: what about finding out the discriminant of enums?\n frame.tracker = Tracker::Init;\n Ok(self)\n }\n Err(e) => Err(e),\n }\n }\n\n /// Parses a string value into the current frame using the type's ParseFn from the vtable\n pub fn parse_from_str(&mut self, s: &str) -> Result<&mut Self, ReflectError> {\n self.require_active()?;\n\n let frame = self.frames.last_mut().unwrap();\n\n // Check if the type has a parse function\n let parse_fn = match frame.shape.vtable.sized().and_then(|v| (v.parse)()) {\n Some(parse_fn) => parse_fn,\n None => {\n return Err(ReflectError::OperationFailed {\n shape: frame.shape,\n operation: \"Type does not support parsing from string\",\n });\n }\n };\n\n // Check if we need to drop an existing value\n if matches!(frame.tracker, Tracker::Init) {\n if let Some(drop_fn) = frame.shape.vtable.sized().and_then(|v| (v.drop_in_place)()) {\n unsafe { drop_fn(PtrMut::new(frame.data.as_mut_byte_ptr())) };\n }\n }\n\n // Don't allow overwriting when building an Option's inner value\n if matches!(\n frame.tracker,\n Tracker::Option {\n building_inner: true\n }\n ) {\n return Err(ReflectError::OperationFailed {\n shape: frame.shape,\n operation: \"Cannot overwrite while building Option inner value\",\n });\n }\n\n // Parse the string value using the type's parse function\n let result = unsafe { parse_fn(s, frame.data) };\n match result {\n Ok(_) => {\n frame.tracker = Tracker::Init;\n Ok(self)\n }\n Err(_parse_error) => Err(ReflectError::OperationFailed {\n shape: frame.shape,\n operation: \"Failed to parse string value\",\n }),\n }\n }\n\n /// Pushes a variant for enum initialization by name\n pub fn select_variant_named(&mut self, variant_name: &str) -> Result<&mut Self, ReflectError> {\n self.require_active()?;\n\n let fr = self.frames.last_mut().unwrap();\n\n // Check that we're dealing with an enum\n let enum_type = match fr.shape.ty {\n Type::User(UserType::Enum(e)) => e,\n _ => {\n return Err(ReflectError::OperationFailed {\n shape: fr.shape,\n operation: \"push_variant_named requires an enum type\",\n });\n }\n };\n\n // Find the variant with the matching name\n let variant = match enum_type.variants.iter().find(|v| v.name == variant_name) {\n Some(v) => v,\n None => {\n return Err(ReflectError::OperationFailed {\n shape: fr.shape,\n operation: \"No variant found with the given name\",\n });\n }\n };\n\n // Get the discriminant value\n let discriminant = match variant.discriminant {\n Some(d) => d,\n None => {\n return Err(ReflectError::OperationFailed {\n shape: fr.shape,\n operation: \"Variant has no discriminant value\",\n });\n }\n };\n\n // Delegate to push_variant\n self.select_variant(discriminant)\n }\n\n /// Pushes a variant for enum initialization\n pub fn select_variant(&mut self, discriminant: i64) -> Result<&mut Self, ReflectError> {\n self.require_active()?;\n\n // Check all invariants early before making any changes\n let fr = self.frames.last().unwrap();\n\n // Check that we're dealing with an enum\n let enum_type = match fr.shape.ty {\n Type::User(UserType::Enum(e)) => e,\n _ => {\n return Err(ReflectError::WasNotA {\n expected: \"enum\",\n actual: fr.shape,\n });\n }\n };\n\n // Find the variant with the matching discriminant\n let variant = match enum_type\n .variants\n .iter()\n .find(|v| v.discriminant == Some(discriminant))\n {\n Some(v) => v,\n None => {\n return Err(ReflectError::OperationFailed {\n shape: fr.shape,\n operation: \"No variant found with the given discriminant\",\n });\n }\n };\n\n // Check enum representation early\n match enum_type.enum_repr {\n EnumRepr::RustNPO => {\n return Err(ReflectError::OperationFailed {\n shape: fr.shape,\n operation: \"RustNPO enums are not supported for incremental building\",\n });\n }\n EnumRepr::U8\n | EnumRepr::U16\n | EnumRepr::U32\n | EnumRepr::U64\n | EnumRepr::I8\n | EnumRepr::I16\n | EnumRepr::I32\n | EnumRepr::I64\n | EnumRepr::USize\n | EnumRepr::ISize => {\n // These are supported, continue\n }\n }\n\n // All checks passed, now we can safely make changes\n let fr = self.frames.last_mut().unwrap();\n\n // Write the discriminant to memory\n unsafe {\n match enum_type.enum_repr {\n EnumRepr::U8 => {\n let ptr = fr.data.as_mut_byte_ptr();\n *ptr = discriminant as u8;\n }\n EnumRepr::U16 => {\n let ptr = fr.data.as_mut_byte_ptr() as *mut u16;\n *ptr = discriminant as u16;\n }\n EnumRepr::U32 => {\n let ptr = fr.data.as_mut_byte_ptr() as *mut u32;\n *ptr = discriminant as u32;\n }\n EnumRepr::U64 => {\n let ptr = fr.data.as_mut_byte_ptr() as *mut u64;\n *ptr = discriminant as u64;\n }\n EnumRepr::I8 => {\n let ptr = fr.data.as_mut_byte_ptr() as *mut i8;\n *ptr = discriminant as i8;\n }\n EnumRepr::I16 => {\n let ptr = fr.data.as_mut_byte_ptr() as *mut i16;\n *ptr = discriminant as i16;\n }\n EnumRepr::I32 => {\n let ptr = fr.data.as_mut_byte_ptr() as *mut i32;\n *ptr = discriminant as i32;\n }\n EnumRepr::I64 => {\n let ptr = fr.data.as_mut_byte_ptr() as *mut i64;\n *ptr = discriminant;\n }\n EnumRepr::USize => {\n let ptr = fr.data.as_mut_byte_ptr() as *mut usize;\n *ptr = discriminant as usize;\n }\n EnumRepr::ISize => {\n let ptr = fr.data.as_mut_byte_ptr() as *mut isize;\n *ptr = discriminant as isize;\n }\n _ => unreachable!(\"Already checked enum representation above\"),\n }\n }\n\n // Update tracker to track the variant\n fr.tracker = Tracker::Enum {\n variant,\n data: ISet::new(variant.data.fields.len()),\n current_child: None,\n };\n\n Ok(self)\n }\n\n /// Selects a field of a struct with a given name\n pub fn begin_field(&mut self, field_name: &str) -> Result<&mut Self, ReflectError> {\n self.require_active()?;\n\n let frame = self.frames.last_mut().unwrap();\n match frame.shape.ty {\n Type::Primitive(_) => Err(ReflectError::OperationFailed {\n shape: frame.shape,\n operation: \"cannot select a field from a primitive type\",\n }),\n Type::Sequence(_) => Err(ReflectError::OperationFailed {\n shape: frame.shape,\n operation: \"cannot select a field from a sequence type\",\n }),\n Type::User(user_type) => match user_type {\n UserType::Struct(struct_type) => {\n let idx = struct_type.fields.iter().position(|f| f.name == field_name);\n let idx = match idx {\n Some(idx) => idx,\n None => {\n return Err(ReflectError::OperationFailed {\n shape: frame.shape,\n operation: \"field not found\",\n });\n }\n };\n self.begin_nth_field(idx)\n }\n UserType::Enum(_) => {\n // Check if we have a variant selected\n match &frame.tracker {\n Tracker::Enum { variant, .. } => {\n let idx = variant\n .data\n .fields\n .iter()\n .position(|f| f.name == field_name);\n let idx = match idx {\n Some(idx) => idx,\n None => {\n return Err(ReflectError::OperationFailed {\n shape: frame.shape,\n operation: \"field not found in current enum variant\",\n });\n }\n };\n self.begin_nth_enum_field(idx)\n }\n _ => Err(ReflectError::OperationFailed {\n shape: frame.shape,\n operation: \"must call push_variant before selecting enum fields\",\n }),\n }\n }\n UserType::Union(_) => Err(ReflectError::OperationFailed {\n shape: frame.shape,\n operation: \"unions are not supported\",\n }),\n UserType::Opaque => Err(ReflectError::OperationFailed {\n shape: frame.shape,\n operation: \"opaque types cannot be reflected upon\",\n }),\n },\n Type::Pointer(_) => Err(ReflectError::OperationFailed {\n shape: frame.shape,\n operation: \"cannot select a field from a pointer type\",\n }),\n }\n }\n\n /// Selects a variant for enum initialization, by variant index in the enum's variant list (0-based)\n pub fn select_nth_variant(&mut self, index: usize) -> Result<&mut Self, ReflectError> {\n self.require_active()?;\n\n let fr = self.frames.last().unwrap();\n\n // Check that we're dealing with an enum\n let enum_type = match fr.shape.ty {\n Type::User(UserType::Enum(e)) => e,\n _ => {\n return Err(ReflectError::OperationFailed {\n shape: fr.shape,\n operation: \"select_nth_variant requires an enum type\",\n });\n }\n };\n\n if index >= enum_type.variants.len() {\n return Err(ReflectError::OperationFailed {\n shape: fr.shape,\n operation: \"variant index out of bounds\",\n });\n }\n let variant = &enum_type.variants[index];\n\n // Get the discriminant value\n let discriminant = match variant.discriminant {\n Some(d) => d,\n None => {\n return Err(ReflectError::OperationFailed {\n shape: fr.shape,\n operation: \"Variant has no discriminant value\",\n });\n }\n };\n\n // Delegate to select_variant\n self.select_variant(discriminant)\n }\n\n /// Selects the nth field of a struct by index\n pub fn begin_nth_field(&mut self, idx: usize) -> Result<&mut Self, ReflectError> {\n self.require_active()?;\n let frame = self.frames.last_mut().unwrap();\n match frame.shape.ty {\n Type::User(user_type) => match user_type {\n UserType::Struct(struct_type) => {\n if idx >= struct_type.fields.len() {\n return Err(ReflectError::OperationFailed {\n shape: frame.shape,\n operation: \"field index out of bounds\",\n });\n }\n let field = &struct_type.fields[idx];\n\n match &mut frame.tracker {\n Tracker::Uninit => {\n frame.tracker = Tracker::Struct {\n iset: ISet::new(struct_type.fields.len()),\n current_child: Some(idx),\n }\n }\n Tracker::Struct {\n iset,\n current_child,\n } => {\n // Check if this field was already initialized\n if iset.get(idx) {\n // Drop the existing value before re-initializing\n let field_ptr = unsafe { frame.data.field_init_at(field.offset) };\n if let Some(drop_fn) =\n field.shape.vtable.sized().and_then(|v| (v.drop_in_place)())\n {\n unsafe { drop_fn(field_ptr) };\n }\n // Unset the bit so we can re-initialize\n iset.unset(idx);\n }\n *current_child = Some(idx);\n }\n _ => unreachable!(),\n }\n\n // Push a new frame for this field onto the frames stack.\n let field_ptr = unsafe { frame.data.field_uninit_at(field.offset) };\n let field_shape = field.shape;\n self.frames\n .push(Frame::new(field_ptr, field_shape, FrameOwnership::Field));\n\n Ok(self)\n }\n UserType::Enum(_) => {\n // Check if we have a variant selected\n match &frame.tracker {\n Tracker::Enum { variant, .. } => {\n if idx >= variant.data.fields.len() {\n return Err(ReflectError::OperationFailed {\n shape: frame.shape,\n operation: \"enum field index out of bounds\",\n });\n }\n self.begin_nth_enum_field(idx)\n }\n _ => Err(ReflectError::OperationFailed {\n shape: frame.shape,\n operation: \"must call select_variant before selecting enum fields\",\n }),\n }\n }\n UserType::Union(_) => Err(ReflectError::OperationFailed {\n shape: frame.shape,\n operation: \"unions are not supported\",\n }),\n UserType::Opaque => Err(ReflectError::OperationFailed {\n shape: frame.shape,\n operation: \"opaque types cannot be reflected upon\",\n }),\n },\n _ => Err(ReflectError::OperationFailed {\n shape: frame.shape,\n operation: \"cannot select a field from this type\",\n }),\n }\n }\n\n /// Selects the nth element of an array by index\n pub fn begin_nth_element(&mut self, idx: usize) -> Result<&mut Self, ReflectError> {\n self.require_active()?;\n let frame = self.frames.last_mut().unwrap();\n match frame.shape.ty {\n Type::Sequence(seq_type) => match seq_type {\n facet_core::SequenceType::Array(array_def) => {\n if idx >= array_def.n {\n return Err(ReflectError::OperationFailed {\n shape: frame.shape,\n operation: \"array index out of bounds\",\n });\n }\n\n if array_def.n > 63 {\n return Err(ReflectError::OperationFailed {\n shape: frame.shape,\n operation: \"arrays larger than 63 elements are not yet supported\",\n });\n }\n\n // Ensure frame is in Array state\n if matches!(frame.tracker, Tracker::Uninit) {\n frame.tracker = Tracker::Array {\n iset: ISet::default(),\n current_child: None,\n };\n }\n\n match &mut frame.tracker {\n Tracker::Array {\n iset,\n current_child,\n } => {\n // Calculate the offset for this array element\n let element_layout = match array_def.t.layout.sized_layout() {\n Ok(layout) => layout,\n Err(_) => {\n return Err(ReflectError::Unsized {\n shape: array_def.t,\n operation: \"begin_nth_element, calculating array element offset\",\n });\n }\n };\n let offset = element_layout.size() * idx;\n\n // Check if this element was already initialized\n if iset.get(idx) {\n // Drop the existing value before re-initializing\n let element_ptr = unsafe { frame.data.field_init_at(offset) };\n if let Some(drop_fn) =\n array_def.t.vtable.sized().and_then(|v| (v.drop_in_place)())\n {\n unsafe { drop_fn(element_ptr) };\n }\n // Unset the bit so we can re-initialize\n iset.unset(idx);\n }\n\n *current_child = Some(idx);\n\n // Create a new frame for the array element\n let element_data = unsafe { frame.data.field_uninit_at(offset) };\n self.frames.push(Frame::new(\n element_data,\n array_def.t,\n FrameOwnership::Field,\n ));\n\n Ok(self)\n }\n _ => Err(ReflectError::OperationFailed {\n shape: frame.shape,\n operation: \"expected array tracker state\",\n }),\n }\n }\n _ => Err(ReflectError::OperationFailed {\n shape: frame.shape,\n operation: \"can only select elements from arrays\",\n }),\n },\n _ => Err(ReflectError::OperationFailed {\n shape: frame.shape,\n operation: \"cannot select an element from this type\",\n }),\n }\n }\n\n /// Selects the nth field of an enum variant by index\n pub fn begin_nth_enum_field(&mut self, idx: usize) -> Result<&mut Self, ReflectError> {\n self.require_active()?;\n let frame = self.frames.last_mut().unwrap();\n\n // Ensure we're in an enum with a variant selected\n let (variant, enum_type) = match (&frame.tracker, &frame.shape.ty) {\n (Tracker::Enum { variant, .. }, Type::User(UserType::Enum(e))) => (variant, e),\n _ => {\n return Err(ReflectError::OperationFailed {\n shape: frame.shape,\n operation: \"push_nth_enum_field requires an enum with a variant selected\",\n });\n }\n };\n\n // Check bounds\n if idx >= variant.data.fields.len() {\n return Err(ReflectError::OperationFailed {\n shape: frame.shape,\n operation: \"enum field index out of bounds\",\n });\n }\n\n let field = &variant.data.fields[idx];\n\n // Update tracker\n match &mut frame.tracker {\n Tracker::Enum {\n data,\n current_child,\n ..\n } => {\n // Check if field was already initialized and drop if needed\n if data.get(idx) {\n // Calculate the field offset, taking into account the discriminant\n let _discriminant_size = match enum_type.enum_repr {\n EnumRepr::U8 | EnumRepr::I8 => 1,\n EnumRepr::U16 | EnumRepr::I16 => 2,\n EnumRepr::U32 | EnumRepr::I32 => 4,\n EnumRepr::U64 | EnumRepr::I64 => 8,\n EnumRepr::USize | EnumRepr::ISize => core::mem::size_of::(),\n EnumRepr::RustNPO => {\n return Err(ReflectError::OperationFailed {\n shape: frame.shape,\n operation: \"RustNPO enums are not supported\",\n });\n }\n };\n\n // The field offset already includes the discriminant offset\n let field_ptr = unsafe { frame.data.as_mut_byte_ptr().add(field.offset) };\n\n if let Some(drop_fn) =\n field.shape.vtable.sized().and_then(|v| (v.drop_in_place)())\n {\n unsafe { drop_fn(PtrMut::new(field_ptr)) };\n }\n\n // Unset the bit so we can re-initialize\n data.unset(idx);\n }\n\n // Set current_child to track which field we're initializing\n *current_child = Some(idx);\n }\n _ => unreachable!(\"Already checked that we have Enum tracker\"),\n }\n\n // Extract data we need before pushing frame\n let field_ptr = unsafe { frame.data.as_mut_byte_ptr().add(field.offset) };\n let field_shape = field.shape;\n\n // Push new frame for the field\n self.frames.push(Frame::new(\n PtrUninit::new(field_ptr),\n field_shape,\n FrameOwnership::Field,\n ));\n\n Ok(self)\n }\n\n /// Pushes a frame to initialize the inner value of a smart pointer (`Box`, `Arc`, etc.)\n pub fn begin_smart_ptr(&mut self) -> Result<&mut Self, ReflectError> {\n crate::trace!(\"begin_smart_ptr()\");\n self.require_active()?;\n let frame = self.frames.last_mut().unwrap();\n\n // Check that we have a SmartPointer\n match &frame.shape.def {\n Def::Pointer(smart_ptr_def) => {\n // Check for supported smart pointer types\n match smart_ptr_def.known {\n Some(KnownPointer::Box)\n | Some(KnownPointer::Rc)\n | Some(KnownPointer::Arc)\n | Some(KnownPointer::SharedReference) => {\n // Supported types, continue\n }\n _ => {\n return Err(ReflectError::OperationFailed {\n shape: frame.shape,\n operation: \"only the following pointers are currently supported: Box, Rc, Arc, and &T\",\n });\n }\n }\n\n // Get the pointee shape\n let pointee_shape = match smart_ptr_def.pointee() {\n Some(shape) => shape,\n None => {\n return Err(ReflectError::OperationFailed {\n shape: frame.shape,\n operation: \"Box must have a pointee shape\",\n });\n }\n };\n\n if pointee_shape.layout.sized_layout().is_ok() {\n // pointee is sized, we can allocate it — for `Arc` we'll be allocating a `T` and\n // holding onto it. We'll build a new Arc with it when ending the smart pointer frame.\n\n if matches!(frame.tracker, Tracker::Uninit) {\n frame.tracker = Tracker::SmartPointer {\n is_initialized: false,\n };\n }\n\n let inner_layout = match pointee_shape.layout.sized_layout() {\n Ok(layout) => layout,\n Err(_) => {\n return Err(ReflectError::Unsized {\n shape: pointee_shape,\n operation: \"begin_smart_ptr, calculating inner value layout\",\n });\n }\n };\n let inner_ptr: *mut u8 = unsafe { alloc::alloc::alloc(inner_layout) };\n if inner_ptr.is_null() {\n return Err(ReflectError::OperationFailed {\n shape: frame.shape,\n operation: \"failed to allocate memory for smart pointer inner value\",\n });\n }\n\n // Push a new frame for the inner value\n self.frames.push(Frame::new(\n PtrUninit::new(inner_ptr),\n pointee_shape,\n FrameOwnership::Owned,\n ));\n } else {\n // pointee is unsized, we only support a handful of cases there\n if pointee_shape == str::SHAPE {\n crate::trace!(\"Pointee is str\");\n // Allocate space for a String\n let string_layout = String::SHAPE\n .layout\n .sized_layout()\n .expect(\"String must have a sized layout\");\n let string_ptr: *mut u8 = unsafe { alloc::alloc::alloc(string_layout) };\n if string_ptr.is_null() {\n alloc::alloc::handle_alloc_error(string_layout);\n }\n let mut frame = Frame::new(\n PtrUninit::new(string_ptr),\n String::SHAPE,\n FrameOwnership::Owned,\n );\n frame.tracker = Tracker::SmartPointerStr;\n self.frames.push(frame);\n } else if let Type::Sequence(SequenceType::Slice(_st)) = pointee_shape.ty {\n crate::trace!(\"Pointee is [{}]\", _st.t);\n\n // Get the slice builder vtable\n let slice_builder_vtable = smart_ptr_def\n .vtable\n .slice_builder_vtable\n .ok_or(ReflectError::OperationFailed {\n shape: frame.shape,\n operation: \"smart pointer does not support slice building\",\n })?;\n\n // Create a new builder\n let builder_ptr = (slice_builder_vtable.new_fn)();\n\n // Deallocate the original Arc allocation before replacing with slice builder\n if let FrameOwnership::Owned = frame.ownership {\n if let Ok(layout) = frame.shape.layout.sized_layout() {\n if layout.size() > 0 {\n unsafe {\n alloc::alloc::dealloc(frame.data.as_mut_byte_ptr(), layout)\n };\n }\n }\n }\n\n // Update the current frame to use the slice builder\n frame.data = PtrUninit::new(builder_ptr.as_mut_byte_ptr());\n frame.tracker = Tracker::SmartPointerSlice {\n vtable: slice_builder_vtable,\n building_item: false,\n };\n // The slice builder memory is managed by the vtable, not by us\n frame.ownership = FrameOwnership::ManagedElsewhere;\n } else {\n todo!(\"unsupported unsize pointee shape: {}\", pointee_shape)\n }\n }\n\n Ok(self)\n }\n _ => Err(ReflectError::OperationFailed {\n shape: frame.shape,\n operation: \"push_smart_ptr can only be called on compatible types\",\n }),\n }\n }\n\n /// Begins a pushback operation for a list (Vec, etc.)\n /// This initializes the list with default capacity and allows pushing elements\n pub fn begin_list(&mut self) -> Result<&mut Self, ReflectError> {\n crate::trace!(\"begin_list()\");\n self.require_active()?;\n let frame = self.frames.last_mut().unwrap();\n\n // Check if we're in a SmartPointerSlice state - if so, the list is already initialized\n if matches!(frame.tracker, Tracker::SmartPointerSlice { .. }) {\n crate::trace!(\n \"begin_list is kinda superfluous when we're in a SmartPointerSlice state\"\n );\n return Ok(self);\n }\n\n // Check that we have a List\n let list_def = match &frame.shape.def {\n Def::List(list_def) => list_def,\n _ => {\n return Err(ReflectError::OperationFailed {\n shape: frame.shape,\n operation: \"begin_pushback can only be called on List types\",\n });\n }\n };\n\n // Check that we have init_in_place_with_capacity function\n let init_fn = match list_def.vtable.init_in_place_with_capacity {\n Some(f) => f,\n None => {\n return Err(ReflectError::OperationFailed {\n shape: frame.shape,\n operation: \"list type does not support initialization with capacity\",\n });\n }\n };\n\n // Initialize the list with default capacity (0)\n unsafe {\n init_fn(frame.data, 0);\n }\n\n // Update tracker to List state\n frame.tracker = Tracker::List {\n is_initialized: true,\n current_child: false,\n };\n\n Ok(self)\n }\n\n /// Begins a map initialization operation\n /// This initializes the map with default capacity and allows inserting key-value pairs\n pub fn begin_map(&mut self) -> Result<&mut Self, ReflectError> {\n self.require_active()?;\n let frame = self.frames.last_mut().unwrap();\n\n // Check that we have a Map\n let map_def = match &frame.shape.def {\n Def::Map(map_def) => map_def,\n _ => {\n return Err(ReflectError::OperationFailed {\n shape: frame.shape,\n operation: \"begin_map can only be called on Map types\",\n });\n }\n };\n\n // Check that we have init_in_place_with_capacity function\n let init_fn = map_def.vtable.init_in_place_with_capacity_fn;\n\n // Initialize the map with default capacity (0)\n unsafe {\n init_fn(frame.data, 0);\n }\n\n // Update tracker to Map state\n frame.tracker = Tracker::Map {\n is_initialized: true,\n insert_state: MapInsertState::Idle,\n };\n\n Ok(self)\n }\n\n /// Pushes a frame for the map key\n /// Automatically starts a new insert if we're idle\n pub fn begin_key(&mut self) -> Result<&mut Self, ReflectError> {\n self.require_active()?;\n let frame = self.frames.last_mut().unwrap();\n\n // Check that we have a Map and set up for key insertion\n let map_def = match (&frame.shape.def, &mut frame.tracker) {\n (\n Def::Map(map_def),\n Tracker::Map {\n is_initialized: true,\n insert_state,\n },\n ) => {\n match insert_state {\n MapInsertState::Idle => {\n // Start a new insert automatically\n *insert_state = MapInsertState::PushingKey { key_ptr: None };\n }\n MapInsertState::PushingKey { key_ptr } => {\n if key_ptr.is_some() {\n return Err(ReflectError::OperationFailed {\n shape: frame.shape,\n operation: \"already pushing a key, call end() first\",\n });\n }\n }\n _ => {\n return Err(ReflectError::OperationFailed {\n shape: frame.shape,\n operation: \"must complete current operation before begin_key()\",\n });\n }\n }\n map_def\n }\n _ => {\n return Err(ReflectError::OperationFailed {\n shape: frame.shape,\n operation: \"must call begin_map() before begin_key()\",\n });\n }\n };\n\n // Get the key shape\n let key_shape = map_def.k();\n\n // Allocate space for the key\n let key_layout = match key_shape.layout.sized_layout() {\n Ok(layout) => layout,\n Err(_) => {\n return Err(ReflectError::Unsized {\n shape: key_shape,\n operation: \"begin_key allocating key\",\n });\n }\n };\n let key_ptr_raw: *mut u8 = unsafe { alloc::alloc::alloc(key_layout) };\n\n if key_ptr_raw.is_null() {\n return Err(ReflectError::OperationFailed {\n shape: frame.shape,\n operation: \"failed to allocate memory for map key\",\n });\n }\n\n // Store the key pointer in the insert state\n match &mut frame.tracker {\n Tracker::Map {\n insert_state: MapInsertState::PushingKey { key_ptr: kp },\n ..\n } => {\n *kp = Some(PtrUninit::new(key_ptr_raw));\n }\n _ => unreachable!(),\n }\n\n // Push a new frame for the key\n self.frames.push(Frame::new(\n PtrUninit::new(key_ptr_raw),\n key_shape,\n FrameOwnership::ManagedElsewhere, // Ownership tracked in MapInsertState\n ));\n\n Ok(self)\n }\n\n /// Pushes a frame for the map value\n /// Must be called after the key has been set and popped\n pub fn begin_value(&mut self) -> Result<&mut Self, ReflectError> {\n self.require_active()?;\n let frame = self.frames.last_mut().unwrap();\n\n // Check that we have a Map in PushingValue state\n let map_def = match (&frame.shape.def, &mut frame.tracker) {\n (\n Def::Map(map_def),\n Tracker::Map {\n insert_state: MapInsertState::PushingValue { value_ptr, .. },\n ..\n },\n ) => {\n if value_ptr.is_some() {\n return Err(ReflectError::OperationFailed {\n shape: frame.shape,\n operation: \"already pushing a value, call pop() first\",\n });\n }\n map_def\n }\n _ => {\n return Err(ReflectError::OperationFailed {\n shape: frame.shape,\n operation: \"must complete key before push_value()\",\n });\n }\n };\n\n // Get the value shape\n let value_shape = map_def.v();\n\n // Allocate space for the value\n let value_layout = match value_shape.layout.sized_layout() {\n Ok(layout) => layout,\n Err(_) => {\n return Err(ReflectError::Unsized {\n shape: value_shape,\n operation: \"begin_value allocating value\",\n });\n }\n };\n let value_ptr_raw: *mut u8 = unsafe { alloc::alloc::alloc(value_layout) };\n\n if value_ptr_raw.is_null() {\n return Err(ReflectError::OperationFailed {\n shape: frame.shape,\n operation: \"failed to allocate memory for map value\",\n });\n }\n\n // Store the value pointer in the insert state\n match &mut frame.tracker {\n Tracker::Map {\n insert_state: MapInsertState::PushingValue { value_ptr: vp, .. },\n ..\n } => {\n *vp = Some(PtrUninit::new(value_ptr_raw));\n }\n _ => unreachable!(),\n }\n\n // Push a new frame for the value\n self.frames.push(Frame::new(\n PtrUninit::new(value_ptr_raw),\n value_shape,\n FrameOwnership::ManagedElsewhere, // Ownership tracked in MapInsertState\n ));\n\n Ok(self)\n }\n\n /// Pushes an element to the list\n /// The element should be set using `set()` or similar methods, then `pop()` to complete\n pub fn begin_list_item(&mut self) -> Result<&mut Self, ReflectError> {\n crate::trace!(\"begin_list_item()\");\n self.require_active()?;\n let frame = self.frames.last_mut().unwrap();\n\n // Check if we're building a smart pointer slice\n if let Tracker::SmartPointerSlice {\n building_item,\n vtable: _,\n } = &frame.tracker\n {\n if *building_item {\n return Err(ReflectError::OperationFailed {\n shape: frame.shape,\n operation: \"already building an item, call end() first\",\n });\n }\n\n // Get the element type from the smart pointer's pointee\n let element_shape = match &frame.shape.def {\n Def::Pointer(smart_ptr_def) => match smart_ptr_def.pointee() {\n Some(pointee_shape) => match &pointee_shape.ty {\n Type::Sequence(SequenceType::Slice(slice_type)) => slice_type.t,\n _ => {\n return Err(ReflectError::OperationFailed {\n shape: frame.shape,\n operation: \"smart pointer pointee is not a slice\",\n });\n }\n },\n None => {\n return Err(ReflectError::OperationFailed {\n shape: frame.shape,\n operation: \"smart pointer has no pointee\",\n });\n }\n },\n _ => {\n return Err(ReflectError::OperationFailed {\n shape: frame.shape,\n operation: \"expected smart pointer definition\",\n });\n }\n };\n\n // Allocate space for the element\n crate::trace!(\"Pointee is a slice of {element_shape}\");\n let element_layout = match element_shape.layout.sized_layout() {\n Ok(layout) => layout,\n Err(_) => {\n return Err(ReflectError::OperationFailed {\n shape: element_shape,\n operation: \"cannot allocate unsized element\",\n });\n }\n };\n\n let element_ptr: *mut u8 = unsafe { alloc::alloc::alloc(element_layout) };\n if element_ptr.is_null() {\n alloc::alloc::handle_alloc_error(element_layout);\n }\n\n // Create and push the element frame\n crate::trace!(\"Pushing element frame, which we just allocated\");\n let element_frame = Frame::new(\n PtrUninit::new(element_ptr),\n element_shape,\n FrameOwnership::Owned,\n );\n self.frames.push(element_frame);\n\n // Mark that we're building an item\n // We need to update the tracker after pushing the frame\n let parent_idx = self.frames.len() - 2;\n if let Tracker::SmartPointerSlice { building_item, .. } =\n &mut self.frames[parent_idx].tracker\n {\n crate::trace!(\"Marking element frame as building item\");\n *building_item = true;\n }\n\n return Ok(self);\n }\n\n // Check that we have a List that's been initialized\n let list_def = match &frame.shape.def {\n Def::List(list_def) => list_def,\n _ => {\n return Err(ReflectError::OperationFailed {\n shape: frame.shape,\n operation: \"push can only be called on List types\",\n });\n }\n };\n\n // Verify the tracker is in List state and initialized\n match &mut frame.tracker {\n Tracker::List {\n is_initialized: true,\n current_child,\n } => {\n if *current_child {\n return Err(ReflectError::OperationFailed {\n shape: frame.shape,\n operation: \"already pushing an element, call pop() first\",\n });\n }\n *current_child = true;\n }\n _ => {\n return Err(ReflectError::OperationFailed {\n shape: frame.shape,\n operation: \"must call begin_pushback() before push()\",\n });\n }\n }\n\n // Get the element shape\n let element_shape = list_def.t();\n\n // Allocate space for the new element\n let element_layout = match element_shape.layout.sized_layout() {\n Ok(layout) => layout,\n Err(_) => {\n return Err(ReflectError::Unsized {\n shape: element_shape,\n operation: \"begin_list_item: calculating element layout\",\n });\n }\n };\n let element_ptr: *mut u8 = unsafe { alloc::alloc::alloc(element_layout) };\n\n if element_ptr.is_null() {\n return Err(ReflectError::OperationFailed {\n shape: frame.shape,\n operation: \"failed to allocate memory for list element\",\n });\n }\n\n // Push a new frame for the element\n self.frames.push(Frame::new(\n PtrUninit::new(element_ptr),\n element_shape,\n FrameOwnership::Owned,\n ));\n\n Ok(self)\n }\n\n /// Pops the current frame off the stack, indicating we're done initializing the current field\n pub fn end(&mut self) -> Result<&mut Self, ReflectError> {\n crate::trace!(\"end() called\");\n self.require_active()?;\n\n // Special handling for SmartPointerSlice - convert builder to Arc\n if self.frames.len() == 1 {\n if let Tracker::SmartPointerSlice {\n vtable,\n building_item,\n } = &self.frames[0].tracker\n {\n if *building_item {\n return Err(ReflectError::OperationFailed {\n shape: self.frames[0].shape,\n operation: \"still building an item, finish it first\",\n });\n }\n\n // Convert the builder to Arc<[T]>\n let builder_ptr = unsafe { self.frames[0].data.assume_init() };\n let arc_ptr = unsafe { (vtable.convert_fn)(builder_ptr) };\n\n // Update the frame to store the Arc\n self.frames[0].data = PtrUninit::new(arc_ptr.as_byte_ptr() as *mut u8);\n self.frames[0].tracker = Tracker::Init;\n // The builder memory has been consumed by convert_fn, so we no longer own it\n self.frames[0].ownership = FrameOwnership::ManagedElsewhere;\n\n return Ok(self);\n }\n }\n\n if self.frames.len() <= 1 {\n // Never pop the last/root frame.\n return Err(ReflectError::InvariantViolation {\n invariant: \"Partial::end() called with only one frame on the stack\",\n });\n }\n\n // Require that the top frame is fully initialized before popping.\n {\n let frame = self.frames.last().unwrap();\n trace!(\n \"end(): Checking full initialization for frame with shape {}\",\n frame.shape\n );\n frame.require_full_initialization()?\n }\n\n // Pop the frame and save its data pointer for SmartPointer handling\n let popped_frame = self.frames.pop().unwrap();\n trace!(\n \"end(): Popped frame with shape {}, tracker {:?}\",\n popped_frame.shape, popped_frame.tracker\n );\n\n // Update parent frame's tracking when popping from a child\n let parent_frame = self.frames.last_mut().unwrap();\n\n trace!(\n \"end(): Parent frame shape: {}, tracker: {:?}\",\n parent_frame.shape, parent_frame.tracker\n );\n\n // Check if we need to do a conversion - this happens when:\n // 1. The parent frame has an inner type that matches the popped frame's shape\n // 2. The parent frame has try_from\n // 3. The parent frame is not yet initialized\n let needs_conversion = matches!(parent_frame.tracker, Tracker::Uninit)\n && parent_frame.shape.inner.is_some()\n && parent_frame.shape.inner.unwrap()() == popped_frame.shape\n && parent_frame\n .shape\n .vtable\n .sized()\n .and_then(|v| (v.try_from)())\n .is_some();\n\n if needs_conversion {\n trace!(\n \"Detected implicit conversion needed from {} to {}\",\n popped_frame.shape, parent_frame.shape\n );\n // Perform the conversion\n if let Some(try_from_fn) = parent_frame\n .shape\n .vtable\n .sized()\n .and_then(|v| (v.try_from)())\n {\n let inner_ptr = unsafe { popped_frame.data.assume_init().as_const() };\n let inner_shape = popped_frame.shape;\n\n trace!(\"Converting from {} to {}\", inner_shape, parent_frame.shape);\n let result = unsafe { try_from_fn(inner_ptr, inner_shape, parent_frame.data) };\n\n if let Err(e) = result {\n trace!(\"Conversion failed: {e:?}\");\n\n // Deallocate the inner value's memory since conversion failed\n if let FrameOwnership::Owned = popped_frame.ownership {\n if let Ok(layout) = popped_frame.shape.layout.sized_layout() {\n if layout.size() > 0 {\n trace!(\n \"Deallocating conversion frame memory after failure: size={}, align={}\",\n layout.size(),\n layout.align()\n );\n unsafe {\n alloc::alloc::dealloc(\n popped_frame.data.as_mut_byte_ptr(),\n layout,\n );\n }\n }\n }\n }\n\n return Err(ReflectError::TryFromError {\n src_shape: inner_shape,\n dst_shape: parent_frame.shape,\n inner: e,\n });\n }\n\n trace!(\"Conversion succeeded, marking parent as initialized\");\n parent_frame.tracker = Tracker::Init;\n\n // Deallocate the inner value's memory since try_from consumed it\n if let FrameOwnership::Owned = popped_frame.ownership {\n if let Ok(layout) = popped_frame.shape.layout.sized_layout() {\n if layout.size() > 0 {\n trace!(\n \"Deallocating conversion frame memory: size={}, align={}\",\n layout.size(),\n layout.align()\n );\n unsafe {\n alloc::alloc::dealloc(popped_frame.data.as_mut_byte_ptr(), layout);\n }\n }\n }\n }\n\n return Ok(self);\n }\n }\n\n match &mut parent_frame.tracker {\n Tracker::Struct {\n iset,\n current_child,\n } => {\n if let Some(idx) = *current_child {\n iset.set(idx);\n *current_child = None;\n }\n }\n Tracker::Array {\n iset,\n current_child,\n } => {\n if let Some(idx) = *current_child {\n iset.set(idx);\n *current_child = None;\n }\n }\n Tracker::SmartPointer { is_initialized } => {\n // We just popped the inner value frame, so now we need to create the smart pointer\n if let Def::Pointer(smart_ptr_def) = parent_frame.shape.def {\n if let Some(new_into_fn) = smart_ptr_def.vtable.new_into_fn {\n // The child frame contained the inner value\n let inner_ptr = PtrMut::new(popped_frame.data.as_mut_byte_ptr());\n\n // Use new_into_fn to create the Box\n unsafe {\n new_into_fn(parent_frame.data, inner_ptr);\n }\n\n // Deallocate the inner value's memory since new_into_fn moved it\n if let FrameOwnership::Owned = popped_frame.ownership {\n if let Ok(layout) = popped_frame.shape.layout.sized_layout() {\n if layout.size() > 0 {\n unsafe {\n alloc::alloc::dealloc(\n popped_frame.data.as_mut_byte_ptr(),\n layout,\n );\n }\n }\n }\n }\n\n *is_initialized = true;\n } else {\n return Err(ReflectError::OperationFailed {\n shape: parent_frame.shape,\n operation: \"SmartPointer missing new_into_fn\",\n });\n }\n }\n }\n Tracker::Enum {\n data,\n current_child,\n ..\n } => {\n if let Some(idx) = *current_child {\n data.set(idx);\n *current_child = None;\n }\n }\n Tracker::List {\n is_initialized: true,\n current_child,\n } => {\n if *current_child {\n // We just popped an element frame, now push it to the list\n if let Def::List(list_def) = parent_frame.shape.def {\n if let Some(push_fn) = list_def.vtable.push {\n // The child frame contained the element value\n let element_ptr = PtrMut::new(popped_frame.data.as_mut_byte_ptr());\n\n // Use push to add element to the list\n unsafe {\n push_fn(\n PtrMut::new(parent_frame.data.as_mut_byte_ptr()),\n element_ptr,\n );\n }\n\n // Deallocate the element's memory since push moved it\n if let FrameOwnership::Owned = popped_frame.ownership {\n if let Ok(layout) = popped_frame.shape.layout.sized_layout() {\n if layout.size() > 0 {\n unsafe {\n alloc::alloc::dealloc(\n popped_frame.data.as_mut_byte_ptr(),\n layout,\n );\n }\n }\n }\n }\n\n *current_child = false;\n } else {\n return Err(ReflectError::OperationFailed {\n shape: parent_frame.shape,\n operation: \"List missing push function\",\n });\n }\n }\n }\n }\n Tracker::Map {\n is_initialized: true,\n insert_state,\n } => {\n match insert_state {\n MapInsertState::PushingKey { key_ptr } => {\n // We just popped the key frame\n if let Some(key_ptr) = key_ptr {\n // Transition to PushingValue state\n *insert_state = MapInsertState::PushingValue {\n key_ptr: *key_ptr,\n value_ptr: None,\n };\n }\n }\n MapInsertState::PushingValue { key_ptr, value_ptr } => {\n // We just popped the value frame, now insert the pair\n if let (Some(value_ptr), Def::Map(map_def)) =\n (value_ptr, parent_frame.shape.def)\n {\n let insert_fn = map_def.vtable.insert_fn;\n\n // Use insert to add key-value pair to the map\n unsafe {\n insert_fn(\n PtrMut::new(parent_frame.data.as_mut_byte_ptr()),\n PtrMut::new(key_ptr.as_mut_byte_ptr()),\n PtrMut::new(value_ptr.as_mut_byte_ptr()),\n );\n }\n\n // Note: We don't deallocate the key and value memory here.\n // The insert function has semantically moved the values into the map,\n // but we still need to deallocate the temporary buffers.\n // However, since we don't have frames for them anymore (they were popped),\n // we need to handle deallocation here.\n if let Ok(key_shape) = map_def.k().layout.sized_layout() {\n if key_shape.size() > 0 {\n unsafe {\n alloc::alloc::dealloc(key_ptr.as_mut_byte_ptr(), key_shape);\n }\n }\n }\n if let Ok(value_shape) = map_def.v().layout.sized_layout() {\n if value_shape.size() > 0 {\n unsafe {\n alloc::alloc::dealloc(\n value_ptr.as_mut_byte_ptr(),\n value_shape,\n );\n }\n }\n }\n\n // Reset to idle state\n *insert_state = MapInsertState::Idle;\n }\n }\n MapInsertState::Idle => {\n // Nothing to do\n }\n }\n }\n Tracker::Option { building_inner } => {\n // We just popped the inner value frame for an Option's Some variant\n if *building_inner {\n if let Def::Option(option_def) = parent_frame.shape.def {\n // Use the Option vtable to initialize Some(inner_value)\n let init_some_fn = option_def.vtable.init_some_fn;\n\n // The popped frame contains the inner value\n let inner_value_ptr = unsafe { popped_frame.data.assume_init().as_const() };\n\n // Initialize the Option as Some(inner_value)\n unsafe {\n init_some_fn(parent_frame.data, inner_value_ptr);\n }\n\n // Deallocate the inner value's memory since init_some_fn moved it\n if let FrameOwnership::Owned = popped_frame.ownership {\n if let Ok(layout) = popped_frame.shape.layout.sized_layout() {\n if layout.size() > 0 {\n unsafe {\n alloc::alloc::dealloc(\n popped_frame.data.as_mut_byte_ptr(),\n layout,\n );\n }\n }\n }\n }\n\n // Mark that we're no longer building the inner value\n *building_inner = false;\n } else {\n return Err(ReflectError::OperationFailed {\n shape: parent_frame.shape,\n operation: \"Option frame without Option definition\",\n });\n }\n }\n }\n Tracker::Uninit => {\n // if the just-popped frame was a SmartPointerStr, we have some conversion to do:\n // Special-case: SmartPointer (Box, Arc, Rc) via SmartPointerStr tracker\n // Here, popped_frame actually contains a value for String that should be moved into the smart pointer.\n // We convert the String into Box, Arc, or Rc as appropriate and write it to the parent frame.\n use alloc::{rc::Rc, string::String, sync::Arc};\n let parent_shape = parent_frame.shape;\n if let Def::Pointer(smart_ptr_def) = parent_shape.def {\n if let Some(known) = smart_ptr_def.known {\n // The popped_frame (child) must be a Tracker::SmartPointerStr (checked above)\n // Interpret the memory as a String, then convert and write.\n let string_ptr = popped_frame.data.as_mut_byte_ptr() as *mut String;\n let string_value = unsafe { core::ptr::read(string_ptr) };\n match known {\n KnownPointer::Box => {\n let boxed: Box = string_value.into_boxed_str();\n unsafe {\n core::ptr::write(\n parent_frame.data.as_mut_byte_ptr() as *mut Box,\n boxed,\n );\n }\n }\n KnownPointer::Arc => {\n let arc: Arc = Arc::from(string_value.into_boxed_str());\n unsafe {\n core::ptr::write(\n parent_frame.data.as_mut_byte_ptr() as *mut Arc,\n arc,\n );\n }\n }\n KnownPointer::Rc => {\n let rc: Rc = Rc::from(string_value.into_boxed_str());\n unsafe {\n core::ptr::write(\n parent_frame.data.as_mut_byte_ptr() as *mut Rc,\n rc,\n );\n }\n }\n _ => {}\n }\n parent_frame.tracker = Tracker::Init;\n // Now, deallocate temporary String allocation if necessary\n if let FrameOwnership::Owned = popped_frame.ownership {\n if let Ok(layout) = String::SHAPE.layout.sized_layout() {\n if layout.size() > 0 {\n unsafe {\n alloc::alloc::dealloc(\n popped_frame.data.as_mut_byte_ptr(),\n layout,\n )\n };\n }\n }\n }\n } else {\n return Err(ReflectError::OperationFailed {\n shape: parent_shape,\n operation: \"SmartPointerStr for unknown smart pointer kind\",\n });\n }\n }\n }\n Tracker::SmartPointerSlice {\n vtable,\n building_item,\n } => {\n if *building_item {\n // We just popped an element frame, now push it to the slice builder\n let element_ptr = PtrMut::new(popped_frame.data.as_mut_byte_ptr());\n\n // Use the slice builder's push_fn to add the element\n crate::trace!(\"Pushing element to slice builder\");\n unsafe {\n let parent_ptr = parent_frame.data.assume_init();\n (vtable.push_fn)(parent_ptr, element_ptr);\n }\n\n // Deallocate the element's memory since push_fn moved it\n if let FrameOwnership::Owned = popped_frame.ownership {\n if let Ok(layout) = popped_frame.shape.layout.sized_layout() {\n if layout.size() > 0 {\n unsafe {\n alloc::alloc::dealloc(\n popped_frame.data.as_mut_byte_ptr(),\n layout,\n );\n }\n }\n }\n }\n\n if let Tracker::SmartPointerSlice {\n building_item: bi, ..\n } = &mut parent_frame.tracker\n {\n *bi = false;\n }\n }\n }\n _ => {}\n }\n\n Ok(self)\n }\n\n /// Builds the value\n pub fn build(&mut self) -> Result, ReflectError> {\n self.require_active()?;\n if self.frames.len() != 1 {\n self.state = PartialState::BuildFailed;\n return Err(ReflectError::InvariantViolation {\n invariant: \"Partial::build() expects a single frame — pop until that's the case\",\n });\n }\n\n let frame = self.frames.pop().unwrap();\n\n // Check initialization before proceeding\n if let Err(e) = frame.require_full_initialization() {\n // Put the frame back so Drop can handle cleanup properly\n self.frames.push(frame);\n self.state = PartialState::BuildFailed;\n return Err(e);\n }\n\n // Check invariants if present\n if let Some(invariants_fn) = frame.shape.vtable.sized().and_then(|v| (v.invariants)()) {\n // Safety: The value is fully initialized at this point (we just checked with require_full_initialization)\n let value_ptr = unsafe { frame.data.assume_init().as_const() };\n let invariants_ok = unsafe { invariants_fn(value_ptr) };\n\n if !invariants_ok {\n // Put the frame back so Drop can handle cleanup properly\n self.frames.push(frame);\n self.state = PartialState::BuildFailed;\n return Err(ReflectError::InvariantViolation {\n invariant: \"Type invariants check failed\",\n });\n }\n }\n\n // Mark as built to prevent reuse\n self.state = PartialState::Built;\n\n match frame\n .shape\n .layout\n .sized_layout()\n .map_err(|_layout_err| ReflectError::Unsized {\n shape: frame.shape,\n operation: \"build (final check for sized layout)\",\n }) {\n Ok(layout) => Ok(HeapValue {\n guard: Some(Guard {\n ptr: frame.data.as_mut_byte_ptr(),\n layout,\n }),\n shape: frame.shape,\n phantom: PhantomData,\n }),\n Err(e) => {\n // Put the frame back for proper cleanup\n self.frames.push(frame);\n self.state = PartialState::BuildFailed;\n Err(e)\n }\n }\n }\n\n /// Returns a human-readable path representing the current traversal in the builder,\n /// e.g., `RootStruct.fieldName[index].subfield`.\n pub fn path(&self) -> String {\n let mut out = String::new();\n\n let mut path_components = Vec::new();\n // The stack of enum/struct/sequence names currently in context.\n // Start from root and build upwards.\n for (i, frame) in self.frames.iter().enumerate() {\n match frame.shape.ty {\n Type::User(user_type) => match user_type {\n UserType::Struct(struct_type) => {\n // Try to get currently active field index\n let mut field_str = None;\n if let Tracker::Struct {\n current_child: Some(idx),\n ..\n } = &frame.tracker\n {\n if let Some(field) = struct_type.fields.get(*idx) {\n field_str = Some(field.name);\n }\n }\n if i == 0 {\n // Use Display for the root struct shape\n path_components.push(format!(\"{}\", frame.shape));\n }\n if let Some(field_name) = field_str {\n path_components.push(format!(\".{field_name}\"));\n }\n }\n UserType::Enum(_enum_type) => {\n // Try to get currently active variant and field\n if let Tracker::Enum {\n variant,\n current_child,\n ..\n } = &frame.tracker\n {\n if i == 0 {\n // Use Display for the root enum shape\n path_components.push(format!(\"{}\", frame.shape));\n }\n path_components.push(format!(\"::{}\", variant.name));\n if let Some(idx) = *current_child {\n if let Some(field) = variant.data.fields.get(idx) {\n path_components.push(format!(\".{}\", field.name));\n }\n }\n } else if i == 0 {\n // just the enum display\n path_components.push(format!(\"{}\", frame.shape));\n }\n }\n UserType::Union(_union_type) => {\n path_components.push(format!(\"{}\", frame.shape));\n }\n UserType::Opaque => {\n path_components.push(\"\".to_string());\n }\n },\n Type::Sequence(seq_type) => match seq_type {\n facet_core::SequenceType::Array(_array_def) => {\n // Try to show current element index\n if let Tracker::Array {\n current_child: Some(idx),\n ..\n } = &frame.tracker\n {\n path_components.push(format!(\"[{idx}]\"));\n }\n }\n // You can add more for Slice, Vec, etc., if applicable\n _ => {\n // just indicate \"[]\" for sequence\n path_components.push(\"[]\".to_string());\n }\n },\n Type::Pointer(_) => {\n // Indicate deref\n path_components.push(\"*\".to_string());\n }\n _ => {\n // No structural path\n }\n }\n }\n // Merge the path_components into a single string\n for component in path_components {\n out.push_str(&component);\n }\n out\n }\n\n /// Returns the shape of the current frame.\n #[inline]\n pub fn shape(&self) -> &'static Shape {\n self.frames\n .last()\n .expect(\"Partial always has at least one frame\")\n .shape\n }\n\n /// Returns the innermost shape (alias for shape(), for compatibility)\n #[inline]\n pub fn innermost_shape(&self) -> &'static Shape {\n self.shape()\n }\n\n /// Check if a struct field at the given index has been set\n pub fn is_field_set(&self, index: usize) -> Result {\n let frame = self.frames.last().ok_or(ReflectError::NoActiveFrame)?;\n\n match &frame.tracker {\n Tracker::Uninit => Ok(false),\n Tracker::Init => Ok(true),\n Tracker::Struct { iset, .. } => Ok(iset.get(index)),\n Tracker::Enum { data, .. } => {\n // Check if the field is already marked as set\n if data.get(index) {\n return Ok(true);\n }\n\n // For enum variant fields that are empty structs, they are always initialized\n if let Tracker::Enum { variant, .. } = &frame.tracker {\n if let Some(field) = variant.data.fields.get(index) {\n if let Type::User(UserType::Struct(field_struct)) = field.shape.ty {\n if field_struct.fields.is_empty() {\n return Ok(true);\n }\n }\n }\n }\n\n Ok(false)\n }\n Tracker::Option { building_inner } => {\n // For Options, index 0 represents the inner value\n if index == 0 {\n Ok(!building_inner)\n } else {\n Err(ReflectError::InvalidOperation {\n operation: \"is_field_set\",\n reason: \"Option only has one field (index 0)\",\n })\n }\n }\n _ => Err(ReflectError::InvalidOperation {\n operation: \"is_field_set\",\n reason: \"Current frame is not a struct, enum variant, or option\",\n }),\n }\n }\n\n /// Find the index of a field by name in the current struct\n pub fn field_index(&self, field_name: &str) -> Option {\n let frame = self.frames.last()?;\n\n match frame.shape.ty {\n Type::User(UserType::Struct(struct_def)) => {\n struct_def.fields.iter().position(|f| f.name == field_name)\n }\n Type::User(UserType::Enum(_)) => {\n // If we're in an enum variant, check its fields\n if let Tracker::Enum { variant, .. } = &frame.tracker {\n variant\n .data\n .fields\n .iter()\n .position(|f| f.name == field_name)\n } else {\n None\n }\n }\n _ => None,\n }\n }\n\n /// Get the currently selected variant for an enum\n pub fn selected_variant(&self) -> Option {\n let frame = self.frames.last()?;\n\n match &frame.tracker {\n Tracker::Enum { variant, .. } => Some(**variant),\n _ => None,\n }\n }\n\n /// Find a variant by name in the current enum\n pub fn find_variant(&self, variant_name: &str) -> Option<(usize, &'static Variant)> {\n let frame = self.frames.last()?;\n\n if let Type::User(UserType::Enum(enum_def)) = frame.shape.ty {\n enum_def\n .variants\n .iter()\n .enumerate()\n .find(|(_, v)| v.name == variant_name)\n } else {\n None\n }\n }\n\n /// Begin building the Some variant of an Option\n pub fn begin_some(&mut self) -> Result<&mut Self, ReflectError> {\n self.require_active()?;\n let frame = self.frames.last_mut().unwrap();\n\n // Verify we're working with an Option\n let option_def = match frame.shape.def {\n Def::Option(def) => def,\n _ => {\n return Err(ReflectError::WasNotA {\n expected: \"Option\",\n actual: frame.shape,\n });\n }\n };\n\n // Initialize the tracker for Option building\n if matches!(frame.tracker, Tracker::Uninit) {\n frame.tracker = Tracker::Option {\n building_inner: true,\n };\n }\n\n // Get the inner type shape\n let inner_shape = option_def.t;\n\n // Allocate memory for the inner value\n let inner_layout =\n inner_shape\n .layout\n .sized_layout()\n .map_err(|_| ReflectError::Unsized {\n shape: inner_shape,\n operation: \"begin_some, allocating Option inner value\",\n })?;\n\n let inner_data = if inner_layout.size() == 0 {\n // For ZST, use a non-null but unallocated pointer\n PtrUninit::new(core::ptr::NonNull::::dangling().as_ptr())\n } else {\n // Allocate memory for the inner value\n let ptr = unsafe { alloc::alloc::alloc(inner_layout) };\n if ptr.is_null() {\n alloc::alloc::handle_alloc_error(inner_layout);\n }\n PtrUninit::new(ptr)\n };\n\n // Create a new frame for the inner value\n let inner_frame = Frame::new(inner_data, inner_shape, FrameOwnership::Owned);\n self.frames.push(inner_frame);\n\n Ok(self)\n }\n\n /// Begin building the inner value of a wrapper type\n pub fn begin_inner(&mut self) -> Result<&mut Self, ReflectError> {\n self.require_active()?;\n\n // Get the inner shape and check for try_from\n let (inner_shape, has_try_from, parent_shape) = {\n let frame = self.frames.last().unwrap();\n if let Some(inner_fn) = frame.shape.inner {\n let inner_shape = inner_fn();\n let has_try_from = frame\n .shape\n .vtable\n .sized()\n .and_then(|v| (v.try_from)())\n .is_some();\n (Some(inner_shape), has_try_from, frame.shape)\n } else {\n (None, false, frame.shape)\n }\n };\n\n if let Some(inner_shape) = inner_shape {\n if has_try_from {\n // Create a conversion frame with the inner shape\n\n // For conversion frames, we leave the parent tracker unchanged\n // This allows automatic conversion detection to work properly\n\n // Allocate memory for the inner value (conversion source)\n let inner_layout =\n inner_shape\n .layout\n .sized_layout()\n .map_err(|_| ReflectError::Unsized {\n shape: inner_shape,\n operation: \"begin_inner, getting inner layout\",\n })?;\n\n let inner_data = if inner_layout.size() == 0 {\n // For ZST, use a non-null but unallocated pointer\n PtrUninit::new(core::ptr::NonNull::::dangling().as_ptr())\n } else {\n // Allocate memory for the inner value\n let ptr = unsafe { alloc::alloc::alloc(inner_layout) };\n if ptr.is_null() {\n alloc::alloc::handle_alloc_error(inner_layout);\n }\n PtrUninit::new(ptr)\n };\n\n // For conversion frames, we create a frame directly with the inner shape\n // This allows setting values of the inner type which will be converted\n // The automatic conversion detection in end() will handle the conversion\n trace!(\n \"begin_inner: Creating frame for inner type {inner_shape} (parent is {parent_shape})\"\n );\n self.frames\n .push(Frame::new(inner_data, inner_shape, FrameOwnership::Owned));\n\n Ok(self)\n } else {\n // For wrapper types without try_from, navigate to the first field\n // This is a common pattern for newtype wrappers\n trace!(\"begin_inner: No try_from for {parent_shape}, using field navigation\");\n self.begin_nth_field(0)\n }\n } else {\n Err(ReflectError::OperationFailed {\n shape: parent_shape,\n operation: \"type does not have an inner value\",\n })\n }\n }\n\n /// Copy a value from a Peek into the current position (safe alternative to set_shape)\n pub fn set_from_peek(&mut self, peek: &Peek<'_, '_>) -> Result<&mut Self, ReflectError> {\n self.require_active()?;\n\n // Get the source value's pointer and shape\n let src_ptr = peek.data();\n let src_shape = peek.shape();\n\n // Safety: This is a safe wrapper around set_shape\n // The peek guarantees the source data is valid for its shape\n unsafe { self.set_shape(src_ptr.thin().unwrap(), src_shape) }\n }\n\n /// Copy a field from a struct's default value (safe wrapper for deserialization)\n /// This method creates the Peek internally to avoid exposing unsafe code to callers\n pub fn set_field_from_default(\n &mut self,\n field_data: PtrConst<'_>,\n field_shape: &'static Shape,\n ) -> Result<&mut Self, ReflectError> {\n self.require_active()?;\n\n // Safety: The caller guarantees that field_data points to valid data for field_shape\n // This is typically used when copying default values during deserialization\n unsafe { self.set_shape(field_data, field_shape) }\n }\n\n /// Fill all unset fields from the struct's default value\n /// This is a safe API for format deserializers that forbid unsafe code\n pub fn fill_unset_fields_from_default(&mut self) -> Result<&mut Self, ReflectError> {\n self.require_active()?;\n\n let frame = self.frames.last().unwrap();\n let shape = frame.shape;\n\n // Check if this is a struct with the default attribute\n if !shape.has_default_attr() {\n return Ok(self);\n }\n\n // Make sure we're working with a struct\n let struct_def = match shape.ty {\n Type::User(UserType::Struct(sd)) => sd,\n _ => return Ok(self), // Not a struct, nothing to do\n };\n\n // Check if any fields are unset\n let mut has_unset = false;\n for index in 0..struct_def.fields.len() {\n if !self.is_field_set(index)? {\n has_unset = true;\n break;\n }\n }\n\n if !has_unset {\n return Ok(self); // All fields are set, nothing to do\n }\n\n // Create a default instance\n let default_val = Partial::alloc_shape(shape)?.set_default()?.build()?;\n let peek = default_val.peek();\n\n // Convert to struct peek\n let struct_peek = peek\n .into_struct()\n .map_err(|_| ReflectError::OperationFailed {\n shape,\n operation: \"expected struct peek for default value\",\n })?;\n\n // Copy unset fields from the default\n for (index, _field) in struct_def.fields.iter().enumerate() {\n if !self.is_field_set(index)? {\n self.begin_nth_field(index)?;\n\n // Get the field from the default value\n let def_field =\n struct_peek\n .field(index)\n .map_err(|_| ReflectError::OperationFailed {\n shape,\n operation: \"failed to get field from default struct\",\n })?;\n\n self.set_from_peek(&def_field)?;\n self.end()?;\n }\n }\n\n Ok(self)\n }\n\n /// Convenience shortcut: sets the nth element of an array directly to value, popping after.\n pub fn set_nth_element(&mut self, idx: usize, value: U) -> Result<&mut Self, ReflectError>\n where\n U: Facet<'facet>,\n {\n self.begin_nth_element(idx)?.set(value)?.end()\n }\n\n /// Convenience shortcut: sets the field at index `idx` directly to value, popping after.\n pub fn set_nth_field(&mut self, idx: usize, value: U) -> Result<&mut Self, ReflectError>\n where\n U: Facet<'facet>,\n {\n self.begin_nth_field(idx)?.set(value)?.end()\n }\n\n /// Convenience shortcut: sets the named field to value, popping after.\n pub fn set_field(&mut self, field_name: &str, value: U) -> Result<&mut Self, ReflectError>\n where\n U: Facet<'facet>,\n {\n self.begin_field(field_name)?.set(value)?.end()\n }\n\n /// Convenience shortcut: sets the nth field of an enum variant directly to value, popping after.\n pub fn set_nth_enum_field(&mut self, idx: usize, value: U) -> Result<&mut Self, ReflectError>\n where\n U: Facet<'facet>,\n {\n self.begin_nth_enum_field(idx)?.set(value)?.end()\n }\n\n /// Convenience shortcut: sets the key for a map key-value insertion, then pops after.\n pub fn set_key(&mut self, value: U) -> Result<&mut Self, ReflectError>\n where\n U: Facet<'facet>,\n {\n self.begin_key()?.set(value)?.end()\n }\n\n /// Convenience shortcut: sets the value for a map key-value insertion, then pops after.\n pub fn set_value(&mut self, value: U) -> Result<&mut Self, ReflectError>\n where\n U: Facet<'facet>,\n {\n self.begin_value()?.set(value)?.end()\n }\n\n /// Shorthand for: begin_list_item(), set, end\n pub fn push(&mut self, value: U) -> Result<&mut Self, ReflectError>\n where\n U: Facet<'facet>,\n {\n self.begin_list_item()?.set(value)?.end()\n }\n}\n\n/// A typed wrapper around `Partial`, for when you want to statically\n/// ensure that `build` gives you the proper type.\npub struct TypedPartial<'facet, T> {\n inner: Partial<'facet>,\n phantom: PhantomData,\n}\n\nimpl<'facet, T> TypedPartial<'facet, T> {\n /// Unwraps the underlying Partial, consuming self.\n pub fn inner_mut(&mut self) -> &mut Partial<'facet> {\n &mut self.inner\n }\n\n /// Builds the value and returns a `Box`\n pub fn build(&mut self) -> Result, ReflectError>\n where\n T: Facet<'facet>,\n {\n trace!(\n \"TypedPartial::build: Building value for type {} which should == {}\",\n T::SHAPE,\n self.inner.shape()\n );\n let heap_value = self.inner.build()?;\n trace!(\n \"TypedPartial::build: Built heap value with shape: {}\",\n heap_value.shape()\n );\n // Safety: HeapValue was constructed from T and the shape layout is correct.\n let result = unsafe { heap_value.into_box_unchecked::() };\n trace!(\"TypedPartial::build: Successfully converted to Box\");\n Ok(result)\n }\n\n /// Sets a value wholesale into the current frame\n pub fn set(&mut self, value: U) -> Result<&mut Self, ReflectError>\n where\n U: Facet<'facet>,\n {\n self.inner.set(value)?;\n Ok(self)\n }\n\n /// Sets a value into the current frame by shape, for shape-based operations\n pub fn set_shape(\n &mut self,\n src_value: PtrConst<'_>,\n src_shape: &'static Shape,\n ) -> Result<&mut Self, ReflectError> {\n unsafe { self.inner.set_shape(src_value, src_shape)? };\n Ok(self)\n }\n\n /// Forwards begin_field to the inner partial instance.\n pub fn begin_field(&mut self, field_name: &str) -> Result<&mut Self, ReflectError> {\n self.inner.begin_field(field_name)?;\n Ok(self)\n }\n\n /// Forwards begin_nth_field to the inner partial instance.\n pub fn begin_nth_field(&mut self, idx: usize) -> Result<&mut Self, ReflectError> {\n self.inner.begin_nth_field(idx)?;\n Ok(self)\n }\n\n /// Forwards begin_nth_element to the inner partial instance.\n pub fn begin_nth_element(&mut self, idx: usize) -> Result<&mut Self, ReflectError> {\n self.inner.begin_nth_element(idx)?;\n Ok(self)\n }\n\n /// Forwards begin_smart_ptr to the inner partial instance.\n pub fn begin_smart_ptr(&mut self) -> Result<&mut Self, ReflectError> {\n self.inner.begin_smart_ptr()?;\n Ok(self)\n }\n\n /// Forwards end to the inner partial instance.\n pub fn end(&mut self) -> Result<&mut Self, ReflectError> {\n self.inner.end()?;\n Ok(self)\n }\n\n /// Forwards set_default to the inner partial instance.\n pub fn set_default(&mut self) -> Result<&mut Self, ReflectError> {\n self.inner.set_default()?;\n Ok(self)\n }\n\n /// Forwards set_from_function to the inner partial instance.\n pub fn set_from_function(&mut self, f: F) -> Result<&mut Self, ReflectError>\n where\n F: FnOnce(PtrUninit<'_>) -> Result<(), ReflectError>,\n {\n self.inner.set_from_function(f)?;\n Ok(self)\n }\n\n /// Forwards parse_from_str to the inner partial instance.\n pub fn parse_from_str(&mut self, s: &str) -> Result<&mut Self, ReflectError> {\n self.inner.parse_from_str(s)?;\n Ok(self)\n }\n\n /// Forwards begin_variant to the inner partial instance.\n pub fn select_variant(&mut self, discriminant: i64) -> Result<&mut Self, ReflectError> {\n self.inner.select_variant(discriminant)?;\n Ok(self)\n }\n\n /// Forwards begin_variant_named to the inner partial instance.\n pub fn select_variant_named(&mut self, variant_name: &str) -> Result<&mut Self, ReflectError> {\n self.inner.select_variant_named(variant_name)?;\n Ok(self)\n }\n\n /// Forwards select_nth_variant to the inner partial instance.\n pub fn select_nth_variant(&mut self, index: usize) -> Result<&mut Self, ReflectError> {\n self.inner.select_nth_variant(index)?;\n Ok(self)\n }\n\n /// Forwards begin_nth_enum_field to the inner partial instance.\n pub fn begin_nth_enum_field(&mut self, idx: usize) -> Result<&mut Self, ReflectError> {\n self.inner.begin_nth_enum_field(idx)?;\n Ok(self)\n }\n\n /// Forwards begin_list to the inner partial instance.\n pub fn begin_list(&mut self) -> Result<&mut Self, ReflectError> {\n self.inner.begin_list()?;\n Ok(self)\n }\n\n /// Forwards begin_list_item to the inner partial instance.\n pub fn begin_list_item(&mut self) -> Result<&mut Self, ReflectError> {\n self.inner.begin_list_item()?;\n Ok(self)\n }\n\n /// Forwards begin_map to the inner partial instance.\n pub fn begin_map(&mut self) -> Result<&mut Self, ReflectError> {\n self.inner.begin_map()?;\n Ok(self)\n }\n\n /// Forwards begin_key to the inner partial instance.\n pub fn begin_key(&mut self) -> Result<&mut Self, ReflectError> {\n self.inner.begin_key()?;\n Ok(self)\n }\n\n /// Forwards begin_value to the inner partial instance.\n pub fn begin_value(&mut self) -> Result<&mut Self, ReflectError> {\n self.inner.begin_value()?;\n Ok(self)\n }\n\n /// Returns a human-readable path representing the current traversal in the builder,\n /// e.g., `RootStruct.fieldName[index].subfield`.\n pub fn path(&self) -> String {\n self.inner.path()\n }\n\n /// Returns the shape of the current frame.\n pub fn shape(&self) -> &'static Shape {\n self.inner.shape()\n }\n\n /// Convenience shortcut: sets the nth element of an array directly to value, popping after.\n pub fn set_nth_element(&mut self, idx: usize, value: U) -> Result<&mut Self, ReflectError>\n where\n U: Facet<'facet>,\n {\n self.inner.set_nth_element(idx, value)?;\n Ok(self)\n }\n\n /// Convenience shortcut: sets the field at index `idx` directly to value, popping after.\n pub fn set_nth_field(&mut self, idx: usize, value: U) -> Result<&mut Self, ReflectError>\n where\n U: Facet<'facet>,\n {\n self.inner.set_nth_field(idx, value)?;\n Ok(self)\n }\n\n /// Convenience shortcut: sets the named field to value, popping after.\n pub fn set_field(&mut self, field_name: &str, value: U) -> Result<&mut Self, ReflectError>\n where\n U: Facet<'facet>,\n {\n self.inner.set_field(field_name, value)?;\n Ok(self)\n }\n\n /// Convenience shortcut: sets the nth field of an enum variant directly to value, popping after.\n pub fn set_nth_enum_field(&mut self, idx: usize, value: U) -> Result<&mut Self, ReflectError>\n where\n U: Facet<'facet>,\n {\n self.inner.set_nth_enum_field(idx, value)?;\n Ok(self)\n }\n\n /// Convenience shortcut: sets the key for a map key-value insertion, then pops after.\n pub fn set_key(&mut self, value: U) -> Result<&mut Self, ReflectError>\n where\n U: Facet<'facet>,\n {\n self.inner.set_key(value)?;\n Ok(self)\n }\n\n /// Convenience shortcut: sets the value for a map key-value insertion, then pops after.\n pub fn set_value(&mut self, value: U) -> Result<&mut Self, ReflectError>\n where\n U: Facet<'facet>,\n {\n self.inner.set_value(value)?;\n Ok(self)\n }\n\n /// Shorthand for: begin_list_item(), set, end\n pub fn push(&mut self, value: U) -> Result<&mut Self, ReflectError>\n where\n U: Facet<'facet>,\n {\n self.inner.push(value)?;\n Ok(self)\n }\n\n /// Begin building the Some variant of an Option\n pub fn begin_some(&mut self) -> Result<&mut Self, ReflectError> {\n self.inner.begin_some()?;\n Ok(self)\n }\n\n /// Begin building the inner value of a wrapper type\n pub fn begin_inner(&mut self) -> Result<&mut Self, ReflectError> {\n self.inner.begin_inner()?;\n Ok(self)\n }\n}\n\nimpl<'facet, T> core::fmt::Debug for TypedPartial<'facet, T> {\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n f.debug_struct(\"TypedPartial\")\n .field(\"shape\", &self.inner.frames.last().map(|frame| frame.shape))\n .finish()\n }\n}\n\nimpl<'facet> Drop for Partial<'facet> {\n fn drop(&mut self) {\n trace!(\"🧹 Partial is being dropped\");\n\n // We need to properly drop all initialized fields\n while let Some(frame) = self.frames.pop() {\n match &frame.tracker {\n Tracker::Uninit => {\n // Nothing was initialized, nothing to drop\n }\n Tracker::Init => {\n // Fully initialized, drop it\n if let Some(drop_fn) =\n frame.shape.vtable.sized().and_then(|v| (v.drop_in_place)())\n {\n unsafe { drop_fn(PtrMut::new(frame.data.as_mut_byte_ptr())) };\n }\n }\n Tracker::Array { iset, .. } => {\n // Drop initialized array elements\n if let Type::Sequence(facet_core::SequenceType::Array(array_def)) =\n frame.shape.ty\n {\n let element_layout = array_def.t.layout.sized_layout().ok();\n if let Some(layout) = element_layout {\n for idx in 0..array_def.n {\n if iset.get(idx) {\n let offset = layout.size() * idx;\n let element_ptr = unsafe { frame.data.field_init_at(offset) };\n if let Some(drop_fn) =\n array_def.t.vtable.sized().and_then(|v| (v.drop_in_place)())\n {\n unsafe { drop_fn(element_ptr) };\n }\n }\n }\n }\n }\n }\n Tracker::Struct { iset, .. } => {\n // Drop initialized struct fields\n if let Type::User(UserType::Struct(struct_type)) = frame.shape.ty {\n for (idx, field) in struct_type.fields.iter().enumerate() {\n if iset.get(idx) {\n // This field was initialized, drop it\n let field_ptr = unsafe { frame.data.field_init_at(field.offset) };\n if let Some(drop_fn) =\n field.shape.vtable.sized().and_then(|v| (v.drop_in_place)())\n {\n unsafe { drop_fn(field_ptr) };\n }\n }\n }\n }\n }\n Tracker::Enum { variant, data, .. } => {\n // Drop initialized enum variant fields\n for (idx, field) in variant.data.fields.iter().enumerate() {\n if data.get(idx) {\n // This field was initialized, drop it\n let field_ptr =\n unsafe { frame.data.as_mut_byte_ptr().add(field.offset) };\n if let Some(drop_fn) =\n field.shape.vtable.sized().and_then(|v| (v.drop_in_place)())\n {\n unsafe { drop_fn(PtrMut::new(field_ptr)) };\n }\n }\n }\n }\n Tracker::SmartPointer { is_initialized } => {\n // Drop the initialized Box\n if *is_initialized {\n if let Some(drop_fn) =\n frame.shape.vtable.sized().and_then(|v| (v.drop_in_place)())\n {\n unsafe { drop_fn(PtrMut::new(frame.data.as_mut_byte_ptr())) };\n }\n }\n // Note: we don't deallocate the inner value here because\n // the Box's drop will handle that\n }\n Tracker::SmartPointerStr => {\n // nothing to do for now\n }\n Tracker::SmartPointerSlice { vtable, .. } => {\n // Free the slice builder\n let builder_ptr = unsafe { frame.data.assume_init() };\n unsafe {\n (vtable.free_fn)(builder_ptr);\n }\n }\n Tracker::List { is_initialized, .. } => {\n // Drop the initialized List\n if *is_initialized {\n if let Some(drop_fn) =\n frame.shape.vtable.sized().and_then(|v| (v.drop_in_place)())\n {\n unsafe { drop_fn(PtrMut::new(frame.data.as_mut_byte_ptr())) };\n }\n }\n }\n Tracker::Map {\n is_initialized,\n insert_state,\n } => {\n // Drop the initialized Map\n if *is_initialized {\n if let Some(drop_fn) =\n frame.shape.vtable.sized().and_then(|v| (v.drop_in_place)())\n {\n unsafe { drop_fn(PtrMut::new(frame.data.as_mut_byte_ptr())) };\n }\n }\n\n // Clean up any in-progress insertion state\n match insert_state {\n MapInsertState::PushingKey { key_ptr } => {\n if let Some(key_ptr) = key_ptr {\n // Deallocate the key buffer\n if let Def::Map(map_def) = frame.shape.def {\n if let Ok(key_shape) = map_def.k().layout.sized_layout() {\n if key_shape.size() > 0 {\n unsafe {\n alloc::alloc::dealloc(\n key_ptr.as_mut_byte_ptr(),\n key_shape,\n )\n };\n }\n }\n }\n }\n }\n MapInsertState::PushingValue { key_ptr, value_ptr } => {\n // Drop and deallocate both key and value buffers\n if let Def::Map(map_def) = frame.shape.def {\n // Drop and deallocate the key\n if let Some(drop_fn) =\n map_def.k().vtable.sized().and_then(|v| (v.drop_in_place)())\n {\n unsafe { drop_fn(PtrMut::new(key_ptr.as_mut_byte_ptr())) };\n }\n if let Ok(key_shape) = map_def.k().layout.sized_layout() {\n if key_shape.size() > 0 {\n unsafe {\n alloc::alloc::dealloc(\n key_ptr.as_mut_byte_ptr(),\n key_shape,\n )\n };\n }\n }\n\n // Drop and deallocate the value if it exists\n if let Some(value_ptr) = value_ptr {\n if let Ok(value_shape) = map_def.v().layout.sized_layout() {\n if value_shape.size() > 0 {\n unsafe {\n alloc::alloc::dealloc(\n value_ptr.as_mut_byte_ptr(),\n value_shape,\n )\n };\n }\n }\n }\n }\n }\n MapInsertState::Idle => {}\n }\n }\n Tracker::Option { building_inner } => {\n // If we're building the inner value, it will be handled by the Option vtable\n // No special cleanup needed here as the Option will either be properly\n // initialized or remain uninitialized\n if !building_inner {\n // Option is fully initialized, drop it normally\n if let Some(drop_fn) =\n frame.shape.vtable.sized().and_then(|v| (v.drop_in_place)())\n {\n unsafe { drop_fn(PtrMut::new(frame.data.as_mut_byte_ptr())) };\n }\n }\n }\n }\n\n // Only deallocate if this frame owns the allocation\n if let FrameOwnership::Owned = frame.ownership {\n if let Ok(layout) = frame.shape.layout.sized_layout() {\n if layout.size() > 0 {\n unsafe { alloc::alloc::dealloc(frame.data.as_mut_byte_ptr(), layout) };\n }\n }\n }\n }\n }\n}\n"], ["/facet/facet-core/src/impls_alloc/arc.rs", "use alloc::boxed::Box;\nuse alloc::sync::{Arc, Weak};\nuse alloc::vec::Vec;\n\nuse crate::{\n Def, Facet, KnownPointer, PointerDef, PointerFlags, PointerVTable, PtrConst, PtrConstWide,\n PtrMut, PtrUninit, Shape, SliceBuilderVTable, TryBorrowInnerError, TryFromError,\n TryIntoInnerError, Type, UserType, ValueVTable, value_vtable,\n};\n\nunsafe impl<'a, T: Facet<'a>> Facet<'a> for Arc {\n const VTABLE: &'static ValueVTable = &const {\n // Define the functions for transparent conversion between Arc and T\n unsafe fn try_from<'a, 'src, 'dst, T: Facet<'a>>(\n src_ptr: PtrConst<'src>,\n src_shape: &'static Shape,\n dst: PtrUninit<'dst>,\n ) -> Result, TryFromError> {\n if src_shape.id != T::SHAPE.id {\n return Err(TryFromError::UnsupportedSourceShape {\n src_shape,\n expected: &[T::SHAPE],\n });\n }\n let t = unsafe { src_ptr.read::() };\n let arc = Arc::new(t);\n Ok(unsafe { dst.put(arc) })\n }\n\n unsafe fn try_into_inner<'a, 'src, 'dst, T: Facet<'a>>(\n src_ptr: PtrMut<'src>,\n dst: PtrUninit<'dst>,\n ) -> Result, TryIntoInnerError> {\n use alloc::sync::Arc;\n\n // Read the Arc from the source pointer\n let arc = unsafe { src_ptr.read::>() };\n\n // Try to unwrap the Arc to get exclusive ownership\n match Arc::try_unwrap(arc) {\n Ok(inner) => Ok(unsafe { dst.put(inner) }),\n Err(arc) => {\n // Arc is shared, so we can't extract the inner value\n core::mem::forget(arc);\n Err(TryIntoInnerError::Unavailable)\n }\n }\n }\n\n unsafe fn try_borrow_inner<'a, 'src, T: Facet<'a>>(\n src_ptr: PtrConst<'src>,\n ) -> Result, TryBorrowInnerError> {\n let arc = unsafe { src_ptr.get::>() };\n Ok(PtrConst::new(&**arc))\n }\n\n let mut vtable = value_vtable!(alloc::sync::Arc, |f, opts| {\n write!(f, \"{}\", Self::SHAPE.type_identifier)?;\n if let Some(opts) = opts.for_children() {\n write!(f, \"<\")?;\n (T::SHAPE.vtable.type_name())(f, opts)?;\n write!(f, \">\")?;\n } else {\n write!(f, \"<…>\")?;\n }\n Ok(())\n });\n\n {\n let vtable = vtable.sized_mut().unwrap();\n vtable.try_from = || Some(try_from::);\n vtable.try_into_inner = || Some(try_into_inner::);\n vtable.try_borrow_inner = || Some(try_borrow_inner::);\n }\n vtable\n };\n\n const SHAPE: &'static crate::Shape = &const {\n // Function to return inner type's shape\n fn inner_shape<'a, T: Facet<'a>>() -> &'static Shape {\n T::SHAPE\n }\n\n crate::Shape::builder_for_sized::()\n .type_identifier(\"Arc\")\n .type_params(&[crate::TypeParam {\n name: \"T\",\n shape: || T::SHAPE,\n }])\n .ty(Type::User(UserType::Opaque))\n .def(Def::Pointer(\n PointerDef::builder()\n .pointee(|| T::SHAPE)\n .flags(PointerFlags::ATOMIC)\n .known(KnownPointer::Arc)\n .weak(|| as Facet>::SHAPE)\n .vtable(\n &const {\n PointerVTable::builder()\n .borrow_fn(|this| {\n let arc_ptr = unsafe { this.as_ptr::>() };\n let ptr = unsafe { Arc::as_ptr(&*arc_ptr) };\n PtrConst::new(ptr).into()\n })\n .new_into_fn(|this, ptr| {\n let t = unsafe { ptr.read::() };\n let arc = Arc::new(t);\n unsafe { this.put(arc) }\n })\n .downgrade_into_fn(|strong, weak| unsafe {\n weak.put(Arc::downgrade(strong.get::()))\n })\n .build()\n },\n )\n .build(),\n ))\n .inner(inner_shape::)\n .build()\n };\n}\n\nunsafe impl<'a> Facet<'a> for Arc {\n const VTABLE: &'static ValueVTable = &const {\n value_vtable!(alloc::sync::Arc, |f, opts| {\n write!(f, \"{}\", Self::SHAPE.type_identifier)?;\n if let Some(opts) = opts.for_children() {\n write!(f, \"<\")?;\n (str::SHAPE.vtable.type_name())(f, opts)?;\n write!(f, \">\")?;\n } else {\n write!(f, \"<…>\")?;\n }\n Ok(())\n })\n };\n\n const SHAPE: &'static crate::Shape = &const {\n // Function to return inner type's shape\n fn inner_shape() -> &'static Shape {\n str::SHAPE\n }\n\n crate::Shape::builder_for_sized::()\n .type_identifier(\"Arc\")\n .type_params(&[crate::TypeParam {\n name: \"T\",\n shape: || str::SHAPE,\n }])\n .ty(Type::User(UserType::Opaque))\n .def(Def::Pointer(\n PointerDef::builder()\n .pointee(|| str::SHAPE)\n .flags(PointerFlags::ATOMIC)\n .known(KnownPointer::Arc)\n .weak(|| as Facet>::SHAPE)\n .vtable(\n &const {\n PointerVTable::builder()\n .borrow_fn(|this| unsafe {\n let concrete = this.get::>();\n let s: &str = concrete;\n PtrConstWide::new(&raw const *s).into()\n })\n .new_into_fn(|_this, _ptr| todo!())\n .downgrade_into_fn(|_strong, _weak| todo!())\n .build()\n },\n )\n .build(),\n ))\n .inner(inner_shape)\n .build()\n };\n}\n\nunsafe impl<'a, U: Facet<'a>> Facet<'a> for Arc<[U]> {\n const VTABLE: &'static ValueVTable = &const {\n value_vtable!(alloc::sync::Arc<[U]>, |f, opts| {\n write!(f, \"{}\", Self::SHAPE.type_identifier)?;\n if let Some(opts) = opts.for_children() {\n write!(f, \"<\")?;\n (<[U]>::SHAPE.vtable.type_name())(f, opts)?;\n write!(f, \">\")?;\n } else {\n write!(f, \"<…>\")?;\n }\n Ok(())\n })\n };\n\n const SHAPE: &'static crate::Shape = &const {\n // Function to return inner type's shape\n fn inner_shape<'a, U: Facet<'a>>() -> &'static Shape {\n <[U]>::SHAPE\n }\n\n fn slice_builder_new<'a, U: Facet<'a>>() -> PtrMut<'static> {\n let v = Box::new(Vec::::new());\n let raw = Box::into_raw(v);\n PtrMut::new(raw)\n }\n\n fn slice_builder_push<'a, U: Facet<'a>>(builder: PtrMut, item: PtrMut) {\n unsafe {\n let vec = builder.as_mut::>();\n let value = item.read::();\n vec.push(value);\n }\n }\n\n fn slice_builder_convert<'a, U: Facet<'a>>(builder: PtrMut<'static>) -> PtrConst<'static> {\n unsafe {\n let vec_box = Box::from_raw(builder.as_ptr::>() as *mut Vec);\n let arc: Arc<[U]> = (*vec_box).into();\n let arc_box = Box::new(arc);\n PtrConst::new(Box::into_raw(arc_box) as *const Arc<[U]>)\n }\n }\n\n fn slice_builder_free<'a, U: Facet<'a>>(builder: PtrMut<'static>) {\n unsafe {\n let _ = Box::from_raw(builder.as_ptr::>() as *mut Vec);\n }\n }\n\n crate::Shape::builder_for_sized::()\n .type_identifier(\"Arc\")\n .type_params(&[crate::TypeParam {\n name: \"T\",\n shape: || <[U]>::SHAPE,\n }])\n .ty(Type::User(UserType::Opaque))\n .def(Def::Pointer(\n PointerDef::builder()\n .pointee(|| <[U]>::SHAPE)\n .flags(PointerFlags::ATOMIC)\n .known(KnownPointer::Arc)\n .weak(|| as Facet>::SHAPE)\n .vtable(\n &const {\n PointerVTable::builder()\n .borrow_fn(|this| unsafe {\n let concrete = this.get::>();\n let s: &[U] = concrete;\n PtrConstWide::new(&raw const *s).into()\n })\n .new_into_fn(|_this, _ptr| todo!())\n .downgrade_into_fn(|_strong, _weak| todo!())\n .slice_builder_vtable(\n &const {\n SliceBuilderVTable::builder()\n .new_fn(slice_builder_new::)\n .push_fn(slice_builder_push::)\n .convert_fn(slice_builder_convert::)\n .free_fn(slice_builder_free::)\n .build()\n },\n )\n .build()\n },\n )\n .build(),\n ))\n .inner(inner_shape::)\n .build()\n };\n}\n\nunsafe impl<'a, T: Facet<'a>> Facet<'a> for Weak {\n const VTABLE: &'static ValueVTable = &const {\n value_vtable!(alloc::sync::Weak, |f, opts| {\n write!(f, \"{}\", Self::SHAPE.type_identifier)?;\n if let Some(opts) = opts.for_children() {\n write!(f, \"<\")?;\n (T::SHAPE.vtable.type_name())(f, opts)?;\n write!(f, \">\")?;\n } else {\n write!(f, \"<…>\")?;\n }\n Ok(())\n })\n };\n\n const SHAPE: &'static crate::Shape = &const {\n // Function to return inner type's shape\n fn inner_shape<'a, T: Facet<'a>>() -> &'static Shape {\n T::SHAPE\n }\n\n crate::Shape::builder_for_sized::()\n .type_identifier(\"Weak\")\n .type_params(&[crate::TypeParam {\n name: \"T\",\n shape: || T::SHAPE,\n }])\n .ty(Type::User(UserType::Opaque))\n .def(Def::Pointer(\n PointerDef::builder()\n .pointee(|| T::SHAPE)\n .flags(PointerFlags::ATOMIC.union(PointerFlags::WEAK))\n .known(KnownPointer::ArcWeak)\n .strong(|| as Facet>::SHAPE)\n .vtable(\n &const {\n PointerVTable::builder()\n .upgrade_into_fn(|weak, strong| unsafe {\n Some(strong.put(weak.get::().upgrade()?))\n })\n .build()\n },\n )\n .build(),\n ))\n .inner(inner_shape::)\n .build()\n };\n}\n\nunsafe impl<'a> Facet<'a> for Weak {\n const VTABLE: &'static ValueVTable = &const {\n value_vtable!(alloc::sync::Weak, |f, opts| {\n write!(f, \"{}\", Self::SHAPE.type_identifier)?;\n if let Some(opts) = opts.for_children() {\n write!(f, \"<\")?;\n (str::SHAPE.vtable.type_name())(f, opts)?;\n write!(f, \">\")?;\n } else {\n write!(f, \"<…>\")?;\n }\n Ok(())\n })\n };\n\n const SHAPE: &'static crate::Shape = &const {\n // Function to return inner type's shape\n fn inner_shape() -> &'static Shape {\n str::SHAPE\n }\n\n crate::Shape::builder_for_sized::()\n .type_identifier(\"Weak\")\n .type_params(&[crate::TypeParam {\n name: \"T\",\n shape: || str::SHAPE,\n }])\n .ty(Type::User(UserType::Opaque))\n .def(Def::Pointer(\n PointerDef::builder()\n .pointee(|| str::SHAPE)\n .flags(PointerFlags::ATOMIC.union(PointerFlags::WEAK))\n .known(KnownPointer::ArcWeak)\n .strong(|| as Facet>::SHAPE)\n .vtable(\n &const {\n PointerVTable::builder()\n .upgrade_into_fn(|_weak, _strong| todo!())\n .build()\n },\n )\n .build(),\n ))\n .inner(inner_shape)\n .build()\n };\n}\n\nunsafe impl<'a, U: Facet<'a>> Facet<'a> for Weak<[U]> {\n const VTABLE: &'static ValueVTable = &const {\n value_vtable!(alloc::sync::Weak<[U]>, |f, opts| {\n write!(f, \"{}\", Self::SHAPE.type_identifier)?;\n if let Some(opts) = opts.for_children() {\n write!(f, \"<\")?;\n (<[U]>::SHAPE.vtable.type_name())(f, opts)?;\n write!(f, \">\")?;\n } else {\n write!(f, \"<…>\")?;\n }\n Ok(())\n })\n };\n\n const SHAPE: &'static crate::Shape = &const {\n fn inner_shape<'a, U: Facet<'a>>() -> &'static Shape {\n <[U]>::SHAPE\n }\n\n crate::Shape::builder_for_sized::()\n .type_identifier(\"Weak\")\n .type_params(&[crate::TypeParam {\n name: \"T\",\n shape: || <[U]>::SHAPE,\n }])\n .ty(Type::User(UserType::Opaque))\n .def(Def::Pointer(\n PointerDef::builder()\n .pointee(|| <[U]>::SHAPE)\n .flags(PointerFlags::ATOMIC.union(PointerFlags::WEAK))\n .known(KnownPointer::ArcWeak)\n .strong(|| as Facet>::SHAPE)\n .vtable(\n &const {\n PointerVTable::builder()\n .upgrade_into_fn(|weak, strong| unsafe {\n Some(strong.put(weak.get::().upgrade()?))\n })\n .build()\n },\n )\n .build(),\n ))\n .inner(inner_shape::)\n .build()\n };\n}\n\n#[cfg(test)]\nmod tests {\n use alloc::string::String;\n use alloc::sync::{Arc, Weak as ArcWeak};\n\n use super::*;\n\n #[test]\n fn test_arc_type_params() {\n let [type_param_1] = >::SHAPE.type_params else {\n panic!(\"Arc should only have 1 type param\")\n };\n assert_eq!(type_param_1.shape(), i32::SHAPE);\n }\n\n #[test]\n fn test_arc_vtable_1_new_borrow_drop() {\n facet_testhelpers::setup();\n\n let arc_shape = >::SHAPE;\n let arc_def = arc_shape\n .def\n .into_pointer()\n .expect(\"Arc should have a smart pointer definition\");\n\n // Allocate memory for the Arc\n let arc_uninit_ptr = arc_shape.allocate().unwrap();\n\n // Get the function pointer for creating a new Arc from a value\n let new_into_fn = arc_def\n .vtable\n .new_into_fn\n .expect(\"Arc should have new_into_fn\");\n\n // Create the value and initialize the Arc\n let mut value = String::from(\"example\");\n let arc_ptr = unsafe { new_into_fn(arc_uninit_ptr, PtrMut::new(&raw mut value)) };\n // The value now belongs to the Arc, prevent its drop\n core::mem::forget(value);\n\n // Get the function pointer for borrowing the inner value\n let borrow_fn = arc_def\n .vtable\n .borrow_fn\n .expect(\"Arc should have borrow_fn\");\n\n // Borrow the inner value and check it\n let borrowed_ptr = unsafe { borrow_fn(arc_ptr.as_const()) };\n // SAFETY: borrowed_ptr points to a valid String within the Arc\n assert_eq!(unsafe { borrowed_ptr.get::() }, \"example\");\n\n // Get the function pointer for dropping the Arc\n let drop_fn = (arc_shape.vtable.sized().unwrap().drop_in_place)()\n .expect(\"Arc should have drop_in_place\");\n\n // Drop the Arc in place\n // SAFETY: arc_ptr points to a valid Arc\n unsafe { drop_fn(arc_ptr) };\n\n // Deallocate the memory\n // SAFETY: arc_ptr was allocated by arc_shape and is now dropped (but memory is still valid)\n unsafe { arc_shape.deallocate_mut(arc_ptr).unwrap() };\n }\n\n #[test]\n fn test_arc_vtable_2_downgrade_upgrade_drop() {\n facet_testhelpers::setup();\n\n let arc_shape = >::SHAPE;\n let arc_def = arc_shape\n .def\n .into_pointer()\n .expect(\"Arc should have a smart pointer definition\");\n\n let weak_shape = >::SHAPE;\n let weak_def = weak_shape\n .def\n .into_pointer()\n .expect(\"ArcWeak should have a smart pointer definition\");\n\n // 1. Create the first Arc (arc1)\n let arc1_uninit_ptr = arc_shape.allocate().unwrap();\n let new_into_fn = arc_def.vtable.new_into_fn.unwrap();\n let mut value = String::from(\"example\");\n let arc1_ptr = unsafe { new_into_fn(arc1_uninit_ptr, PtrMut::new(&raw mut value)) };\n core::mem::forget(value); // Value now owned by arc1\n\n // 2. Downgrade arc1 to create a weak pointer (weak1)\n let weak1_uninit_ptr = weak_shape.allocate().unwrap();\n let downgrade_into_fn = arc_def.vtable.downgrade_into_fn.unwrap();\n // SAFETY: arc1_ptr points to a valid Arc, weak1_uninit_ptr is allocated for a Weak\n let weak1_ptr = unsafe { downgrade_into_fn(arc1_ptr, weak1_uninit_ptr) };\n\n // 3. Upgrade weak1 to create a second Arc (arc2)\n let arc2_uninit_ptr = arc_shape.allocate().unwrap();\n let upgrade_into_fn = weak_def.vtable.upgrade_into_fn.unwrap();\n // SAFETY: weak1_ptr points to a valid Weak, arc2_uninit_ptr is allocated for an Arc.\n // Upgrade should succeed as arc1 still exists.\n let arc2_ptr = unsafe { upgrade_into_fn(weak1_ptr, arc2_uninit_ptr) }\n .expect(\"Upgrade should succeed while original Arc exists\");\n\n // Check the content of the upgraded Arc\n let borrow_fn = arc_def.vtable.borrow_fn.unwrap();\n // SAFETY: arc2_ptr points to a valid Arc\n let borrowed_ptr = unsafe { borrow_fn(arc2_ptr.as_const()) };\n // SAFETY: borrowed_ptr points to a valid String\n assert_eq!(unsafe { borrowed_ptr.get::() }, \"example\");\n\n // 4. Drop everything and free memory\n let arc_drop_fn = (arc_shape.vtable.sized().unwrap().drop_in_place)().unwrap();\n let weak_drop_fn = (weak_shape.vtable.sized().unwrap().drop_in_place)().unwrap();\n\n unsafe {\n // Drop Arcs\n arc_drop_fn(arc1_ptr);\n arc_shape.deallocate_mut(arc1_ptr).unwrap();\n arc_drop_fn(arc2_ptr);\n arc_shape.deallocate_mut(arc2_ptr).unwrap();\n\n // Drop Weak\n weak_drop_fn(weak1_ptr);\n weak_shape.deallocate_mut(weak1_ptr).unwrap();\n }\n }\n\n #[test]\n fn test_arc_vtable_3_downgrade_drop_try_upgrade() {\n facet_testhelpers::setup();\n\n let arc_shape = >::SHAPE;\n let arc_def = arc_shape\n .def\n .into_pointer()\n .expect(\"Arc should have a smart pointer definition\");\n\n let weak_shape = >::SHAPE;\n let weak_def = weak_shape\n .def\n .into_pointer()\n .expect(\"ArcWeak should have a smart pointer definition\");\n\n // 1. Create the strong Arc (arc1)\n let arc1_uninit_ptr = arc_shape.allocate().unwrap();\n let new_into_fn = arc_def.vtable.new_into_fn.unwrap();\n let mut value = String::from(\"example\");\n let arc1_ptr = unsafe { new_into_fn(arc1_uninit_ptr, PtrMut::new(&raw mut value)) };\n core::mem::forget(value);\n\n // 2. Downgrade arc1 to create a weak pointer (weak1)\n let weak1_uninit_ptr = weak_shape.allocate().unwrap();\n let downgrade_into_fn = arc_def.vtable.downgrade_into_fn.unwrap();\n // SAFETY: arc1_ptr is valid, weak1_uninit_ptr is allocated for Weak\n let weak1_ptr = unsafe { downgrade_into_fn(arc1_ptr, weak1_uninit_ptr) };\n\n // 3. Drop and free the strong pointer (arc1)\n let arc_drop_fn = (arc_shape.vtable.sized().unwrap().drop_in_place)().unwrap();\n unsafe {\n arc_drop_fn(arc1_ptr);\n arc_shape.deallocate_mut(arc1_ptr).unwrap();\n }\n\n // 4. Attempt to upgrade the weak pointer (weak1)\n let upgrade_into_fn = weak_def.vtable.upgrade_into_fn.unwrap();\n let arc2_uninit_ptr = arc_shape.allocate().unwrap();\n // SAFETY: weak1_ptr is valid (though points to dropped data), arc2_uninit_ptr is allocated for Arc\n let upgrade_result = unsafe { upgrade_into_fn(weak1_ptr, arc2_uninit_ptr) };\n\n // Assert that the upgrade failed\n assert!(\n upgrade_result.is_none(),\n \"Upgrade should fail after the strong Arc is dropped\"\n );\n\n // 5. Clean up: Deallocate the memory intended for the failed upgrade and drop/deallocate the weak pointer\n let weak_drop_fn = (weak_shape.vtable.sized().unwrap().drop_in_place)().unwrap();\n unsafe {\n // Deallocate the *uninitialized* memory allocated for the failed upgrade attempt\n arc_shape.deallocate_uninit(arc2_uninit_ptr).unwrap();\n\n // Drop and deallocate the weak pointer\n weak_drop_fn(weak1_ptr);\n weak_shape.deallocate_mut(weak1_ptr).unwrap();\n }\n }\n\n #[test]\n fn test_arc_vtable_4_try_from() {\n facet_testhelpers::setup();\n\n // Get the shapes we'll be working with\n let string_shape = ::SHAPE;\n let arc_shape = >::SHAPE;\n let arc_def = arc_shape\n .def\n .into_pointer()\n .expect(\"Arc should have a smart pointer definition\");\n\n // 1. Create a String value\n let value = String::from(\"try_from test\");\n let value_ptr = PtrConst::new(&value as *const String as *const u8);\n\n // 2. Allocate memory for the Arc\n let arc_uninit_ptr = arc_shape.allocate().unwrap();\n\n // 3. Get the try_from function from the Arc shape's ValueVTable\n let try_from_fn =\n (arc_shape.vtable.sized().unwrap().try_from)().expect(\"Arc should have try_from\");\n\n // 4. Try to convert String to Arc\n let arc_ptr = unsafe { try_from_fn(value_ptr, string_shape, arc_uninit_ptr) }\n .expect(\"try_from should succeed\");\n core::mem::forget(value);\n\n // 5. Borrow the inner value and verify it's correct\n let borrow_fn = arc_def\n .vtable\n .borrow_fn\n .expect(\"Arc should have borrow_fn\");\n let borrowed_ptr = unsafe { borrow_fn(arc_ptr.as_const()) };\n\n // SAFETY: borrowed_ptr points to a valid String within the Arc\n assert_eq!(unsafe { borrowed_ptr.get::() }, \"try_from test\");\n\n // 6. Clean up\n let drop_fn = (arc_shape.vtable.sized().unwrap().drop_in_place)()\n .expect(\"Arc should have drop_in_place\");\n\n unsafe {\n drop_fn(arc_ptr);\n arc_shape.deallocate_mut(arc_ptr).unwrap();\n }\n }\n\n #[test]\n fn test_arc_vtable_5_try_into_inner() {\n facet_testhelpers::setup();\n\n // Get the shapes we'll be working with\n let string_shape = ::SHAPE;\n let arc_shape = >::SHAPE;\n let arc_def = arc_shape\n .def\n .into_pointer()\n .expect(\"Arc should have a smart pointer definition\");\n\n // 1. Create an Arc\n let arc_uninit_ptr = arc_shape.allocate().unwrap();\n let new_into_fn = arc_def\n .vtable\n .new_into_fn\n .expect(\"Arc should have new_into_fn\");\n\n let mut value = String::from(\"try_into_inner test\");\n let arc_ptr = unsafe { new_into_fn(arc_uninit_ptr, PtrMut::new(&raw mut value)) };\n core::mem::forget(value); // Value now owned by arc\n\n // 2. Allocate memory for the extracted String\n let string_uninit_ptr = string_shape.allocate().unwrap();\n\n // 3. Get the try_into_inner function from the Arc's ValueVTable\n let try_into_inner_fn = (arc_shape.vtable.sized().unwrap().try_into_inner)()\n .expect(\"Arc Shape should have try_into_inner\");\n\n // 4. Try to extract the String from the Arc\n // This should succeed because we have exclusive access to the Arc (strong count = 1)\n let string_ptr = unsafe { try_into_inner_fn(arc_ptr, string_uninit_ptr) }\n .expect(\"try_into_inner should succeed with exclusive access\");\n\n // 5. Verify the extracted String\n assert_eq!(\n unsafe { string_ptr.as_const().get::() },\n \"try_into_inner test\"\n );\n\n // 6. Clean up\n let string_drop_fn = (string_shape.vtable.sized().unwrap().drop_in_place)()\n .expect(\"String should have drop_in_place\");\n\n unsafe {\n // The Arc should already be dropped by try_into_inner\n // But we still need to deallocate its memory\n arc_shape.deallocate_mut(arc_ptr).unwrap();\n\n // Drop and deallocate the extracted String\n string_drop_fn(string_ptr);\n string_shape.deallocate_mut(string_ptr).unwrap();\n }\n }\n\n #[test]\n fn test_arc_vtable_6_slice_builder() {\n facet_testhelpers::setup();\n\n // Get the shapes we'll be working with\n let arc_slice_shape = >::SHAPE;\n let arc_slice_def = arc_slice_shape\n .def\n .into_pointer()\n .expect(\"Arc<[i32]> should have a smart pointer definition\");\n\n // Get the slice builder vtable\n let slice_builder_vtable = arc_slice_def\n .vtable\n .slice_builder_vtable\n .expect(\"Arc<[i32]> should have slice_builder_vtable\");\n\n // 1. Create a new builder\n let builder_ptr = (slice_builder_vtable.new_fn)();\n\n // 2. Push some items to the builder\n let push_fn = slice_builder_vtable.push_fn;\n let values = [1i32, 2, 3, 4, 5];\n for &value in &values {\n let mut value_copy = value;\n let value_ptr = PtrMut::new(&raw mut value_copy);\n unsafe { push_fn(builder_ptr, value_ptr) };\n let _ = value_copy; // Value now owned by the builder\n }\n\n // 3. Convert the builder to Arc<[i32]>\n let convert_fn = slice_builder_vtable.convert_fn;\n let arc_slice_ptr = unsafe { convert_fn(builder_ptr) };\n\n // 4. Verify the contents by borrowing\n let borrow_fn = arc_slice_def\n .vtable\n .borrow_fn\n .expect(\"Arc<[i32]> should have borrow_fn\");\n let borrowed_ptr = unsafe { borrow_fn(arc_slice_ptr) };\n\n // Convert the wide pointer to a slice reference\n let slice = unsafe { borrowed_ptr.get::<[i32]>() };\n assert_eq!(slice, &[1, 2, 3, 4, 5]);\n\n // 5. Clean up - the Arc<[i32]> was boxed by convert_fn, we need to deallocate the Box\n unsafe {\n let _ = Box::from_raw(arc_slice_ptr.as_ptr::>() as *mut Arc<[i32]>);\n }\n }\n\n #[test]\n fn test_arc_vtable_7_slice_builder_free() {\n facet_testhelpers::setup();\n\n // Get the shapes we'll be working with\n let arc_slice_shape = >::SHAPE;\n let arc_slice_def = arc_slice_shape\n .def\n .into_pointer()\n .expect(\"Arc<[String]> should have a smart pointer definition\");\n\n // Get the slice builder vtable\n let slice_builder_vtable = arc_slice_def\n .vtable\n .slice_builder_vtable\n .expect(\"Arc<[String]> should have slice_builder_vtable\");\n\n // 1. Create a new builder\n let builder_ptr = (slice_builder_vtable.new_fn)();\n\n // 2. Push some items to the builder\n let push_fn = slice_builder_vtable.push_fn;\n let strings = [\"hello\", \"world\", \"test\"];\n for &s in &strings {\n let mut value = String::from(s);\n let value_ptr = PtrMut::new(&raw mut value);\n unsafe { push_fn(builder_ptr, value_ptr) };\n core::mem::forget(value); // Value now owned by the builder\n }\n\n // 3. Instead of converting, test the free function\n // This simulates abandoning the builder without creating the Arc\n let free_fn = slice_builder_vtable.free_fn;\n unsafe { free_fn(builder_ptr) };\n\n // If we get here without panicking, the free worked correctly\n }\n}\n"], ["/facet/facet-core/src/impls_alloc/string.rs", "use crate::{Def, Facet, Shape, Type, UserType, ValueVTable, value_vtable};\nuse alloc::string::ToString;\n\n#[cfg(feature = \"alloc\")]\nunsafe impl Facet<'_> for alloc::string::String {\n const VTABLE: &'static ValueVTable = &const {\n let mut vtable = value_vtable!(alloc::string::String, |f, _opts| write!(\n f,\n \"{}\",\n Self::SHAPE.type_identifier\n ));\n\n let vtable_sized = vtable.sized_mut().unwrap();\n vtable_sized.parse = || {\n Some(|s, target| {\n // For String, parsing from a string is just copying the string\n Ok(unsafe { target.put(s.to_string()) })\n })\n };\n\n vtable\n };\n\n const SHAPE: &'static Shape = &const {\n Shape::builder_for_sized::()\n .def(Def::Scalar)\n .type_identifier(\"String\")\n .ty(Type::User(UserType::Opaque))\n .build()\n };\n}\n\nunsafe impl<'a> Facet<'a> for alloc::borrow::Cow<'a, str> {\n const VTABLE: &'static ValueVTable = &const {\n value_vtable!(alloc::borrow::Cow<'_, str>, |f, _opts| write!(\n f,\n \"Cow<'_, str>\"\n ))\n };\n\n const SHAPE: &'static Shape = &const {\n Shape::builder_for_sized::()\n .def(Def::Scalar)\n .type_identifier(\"Cow\")\n .ty(Type::User(UserType::Opaque))\n .build()\n };\n}\n\n#[cfg(test)]\nmod tests {\n use crate::Facet;\n use crate::ptr::PtrUninit;\n use alloc::string::String;\n\n #[test]\n fn test_string_has_parse() {\n // Check that String has a parse function in its vtable\n let shape = String::SHAPE;\n assert!(\n shape.vtable.has_parse(),\n \"String should have parse function\"\n );\n }\n\n #[test]\n fn test_string_parse() {\n // Test that we can parse a string into a String\n let shape = String::SHAPE;\n let parse_fn = (shape.vtable.sized().unwrap().parse)().unwrap();\n\n // Allocate memory for the String\n let layout = shape.layout.sized_layout().unwrap();\n let ptr = unsafe { alloc::alloc::alloc(layout) };\n let uninit = PtrUninit::new(ptr);\n\n // Parse the string\n let result = unsafe { parse_fn(\"hello world\", uninit) };\n assert!(result.is_ok());\n\n // Get the parsed value\n let ptr_mut = result.unwrap();\n let parsed = unsafe { ptr_mut.get::() };\n assert_eq!(parsed, &String::from(\"hello world\"));\n\n // Clean up\n unsafe {\n ptr_mut.drop_in_place::();\n alloc::alloc::dealloc(ptr, layout);\n }\n }\n}\n"], ["/facet/facet-core/src/types/mod.rs", "//! structs and vtable definitions used by Facet\n\n#[cfg(feature = \"alloc\")]\nuse crate::PtrMut;\n\nuse core::alloc::Layout;\n\nmod characteristic;\npub use characteristic::*;\n\nmod value;\npub use value::*;\n\nmod def;\npub use def::*;\n\nmod ty;\npub use ty::*;\n\nuse crate::{ConstTypeId, Facet};\n\n/// Schema for reflection of a type\n#[derive(Clone, Copy)]\n#[repr(C)]\npub struct Shape {\n /// Unique type identifier, provided by the compiler.\n pub id: ConstTypeId,\n\n /// Size, alignment — enough to allocate a value of this type\n /// (but not initialize it.)\n pub layout: ShapeLayout,\n\n /// Function pointers to perform various operations: print the full type\n /// name (with generic type parameters), use the Display implementation,\n /// the Debug implementation, build a default value, clone, etc.\n ///\n /// If the shape has `ShapeLayout::Unsized`, then the parent pointer needs to be passed.\n ///\n /// There are more specific vtables in variants of [`Def`]\n pub vtable: &'static ValueVTable,\n\n /// Underlying type: primitive, sequence, user, pointer.\n ///\n /// This follows the [`Rust Reference`](https://doc.rust-lang.org/reference/types.html), but\n /// omits function types, and trait types, as they cannot be represented here.\n pub ty: Type,\n\n /// Functional definition of the value: details for scalars, functions for inserting values into\n /// a map, or fetching a value from a list.\n pub def: Def,\n\n /// Identifier for a type: the type's name without generic parameters. To get the type's full\n /// name with generic parameters, see [`ValueVTable::type_name`].\n pub type_identifier: &'static str,\n\n /// Generic parameters for the shape\n pub type_params: &'static [TypeParam],\n\n /// Doc comment lines, collected by facet-macros. Note that they tend to\n /// start with a space.\n pub doc: &'static [&'static str],\n\n /// Attributes that can be applied to a shape\n pub attributes: &'static [ShapeAttribute],\n\n /// Shape type tag, used to identify the type in self describing formats.\n ///\n /// For some formats, this is a fully or partially qualified name.\n /// For other formats, this is a simple string or integer type.\n pub type_tag: Option<&'static str>,\n\n /// As far as serialization and deserialization goes, we consider that this shape is a wrapper\n /// for that shape This is true for \"newtypes\" like `NonZero`, wrappers like `Utf8PathBuf`,\n /// smart pointers like `Arc`, etc.\n ///\n /// When this is set, deserialization takes that into account. For example, facet-json\n /// doesn't expect:\n ///\n /// { \"NonZero\": { \"value\": 128 } }\n ///\n /// It expects just\n ///\n /// 128\n ///\n /// Same for `Utf8PathBuf`, which is parsed from and serialized to \"just a string\".\n ///\n /// See Partial's `innermost_shape` function (and its support in `put`).\n pub inner: Option &'static Shape>,\n}\n\n/// Layout of the shape\n#[derive(Clone, Copy, Debug, Hash)]\npub enum ShapeLayout {\n /// `Sized` type\n Sized(Layout),\n /// `!Sized` type\n Unsized,\n}\n\nimpl ShapeLayout {\n /// `Layout` if this type is `Sized`\n #[inline]\n pub fn sized_layout(self) -> Result {\n match self {\n ShapeLayout::Sized(layout) => Ok(layout),\n ShapeLayout::Unsized => Err(UnsizedError),\n }\n }\n}\n\n/// Tried to get the `Layout` of an unsized type\n#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Hash)]\npub struct UnsizedError;\n\nimpl core::fmt::Display for UnsizedError {\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n write!(f, \"Not a Sized type\")\n }\n}\n\nimpl core::error::Error for UnsizedError {}\n\n/// An attribute that can be applied to a shape\n#[derive(Debug, PartialEq)]\npub enum ShapeAttribute {\n /// Reject deserialization upon encountering an unknown key.\n DenyUnknownFields,\n /// Indicates that, when deserializing, fields from this shape that are\n /// missing in the input should be filled with corresponding field values from\n /// a `T::default()` (where T is this shape)\n Default,\n /// Indicates that this is a transparent wrapper type, like `NewType(T)`\n /// it should not be treated like a struct, but like something that can be built\n /// from `T` and converted back to `T`\n Transparent,\n /// Specifies a case conversion rule for all fields or variants\n RenameAll(&'static str),\n /// Custom field attribute containing arbitrary text\n Arbitrary(&'static str),\n}\n\nimpl Shape {\n /// Returns a builder for a shape for some type `T`.\n pub const fn builder_for_sized<'a, T: Facet<'a>>() -> ShapeBuilder {\n ShapeBuilder::new(T::VTABLE)\n .layout(Layout::new::())\n .id(ConstTypeId::of::())\n }\n\n /// Returns a builder for a shape for some type `T`.\n pub const fn builder_for_unsized<'a, T: Facet<'a> + ?Sized>() -> ShapeBuilder {\n ShapeBuilder::new(T::VTABLE)\n .set_unsized()\n .id(ConstTypeId::of::())\n }\n\n /// Check if this shape is of the given type\n pub fn is_type<'facet, Other: Facet<'facet>>(&self) -> bool {\n let l = self;\n let r = Other::SHAPE;\n l == r\n }\n\n /// Assert that this shape is of the given type, panicking if it's not\n pub fn assert_type<'facet, Other: Facet<'facet>>(&self) {\n assert!(\n self.is_type::(),\n \"Type mismatch: expected {}, found {self}\",\n Other::SHAPE,\n );\n }\n\n /// See [`ShapeAttribute::DenyUnknownFields`]\n #[inline]\n pub fn has_deny_unknown_fields_attr(&self) -> bool {\n self.attributes.contains(&ShapeAttribute::DenyUnknownFields)\n }\n\n /// See [`ShapeAttribute::Default`]\n #[inline]\n pub fn has_default_attr(&self) -> bool {\n self.attributes.contains(&ShapeAttribute::Default)\n }\n\n /// See [`ShapeAttribute::RenameAll`]\n #[inline]\n pub fn get_rename_all_attr(&self) -> Option<&str> {\n self.attributes.iter().find_map(|attr| {\n if let ShapeAttribute::RenameAll(rule) = attr {\n Some(*rule)\n } else {\n None\n }\n })\n }\n}\n\n/// Builder for [`Shape`]\npub struct ShapeBuilder {\n id: Option,\n layout: Option,\n vtable: &'static ValueVTable,\n def: Def,\n ty: Option,\n type_identifier: Option<&'static str>,\n type_params: &'static [TypeParam],\n doc: &'static [&'static str],\n attributes: &'static [ShapeAttribute],\n type_tag: Option<&'static str>,\n inner: Option &'static Shape>,\n}\n\nimpl ShapeBuilder {\n /// Creates a new `ShapeBuilder` with all fields set to `None`.\n #[allow(clippy::new_without_default)]\n pub const fn new(vtable: &'static ValueVTable) -> Self {\n Self {\n id: None,\n layout: None,\n vtable,\n def: Def::Undefined,\n ty: None,\n type_identifier: None,\n type_params: &[],\n doc: &[],\n attributes: &[],\n type_tag: None,\n inner: None,\n }\n }\n\n /// Sets the id field of the `ShapeBuilder`.\n #[inline]\n pub const fn id(mut self, id: ConstTypeId) -> Self {\n self.id = Some(id);\n self\n }\n\n /// Sets the `layout` field of the `ShapeBuilder`.\n #[inline]\n pub const fn layout(mut self, layout: Layout) -> Self {\n self.layout = Some(ShapeLayout::Sized(layout));\n self\n }\n\n /// Sets the type as unsized\n #[inline]\n pub const fn set_unsized(mut self) -> Self {\n self.layout = Some(ShapeLayout::Unsized);\n self\n }\n\n /// Sets the `def` field of the `ShapeBuilder`.\n #[inline]\n pub const fn def(mut self, def: Def) -> Self {\n self.def = def;\n self\n }\n\n /// Sets the `ty` field of the `ShapeBuilder`.\n #[inline]\n pub const fn ty(mut self, ty: Type) -> Self {\n self.ty = Some(ty);\n self\n }\n\n /// Sets the `type_identifier` field of the `ShapeBuilder`.\n #[inline]\n pub const fn type_identifier(mut self, type_identifier: &'static str) -> Self {\n self.type_identifier = Some(type_identifier);\n self\n }\n\n /// Sets the `type_params` field of the `ShapeBuilder`.\n #[inline]\n pub const fn type_params(mut self, type_params: &'static [TypeParam]) -> Self {\n self.type_params = type_params;\n self\n }\n\n /// Sets the `doc` field of the `ShapeBuilder`.\n #[inline]\n pub const fn doc(mut self, doc: &'static [&'static str]) -> Self {\n self.doc = doc;\n self\n }\n\n /// Sets the `attributes` field of the `ShapeBuilder`.\n #[inline]\n pub const fn attributes(mut self, attributes: &'static [ShapeAttribute]) -> Self {\n self.attributes = attributes;\n self\n }\n\n /// Sets the `type_tag` field of the `ShapeBuilder`.\n #[inline]\n pub const fn type_tag(mut self, type_tag: &'static str) -> Self {\n self.type_tag = Some(type_tag);\n self\n }\n\n /// Sets the `inner` field of the `ShapeBuilder`.\n ///\n /// This indicates that this shape is a transparent wrapper for another shape,\n /// like a newtype or smart pointer, and should be treated as such for serialization\n /// and deserialization.\n ///\n /// The function `inner_fn` should return the static shape of the inner type.\n #[inline]\n pub const fn inner(mut self, inner_fn: fn() -> &'static Shape) -> Self {\n self.inner = Some(inner_fn);\n self\n }\n\n /// Builds a `Shape` from the `ShapeBuilder`.\n ///\n /// # Panics\n ///\n /// This method will panic if any of the required fields (`id`, `layout`, `type_identifier`, or `ty`) are `None`.\n #[inline]\n pub const fn build(self) -> Shape {\n Shape {\n id: self.id.unwrap(),\n layout: self.layout.unwrap(),\n vtable: self.vtable,\n type_identifier: self.type_identifier.unwrap(),\n type_params: self.type_params,\n def: self.def,\n ty: self.ty.unwrap(),\n doc: self.doc,\n attributes: self.attributes,\n type_tag: self.type_tag,\n inner: self.inner,\n }\n }\n}\n\nimpl PartialEq for Shape {\n #[inline]\n fn eq(&self, other: &Self) -> bool {\n self.id == other.id\n }\n}\n\nimpl Eq for Shape {}\n\nimpl core::hash::Hash for Shape {\n fn hash(&self, state: &mut H) {\n self.id.hash(state);\n self.layout.hash(state);\n }\n}\n\nimpl Shape {\n /// Check if this shape is of the given type\n #[inline]\n pub fn is_shape(&self, other: &Shape) -> bool {\n self == other\n }\n\n /// Assert that this shape is equal to the given shape, panicking if it's not\n pub fn assert_shape(&self, other: &Shape) {\n assert!(\n self.is_shape(other),\n \"Shape mismatch: expected {other}, found {self}\",\n );\n }\n}\n\n// Helper struct to format the name for display\nimpl core::fmt::Display for Shape {\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n (self.vtable.type_name())(f, TypeNameOpts::default())\n }\n}\n\nimpl core::fmt::Debug for Shape {\n fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {\n // NOTE:\n // This dummy destructuring is present to ensure that if fields are added,\n // developers will get a compiler error in this function, reminding them\n // to carefully consider whether it should be shown when debug formatting.\n let Self {\n id: _, // omit by default\n layout: _,\n vtable: _, // omit by default\n ty: _,\n def: _,\n type_identifier: _,\n type_params: _,\n doc: _,\n attributes: _,\n type_tag: _,\n inner: _,\n } = self;\n\n if f.alternate() {\n f.debug_struct(\"Shape\")\n .field(\"id\", &self.id)\n .field(\"layout\", &format_args!(\"{:?}\", self.layout))\n .field(\"vtable\", &format_args!(\"ValueVTable {{ .. }}\"))\n .field(\"ty\", &self.ty)\n .field(\"def\", &self.def)\n .field(\"type_identifier\", &self.type_identifier)\n .field(\"type_params\", &self.type_params)\n .field(\"doc\", &self.doc)\n .field(\"attributes\", &self.attributes)\n .field(\"type_tag\", &self.type_tag)\n .field(\"inner\", &self.inner)\n .finish()\n } else {\n let mut debug_struct = f.debug_struct(\"Shape\");\n\n macro_rules! field {\n ( $field:literal, $( $fmt_args:tt )* ) => {{\n debug_struct.field($field, &format_args!($($fmt_args)*));\n }};\n }\n\n field!(\"type_identifier\", \"{:?}\", self.type_identifier);\n\n if !self.type_params.is_empty() {\n // Use `[]` to indicate empty `type_params` (a real empty slice),\n // and `«(...)»` to show custom-formatted parameter sets when present.\n // Avoids visual conflict with array types like `[T; N]` in other fields.\n field!(\"type_params\", \"{}\", {\n struct TypeParams<'shape>(&'shape [TypeParam]);\n impl core::fmt::Display for TypeParams<'_> {\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n let mut iter = self.0.iter();\n if let Some(first) = iter.next() {\n write!(f, \"«({}: {}\", first.name, (first.shape)())?;\n for next in iter {\n write!(f, \", {}: {}\", next.name, (next.shape)())?;\n }\n write!(f, \")»\")?;\n } else {\n write!(f, \"[]\")?;\n }\n Ok(())\n }\n }\n TypeParams(self.type_params)\n });\n }\n\n if let Some(type_tag) = self.type_tag {\n field!(\"type_tag\", \"{:?}\", type_tag);\n }\n\n if !self.attributes.is_empty() {\n field!(\"attributes\", \"{:?}\", self.attributes);\n }\n\n // Omit the `inner` field if this shape is not a transparent wrapper.\n if let Some(inner) = self.inner {\n field!(\"inner\", \"{:?}\", (inner)());\n }\n\n // Uses `Display` to potentially format with shorthand syntax.\n field!(\"ty\", \"{}\", self.ty);\n\n // For sized layouts, display size and alignment in shorthand.\n // NOTE: If you wish to display the bitshift for alignment, please open an issue.\n if let ShapeLayout::Sized(layout) = self.layout {\n field!(\n \"layout\",\n \"Sized(«{} align {}»)\",\n layout.size(),\n layout.align()\n );\n } else {\n field!(\"layout\", \"{:?}\", self.layout);\n }\n\n // If `def` is `Undefined`, the information in `ty` would be more useful.\n if !matches!(self.def, Def::Undefined) {\n field!(\"def\", \"{:?}\", self.def);\n }\n\n if !self.doc.is_empty() {\n // TODO: Should these be called \"strings\"? Because `#[doc]` can contain newlines.\n field!(\"doc\", \"«{} lines»\", self.doc.len());\n }\n\n debug_struct.finish_non_exhaustive()\n }\n }\n}\n\nimpl Shape {\n /// Heap-allocate a value of this shape\n #[cfg(feature = \"alloc\")]\n #[inline]\n pub fn allocate(&self) -> Result, UnsizedError> {\n let layout = self.layout.sized_layout()?;\n\n Ok(crate::ptr::PtrUninit::new(if layout.size() == 0 {\n core::ptr::without_provenance_mut(layout.align())\n } else {\n // SAFETY: We have checked that layout's size is non-zero\n unsafe { alloc::alloc::alloc(layout) }\n }))\n }\n\n /// Deallocate a heap-allocated value of this shape\n ///\n /// # Safety\n ///\n /// - `ptr` must have been allocated using [`Self::allocate`] and be aligned for this shape.\n /// - `ptr` must point to a region that is not already deallocated.\n #[cfg(feature = \"alloc\")]\n #[inline]\n pub unsafe fn deallocate_mut(&self, ptr: PtrMut) -> Result<(), UnsizedError> {\n use alloc::alloc::dealloc;\n\n let layout = self.layout.sized_layout()?;\n\n if layout.size() == 0 {\n // Nothing to deallocate\n return Ok(());\n }\n // SAFETY: The user guarantees ptr is valid and from allocate, we checked size isn't 0\n unsafe { dealloc(ptr.as_mut_byte_ptr(), layout) }\n\n Ok(())\n }\n\n /// Deallocate a heap-allocated, uninitialized value of this shape.\n ///\n /// # Safety\n ///\n /// - `ptr` must have been allocated using [`Self::allocate`] (or equivalent) for this shape.\n /// - `ptr` must not have been already deallocated.\n /// - `ptr` must be properly aligned for this shape.\n #[cfg(feature = \"alloc\")]\n #[inline]\n pub unsafe fn deallocate_uninit(\n &self,\n ptr: crate::ptr::PtrUninit<'static>,\n ) -> Result<(), UnsizedError> {\n use alloc::alloc::dealloc;\n\n let layout = self.layout.sized_layout()?;\n\n if layout.size() == 0 {\n // Nothing to deallocate\n return Ok(());\n }\n // SAFETY: The user guarantees ptr is valid and from allocate; layout is nonzero\n unsafe { dealloc(ptr.as_mut_byte_ptr(), layout) };\n\n Ok(())\n }\n}\n\n/// Represents a lifetime parameter, e.g., `'a` or `'a: 'b + 'c`.\n///\n/// Note: these are subject to change — it's a bit too stringly-typed for now.\n#[derive(Debug, Clone)]\npub struct TypeParam {\n /// The name of the type parameter (e.g., `T`).\n pub name: &'static str,\n\n /// The shape of the type parameter (e.g. `String`)\n pub shape: fn() -> &'static Shape,\n}\n\nimpl TypeParam {\n /// Returns the shape of the type parameter.\n #[inline]\n pub fn shape(&self) -> &'static Shape {\n (self.shape)()\n }\n}\n"], ["/facet/facet-core/src/impls_alloc/rc.rs", "use alloc::rc::{Rc, Weak};\n\nuse crate::{\n Def, Facet, KnownPointer, PointerDef, PointerFlags, PointerVTable, PtrConst, PtrConstWide,\n PtrMut, PtrUninit, Shape, TryBorrowInnerError, TryFromError, TryIntoInnerError, Type, UserType,\n ValueVTable, value_vtable,\n};\n\nunsafe impl<'a, T: Facet<'a>> Facet<'a> for Rc {\n const VTABLE: &'static ValueVTable = &const {\n // Define the functions for transparent conversion between Rc and T\n unsafe fn try_from<'a, 'src, 'dst, T: Facet<'a>>(\n src_ptr: PtrConst<'src>,\n src_shape: &'static Shape,\n dst: PtrUninit<'dst>,\n ) -> Result, TryFromError> {\n if src_shape.id != T::SHAPE.id {\n return Err(TryFromError::UnsupportedSourceShape {\n src_shape,\n expected: &[T::SHAPE],\n });\n }\n let t = unsafe { src_ptr.read::() };\n let rc = Rc::new(t);\n Ok(unsafe { dst.put(rc) })\n }\n\n unsafe fn try_into_inner<'a, 'src, 'dst, T: Facet<'a>>(\n src_ptr: PtrMut<'src>,\n dst: PtrUninit<'dst>,\n ) -> Result, TryIntoInnerError> {\n let rc = unsafe { src_ptr.get::>() };\n match Rc::try_unwrap(rc.clone()) {\n Ok(t) => Ok(unsafe { dst.put(t) }),\n Err(_) => Err(TryIntoInnerError::Unavailable),\n }\n }\n\n unsafe fn try_borrow_inner<'a, 'src, T: Facet<'a>>(\n src_ptr: PtrConst<'src>,\n ) -> Result, TryBorrowInnerError> {\n let rc = unsafe { src_ptr.get::>() };\n Ok(PtrConst::new(&**rc))\n }\n\n let mut vtable = value_vtable!(alloc::rc::Rc, |f, opts| {\n write!(f, \"{}\", Self::SHAPE.type_identifier)?;\n if let Some(opts) = opts.for_children() {\n write!(f, \"<\")?;\n T::SHAPE.vtable.type_name()(f, opts)?;\n write!(f, \">\")?;\n } else {\n write!(f, \"<…>\")?;\n }\n Ok(())\n });\n {\n let vtable = vtable.sized_mut().unwrap();\n vtable.try_from = || Some(try_from::);\n vtable.try_into_inner = || Some(try_into_inner::);\n vtable.try_borrow_inner = || Some(try_borrow_inner::);\n }\n vtable\n };\n\n const SHAPE: &'static crate::Shape = &const {\n // Function to return inner type's shape\n fn inner_shape<'a, T: Facet<'a>>() -> &'static Shape {\n T::SHAPE\n }\n\n crate::Shape::builder_for_sized::()\n .type_identifier(\"Rc\")\n .type_params(&[crate::TypeParam {\n name: \"T\",\n shape: || T::SHAPE,\n }])\n .ty(Type::User(UserType::Opaque))\n .def(Def::Pointer(\n PointerDef::builder()\n .pointee(|| T::SHAPE)\n .flags(PointerFlags::EMPTY)\n .known(KnownPointer::Rc)\n .weak(|| as Facet>::SHAPE)\n .vtable(\n &const {\n PointerVTable::builder()\n .borrow_fn(|this| {\n let ptr = Self::as_ptr(unsafe { this.get() });\n PtrConst::new(ptr).into()\n })\n .new_into_fn(|this, ptr| {\n let t = unsafe { ptr.read::() };\n let rc = Rc::new(t);\n unsafe { this.put(rc) }\n })\n .downgrade_into_fn(|strong, weak| unsafe {\n weak.put(Rc::downgrade(strong.get::()))\n })\n .build()\n },\n )\n .build(),\n ))\n .inner(inner_shape::)\n .build()\n };\n}\n\nunsafe impl<'a> Facet<'a> for Rc {\n const VTABLE: &'static ValueVTable = &const {\n value_vtable!(alloc::rc::Rc, |f, opts| {\n write!(f, \"{}\", Self::SHAPE.type_identifier)?;\n if let Some(opts) = opts.for_children() {\n write!(f, \"<\")?;\n (str::SHAPE.vtable.type_name())(f, opts)?;\n write!(f, \">\")?;\n } else {\n write!(f, \"<…>\")?;\n }\n Ok(())\n })\n };\n\n const SHAPE: &'static crate::Shape = &const {\n // Function to return inner type's shape\n fn inner_shape() -> &'static Shape {\n str::SHAPE\n }\n\n crate::Shape::builder_for_sized::()\n .type_identifier(\"Rc\")\n .type_params(&[crate::TypeParam {\n name: \"T\",\n shape: || str::SHAPE,\n }])\n .ty(Type::User(UserType::Opaque))\n .def(Def::Pointer(\n PointerDef::builder()\n .pointee(|| str::SHAPE)\n .flags(PointerFlags::EMPTY)\n .known(KnownPointer::Rc)\n .weak(|| as Facet>::SHAPE)\n .vtable(\n &const {\n PointerVTable::builder()\n .borrow_fn(|this| unsafe {\n let concrete = this.get::>();\n let s: &str = concrete;\n PtrConstWide::new(&raw const *s).into()\n })\n .new_into_fn(|_this, _ptr| todo!())\n .downgrade_into_fn(|_strong, _weak| todo!())\n .build()\n },\n )\n .build(),\n ))\n .inner(inner_shape)\n .build()\n };\n}\n\nunsafe impl<'a, T: Facet<'a>> Facet<'a> for Weak {\n const VTABLE: &'static ValueVTable = &const {\n value_vtable!(alloc::rc::Weak, |f, opts| {\n write!(f, \"{}\", Self::SHAPE.type_identifier)?;\n if let Some(opts) = opts.for_children() {\n write!(f, \"<\")?;\n T::SHAPE.vtable.type_name()(f, opts)?;\n write!(f, \">\")?;\n } else {\n write!(f, \"<…>\")?;\n }\n Ok(())\n })\n };\n\n const SHAPE: &'static crate::Shape = &const {\n // Function to return inner type's shape\n fn inner_shape<'a, T: Facet<'a>>() -> &'static Shape {\n T::SHAPE\n }\n\n crate::Shape::builder_for_sized::()\n .type_identifier(\"Weak\")\n .type_params(&[crate::TypeParam {\n name: \"T\",\n shape: || T::SHAPE,\n }])\n .ty(Type::User(UserType::Opaque))\n .def(Def::Pointer(\n PointerDef::builder()\n .pointee(|| T::SHAPE)\n .flags(PointerFlags::WEAK)\n .known(KnownPointer::RcWeak)\n .strong(|| as Facet>::SHAPE)\n .vtable(\n &const {\n PointerVTable::builder()\n .upgrade_into_fn(|weak, strong| unsafe {\n Some(strong.put(weak.get::().upgrade()?))\n })\n .build()\n },\n )\n .build(),\n ))\n .inner(inner_shape::)\n .build()\n };\n}\n\nunsafe impl<'a> Facet<'a> for Weak {\n const VTABLE: &'static ValueVTable = &const {\n value_vtable!(alloc::rc::Weak, |f, opts| {\n write!(f, \"{}\", Self::SHAPE.type_identifier)?;\n if let Some(opts) = opts.for_children() {\n write!(f, \"<\")?;\n (str::SHAPE.vtable.type_name())(f, opts)?;\n write!(f, \">\")?;\n } else {\n write!(f, \"<…>\")?;\n }\n Ok(())\n })\n };\n\n const SHAPE: &'static crate::Shape = &const {\n // Function to return inner type's shape\n fn inner_shape() -> &'static Shape {\n str::SHAPE\n }\n\n crate::Shape::builder_for_sized::()\n .type_identifier(\"Weak\")\n .type_params(&[crate::TypeParam {\n name: \"T\",\n shape: || str::SHAPE,\n }])\n .ty(Type::User(UserType::Opaque))\n .def(Def::Pointer(\n PointerDef::builder()\n .pointee(|| str::SHAPE)\n .flags(PointerFlags::WEAK)\n .known(KnownPointer::RcWeak)\n .strong(|| as Facet>::SHAPE)\n .vtable(\n &const {\n PointerVTable::builder()\n .upgrade_into_fn(|_weak, _strong| todo!())\n .build()\n },\n )\n .build(),\n ))\n .inner(inner_shape)\n .build()\n };\n}\n\n#[cfg(test)]\nmod tests {\n use alloc::rc::{Rc, Weak as RcWeak};\n use alloc::string::String;\n\n use super::*;\n\n #[test]\n fn test_rc_type_params() {\n let [type_param_1] = >::SHAPE.type_params else {\n panic!(\"Rc should only have 1 type param\")\n };\n assert_eq!(type_param_1.shape(), i32::SHAPE);\n }\n\n #[test]\n fn test_rc_vtable_1_new_borrow_drop() {\n facet_testhelpers::setup();\n\n let rc_shape = >::SHAPE;\n let rc_def = rc_shape\n .def\n .into_pointer()\n .expect(\"Rc should have a smart pointer definition\");\n\n // Allocate memory for the Rc\n let rc_uninit_ptr = rc_shape.allocate().unwrap();\n\n // Get the function pointer for creating a new Rc from a value\n let new_into_fn = rc_def\n .vtable\n .new_into_fn\n .expect(\"Rc should have new_into_fn\");\n\n // Create the value and initialize the Rc\n let mut value = String::from(\"example\");\n let rc_ptr = unsafe { new_into_fn(rc_uninit_ptr, PtrMut::new(&raw mut value)) };\n // The value now belongs to the Rc, prevent its drop\n core::mem::forget(value);\n\n // Get the function pointer for borrowing the inner value\n let borrow_fn = rc_def\n .vtable\n .borrow_fn\n .expect(\"Rc should have borrow_fn\");\n\n // Borrow the inner value and check it\n let borrowed_ptr = unsafe { borrow_fn(rc_ptr.as_const()) };\n // SAFETY: borrowed_ptr points to a valid String within the Rc\n assert_eq!(unsafe { borrowed_ptr.get::() }, \"example\");\n\n // Get the function pointer for dropping the Rc\n let drop_fn = (rc_shape.vtable.sized().unwrap().drop_in_place)()\n .expect(\"Rc should have drop_in_place\");\n\n // Drop the Rc in place\n // SAFETY: rc_ptr points to a valid Rc\n unsafe { drop_fn(rc_ptr) };\n\n // Deallocate the memory\n // SAFETY: rc_ptr was allocated by rc_shape and is now dropped (but memory is still valid)\n unsafe { rc_shape.deallocate_mut(rc_ptr).unwrap() };\n }\n\n #[test]\n fn test_rc_vtable_2_downgrade_upgrade_drop() {\n facet_testhelpers::setup();\n\n let rc_shape = >::SHAPE;\n let rc_def = rc_shape\n .def\n .into_pointer()\n .expect(\"Rc should have a smart pointer definition\");\n\n let weak_shape = >::SHAPE;\n let weak_def = weak_shape\n .def\n .into_pointer()\n .expect(\"RcWeak should have a smart pointer definition\");\n\n // 1. Create the first Rc (rc1)\n let rc1_uninit_ptr = rc_shape.allocate().unwrap();\n let new_into_fn = rc_def.vtable.new_into_fn.unwrap();\n let mut value = String::from(\"example\");\n let rc1_ptr = unsafe { new_into_fn(rc1_uninit_ptr, PtrMut::new(&raw mut value)) };\n core::mem::forget(value); // Value now owned by rc1\n\n // 2. Downgrade rc1 to create a weak pointer (weak1)\n let weak1_uninit_ptr = weak_shape.allocate().unwrap();\n let downgrade_into_fn = rc_def.vtable.downgrade_into_fn.unwrap();\n // SAFETY: rc1_ptr points to a valid Rc, weak1_uninit_ptr is allocated for a Weak\n let weak1_ptr = unsafe { downgrade_into_fn(rc1_ptr, weak1_uninit_ptr) };\n\n // 3. Upgrade weak1 to create a second Rc (rc2)\n let rc2_uninit_ptr = rc_shape.allocate().unwrap();\n let upgrade_into_fn = weak_def.vtable.upgrade_into_fn.unwrap();\n // SAFETY: weak1_ptr points to a valid Weak, rc2_uninit_ptr is allocated for an Rc.\n // Upgrade should succeed as rc1 still exists.\n let rc2_ptr = unsafe { upgrade_into_fn(weak1_ptr, rc2_uninit_ptr) }\n .expect(\"Upgrade should succeed while original Rc exists\");\n\n // Check the content of the upgraded Rc\n let borrow_fn = rc_def.vtable.borrow_fn.unwrap();\n // SAFETY: rc2_ptr points to a valid Rc\n let borrowed_ptr = unsafe { borrow_fn(rc2_ptr.as_const()) };\n // SAFETY: borrowed_ptr points to a valid String\n assert_eq!(unsafe { borrowed_ptr.get::() }, \"example\");\n\n // 4. Drop everything and free memory\n let rc_drop_fn = (rc_shape.vtable.sized().unwrap().drop_in_place)().unwrap();\n let weak_drop_fn = (weak_shape.vtable.sized().unwrap().drop_in_place)().unwrap();\n\n unsafe {\n // Drop Rcs\n rc_drop_fn(rc1_ptr);\n rc_shape.deallocate_mut(rc1_ptr).unwrap();\n rc_drop_fn(rc2_ptr);\n rc_shape.deallocate_mut(rc2_ptr).unwrap();\n\n // Drop Weak\n weak_drop_fn(weak1_ptr);\n weak_shape.deallocate_mut(weak1_ptr).unwrap();\n }\n }\n\n #[test]\n fn test_rc_vtable_3_downgrade_drop_try_upgrade() {\n facet_testhelpers::setup();\n\n let rc_shape = >::SHAPE;\n let rc_def = rc_shape\n .def\n .into_pointer()\n .expect(\"Rc should have a smart pointer definition\");\n\n let weak_shape = >::SHAPE;\n let weak_def = weak_shape\n .def\n .into_pointer()\n .expect(\"RcWeak should have a smart pointer definition\");\n\n // 1. Create the strong Rc (rc1)\n let rc1_uninit_ptr = rc_shape.allocate().unwrap();\n let new_into_fn = rc_def.vtable.new_into_fn.unwrap();\n let mut value = String::from(\"example\");\n let rc1_ptr = unsafe { new_into_fn(rc1_uninit_ptr, PtrMut::new(&raw mut value)) };\n core::mem::forget(value);\n\n // 2. Downgrade rc1 to create a weak pointer (weak1)\n let weak1_uninit_ptr = weak_shape.allocate().unwrap();\n let downgrade_into_fn = rc_def.vtable.downgrade_into_fn.unwrap();\n // SAFETY: rc1_ptr is valid, weak1_uninit_ptr is allocated for Weak\n let weak1_ptr = unsafe { downgrade_into_fn(rc1_ptr, weak1_uninit_ptr) };\n\n // 3. Drop and free the strong pointer (rc1)\n let rc_drop_fn = (rc_shape.vtable.sized().unwrap().drop_in_place)().unwrap();\n unsafe {\n rc_drop_fn(rc1_ptr);\n rc_shape.deallocate_mut(rc1_ptr).unwrap();\n }\n\n // 4. Attempt to upgrade the weak pointer (weak1)\n let upgrade_into_fn = weak_def.vtable.upgrade_into_fn.unwrap();\n let rc2_uninit_ptr = rc_shape.allocate().unwrap();\n // SAFETY: weak1_ptr is valid (though points to dropped data), rc2_uninit_ptr is allocated for Rc\n let upgrade_result = unsafe { upgrade_into_fn(weak1_ptr, rc2_uninit_ptr) };\n\n // Assert that the upgrade failed\n assert!(\n upgrade_result.is_none(),\n \"Upgrade should fail after the strong Rc is dropped\"\n );\n\n // 5. Clean up: Deallocate the memory intended for the failed upgrade and drop/deallocate the weak pointer\n let weak_drop_fn = (weak_shape.vtable.sized().unwrap().drop_in_place)().unwrap();\n unsafe {\n // Deallocate the *uninitialized* memory allocated for the failed upgrade attempt\n rc_shape.deallocate_uninit(rc2_uninit_ptr).unwrap();\n\n // Drop and deallocate the weak pointer\n weak_drop_fn(weak1_ptr);\n weak_shape.deallocate_mut(weak1_ptr).unwrap();\n }\n }\n}\n"], ["/facet/facet-core/src/impls_alloc/boxed.rs", "use alloc::boxed::Box;\n\nuse crate::{\n Def, Facet, KnownPointer, PointerDef, PointerFlags, PointerVTable, PtrConst, PtrConstWide,\n PtrMut, PtrUninit, Shape, TryBorrowInnerError, TryFromError, TryIntoInnerError, Type, UserType,\n ValueVTable, value_vtable,\n};\n\nunsafe impl<'a, T: Facet<'a>> Facet<'a> for Box {\n const VTABLE: &'static ValueVTable = &const {\n // Define the functions for transparent conversion between Box and T\n unsafe fn try_from<'a, 'src, 'dst, T: Facet<'a>>(\n src_ptr: PtrConst<'src>,\n src_shape: &'static Shape,\n dst: PtrUninit<'dst>,\n ) -> Result, TryFromError> {\n if src_shape.id != T::SHAPE.id {\n return Err(TryFromError::UnsupportedSourceShape {\n src_shape,\n expected: &[T::SHAPE],\n });\n }\n let t = unsafe { src_ptr.read::() };\n let boxed = Box::new(t);\n Ok(unsafe { dst.put(boxed) })\n }\n\n unsafe fn try_into_inner<'a, 'src, 'dst, T: Facet<'a>>(\n src_ptr: PtrMut<'src>,\n dst: PtrUninit<'dst>,\n ) -> Result, TryIntoInnerError> {\n let boxed = unsafe { src_ptr.read::>() };\n Ok(unsafe { dst.put(*boxed) })\n }\n\n unsafe fn try_borrow_inner<'a, 'src, T: Facet<'a>>(\n src_ptr: PtrConst<'src>,\n ) -> Result, TryBorrowInnerError> {\n let boxed = unsafe { src_ptr.get::>() };\n Ok(PtrConst::new(&**boxed))\n }\n\n let mut vtable = value_vtable!(alloc::boxed::Box, |f, opts| {\n write!(f, \"{}\", Self::SHAPE.type_identifier)?;\n if let Some(opts) = opts.for_children() {\n write!(f, \"<\")?;\n (T::SHAPE.vtable.type_name())(f, opts)?;\n write!(f, \">\")?;\n } else {\n write!(f, \"<…>\")?;\n }\n Ok(())\n });\n {\n let vtable = vtable.sized_mut().unwrap();\n vtable.try_from = || Some(try_from::);\n vtable.try_into_inner = || Some(try_into_inner::);\n vtable.try_borrow_inner = || Some(try_borrow_inner::);\n }\n vtable\n };\n\n const SHAPE: &'static crate::Shape = &const {\n // Function to return inner type's shape\n fn inner_shape<'a, T: Facet<'a>>() -> &'static Shape {\n T::SHAPE\n }\n\n crate::Shape::builder_for_sized::()\n .type_identifier(\"Box\")\n .type_params(&[crate::TypeParam {\n name: \"T\",\n shape: || T::SHAPE,\n }])\n .ty(Type::User(UserType::Opaque))\n .def(Def::Pointer(\n PointerDef::builder()\n .pointee(|| T::SHAPE)\n .flags(PointerFlags::EMPTY)\n .known(KnownPointer::Box)\n .vtable(\n &const {\n PointerVTable::builder()\n .borrow_fn(|this| unsafe {\n let concrete = this.get::>();\n let t: &T = concrete.as_ref();\n PtrConst::new(t as *const T).into()\n })\n .new_into_fn(|this, ptr| {\n let t = unsafe { ptr.read::() };\n let boxed = Box::new(t);\n unsafe { this.put(boxed) }\n })\n .build()\n },\n )\n .build(),\n ))\n .inner(inner_shape::)\n .build()\n };\n}\n\nunsafe impl<'a> Facet<'a> for Box {\n const VTABLE: &'static ValueVTable = &const {\n value_vtable!(alloc::boxed::Box, |f, opts| {\n write!(f, \"{}\", Self::SHAPE.type_identifier)?;\n if let Some(opts) = opts.for_children() {\n write!(f, \"<\")?;\n (str::SHAPE.vtable.type_name())(f, opts)?;\n write!(f, \">\")?;\n } else {\n write!(f, \"<…>\")?;\n }\n Ok(())\n })\n };\n\n const SHAPE: &'static crate::Shape = &const {\n fn inner_shape() -> &'static Shape {\n str::SHAPE\n }\n\n crate::Shape::builder_for_sized::()\n .type_identifier(\"Box\")\n .type_params(&[crate::TypeParam {\n name: \"T\",\n shape: || str::SHAPE,\n }])\n .ty(Type::User(UserType::Opaque))\n .def(Def::Pointer(\n PointerDef::builder()\n .pointee(|| str::SHAPE)\n .flags(PointerFlags::EMPTY)\n .known(KnownPointer::Box)\n .vtable(\n &const {\n PointerVTable::builder()\n .borrow_fn(|this| unsafe {\n let concrete = this.get::>();\n let s: &str = concrete;\n PtrConstWide::new(&raw const *s).into()\n })\n .new_into_fn(|_this, _ptr| todo!())\n .build()\n },\n )\n .build(),\n ))\n .inner(inner_shape)\n .build()\n };\n}\n\n#[cfg(test)]\nmod tests {\n use alloc::boxed::Box;\n use alloc::string::String;\n\n use super::*;\n\n #[test]\n fn test_box_type_params() {\n let [type_param_1] = >::SHAPE.type_params else {\n panic!(\"Box should only have 1 type param\")\n };\n assert_eq!(type_param_1.shape(), i32::SHAPE);\n }\n\n #[test]\n fn test_box_vtable_1_new_borrow_drop() {\n facet_testhelpers::setup();\n\n let box_shape = >::SHAPE;\n let box_def = box_shape\n .def\n .into_pointer()\n .expect(\"Box should have a smart pointer definition\");\n\n // Allocate memory for the Box\n let box_uninit_ptr = box_shape.allocate().unwrap();\n\n // Get the function pointer for creating a new Box from a value\n let new_into_fn = box_def\n .vtable\n .new_into_fn\n .expect(\"Box should have new_into_fn\");\n\n // Create the value and initialize the Box\n let mut value = String::from(\"example\");\n let box_ptr = unsafe { new_into_fn(box_uninit_ptr, PtrMut::new(&raw mut value)) };\n // The value now belongs to the Box, prevent its drop\n core::mem::forget(value);\n\n // Get the function pointer for borrowing the inner value\n let borrow_fn = box_def\n .vtable\n .borrow_fn\n .expect(\"Box should have borrow_fn\");\n\n // Borrow the inner value and check it\n let borrowed_ptr = unsafe { borrow_fn(box_ptr.as_const()) };\n // SAFETY: borrowed_ptr points to a valid String within the Box\n assert_eq!(unsafe { borrowed_ptr.get::() }, \"example\");\n\n // Get the function pointer for dropping the Box\n let drop_fn = (box_shape.vtable.sized().unwrap().drop_in_place)()\n .expect(\"Box should have drop_in_place\");\n\n // Drop the Box in place\n // SAFETY: box_ptr points to a valid Box\n unsafe { drop_fn(box_ptr) };\n\n // Deallocate the memory\n // SAFETY: box_ptr was allocated by box_shape and is now dropped (but memory is still valid)\n unsafe { box_shape.deallocate_mut(box_ptr).unwrap() };\n }\n}\n"], ["/facet/facet-core/src/impls_time.rs", "use alloc::string::String;\nuse time::{OffsetDateTime, UtcDateTime};\n\nuse crate::{\n Def, Facet, ParseError, PtrConst, PtrUninit, Shape, Type, UserType, ValueVTable, value_vtable,\n};\n\nunsafe impl Facet<'_> for UtcDateTime {\n const VTABLE: &'static ValueVTable = &const {\n let mut vtable = value_vtable!(UtcDateTime, |f, _opts| write!(\n f,\n \"{}\",\n Self::SHAPE.type_identifier\n ));\n {\n let vtable = vtable.sized_mut().unwrap();\n vtable.try_from = || {\n Some(\n |source: PtrConst, source_shape: &Shape, target: PtrUninit| {\n if source_shape.is_type::() {\n let source = unsafe { source.read::() };\n let parsed = UtcDateTime::parse(\n &source,\n &time::format_description::well_known::Rfc3339,\n )\n .map_err(|_| ParseError::Generic(\"could not parse date\"));\n match parsed {\n Ok(val) => Ok(unsafe { target.put(val) }),\n Err(_e) => {\n Err(crate::TryFromError::Generic(\"could not parse date\"))\n }\n }\n } else {\n Err(crate::TryFromError::UnsupportedSourceShape {\n src_shape: source_shape,\n expected: &[String::SHAPE],\n })\n }\n },\n )\n };\n vtable.parse = || {\n Some(|s: &str, target: PtrUninit| {\n let parsed =\n UtcDateTime::parse(s, &time::format_description::well_known::Rfc3339)\n .map_err(|_| ParseError::Generic(\"could not parse date\"))?;\n Ok(unsafe { target.put(parsed) })\n })\n };\n vtable.display = || {\n Some(|value, f| unsafe {\n let udt = value.get::();\n match udt.format(&time::format_description::well_known::Rfc3339) {\n Ok(s) => write!(f, \"{s}\"),\n Err(_) => write!(f, \"\"),\n }\n })\n };\n }\n vtable\n };\n\n const SHAPE: &'static Shape = &const {\n Shape::builder_for_sized::()\n .type_identifier(\"UtcDateTime\")\n .ty(Type::User(UserType::Opaque))\n .def(Def::Scalar)\n .build()\n };\n}\n\nunsafe impl Facet<'_> for OffsetDateTime {\n const VTABLE: &'static ValueVTable = &const {\n let mut vtable = value_vtable!(OffsetDateTime, |f, _opts| write!(\n f,\n \"{}\",\n Self::SHAPE.type_identifier\n ));\n {\n let vtable = vtable.sized_mut().unwrap();\n vtable.try_from = || {\n Some(\n |source: PtrConst, source_shape: &Shape, target: PtrUninit| {\n if source_shape.is_type::() {\n let source = unsafe { source.read::() };\n let parsed = OffsetDateTime::parse(\n &source,\n &time::format_description::well_known::Rfc3339,\n )\n .map_err(|_| ParseError::Generic(\"could not parse date\"));\n match parsed {\n Ok(val) => Ok(unsafe { target.put(val) }),\n Err(_e) => {\n Err(crate::TryFromError::Generic(\"could not parse date\"))\n }\n }\n } else {\n Err(crate::TryFromError::UnsupportedSourceShape {\n src_shape: source_shape,\n expected: &[String::SHAPE],\n })\n }\n },\n )\n };\n vtable.parse = || {\n Some(|s: &str, target: PtrUninit| {\n let parsed =\n OffsetDateTime::parse(s, &time::format_description::well_known::Rfc3339)\n .map_err(|_| ParseError::Generic(\"could not parse date\"))?;\n Ok(unsafe { target.put(parsed) })\n })\n };\n vtable.display = || {\n Some(|value, f| unsafe {\n let odt = value.get::();\n match odt.format(&time::format_description::well_known::Rfc3339) {\n Ok(s) => write!(f, \"{s}\"),\n Err(_) => write!(f, \"\"),\n }\n })\n };\n }\n vtable\n };\n\n const SHAPE: &'static Shape = &const {\n Shape::builder_for_sized::()\n .type_identifier(\"OffsetDateTime\")\n .ty(Type::User(UserType::Opaque))\n .def(Def::Scalar)\n .build()\n };\n}\n\n#[cfg(test)]\nmod tests {\n use core::fmt;\n\n use time::OffsetDateTime;\n\n use crate::{Facet, PtrConst};\n\n #[test]\n fn parse_offset_date_time() {\n facet_testhelpers::setup();\n\n let target = OffsetDateTime::SHAPE.allocate().unwrap();\n unsafe {\n ((OffsetDateTime::VTABLE.sized().unwrap().parse)().unwrap())(\n \"2023-03-14T15:09:26Z\",\n target,\n )\n .unwrap();\n }\n let odt: OffsetDateTime = unsafe { target.assume_init().read() };\n assert_eq!(\n odt,\n OffsetDateTime::parse(\n \"2023-03-14T15:09:26Z\",\n &time::format_description::well_known::Rfc3339\n )\n .unwrap()\n );\n\n struct DisplayWrapper<'a>(PtrConst<'a>);\n\n impl fmt::Display for DisplayWrapper<'_> {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n unsafe { ((OffsetDateTime::VTABLE.sized().unwrap().display)().unwrap())(self.0, f) }\n }\n }\n\n let s = format!(\"{}\", DisplayWrapper(PtrConst::new(&odt as *const _)));\n assert_eq!(s, \"2023-03-14T15:09:26Z\");\n\n // Deallocate the heap allocation to avoid memory leaks under Miri\n unsafe {\n OffsetDateTime::SHAPE.deallocate_uninit(target).unwrap();\n }\n }\n}\n"], ["/facet/facet-core/src/impls_jiff.rs", "use alloc::string::String;\nuse jiff::{Timestamp, Zoned, civil::DateTime};\n\nuse crate::{\n Def, Facet, ParseError, PtrConst, PtrUninit, Shape, Type, UserType, ValueVTable, value_vtable,\n};\n\nconst ZONED_ERROR: &str = \"could not parse time-zone aware instant of time\";\n\nunsafe impl Facet<'_> for Zoned {\n const VTABLE: &'static ValueVTable = &const {\n let mut vtable = value_vtable!(Zoned, |f, _opts| write!(\n f,\n \"{}\",\n Self::SHAPE.type_identifier\n ));\n {\n let vtable = vtable.sized_mut().unwrap();\n vtable.try_from = || {\n Some(\n |source: PtrConst, source_shape: &Shape, target: PtrUninit| {\n if source_shape.is_type::() {\n let source = unsafe { source.read::() };\n let parsed = source\n .parse::()\n .map_err(|_| ParseError::Generic(ZONED_ERROR));\n match parsed {\n Ok(val) => Ok(unsafe { target.put(val) }),\n Err(_e) => Err(crate::TryFromError::Generic(ZONED_ERROR)),\n }\n } else {\n Err(crate::TryFromError::UnsupportedSourceShape {\n src_shape: source_shape,\n expected: &[String::SHAPE],\n })\n }\n },\n )\n };\n vtable.parse = || {\n Some(|s: &str, target: PtrUninit| {\n let parsed: Zoned = s.parse().map_err(|_| ParseError::Generic(ZONED_ERROR))?;\n Ok(unsafe { target.put(parsed) })\n })\n };\n vtable.display = || Some(|value, f| unsafe { write!(f, \"{}\", value.get::()) });\n }\n vtable\n };\n\n const SHAPE: &'static Shape = &const {\n Shape::builder_for_sized::()\n .type_identifier(\"Zoned\")\n .ty(Type::User(UserType::Opaque))\n .def(Def::Scalar)\n .build()\n };\n}\n\nconst TIMESTAMP_ERROR: &str = \"could not parse timestamp\";\n\nunsafe impl Facet<'_> for Timestamp {\n const VTABLE: &'static ValueVTable = &const {\n let mut vtable = value_vtable!(Timestamp, |f, _opts| write!(\n f,\n \"{}\",\n Self::SHAPE.type_identifier\n ));\n {\n let vtable = vtable.sized_mut().unwrap();\n vtable.try_from = || {\n Some(\n |source: PtrConst, source_shape: &Shape, target: PtrUninit| {\n if source_shape.is_type::() {\n let source = unsafe { source.read::() };\n let parsed = source\n .parse::()\n .map_err(|_| ParseError::Generic(TIMESTAMP_ERROR));\n match parsed {\n Ok(val) => Ok(unsafe { target.put(val) }),\n Err(_e) => Err(crate::TryFromError::Generic(TIMESTAMP_ERROR)),\n }\n } else {\n Err(crate::TryFromError::UnsupportedSourceShape {\n src_shape: source_shape,\n expected: &[String::SHAPE],\n })\n }\n },\n )\n };\n vtable.parse = || {\n Some(|s: &str, target: PtrUninit| {\n let parsed: Timestamp = s\n .parse()\n .map_err(|_| ParseError::Generic(TIMESTAMP_ERROR))?;\n Ok(unsafe { target.put(parsed) })\n })\n };\n vtable.display =\n || Some(|value, f| unsafe { write!(f, \"{}\", value.get::()) });\n }\n vtable\n };\n\n const SHAPE: &'static Shape = &const {\n Shape::builder_for_sized::()\n .type_identifier(\"Timestamp\")\n .ty(Type::User(UserType::Opaque))\n .def(Def::Scalar)\n .build()\n };\n}\n\nconst DATETIME_ERROR: &str = \"could not parse civil datetime\";\n\nunsafe impl Facet<'_> for DateTime {\n const VTABLE: &'static ValueVTable = &const {\n let mut vtable = value_vtable!(DateTime, |f, _opts| write!(\n f,\n \"{}\",\n Self::SHAPE.type_identifier\n ));\n {\n let vtable = vtable.sized_mut().unwrap();\n vtable.try_from = || {\n Some(\n |source: PtrConst, source_shape: &Shape, target: PtrUninit| {\n if source_shape.is_type::() {\n let source = unsafe { source.read::() };\n let parsed = source\n .parse::()\n .map_err(|_| ParseError::Generic(DATETIME_ERROR));\n match parsed {\n Ok(val) => Ok(unsafe { target.put(val) }),\n Err(_e) => Err(crate::TryFromError::Generic(DATETIME_ERROR)),\n }\n } else {\n Err(crate::TryFromError::UnsupportedSourceShape {\n src_shape: source_shape,\n expected: &[String::SHAPE],\n })\n }\n },\n )\n };\n vtable.parse = || {\n Some(|s: &str, target: PtrUninit| {\n let parsed: DateTime =\n s.parse().map_err(|_| ParseError::Generic(DATETIME_ERROR))?;\n Ok(unsafe { target.put(parsed) })\n })\n };\n vtable.display =\n || Some(|value, f| unsafe { write!(f, \"{}\", value.get::()) });\n }\n vtable\n };\n\n const SHAPE: &'static Shape = &const {\n Shape::builder_for_sized::()\n .type_identifier(\"DateTime\")\n .ty(Type::User(UserType::Opaque))\n .def(Def::Scalar)\n .build()\n };\n}\n\n#[cfg(test)]\nmod tests {\n use core::fmt;\n\n use jiff::{Timestamp, civil::DateTime};\n\n use crate::{Facet, PtrConst};\n\n #[test]\n #[cfg(not(miri))] // I don't think we can read time zones from miri, the test just fails\n fn parse_zoned() {\n use jiff::Zoned;\n\n facet_testhelpers::setup();\n\n let target = Zoned::SHAPE.allocate().unwrap();\n unsafe {\n ((Zoned::VTABLE.sized().unwrap().parse)().unwrap())(\n \"2023-12-31T18:30:00+07:00[Asia/Ho_Chi_Minh]\",\n target,\n )\n .unwrap();\n }\n let odt: Zoned = unsafe { target.assume_init().read() };\n assert_eq!(\n odt,\n \"2023-12-31T18:30:00+07:00[Asia/Ho_Chi_Minh]\"\n .parse()\n .unwrap()\n );\n\n struct DisplayWrapper<'a>(PtrConst<'a>);\n\n impl fmt::Display for DisplayWrapper<'_> {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n unsafe { ((Zoned::VTABLE.sized().unwrap().display)().unwrap())(self.0, f) }\n }\n }\n\n let s = format!(\"{}\", DisplayWrapper(PtrConst::new(&odt as *const _)));\n assert_eq!(s, \"2023-12-31T18:30:00+07:00[Asia/Ho_Chi_Minh]\");\n\n // Deallocate the heap allocation to avoid memory leaks under Miri\n unsafe {\n Zoned::SHAPE.deallocate_uninit(target).unwrap();\n }\n }\n\n #[test]\n fn parse_timestamp() {\n facet_testhelpers::setup();\n\n let target = Timestamp::SHAPE.allocate().unwrap();\n unsafe {\n ((Timestamp::VTABLE.sized().unwrap().parse)().unwrap())(\"2024-06-19T15:22:45Z\", target)\n .unwrap();\n }\n let odt: Timestamp = unsafe { target.assume_init().read() };\n assert_eq!(odt, \"2024-06-19T15:22:45Z\".parse().unwrap());\n\n struct DisplayWrapper<'a>(PtrConst<'a>);\n\n impl fmt::Display for DisplayWrapper<'_> {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n unsafe { ((Timestamp::VTABLE.sized().unwrap().display)().unwrap())(self.0, f) }\n }\n }\n\n let s = format!(\"{}\", DisplayWrapper(PtrConst::new(&odt as *const _)));\n assert_eq!(s, \"2024-06-19T15:22:45Z\");\n\n // Deallocate the heap allocation to avoid memory leaks under Miri\n unsafe {\n Timestamp::SHAPE.deallocate_uninit(target).unwrap();\n }\n }\n\n #[test]\n fn parse_datetime() {\n facet_testhelpers::setup();\n\n let target = DateTime::SHAPE.allocate().unwrap();\n unsafe {\n ((DateTime::VTABLE.sized().unwrap().parse)().unwrap())(\"2024-06-19T15:22:45\", target)\n .unwrap();\n }\n let odt: DateTime = unsafe { target.assume_init().read() };\n assert_eq!(odt, \"2024-06-19T15:22:45\".parse().unwrap());\n\n struct DisplayWrapper<'a>(PtrConst<'a>);\n\n impl fmt::Display for DisplayWrapper<'_> {\n fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {\n unsafe { ((DateTime::VTABLE.sized().unwrap().display)().unwrap())(self.0, f) }\n }\n }\n\n let s = format!(\"{}\", DisplayWrapper(PtrConst::new(&odt as *const _)));\n assert_eq!(s, \"2024-06-19T15:22:45\");\n\n // Deallocate the heap allocation to avoid memory leaks under Miri\n unsafe {\n DateTime::SHAPE.deallocate_uninit(target).unwrap();\n }\n }\n}\n"], ["/facet/facet-core/src/types/value.rs", "use crate::{\n PtrConstWide, PtrMutWide, PtrUninitWide, TypedPtrUninit,\n ptr::{PtrConst, PtrMut, PtrUninit},\n};\nuse bitflags::bitflags;\nuse core::{cmp::Ordering, marker::PhantomData, mem};\n\nuse crate::Shape;\n\nuse super::UnsizedError;\n\n//======== Type Information ========\n\n/// A function that formats the name of a type.\n///\n/// This helps avoid allocations, and it takes options.\npub type TypeNameFn = fn(f: &mut core::fmt::Formatter, opts: TypeNameOpts) -> core::fmt::Result;\n\n/// Options for formatting the name of a type\n#[derive(Clone, Copy)]\npub struct TypeNameOpts {\n /// as long as this is > 0, keep formatting the type parameters\n /// when it reaches 0, format type parameters as `...`\n /// if negative, all type parameters are formatted\n pub recurse_ttl: isize,\n}\n\nimpl Default for TypeNameOpts {\n #[inline]\n fn default() -> Self {\n Self { recurse_ttl: -1 }\n }\n}\n\nimpl TypeNameOpts {\n /// Create a new `NameOpts` for which none of the type parameters are formatted\n #[inline]\n pub fn none() -> Self {\n Self { recurse_ttl: 0 }\n }\n\n /// Create a new `NameOpts` for which only the direct children are formatted\n #[inline]\n pub fn one() -> Self {\n Self { recurse_ttl: 1 }\n }\n\n /// Create a new `NameOpts` for which all type parameters are formatted\n #[inline]\n pub fn infinite() -> Self {\n Self { recurse_ttl: -1 }\n }\n\n /// Decrease the `recurse_ttl` — if it's != 0, returns options to pass when\n /// formatting children type parameters.\n ///\n /// If this returns `None` and you have type parameters, you should render a\n /// `…` (unicode ellipsis) character instead of your list of types.\n ///\n /// See the implementation for `Vec` for examples.\n #[inline]\n pub fn for_children(&self) -> Option {\n match self.recurse_ttl.cmp(&0) {\n Ordering::Greater => Some(Self {\n recurse_ttl: self.recurse_ttl - 1,\n }),\n Ordering::Less => Some(Self {\n recurse_ttl: self.recurse_ttl,\n }),\n Ordering::Equal => None,\n }\n }\n}\n\n//======== Invariants ========\n\n/// Function to validate the invariants of a value. If it returns false, the value is considered invalid.\n///\n/// # Safety\n///\n/// The `value` parameter must point to aligned, initialized memory of the correct type.\npub type InvariantsFn = for<'mem> unsafe fn(value: PtrConst<'mem>) -> bool;\n\n/// Function to validate the invariants of a value. If it returns false, the value is considered invalid (wide pointer version).\n///\n/// # Safety\n///\n/// The `value` parameter must point to aligned, initialized memory of the correct type.\npub type InvariantsFnWide = for<'mem> unsafe fn(value: PtrConstWide<'mem>) -> bool;\n\n/// Function to validate the invariants of a value. If it returns false, the value is considered invalid.\npub type InvariantsFnTyped = fn(value: &T) -> bool;\n\n//======== Memory Management ========\n\n/// Function to drop a value\n///\n/// # Safety\n///\n/// The `value` parameter must point to aligned, initialized memory of the correct type.\n/// After calling this function, the memory pointed to by `value` should not be accessed again\n/// until it is properly reinitialized.\npub type DropInPlaceFn = for<'mem> unsafe fn(value: PtrMut<'mem>) -> PtrUninit<'mem>;\n\n/// Function to drop a value (wide pointer version)\n///\n/// # Safety\n///\n/// The `value` parameter must point to aligned, initialized memory of the correct type.\n/// After calling this function, the memory pointed to by `value` should not be accessed again\n/// until it is properly reinitialized.\npub type DropInPlaceFnWide = for<'mem> unsafe fn(value: PtrMutWide<'mem>) -> PtrUninitWide<'mem>;\n\n/// Function to clone a value into another already-allocated value\n///\n/// # Safety\n///\n/// The `source` parameter must point to aligned, initialized memory of the correct type.\n/// The `target` parameter has the correct layout and alignment, but points to\n/// uninitialized memory. The function returns the same pointer wrapped in an [`PtrMut`].\npub type CloneIntoFn =\n for<'src, 'dst> unsafe fn(source: PtrConst<'src>, target: PtrUninit<'dst>) -> PtrMut<'dst>;\n/// Function to clone a value into another already-allocated value\npub type CloneIntoFnTyped =\n for<'src, 'dst> fn(source: &'src T, target: TypedPtrUninit<'dst, T>) -> &'dst mut T;\n\n/// Function to set a value to its default in-place\n///\n/// # Safety\n///\n/// The `target` parameter has the correct layout and alignment, but points to\n/// uninitialized memory. The function returns the same pointer wrapped in an [`PtrMut`].\npub type DefaultInPlaceFn = for<'mem> unsafe fn(target: PtrUninit<'mem>) -> PtrMut<'mem>;\n/// Function to set a value to its default in-place\npub type DefaultInPlaceFnTyped = for<'mem> fn(target: TypedPtrUninit<'mem, T>) -> &'mem mut T;\n\n//======== Conversion ========\n\n/// Function to parse a value from a string.\n///\n/// If both [`DisplayFn`] and [`ParseFn`] are set, we should be able to round-trip the value.\n///\n/// # Safety\n///\n/// The `target` parameter has the correct layout and alignment, but points to\n/// uninitialized memory. If this function succeeds, it should return `Ok` with the\n/// same pointer wrapped in an [`PtrMut`]. If parsing fails, it returns `Err` with an error.\npub type ParseFn =\n for<'mem> unsafe fn(s: &str, target: PtrUninit<'mem>) -> Result, ParseError>;\n\n/// Function to parse a value from a string.\n///\n/// If both [`DisplayFn`] and [`ParseFn`] are set, we should be able to round-trip the value.\npub type ParseFnTyped =\n for<'mem> fn(s: &str, target: TypedPtrUninit<'mem, T>) -> Result<&'mem mut T, ParseError>;\n\n/// Error returned by [`ParseFn`]\n#[derive(Debug)]\npub enum ParseError {\n /// Generic error message\n Generic(&'static str),\n}\n\nimpl core::fmt::Display for ParseError {\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n match self {\n ParseError::Generic(msg) => write!(f, \"Parse failed: {msg}\"),\n }\n }\n}\n\nimpl core::error::Error for ParseError {}\n\n/// Function to try converting from another type\n///\n/// # Safety\n///\n/// The `target` parameter has the correct layout and alignment, but points to\n/// uninitialized memory. If this function succeeds, it should return `Ok` with the\n/// same pointer wrapped in an [`PtrMut`]. If conversion fails, it returns `Err` with an error.\npub type TryFromFn = for<'src, 'mem, 'shape> unsafe fn(\n source: PtrConst<'src>,\n source_shape: &'static Shape,\n target: PtrUninit<'mem>,\n) -> Result, TryFromError>;\n\n/// Function to try converting from another type\npub type TryFromFnTyped = for<'src, 'mem, 'shape> fn(\n source: &'src T,\n source_shape: &'static Shape,\n target: TypedPtrUninit<'mem, T>,\n) -> Result<&'mem mut T, TryFromError>;\n\n/// Error type for TryFrom conversion failures\n#[derive(Debug, PartialEq, Clone)]\npub enum TryFromError {\n /// Generic conversion error\n Generic(&'static str),\n\n /// The target shape doesn't implement conversion from any source shape (no try_from in vtable)\n Unimplemented,\n\n /// The target shape has a conversion implementation, but it doesn't support converting from this specific source shape\n UnsupportedSourceShape {\n /// The source shape that failed to convert\n src_shape: &'static Shape,\n\n /// The shapes that the `TryFrom` implementation supports\n expected: &'static [&'static Shape],\n },\n\n /// `!Sized` type\n Unsized,\n}\n\nimpl core::fmt::Display for TryFromError {\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n match self {\n TryFromError::Generic(msg) => write!(f, \"{msg}\"),\n TryFromError::Unimplemented => write!(\n f,\n \"Shape doesn't implement any conversions (no try_from function)\",\n ),\n TryFromError::UnsupportedSourceShape {\n src_shape: source_shape,\n expected,\n } => {\n write!(f, \"Incompatible types: {source_shape} (expected one of \")?;\n for (index, sh) in expected.iter().enumerate() {\n if index > 0 {\n write!(f, \", \")?;\n }\n write!(f, \"{sh}\")?;\n }\n write!(f, \")\")?;\n Ok(())\n }\n TryFromError::Unsized => write!(f, \"Unsized type\"),\n }\n }\n}\n\nimpl core::error::Error for TryFromError {}\n\nimpl From for TryFromError {\n #[inline]\n fn from(_value: UnsizedError) -> Self {\n Self::Unsized\n }\n}\n\n/// Function to convert a transparent/newtype wrapper into its inner type.\n///\n/// This is used for types that wrap another type (like smart pointers, newtypes, etc.)\n/// where the wrapper can be unwrapped to access the inner value. Primarily used during serialization.\n///\n/// # Safety\n///\n/// This function is unsafe because it operates on raw pointers.\n///\n/// The `src_ptr` must point to a valid, initialized instance of the wrapper type.\n/// The `dst` pointer must point to valid, uninitialized memory suitable for holding an instance\n/// of the inner type.\n///\n/// The function will return a pointer to the initialized inner value.\npub type TryIntoInnerFn = for<'src, 'dst> unsafe fn(\n src_ptr: PtrMut<'src>,\n dst: PtrUninit<'dst>,\n) -> Result, TryIntoInnerError>;\n/// Function to convert a transparent/newtype wrapper into its inner type.\n///\n/// This is used for types that wrap another type (like smart pointers, newtypes, etc.)\n/// where the wrapper can be unwrapped to access the inner value. Primarily used during serialization.\npub type TryIntoInnerFnTyped = for<'src, 'dst> fn(\n src_ptr: &'src T,\n dst: TypedPtrUninit<'dst, T>,\n) -> Result<&'dst mut T, TryIntoInnerError>;\n\n/// Error type returned by [`TryIntoInnerFn`] when attempting to extract\n/// the inner value from a wrapper type.\n#[derive(Debug, Clone, PartialEq, Eq)]\npub enum TryIntoInnerError {\n /// Indicates that the inner value cannot be extracted at this time,\n /// such as when a mutable borrow is already active.\n Unavailable,\n /// Indicates that another unspecified error occurred during extraction.\n Other(&'static str),\n}\n\nimpl core::fmt::Display for TryIntoInnerError {\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n match self {\n TryIntoInnerError::Unavailable => {\n write!(f, \"inner value is unavailable for extraction\")\n }\n TryIntoInnerError::Other(msg) => write!(f, \"{msg}\"),\n }\n }\n}\n\nimpl core::error::Error for TryIntoInnerError {}\n\n/// Function to borrow the inner value from a transparent/newtype wrapper without copying.\n///\n/// This is used for types that wrap another type (like smart pointers, newtypes, etc.)\n/// to efficiently access the inner value without transferring ownership.\n///\n/// # Safety\n///\n/// This function is unsafe because it operates on raw pointers.\n///\n/// The `src_ptr` must point to a valid, initialized instance of the wrapper type.\n/// The returned pointer points to memory owned by the wrapper and remains valid\n/// as long as the wrapper is valid and not mutated.\npub type TryBorrowInnerFn =\n for<'src> unsafe fn(src_ptr: PtrConst<'src>) -> Result, TryBorrowInnerError>;\n\n/// Function to borrow the inner value from a transparent/newtype wrapper without copying (wide pointer version).\npub type TryBorrowInnerFnWide =\n for<'src> unsafe fn(\n src_ptr: PtrConstWide<'src>,\n ) -> Result, TryBorrowInnerError>;\n\n/// Function to borrow the inner value from a transparent/newtype wrapper without copying.\n///\n/// This is used for types that wrap another type (like smart pointers, newtypes, etc.)\n/// to efficiently access the inner value without transferring ownership.\npub type TryBorrowInnerFnTyped =\n for<'src> fn(src_ptr: &'src T) -> Result<&'src T, TryBorrowInnerError>;\n\n/// Error type returned by [`TryBorrowInnerFn`] when attempting to borrow\n/// the inner value from a wrapper type.\n#[derive(Debug, Clone, PartialEq, Eq)]\npub enum TryBorrowInnerError {\n /// Indicates that the inner value cannot be borrowed at this time,\n /// such as when a mutable borrow is already active.\n Unavailable,\n /// Indicates an other, unspecified error occurred during the borrow attempt.\n /// The contained string provides a description of the error.\n Other(&'static str),\n}\n\nimpl core::fmt::Display for TryBorrowInnerError {\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n match self {\n TryBorrowInnerError::Unavailable => {\n write!(f, \"inner value is unavailable for borrowing\")\n }\n TryBorrowInnerError::Other(msg) => {\n write!(f, \"{msg}\")\n }\n }\n }\n}\n\nimpl core::error::Error for TryBorrowInnerError {}\n\n//======== Comparison ========\n\n/// Function to check if two values are partially equal\n///\n/// # Safety\n///\n/// Both `left` and `right` parameters must point to aligned, initialized memory of the correct type.\npub type PartialEqFn = for<'l, 'r> unsafe fn(left: PtrConst<'l>, right: PtrConst<'r>) -> bool;\n/// Function to check if two values are partially equal (wide pointer version)\n///\n/// # Safety\n///\n/// Both `left` and `right` parameters must point to aligned, initialized memory of the correct type.\npub type PartialEqFnWide =\n for<'l, 'r> unsafe fn(left: PtrConstWide<'l>, right: PtrConstWide<'r>) -> bool;\n/// Function to check if two values are partially equal\npub type PartialEqFnTyped = fn(left: &T, right: &T) -> bool;\n\n/// Function to compare two values and return their ordering if comparable\n///\n/// # Safety\n///\n/// Both `left` and `right` parameters must point to aligned, initialized memory of the correct type.\npub type PartialOrdFn =\n for<'l, 'r> unsafe fn(left: PtrConst<'l>, right: PtrConst<'r>) -> Option;\n/// Function to compare two values and return their ordering if comparable (wide pointer version)\n///\n/// # Safety\n///\n/// Both `left` and `right` parameters must point to aligned, initialized memory of the correct type.\npub type PartialOrdFnWide =\n for<'l, 'r> unsafe fn(left: PtrConstWide<'l>, right: PtrConstWide<'r>) -> Option;\n/// Function to compare two values and return their ordering if comparable\npub type PartialOrdFnTyped = fn(left: &T, right: &T) -> Option;\n\n/// Function to compare two values and return their ordering\n///\n/// # Safety\n///\n/// Both `left` and `right` parameters must point to aligned, initialized memory of the correct type.\npub type CmpFn = for<'l, 'r> unsafe fn(left: PtrConst<'l>, right: PtrConst<'r>) -> Ordering;\n/// Function to compare two values and return their ordering (wide pointer version)\n///\n/// # Safety\n///\n/// Both `left` and `right` parameters must point to aligned, initialized memory of the correct type.\npub type CmpFnWide =\n for<'l, 'r> unsafe fn(left: PtrConstWide<'l>, right: PtrConstWide<'r>) -> Ordering;\n/// Function to compare two values and return their ordering\npub type CmpFnTyped = fn(left: &T, right: &T) -> Ordering;\n\n//======== Hashing ========\n\n/// Function to hash a value\n///\n/// # Safety\n///\n/// The `value` parameter must point to aligned, initialized memory of the correct type.\n/// The hasher pointer must be a valid pointer to a Hasher trait object.\npub type HashFn = for<'mem> unsafe fn(\n value: PtrConst<'mem>,\n // TODO: Should this be wide? According to the documentation this is a trait object\n hasher_this: PtrMut<'mem>,\n hasher_write_fn: HasherWriteFn,\n);\n\n/// Function to hash a value\n///\n/// # Safety\n///\n/// The `value` parameter must point to aligned, initialized memory of the correct type.\n/// The hasher pointer must be a valid pointer to a Hasher trait object.\npub type HashFnWide = for<'mem> unsafe fn(\n value: PtrConstWide<'mem>,\n\n // TODO: Should this be wide? According to the documentation this is a trait object\n hasher_this: PtrMut<'mem>,\n hasher_write_fn: HasherWriteFn,\n);\n\n/// Function to hash a value\npub type HashFnTyped =\n for<'mem> fn(value: &'mem T, hasher_this: PtrMut<'mem>, hasher_write_fn: HasherWriteFn);\n\n/// Function to write bytes to a hasher\n///\n/// # Safety\n///\n/// The `hasher_self` parameter must be a valid pointer to a hasher\npub type HasherWriteFn = for<'mem> unsafe fn(hasher_self: PtrMut<'mem>, bytes: &[u8]);\n/// Function to write bytes to a hasher\npub type HasherWriteFnTyped = for<'mem> fn(hasher_self: &'mem mut T, bytes: &[u8]);\n\n/// Provides an implementation of [`core::hash::Hasher`] for a given hasher pointer and write function\n///\n/// See [`HashFn`] for more details on the parameters.\npub struct HasherProxy<'a> {\n hasher_this: PtrMut<'a>,\n hasher_write_fn: HasherWriteFn,\n}\n\nimpl<'a> HasherProxy<'a> {\n /// Create a new `HasherProxy` from a hasher pointer and a write function\n ///\n /// # Safety\n ///\n /// The `hasher_this` parameter must be a valid pointer to a Hasher trait object.\n /// The `hasher_write_fn` parameter must be a valid function pointer.\n #[inline]\n pub unsafe fn new(hasher_this: PtrMut<'a>, hasher_write_fn: HasherWriteFn) -> Self {\n Self {\n hasher_this,\n hasher_write_fn,\n }\n }\n}\n\nimpl core::hash::Hasher for HasherProxy<'_> {\n fn finish(&self) -> u64 {\n unimplemented!(\"finish is not needed for this implementation\")\n }\n #[inline]\n fn write(&mut self, bytes: &[u8]) {\n unsafe { (self.hasher_write_fn)(self.hasher_this, bytes) }\n }\n}\n\n//======== Marker Traits ========\n\nbitflags! {\n /// Bitflags for common marker traits that a type may implement\n ///\n /// Note: facet is not able to see negative impls, so it might mistakenly think a struct `S`\n /// is `Send` because all its fields are, ignoring that there is an `impl !Send for S`.\n ///\n /// Similarly, it might think a struct `S` is `!Send` just because one of the fields is an\n /// `UnsafeCell` (which is `!Send`), ignoring that there is an `unsafe impl Send for S`.\n ///\n /// The reason facet's determination of `Send` or `!Send` is based on fields is because structs\n /// can be generic, in which case our specialization trick does not work.\n #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]\n pub struct MarkerTraits: u8 {\n /// Indicates that the type implements the [`Eq`] marker trait\n const EQ = 1 << 0;\n /// Indicates that the type implements the [`Send`] marker trait.\n ///\n /// Note: this is a best-effort guess, see the documentation about negative impls in [MarkerTraits].\n const SEND = 1 << 1;\n /// Indicates that the type implements the [`Sync`] marker trait\n ///\n /// Note: this is a best-effort guess, see the documentation about negative impls in [MarkerTraits].\n const SYNC = 1 << 2;\n /// Indicates that the type implements the [`Copy`] marker trait\n const COPY = 1 << 3;\n /// Indicates that the type implements the [`Unpin`] marker trait\n const UNPIN = 1 << 4;\n /// Indicates that the type implements the [`UnwindSafe`](core::panic::UnwindSafe) marker trait\n ///\n /// Note: this is a best-effort guess, see the documentation about negative impls in [MarkerTraits].\n const UNWIND_SAFE = 1 << 5;\n /// Indicates that the type implements the [`RefUnwindSafe`](core::panic::RefUnwindSafe) marker trait\n ///\n /// Note: this is a best-effort guess, see the documentation about negative impls in [MarkerTraits].\n const REF_UNWIND_SAFE = 1 << 6;\n }\n}\n\n//======== Display and Debug ========\n\n/// Function to format a value for display\n///\n/// If both [`DisplayFn`] and [`ParseFn`] are set, we should be able to round-trip the value.\n///\n/// # Safety\n///\n/// The `value` parameter must point to aligned, initialized memory of the correct type.\npub type DisplayFn =\n for<'mem> unsafe fn(value: PtrConst<'mem>, f: &mut core::fmt::Formatter) -> core::fmt::Result;\n\n/// Function to format a value for display (wide pointer version)\n///\n/// If both [`DisplayFnWide`] and [`ParseFn`] are set, we should be able to round-trip the value.\n///\n/// # Safety\n///\n/// The `value` parameter must point to aligned, initialized memory of the correct type.\npub type DisplayFnWide = for<'mem> unsafe fn(\n value: PtrConstWide<'mem>,\n f: &mut core::fmt::Formatter,\n) -> core::fmt::Result;\n\n/// Function to format a value for display\n///\n/// If both [`DisplayFn`] and [`ParseFn`] are set, we should be able to round-trip the value.\npub type DisplayFnTyped = fn(value: &T, f: &mut core::fmt::Formatter) -> core::fmt::Result;\n\n/// Function to format a value for debug.\n/// If this returns None, the shape did not implement Debug.\npub type DebugFn =\n for<'mem> unsafe fn(value: PtrConst<'mem>, f: &mut core::fmt::Formatter) -> core::fmt::Result;\n\n/// Function to format a value for debug (wide pointer version).\n/// If this returns None, the shape did not implement Debug (wide).\npub type DebugFnWide = for<'mem> unsafe fn(\n value: PtrConstWide<'mem>,\n f: &mut core::fmt::Formatter,\n) -> core::fmt::Result;\n\n/// Function to format a value for debug.\n/// If this returns None, the shape did not implement Debug.\npub type DebugFnTyped = fn(value: &T, f: &mut core::fmt::Formatter) -> core::fmt::Result;\n\n/// A vtable representing the operations that can be performed on a type,\n/// either for sized or unsized types.\n///\n/// This enum encapsulates the specific vtables for sized ([`ValueVTableSized`])\n/// and unsized ([`ValueVTableUnsized`]) shapes, allowing generic type-agnostic\n/// dynamic dispatch for core capabilities (clone, drop, compare, hash, etc).\n#[derive(Debug, Clone, Copy)]\n#[repr(C)]\npub enum ValueVTable {\n /// VTable for operations on sized types.\n Sized(ValueVTableSized),\n /// VTable for operations on unsized types.\n Unsized(ValueVTableUnsized),\n}\n\n/// VTable for common operations that can be performed on any `Sized` shape\n#[derive(Debug, Clone, Copy)]\n#[repr(C)]\npub struct ValueVTableSized {\n /// cf. [`TypeNameFn`]\n pub type_name: TypeNameFn,\n /// Marker traits implemented by the type\n // FIXME: move out of vtable, it's not really... functions.\n // Belongs in Shape directly.\n pub marker_traits: fn() -> MarkerTraits,\n\n /// cf. [`DropInPlaceFn`] — if None, drops without side-effects\n pub drop_in_place: fn() -> Option,\n\n /// cf. [`InvariantsFn`]\n pub invariants: fn() -> Option,\n\n /// cf. [`DisplayFn`]\n pub display: fn() -> Option,\n\n /// cf. [`DebugFn`]\n pub debug: fn() -> Option,\n\n /// cf. [`DefaultInPlaceFn`]\n pub default_in_place: fn() -> Option,\n\n /// cf. [`CloneIntoFn`]\n pub clone_into: fn() -> Option,\n\n /// cf. [`PartialEqFn`] for equality comparison\n pub partial_eq: fn() -> Option,\n\n /// cf. [`PartialOrdFn`] for partial ordering comparison\n pub partial_ord: fn() -> Option,\n\n /// cf. [`CmpFn`] for total ordering\n pub ord: fn() -> Option,\n\n /// cf. [`HashFn`]\n pub hash: fn() -> Option,\n\n /// cf. [`ParseFn`]\n pub parse: fn() -> Option,\n\n /// cf. [`TryFromFn`]\n ///\n /// This also acts as a \"TryFromInner\" — you can use it to go:\n ///\n /// * `String` => `Utf8PathBuf`\n /// * `String` => `Uuid`\n /// * `T` => `Option`\n /// * `T` => `Arc`\n /// * `T` => `NonZero`\n /// * etc.\n ///\n pub try_from: fn() -> Option,\n\n /// cf. [`TryIntoInnerFn`]\n ///\n /// This is used by transparent types to convert the wrapper type into its inner value.\n /// Primarily used during serialization.\n pub try_into_inner: fn() -> Option,\n\n /// cf. [`TryBorrowInnerFn`]\n ///\n /// This is used by transparent types to efficiently access the inner value without copying.\n pub try_borrow_inner: fn() -> Option,\n}\n\n/// VTable for common operations that can be performed on any `!Sized` shape\n#[derive(Debug, Clone, Copy)]\n#[repr(C)]\npub struct ValueVTableUnsized {\n /// cf. [`TypeNameFn`]\n pub type_name: TypeNameFn,\n /// Marker traits implemented by the type\n // FIXME: move out of vtable, it's not really... functions.\n // Belongs in Shape directly.\n pub marker_traits: fn() -> MarkerTraits,\n\n /// cf. [`DropInPlaceFnWide`] — if None, drops without side-effects\n pub drop_in_place: fn() -> Option,\n\n /// cf. [`InvariantsFnWide`]\n pub invariants: fn() -> Option,\n\n /// cf. [`DisplayFnWide`]\n pub display: fn() -> Option,\n\n /// cf. [`DebugFnWide`]\n pub debug: fn() -> Option,\n\n /// cf. [`PartialEqFnWide`] for equality comparison\n pub partial_eq: fn() -> Option,\n\n /// cf. [`PartialOrdFnWide`] for partial ordering comparison\n pub partial_ord: fn() -> Option,\n\n /// cf. [`CmpFnWide`] for total ordering\n pub ord: fn() -> Option,\n\n /// cf. [`HashFnWide`]\n pub hash: fn() -> Option,\n\n /// cf. [`TryBorrowInnerFnWide`]\n ///\n /// This is used by transparent types to efficiently access the inner value without copying.\n pub try_borrow_inner: fn() -> Option,\n}\n\nmacro_rules! has_fn {\n ($self:expr, $name:tt) => {\n match $self {\n ValueVTable::Sized(inner) => (inner.$name)().is_some(),\n ValueVTable::Unsized(inner) => (inner.$name)().is_some(),\n }\n };\n}\n\nmacro_rules! has_fn_sized {\n ($self:expr, $name:tt) => {\n match $self {\n ValueVTable::Sized(inner) => (inner.$name)().is_some(),\n ValueVTable::Unsized(_) => false,\n }\n };\n}\n\nimpl ValueVTable {\n /// Returns a reference to the [`ValueVTableSized`] if this vtable is for a sized type.\n ///\n /// # Returns\n ///\n /// - `Some(&ValueVTableSized)` if the type is sized.\n /// - `None` if the type is unsized.\n pub const fn sized(&self) -> Option<&ValueVTableSized> {\n match self {\n ValueVTable::Sized(inner) => Some(inner),\n ValueVTable::Unsized(_) => None,\n }\n }\n\n /// Returns a mutable reference to the [`ValueVTableSized`] if this vtable is for a sized type.\n ///\n /// # Returns\n ///\n /// - `Some(&mut ValueVTableSized)` if the type is sized.\n /// - `None` if the type is unsized.\n pub const fn sized_mut(&mut self) -> Option<&mut ValueVTableSized> {\n match self {\n ValueVTable::Sized(inner) => Some(inner),\n ValueVTable::Unsized(_) => None,\n }\n }\n\n /// Returns a reference to the [`ValueVTableUnsized`] if this vtable is for an unsized type.\n ///\n /// # Returns\n ///\n /// - `Some(&ValueVTableUnsized)` if the type is unsized.\n /// - `None` if the type is sized.\n pub const fn r#unsized(&self) -> Option<&ValueVTableUnsized> {\n match self {\n ValueVTable::Sized(_) => None,\n ValueVTable::Unsized(inner) => Some(inner),\n }\n }\n\n /// Get the marker traits implemented for the type\n #[inline]\n pub fn marker_traits(&self) -> MarkerTraits {\n match self {\n ValueVTable::Sized(inner) => (inner.marker_traits)(),\n ValueVTable::Unsized(inner) => (inner.marker_traits)(),\n }\n }\n\n /// Get the type name fn of the type\n #[inline]\n pub const fn type_name(&self) -> TypeNameFn {\n match self {\n ValueVTable::Sized(inner) => inner.type_name,\n ValueVTable::Unsized(inner) => inner.type_name,\n }\n }\n\n /// Check if the type implements the [`Eq`] marker trait\n #[inline]\n pub fn is_eq(&self) -> bool {\n self.marker_traits().contains(MarkerTraits::EQ)\n }\n\n /// Check if the type implements the [`Send`] marker trait\n #[inline]\n pub fn is_send(&self) -> bool {\n self.marker_traits().contains(MarkerTraits::SEND)\n }\n\n /// Check if the type implements the [`Sync`] marker trait\n #[inline]\n pub fn is_sync(&self) -> bool {\n self.marker_traits().contains(MarkerTraits::SYNC)\n }\n\n /// Check if the type implements the [`Copy`] marker trait\n #[inline]\n pub fn is_copy(&self) -> bool {\n self.marker_traits().contains(MarkerTraits::COPY)\n }\n\n /// Check if the type implements the [`Unpin`] marker trait\n #[inline]\n pub fn is_unpin(&self) -> bool {\n self.marker_traits().contains(MarkerTraits::UNPIN)\n }\n\n /// Check if the type implements the [`UnwindSafe`](core::panic::UnwindSafe) marker trait\n #[inline]\n pub fn is_unwind_safe(&self) -> bool {\n self.marker_traits().contains(MarkerTraits::UNWIND_SAFE)\n }\n\n /// Check if the type implements the [`RefUnwindSafe`](core::panic::RefUnwindSafe) marker trait\n #[inline]\n pub fn is_ref_unwind_safe(&self) -> bool {\n self.marker_traits().contains(MarkerTraits::REF_UNWIND_SAFE)\n }\n\n /// Returns `true` if the type implements the [`Display`](core::fmt::Display) trait and the `display` function is available in the vtable.\n #[inline]\n pub fn has_display(&self) -> bool {\n has_fn!(self, display)\n }\n\n /// Returns `true` if the type implements the [`Debug`] trait and the `debug` function is available in the vtable.\n #[inline]\n pub fn has_debug(&self) -> bool {\n has_fn!(self, debug)\n }\n\n /// Returns `true` if the type implements the [`PartialEq`] trait and the `partial_eq` function is available in the vtable.\n #[inline]\n pub fn has_partial_eq(&self) -> bool {\n has_fn!(self, partial_eq)\n }\n\n /// Returns `true` if the type implements the [`PartialOrd`] trait and the `partial_ord` function is available in the vtable.\n #[inline]\n pub fn has_partial_ord(&self) -> bool {\n has_fn!(self, partial_ord)\n }\n\n /// Returns `true` if the type implements the [`Ord`] trait and the `ord` function is available in the vtable.\n #[inline]\n pub fn has_ord(&self) -> bool {\n has_fn!(self, ord)\n }\n\n /// Returns `true` if the type implements the [`Hash`] trait and the `hash` function is available in the vtable.\n #[inline]\n pub fn has_hash(&self) -> bool {\n has_fn!(self, hash)\n }\n\n /// Returns `true` if the type supports default-in-place construction via the vtable.\n #[inline]\n pub fn has_default_in_place(&self) -> bool {\n has_fn_sized!(self, default_in_place)\n }\n\n /// Returns `true` if the type supports in-place cloning via the vtable.\n #[inline]\n pub fn has_clone_into(&self) -> bool {\n has_fn_sized!(self, clone_into)\n }\n\n /// Returns `true` if the type supports parsing from a string via the vtable.\n #[inline]\n pub fn has_parse(&self) -> bool {\n has_fn_sized!(self, parse)\n }\n /// Creates a new [`ValueVTableBuilder`]\n pub const fn builder() -> ValueVTableBuilder {\n ValueVTableBuilder::new()\n }\n\n /// Creates a new [`ValueVTableBuilderUnsized`]\n pub const fn builder_unsized() -> ValueVTableBuilderUnsized {\n ValueVTableBuilderUnsized::new()\n }\n}\n\n/// A typed view of a [`ValueVTable`].\n#[derive(Debug)]\npub struct VTableView(&'static ValueVTable, PhantomData);\n\nimpl<'a, T: crate::Facet<'a> + ?Sized> VTableView<&'a mut T> {\n /// Fetches the vtable for the type.\n pub fn of_deref() -> Self {\n Self(T::SHAPE.vtable, PhantomData)\n }\n}\n\nimpl<'a, T: crate::Facet<'a> + ?Sized> VTableView<&'a T> {\n /// Fetches the vtable for the type.\n pub fn of_deref() -> Self {\n Self(T::SHAPE.vtable, PhantomData)\n }\n}\n\nmacro_rules! get_fn {\n ($self:expr, $name:tt) => {\n match $self.0 {\n ValueVTable::Sized(inner) => (inner.$name)().map(|f| unsafe { mem::transmute(f) }),\n ValueVTable::Unsized(inner) => (inner.$name)().map(|f| unsafe { mem::transmute(f) }),\n }\n };\n}\n\nimpl<'a, T: crate::Facet<'a> + ?Sized> VTableView {\n /// Fetches the vtable for the type.\n pub fn of() -> Self {\n let this = Self(T::SHAPE.vtable, PhantomData);\n\n match this.0 {\n ValueVTable::Sized(_) => {\n assert!(T::SHAPE.layout.sized_layout().is_ok());\n assert_eq!(\n core::mem::size_of::<*const T>(),\n core::mem::size_of::<*const ()>()\n );\n }\n ValueVTable::Unsized(_) => {\n assert!(T::SHAPE.layout.sized_layout().is_err());\n assert_eq!(\n core::mem::size_of::<*const T>(),\n 2 * core::mem::size_of::<*const ()>()\n );\n }\n }\n\n this\n }\n\n /// cf. [`TypeNameFn`]\n #[inline(always)]\n pub fn type_name(&self) -> TypeNameFn {\n self.0.type_name()\n }\n\n /// cf. [`InvariantsFn`]\n #[inline(always)]\n pub fn invariants(&self) -> Option> {\n get_fn!(self, invariants)\n }\n\n /// cf. [`DisplayFn`]\n #[inline(always)]\n pub fn display(&self) -> Option> {\n get_fn!(self, display)\n }\n\n /// cf. [`DebugFn`]\n #[inline(always)]\n pub fn debug(&self) -> Option> {\n get_fn!(self, debug)\n }\n\n /// cf. [`PartialEqFn`] for equality comparison\n #[inline(always)]\n pub fn partial_eq(&self) -> Option> {\n get_fn!(self, partial_eq)\n }\n\n /// cf. [`PartialOrdFn`] for partial ordering comparison\n #[inline(always)]\n pub fn partial_ord(&self) -> Option> {\n get_fn!(self, partial_ord)\n }\n\n /// cf. [`CmpFn`] for total ordering\n #[inline(always)]\n pub fn ord(&self) -> Option> {\n get_fn!(self, ord)\n }\n\n /// cf. [`HashFn`]\n #[inline(always)]\n pub fn hash(&self) -> Option> {\n get_fn!(self, hash)\n }\n\n /// cf. [`TryBorrowInnerFn`]\n ///\n /// This is used by transparent types to efficiently access the inner value without copying.\n #[inline(always)]\n pub fn try_borrow_inner(&self) -> Option> {\n get_fn!(self, try_borrow_inner)\n }\n}\n\nimpl<'a, T: crate::Facet<'a>> VTableView {\n /// cf. [`DefaultInPlaceFn`]\n #[inline(always)]\n pub fn default_in_place(&self) -> Option> {\n (self.0.sized().unwrap().default_in_place)().map(|default_in_place| unsafe {\n mem::transmute::>(default_in_place)\n })\n }\n\n /// cf. [`CloneIntoFn`]\n #[inline(always)]\n pub fn clone_into(&self) -> Option> {\n (self.0.sized().unwrap().clone_into)().map(|clone_into| unsafe {\n mem::transmute::>(clone_into)\n })\n }\n\n /// cf. [`ParseFn`]\n #[inline(always)]\n pub fn parse(&self) -> Option> {\n (self.0.sized().unwrap().parse)()\n .map(|parse| unsafe { mem::transmute::>(parse) })\n }\n\n /// cf. [`TryFromFn`]\n ///\n /// This also acts as a \"TryFromInner\" — you can use it to go:\n ///\n /// * `String` => `Utf8PathBuf`\n /// * `String` => `Uuid`\n /// * `T` => `Option`\n /// * `T` => `Arc`\n /// * `T` => `NonZero`\n /// * etc.\n ///\n #[inline(always)]\n pub fn try_from(&self) -> Option> {\n (self.0.sized().unwrap().try_from)()\n .map(|try_from| unsafe { mem::transmute::>(try_from) })\n }\n\n /// cf. [`TryIntoInnerFn`]\n ///\n /// This is used by transparent types to convert the wrapper type into its inner value.\n /// Primarily used during serialization.\n #[inline(always)]\n pub fn try_into_inner(&self) -> Option> {\n (self.0.sized().unwrap().try_into_inner)().map(|try_into_inner| unsafe {\n mem::transmute::>(try_into_inner)\n })\n }\n}\n/// Builds a [`ValueVTable`]\npub struct ValueVTableBuilder {\n type_name: Option,\n display: fn() -> Option,\n debug: fn() -> Option,\n default_in_place: fn() -> Option,\n clone_into: fn() -> Option,\n marker_traits: fn() -> MarkerTraits,\n partial_eq: fn() -> Option,\n partial_ord: fn() -> Option,\n ord: fn() -> Option,\n hash: fn() -> Option,\n drop_in_place: fn() -> Option,\n invariants: fn() -> Option,\n parse: fn() -> Option,\n try_from: fn() -> Option,\n try_into_inner: fn() -> Option,\n try_borrow_inner: fn() -> Option,\n _pd: PhantomData,\n}\n\nimpl ValueVTableBuilder {\n /// Creates a new [`ValueVTableBuilder`] with all fields set to `None`.\n #[allow(clippy::new_without_default)]\n pub const fn new() -> Self {\n Self {\n type_name: None,\n display: || None,\n debug: || None,\n default_in_place: || None,\n clone_into: || None,\n marker_traits: || MarkerTraits::empty(),\n partial_eq: || None,\n partial_ord: || None,\n ord: || None,\n hash: || None,\n drop_in_place: || {\n if mem::needs_drop::() {\n Some(|value| unsafe { value.drop_in_place::() })\n } else {\n None\n }\n },\n invariants: || None,\n parse: || None,\n try_from: || None,\n try_into_inner: || None,\n try_borrow_inner: || None,\n _pd: PhantomData,\n }\n }\n\n /// Sets the type name function for this builder.\n pub const fn type_name(mut self, type_name: TypeNameFn) -> Self {\n self.type_name = Some(type_name);\n self\n }\n\n /// Sets the display function for this builder.\n pub const fn display(mut self, display: fn() -> Option>) -> Self {\n self.display = unsafe {\n mem::transmute:: Option>, fn() -> Option>(display)\n };\n self\n }\n\n /// Sets the debug function for this builder.\n pub const fn debug(mut self, debug: fn() -> Option>) -> Self {\n self.debug = unsafe {\n mem::transmute:: Option>, fn() -> Option>(debug)\n };\n self\n }\n\n /// Sets the default_in_place function for this builder.\n pub const fn default_in_place(\n mut self,\n default_in_place: fn() -> Option>,\n ) -> Self {\n self.default_in_place = unsafe {\n mem::transmute::<\n fn() -> Option>,\n fn() -> Option,\n >(default_in_place)\n };\n self\n }\n\n /// Sets the clone_into function for this builder.\n pub const fn clone_into(mut self, clone_into: fn() -> Option>) -> Self {\n self.clone_into = unsafe {\n mem::transmute:: Option>, fn() -> Option>(\n clone_into,\n )\n };\n self\n }\n\n /// Sets the marker traits for this builder.\n pub const fn marker_traits(mut self, marker_traits: fn() -> MarkerTraits) -> Self {\n self.marker_traits = marker_traits;\n self\n }\n\n /// Sets the partial_eq function for this builder.\n pub const fn partial_eq(mut self, partial_eq: fn() -> Option>) -> Self {\n self.partial_eq = unsafe {\n mem::transmute:: Option>, fn() -> Option>(\n partial_eq,\n )\n };\n self\n }\n\n /// Sets the partial_ord function for this builder.\n pub const fn partial_ord(mut self, partial_ord: fn() -> Option>) -> Self {\n self.partial_ord = unsafe {\n mem::transmute:: Option>, fn() -> Option>(\n partial_ord,\n )\n };\n self\n }\n\n /// Sets the ord function for this builder.\n pub const fn ord(mut self, ord: fn() -> Option>) -> Self {\n self.ord =\n unsafe { mem::transmute:: Option>, fn() -> Option>(ord) };\n self\n }\n\n /// Sets the hash function for this builder.\n pub const fn hash(mut self, hash: fn() -> Option>) -> Self {\n self.hash = unsafe {\n mem::transmute:: Option>, fn() -> Option>(hash)\n };\n self\n }\n\n /// Overwrites the drop_in_place function for this builder.\n ///\n /// This is usually not necessary, the builder builder will default this to the appropriate type.\n pub const fn drop_in_place(mut self, drop_in_place: fn() -> Option) -> Self {\n self.drop_in_place = drop_in_place;\n self\n }\n\n /// Sets the invariants function for this builder.\n pub const fn invariants(mut self, invariants: fn() -> Option>) -> Self {\n self.invariants = unsafe {\n mem::transmute:: Option>, fn() -> Option>(\n invariants,\n )\n };\n self\n }\n\n /// Sets the parse function for this builder.\n pub const fn parse(mut self, parse: fn() -> Option>) -> Self {\n self.parse = unsafe {\n mem::transmute:: Option>, fn() -> Option>(parse)\n };\n self\n }\n\n /// Sets the try_from function for this builder.\n pub const fn try_from(mut self, try_from: fn() -> Option>) -> Self {\n self.try_from = unsafe {\n mem::transmute:: Option>, fn() -> Option>(try_from)\n };\n self\n }\n\n /// Sets the try_into_inner function for this builder.\n pub const fn try_into_inner(\n mut self,\n try_into_inner: fn() -> Option>,\n ) -> Self {\n self.try_into_inner = unsafe {\n mem::transmute:: Option>, fn() -> Option>(\n try_into_inner,\n )\n };\n self\n }\n\n /// Sets the borrow_inner function for this builder.\n pub const fn try_borrow_inner(\n mut self,\n try_borrow_inner: fn() -> Option>,\n ) -> Self {\n self.try_borrow_inner = unsafe {\n mem::transmute::<\n fn() -> Option>,\n fn() -> Option,\n >(try_borrow_inner)\n };\n self\n }\n\n /// Builds the [`ValueVTable`] from the current state of the builder.\n pub const fn build(self) -> ValueVTable {\n ValueVTable::Sized(ValueVTableSized {\n type_name: self.type_name.unwrap(),\n marker_traits: self.marker_traits,\n invariants: self.invariants,\n display: self.display,\n debug: self.debug,\n default_in_place: self.default_in_place,\n clone_into: self.clone_into,\n partial_eq: self.partial_eq,\n partial_ord: self.partial_ord,\n ord: self.ord,\n hash: self.hash,\n parse: self.parse,\n try_from: self.try_from,\n try_into_inner: self.try_into_inner,\n try_borrow_inner: self.try_borrow_inner,\n drop_in_place: self.drop_in_place,\n })\n }\n}\n\n/// Builds a [`ValueVTable`] for a `!Sized` type\npub struct ValueVTableBuilderUnsized {\n type_name: Option,\n display: fn() -> Option,\n debug: fn() -> Option,\n marker_traits: fn() -> MarkerTraits,\n partial_eq: fn() -> Option,\n partial_ord: fn() -> Option,\n ord: fn() -> Option,\n hash: fn() -> Option,\n invariants: fn() -> Option,\n try_borrow_inner: fn() -> Option,\n _pd: PhantomData,\n}\n\nimpl ValueVTableBuilderUnsized {\n /// Creates a new [`ValueVTableBuilder`] with all fields set to `None`.\n #[allow(clippy::new_without_default)]\n pub const fn new() -> Self {\n Self {\n type_name: None,\n display: || None,\n debug: || None,\n marker_traits: || MarkerTraits::empty(),\n partial_eq: || None,\n partial_ord: || None,\n ord: || None,\n hash: || None,\n invariants: || None,\n try_borrow_inner: || None,\n _pd: PhantomData,\n }\n }\n\n /// Sets the type name function for this builder.\n pub const fn type_name(mut self, type_name: TypeNameFn) -> Self {\n self.type_name = Some(type_name);\n self\n }\n\n /// Sets the display function for this builder.\n pub const fn display(mut self, display: fn() -> Option>) -> Self {\n self.display = unsafe {\n mem::transmute:: Option>, fn() -> Option>(\n display,\n )\n };\n self\n }\n\n /// Sets the debug function for this builder.\n pub const fn debug(mut self, debug: fn() -> Option>) -> Self {\n self.debug = unsafe {\n mem::transmute:: Option>, fn() -> Option>(debug)\n };\n self\n }\n\n /// Sets the marker traits for this builder.\n pub const fn marker_traits(mut self, marker_traits: fn() -> MarkerTraits) -> Self {\n self.marker_traits = marker_traits;\n self\n }\n\n /// Sets the eq function for this builder.\n pub const fn partial_eq(mut self, partial_eq: fn() -> Option>) -> Self {\n self.partial_eq = unsafe {\n mem::transmute:: Option>, fn() -> Option>(\n partial_eq,\n )\n };\n self\n }\n\n /// Sets the partial_ord function for this builder.\n pub const fn partial_ord(mut self, partial_ord: fn() -> Option>) -> Self {\n self.partial_ord = unsafe {\n mem::transmute:: Option>, fn() -> Option>(\n partial_ord,\n )\n };\n self\n }\n\n /// Sets the ord function for this builder.\n pub const fn ord(mut self, ord: fn() -> Option>) -> Self {\n self.ord = unsafe {\n mem::transmute:: Option>, fn() -> Option>(ord)\n };\n self\n }\n\n /// Sets the hash function for this builder.\n pub const fn hash(mut self, hash: fn() -> Option>) -> Self {\n self.hash = unsafe {\n mem::transmute:: Option>, fn() -> Option>(hash)\n };\n self\n }\n\n /// Sets the invariants function for this builder.\n pub const fn invariants(mut self, invariants: fn() -> Option>) -> Self {\n self.invariants = unsafe {\n mem::transmute:: Option>, fn() -> Option>(\n invariants,\n )\n };\n self\n }\n\n /// Sets the borrow_inner function for this builder.\n pub const fn try_borrow_inner(\n mut self,\n try_borrow_inner: fn() -> Option>,\n ) -> Self {\n self.try_borrow_inner = unsafe {\n mem::transmute::<\n fn() -> Option>,\n fn() -> Option,\n >(try_borrow_inner)\n };\n self\n }\n\n /// Builds the [`ValueVTable`] from the current state of the builder.\n pub const fn build(self) -> ValueVTable {\n ValueVTable::Unsized(ValueVTableUnsized {\n type_name: self.type_name.unwrap(),\n marker_traits: self.marker_traits,\n invariants: self.invariants,\n display: self.display,\n debug: self.debug,\n partial_eq: self.partial_eq,\n partial_ord: self.partial_ord,\n ord: self.ord,\n hash: self.hash,\n try_borrow_inner: self.try_borrow_inner,\n // TODO: Add support for this\n drop_in_place: || None,\n })\n }\n}\n"], ["/facet/facet-core/src/impls_chrono.rs", "use alloc::string::{String, ToString};\nuse chrono::{DateTime, FixedOffset, Local, NaiveDate, NaiveDateTime, NaiveTime, Utc};\n\nuse crate::{\n Def, Facet, ParseError, PtrConst, PtrUninit, Shape, Type, UserType, ValueVTable, value_vtable,\n};\n\nunsafe impl Facet<'_> for DateTime {\n const VTABLE: &'static ValueVTable = &const {\n let mut vtable = value_vtable!(DateTime, |f, _opts| write!(\n f,\n \"{}\",\n Self::SHAPE.type_identifier\n ));\n {\n let vtable = vtable.sized_mut().unwrap();\n vtable.try_from = || {\n Some(\n |source: PtrConst, source_shape: &Shape, target: PtrUninit| {\n if source_shape.is_type::() {\n let source = unsafe { source.read::() };\n let parsed = DateTime::parse_from_rfc3339(&source)\n .map(|dt| dt.with_timezone(&Utc))\n .map_err(|_| ParseError::Generic(\"could not parse date\"));\n match parsed {\n Ok(val) => Ok(unsafe { target.put(val) }),\n Err(_e) => {\n Err(crate::TryFromError::Generic(\"could not parse date\"))\n }\n }\n } else {\n Err(crate::TryFromError::UnsupportedSourceShape {\n src_shape: source_shape,\n expected: &[String::SHAPE],\n })\n }\n },\n )\n };\n vtable.parse = || {\n Some(|s: &str, target: PtrUninit| {\n let parsed = DateTime::parse_from_rfc3339(s)\n .map(|dt| dt.with_timezone(&Utc))\n .map_err(|_| ParseError::Generic(\"could not parse date\"))?;\n Ok(unsafe { target.put(parsed) })\n })\n };\n vtable.display = || {\n Some(|value, f| unsafe {\n let dt = value.get::>();\n use chrono::SecondsFormat;\n let s = dt.to_rfc3339_opts(SecondsFormat::Secs, true);\n write!(f, \"{s}\")\n })\n };\n }\n vtable\n };\n\n const SHAPE: &'static Shape = &const {\n Shape::builder_for_sized::()\n .type_identifier(\"DateTime\")\n .ty(Type::User(UserType::Opaque))\n .def(Def::Scalar)\n .build()\n };\n}\n\nunsafe impl Facet<'_> for DateTime {\n const VTABLE: &'static ValueVTable = &const {\n let mut vtable = value_vtable!(DateTime, |f, _opts| write!(\n f,\n \"{}\",\n Self::SHAPE.type_identifier\n ));\n {\n let vtable = vtable.sized_mut().unwrap();\n vtable.try_from = || {\n Some(\n |source: PtrConst, source_shape: &Shape, target: PtrUninit| {\n if source_shape.is_type::() {\n let source = unsafe { source.read::() };\n let parsed = DateTime::parse_from_rfc3339(&source)\n .map_err(|_| ParseError::Generic(\"could not parse date\"));\n match parsed {\n Ok(val) => Ok(unsafe { target.put(val) }),\n Err(_e) => {\n Err(crate::TryFromError::Generic(\"could not parse date\"))\n }\n }\n } else {\n Err(crate::TryFromError::UnsupportedSourceShape {\n src_shape: source_shape,\n expected: &[String::SHAPE],\n })\n }\n },\n )\n };\n vtable.parse = || {\n Some(|s: &str, target: PtrUninit| {\n let parsed = DateTime::parse_from_rfc3339(s)\n .map_err(|_| ParseError::Generic(\"could not parse date\"))?;\n Ok(unsafe { target.put(parsed) })\n })\n };\n vtable.display = || {\n Some(|value, f| unsafe {\n let dt = value.get::>();\n use chrono::SecondsFormat;\n write!(f, \"{}\", dt.to_rfc3339_opts(SecondsFormat::Secs, true))\n })\n };\n }\n vtable\n };\n\n const SHAPE: &'static Shape = &const {\n Shape::builder_for_sized::()\n .type_identifier(\"DateTime\")\n .ty(Type::User(UserType::Opaque))\n .def(Def::Scalar)\n .build()\n };\n}\n\nunsafe impl Facet<'_> for DateTime {\n const VTABLE: &'static ValueVTable = &const {\n let mut vtable = value_vtable!(DateTime, |f, _opts| write!(\n f,\n \"{}\",\n Self::SHAPE.type_identifier\n ));\n {\n let vtable = vtable.sized_mut().unwrap();\n vtable.try_from = || {\n Some(\n |source: PtrConst, source_shape: &Shape, target: PtrUninit| {\n if source_shape.is_type::() {\n let source = unsafe { source.read::() };\n let parsed = DateTime::parse_from_rfc3339(&source)\n .map(|dt| dt.with_timezone(&Local))\n .map_err(|_| ParseError::Generic(\"could not parse date\"));\n match parsed {\n Ok(val) => Ok(unsafe { target.put(val) }),\n Err(_e) => {\n Err(crate::TryFromError::Generic(\"could not parse date\"))\n }\n }\n } else {\n Err(crate::TryFromError::UnsupportedSourceShape {\n src_shape: source_shape,\n expected: &[String::SHAPE],\n })\n }\n },\n )\n };\n vtable.parse = || {\n Some(|s: &str, target: PtrUninit| {\n let parsed = DateTime::parse_from_rfc3339(s)\n .map(|dt| dt.with_timezone(&Local))\n .map_err(|_| ParseError::Generic(\"could not parse date\"))?;\n Ok(unsafe { target.put(parsed) })\n })\n };\n vtable.display = || {\n Some(|value, f| unsafe {\n let dt = value.get::>();\n use chrono::SecondsFormat;\n write!(f, \"{}\", dt.to_rfc3339_opts(SecondsFormat::Secs, true))\n })\n };\n }\n vtable\n };\n\n const SHAPE: &'static Shape = &const {\n Shape::builder_for_sized::()\n .type_identifier(\"DateTime\")\n .ty(Type::User(UserType::Opaque))\n .def(Def::Scalar)\n .build()\n };\n}\n\nunsafe impl Facet<'_> for NaiveDateTime {\n const VTABLE: &'static ValueVTable = &const {\n let mut vtable = value_vtable!(NaiveDateTime, |f, _opts| write!(\n f,\n \"{}\",\n Self::SHAPE.type_identifier\n ));\n {\n let vtable = vtable.sized_mut().unwrap();\n vtable.try_from = || {\n Some(\n |source: PtrConst, source_shape: &Shape, target: PtrUninit| {\n if source_shape.is_type::() {\n let source = unsafe { source.read::() };\n let parsed =\n NaiveDateTime::parse_from_str(&source, \"%Y-%m-%dT%H:%M:%S\")\n .or_else(|_| {\n NaiveDateTime::parse_from_str(&source, \"%Y-%m-%d %H:%M:%S\")\n })\n .map_err(|_| ParseError::Generic(\"could not parse date\"));\n match parsed {\n Ok(val) => Ok(unsafe { target.put(val) }),\n Err(_e) => {\n Err(crate::TryFromError::Generic(\"could not parse date\"))\n }\n }\n } else {\n Err(crate::TryFromError::UnsupportedSourceShape {\n src_shape: source_shape,\n expected: &[String::SHAPE],\n })\n }\n },\n )\n };\n vtable.parse = || {\n Some(|s: &str, target: PtrUninit| {\n let parsed = NaiveDateTime::parse_from_str(s, \"%Y-%m-%dT%H:%M:%S\")\n .or_else(|_| NaiveDateTime::parse_from_str(s, \"%Y-%m-%d %H:%M:%S\"))\n .map_err(|_| ParseError::Generic(\"could not parse date\"))?;\n Ok(unsafe { target.put(parsed) })\n })\n };\n vtable.display = || {\n Some(|value, f| unsafe {\n let dt = value.get::();\n let formatted = dt.format(\"%Y-%m-%dT%H:%M:%S\").to_string();\n write!(f, \"{formatted}\")\n })\n };\n }\n vtable\n };\n\n const SHAPE: &'static Shape = &const {\n Shape::builder_for_sized::()\n .type_identifier(\"NaiveDateTime\")\n .ty(Type::User(UserType::Opaque))\n .def(Def::Scalar)\n .build()\n };\n}\n\nunsafe impl Facet<'_> for NaiveDate {\n const VTABLE: &'static ValueVTable = &const {\n let mut vtable = value_vtable!(NaiveDate, |f, _opts| write!(\n f,\n \"{}\",\n Self::SHAPE.type_identifier\n ));\n {\n let vtable = vtable.sized_mut().unwrap();\n vtable.try_from = || {\n Some(\n |source: PtrConst, source_shape: &Shape, target: PtrUninit| {\n if source_shape.is_type::() {\n let source = unsafe { source.read::() };\n let parsed = NaiveDate::parse_from_str(&source, \"%Y-%m-%d\")\n .map_err(|_| ParseError::Generic(\"could not parse date\"));\n match parsed {\n Ok(val) => Ok(unsafe { target.put(val) }),\n Err(_e) => {\n Err(crate::TryFromError::Generic(\"could not parse date\"))\n }\n }\n } else {\n Err(crate::TryFromError::UnsupportedSourceShape {\n src_shape: source_shape,\n expected: &[String::SHAPE],\n })\n }\n },\n )\n };\n vtable.parse = || {\n Some(|s: &str, target: PtrUninit| {\n let parsed = NaiveDate::parse_from_str(s, \"%Y-%m-%d\")\n .map_err(|_| ParseError::Generic(\"could not parse date\"))?;\n Ok(unsafe { target.put(parsed) })\n })\n };\n vtable.display = || {\n Some(|value, f| unsafe {\n let dt = value.get::();\n let formatted = dt.format(\"%Y-%m-%d\").to_string();\n write!(f, \"{formatted}\")\n })\n };\n }\n vtable\n };\n\n const SHAPE: &'static Shape = &const {\n Shape::builder_for_sized::()\n .type_identifier(\"NaiveDate\")\n .ty(Type::User(UserType::Opaque))\n .def(Def::Scalar)\n .build()\n };\n}\n\nunsafe impl Facet<'_> for NaiveTime {\n const VTABLE: &'static ValueVTable = &const {\n let mut vtable = value_vtable!(NaiveTime, |f, _opts| write!(\n f,\n \"{}\",\n Self::SHAPE.type_identifier\n ));\n {\n let vtable = vtable.sized_mut().unwrap();\n vtable.try_from = || {\n Some(\n |source: PtrConst, source_shape: &Shape, target: PtrUninit| {\n if source_shape.is_type::() {\n let source = unsafe { source.read::() };\n let parsed = NaiveTime::parse_from_str(&source, \"%H:%M:%S\")\n .or_else(|_| NaiveTime::parse_from_str(&source, \"%H:%M:%S%.f\"))\n .map_err(|_| ParseError::Generic(\"could not parse time\"));\n match parsed {\n Ok(val) => Ok(unsafe { target.put(val) }),\n Err(_e) => {\n Err(crate::TryFromError::Generic(\"could not parse time\"))\n }\n }\n } else {\n Err(crate::TryFromError::UnsupportedSourceShape {\n src_shape: source_shape,\n expected: &[String::SHAPE],\n })\n }\n },\n )\n };\n vtable.parse = || {\n Some(|s: &str, target: PtrUninit| {\n let parsed = NaiveTime::parse_from_str(s, \"%H:%M:%S\")\n .or_else(|_| NaiveTime::parse_from_str(s, \"%H:%M:%S%.f\"))\n .map_err(|_| ParseError::Generic(\"could not parse time\"))?;\n Ok(unsafe { target.put(parsed) })\n })\n };\n vtable.display = || {\n Some(|value, f| unsafe {\n let dt = value.get::();\n let formatted = dt.format(\"%H:%M:%S\").to_string();\n write!(f, \"{formatted}\")\n })\n };\n }\n vtable\n };\n\n const SHAPE: &'static Shape = &const {\n Shape::builder_for_sized::()\n .type_identifier(\"NaiveTime\")\n .ty(Type::User(UserType::Opaque))\n .def(Def::Scalar)\n .build()\n };\n}\n"], ["/facet/facet-core/src/types/ty/mod.rs", "use super::*;\n\nmod field;\npub use field::*;\n\nmod struct_;\npub use struct_::*;\n\nmod enum_;\npub use enum_::*;\n\nmod union_;\npub use union_::*;\n\nmod primitive;\npub use primitive::*;\n\nmod sequence;\npub use sequence::*;\n\nmod user;\npub use user::*;\n\nmod pointer;\npub use pointer::*;\n\n/// The definition of a shape in accordance to rust reference:\n///\n/// See \n#[derive(Clone, Copy, Debug)]\n#[repr(C)]\npub enum Type {\n /// Built-in primitive.\n Primitive(PrimitiveType),\n /// Sequence (tuple, array, slice).\n Sequence(SequenceType),\n /// User-defined type (struct, enum, union).\n User(UserType),\n /// Pointer type (reference, raw, function pointer).\n Pointer(PointerType),\n}\n\n// This implementation of `Display` is user-facing output, where the users are developers.\n// It is intended to show structure up to a certain depth, but for readability and brevity,\n// some complicated types have custom formatting surrounded by guillemet characters\n// (`«` and `»`) to indicate divergence from AST.\nimpl core::fmt::Display for Type {\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n match self {\n Type::Primitive(_) => {\n // Defer to `Debug`, which correctly produces the intended formatting.\n write!(f, \"{self:?}\")?;\n }\n Type::Sequence(SequenceType::Array(ArrayType { t, n })) => {\n write!(f, \"Sequence(Array(«[{t}; {n}]»))\")?;\n }\n Type::Sequence(SequenceType::Slice(SliceType { t })) => {\n write!(f, \"Sequence(Slice(«&[{t}]»))\")?;\n }\n Type::User(UserType::Struct(struct_type)) => {\n struct __Display<'a>(&'a StructType);\n impl core::fmt::Display for __Display<'_> {\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n write!(f, \"«\")?;\n write!(f, \"kind: {:?}\", self.0.kind)?;\n // Field count for `TupleStruct` and `Tuple`, and field names for `Struct`.\n // For `Unit`, we don't show anything.\n if let StructKind::Struct = self.0.kind {\n write!(f, \", fields: (\")?;\n let mut fields_iter = self.0.fields.iter();\n if let Some(field) = fields_iter.next() {\n write!(f, \"{}\", field.name)?;\n for field in fields_iter {\n write!(f, \", {}\", field.name)?;\n }\n }\n write!(f, \")\")?;\n } else if let StructKind::TupleStruct | StructKind::Tuple = self.0.kind {\n write!(f, \", fields: {}\", self.0.fields.len())?;\n }\n // Only show the `#[repr(_)]` if it's not `Rust` (unless it's `repr(packed)`).\n if let BaseRepr::C = self.0.repr.base {\n if self.0.repr.packed {\n // If there are multiple `repr` hints, display as a parenthesized list.\n write!(f, \", repr: (C, packed)\")?;\n } else {\n write!(f, \", repr: C\")?;\n }\n } else if let BaseRepr::Transparent = self.0.repr.base {\n write!(f, \", repr: transparent\")?;\n // Verbatim compiler error:\n assert!(\n !self.0.repr.packed,\n \"transparent struct cannot have other repr hints\"\n );\n } else if self.0.repr.packed {\n // This is potentially meaningless, but we'll show it anyway.\n // In this circumstance, you can assume it's `repr(Rust)`.\n write!(f, \", repr: packed\")?;\n }\n write!(f, \"»\")\n }\n }\n let show_struct = __Display(struct_type);\n write!(f, \"User(Struct({show_struct}))\")?;\n }\n Type::User(UserType::Enum(enum_type)) => {\n struct __Display<'a>(&'a EnumType);\n impl<'a> core::fmt::Display for __Display<'a> {\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n write!(f, \"«\")?;\n write!(f, \"variants: (\")?;\n let mut variants_iter = self.0.variants.iter();\n if let Some(variant) = variants_iter.next() {\n write!(f, \"{}\", variant.name)?;\n for variant in variants_iter {\n write!(f, \", {}\", variant.name)?;\n }\n }\n write!(f, \")\")?;\n // Only show the `#[repr(_)]` if it's not `Rust`.\n if let BaseRepr::C = self.0.repr.base {\n // TODO: `EnumRepr` should probably be optional, and contain the fields of `Repr`.\n // I think it is wrong to have both `Repr` and `EnumRepr` in the same type,\n // since that allows constructing impossible states.\n let repr_ty = match self.0.enum_repr {\n EnumRepr::RustNPO => unreachable!(\n \"null-pointer optimization is only valid for `repr(Rust)`\"\n ),\n EnumRepr::U8 => \"u8\",\n EnumRepr::U16 => \"u16\",\n EnumRepr::U32 => \"u32\",\n EnumRepr::U64 => \"u64\",\n EnumRepr::USize => \"usize\",\n EnumRepr::I8 => \"i8\",\n EnumRepr::I16 => \"i16\",\n EnumRepr::I32 => \"i32\",\n EnumRepr::I64 => \"i64\",\n EnumRepr::ISize => \"isize\",\n };\n // If there are multiple `repr` hints, display as a parenthesized list.\n write!(f, \", repr: (C, {repr_ty})\")?;\n } else if let BaseRepr::Transparent = self.0.repr.base {\n // Extra variant hints are not supported for `repr(transparent)`.\n write!(f, \", repr: transparent\")?;\n }\n // Verbatim compiler error:\n assert!(\n !self.0.repr.packed,\n \"attribute should be applied to a struct or union\"\n );\n write!(f, \"»\")\n }\n }\n let show_enum = __Display(enum_type);\n write!(f, \"User(Enum({show_enum}))\")?;\n }\n Type::User(UserType::Union(union_type)) => {\n struct __Display<'a>(&'a UnionType);\n impl<'a> core::fmt::Display for __Display<'a> {\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n write!(f, \"«\")?;\n write!(f, \"fields: (\")?;\n let mut fields_iter = self.0.fields.iter();\n if let Some(field) = fields_iter.next() {\n write!(f, \"{}\", field.name)?;\n for field in fields_iter {\n write!(f, \", {}\", field.name)?;\n }\n }\n write!(f, \")\")?;\n // Only show the `#[repr(_)]` if it's not `Rust` (unless it's `repr(packed)`).\n if let BaseRepr::C = self.0.repr.base {\n if self.0.repr.packed {\n // If there are multiple `repr` hints, display as a parenthesized list.\n write!(f, \", repr: (C, packed)\")?;\n } else {\n write!(f, \", repr: C\")?;\n }\n } else if let BaseRepr::Transparent = self.0.repr.base {\n // Nothing needs to change if `transparent_unions` is stabilized.\n // \n write!(f, \", repr: transparent\")?;\n // Verbatim compiler error:\n assert!(\n !self.0.repr.packed,\n \"transparent union cannot have other repr hints\"\n );\n } else if self.0.repr.packed {\n // Here `Rust` is displayed because a lint asks you to specify explicitly,\n // despite the fact that `repr(Rust)` is the default.\n write!(f, \", repr: (Rust, packed)\")?;\n }\n write!(f, \"»\")?;\n Ok(())\n }\n }\n let show_union = __Display(union_type);\n write!(f, \"User(Union({show_union}))\")?;\n }\n Type::User(UserType::Opaque) => {\n write!(f, \"User(Opaque)\")?;\n }\n Type::Pointer(PointerType::Reference(ptr_type)) => {\n let show_ref = if ptr_type.mutable { \"&mut \" } else { \"&\" };\n let target = ptr_type.target();\n write!(f, \"Pointer(Reference(«{show_ref}{target}»))\")?;\n }\n Type::Pointer(PointerType::Raw(ptr_type)) => {\n let show_raw = if ptr_type.mutable { \"*mut \" } else { \"*const \" };\n let target = ptr_type.target();\n write!(f, \"Pointer(Raw(«{show_raw}{target}»))\")?;\n }\n Type::Pointer(PointerType::Function(fn_ptr_def)) => {\n struct __Display<'a>(&'a FunctionPointerDef);\n impl core::fmt::Display for __Display<'_> {\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n write!(f, \"«\")?;\n write!(f, \"fn(\")?;\n let mut args_iter = self.0.parameters.iter().map(|f| f());\n if let Some(arg) = args_iter.next() {\n write!(f, \"{arg}\")?;\n for arg in args_iter {\n write!(f, \", {arg}\")?;\n }\n }\n let ret_ty = (self.0.return_type)();\n write!(f, \") -> {ret_ty}\")?;\n write!(f, \"»\")?;\n Ok(())\n }\n }\n let show_fn = __Display(fn_ptr_def);\n write!(f, \"Pointer(Function({show_fn}))\")?;\n }\n }\n Ok(())\n }\n}\n"], ["/facet/facet-reflect/src/peek/value.rs", "use core::{cmp::Ordering, marker::PhantomData};\nuse facet_core::{\n Def, Facet, GenericPtr, PointerType, PtrMut, Shape, StructKind, Type, TypeNameOpts, UserType,\n ValueVTable,\n};\n\nuse crate::{PeekSet, ReflectError, ScalarType};\n\nuse super::{\n ListLikeDef, PeekEnum, PeekList, PeekListLike, PeekMap, PeekOption, PeekPointer, PeekStruct,\n PeekTuple, tuple::TupleType,\n};\n\n/// A unique identifier for a peek value\n#[derive(Clone, Copy, PartialEq, Eq, Hash)]\npub struct ValueId {\n pub(crate) shape: &'static Shape,\n pub(crate) ptr: *const u8,\n}\n\nimpl ValueId {\n #[inline]\n pub(crate) fn new(shape: &'static Shape, ptr: *const u8) -> Self {\n Self { shape, ptr }\n }\n}\n\nimpl core::fmt::Display for ValueId {\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n write!(f, \"{}@{:p}\", self.shape, self.ptr)\n }\n}\n\nimpl core::fmt::Debug for ValueId {\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n core::fmt::Display::fmt(self, f)\n }\n}\n\n/// Lets you read from a value (implements read-only [`ValueVTable`] proxies)\n#[derive(Clone, Copy)]\npub struct Peek<'mem, 'facet> {\n /// Underlying data\n pub(crate) data: GenericPtr<'mem>,\n\n /// Shape of the value\n pub(crate) shape: &'static Shape,\n\n invariant: PhantomData &'facet ()>,\n}\n\nimpl<'mem, 'facet> Peek<'mem, 'facet> {\n /// Creates a new `PeekValue` instance for a value of type `T`.\n pub fn new + ?Sized>(t: &'mem T) -> Self {\n Self {\n data: GenericPtr::new(t),\n shape: T::SHAPE,\n invariant: PhantomData,\n }\n }\n\n /// Creates a new `PeekValue` instance without checking the type.\n ///\n /// # Safety\n ///\n /// This function is unsafe because it doesn't check if the provided data\n /// and shape are compatible. The caller must ensure that the data is valid\n /// for the given shape.\n pub unsafe fn unchecked_new(data: impl Into>, shape: &'static Shape) -> Self {\n Self {\n data: data.into(),\n shape,\n invariant: PhantomData,\n }\n }\n\n /// Returns the vtable\n #[inline(always)]\n pub fn vtable(&self) -> &'static ValueVTable {\n self.shape.vtable\n }\n\n /// Returns a unique identifier for this value, usable for cycle detection\n #[inline]\n pub fn id(&self) -> ValueId {\n ValueId::new(self.shape, self.data.as_byte_ptr())\n }\n\n /// Returns true if the two values are pointer-equal\n #[inline]\n pub fn ptr_eq(&self, other: &Peek<'_, '_>) -> bool {\n self.data.as_byte_ptr() == other.data.as_byte_ptr()\n }\n\n /// Returns true if this scalar is equal to the other scalar\n ///\n /// # Returns\n ///\n /// `false` if equality comparison is not supported for this scalar type\n #[inline]\n pub fn partial_eq(&self, other: &Peek<'_, '_>) -> Option {\n match (self.data, other.data) {\n (GenericPtr::Thin(a), GenericPtr::Thin(b)) => unsafe {\n (self.vtable().sized().unwrap().partial_eq)().map(|f| f(a, b))\n },\n (GenericPtr::Wide(a), GenericPtr::Wide(b)) => unsafe {\n (self.vtable().r#unsized().unwrap().partial_eq)().map(|f| f(a, b))\n },\n _ => None,\n }\n }\n\n /// Compares this scalar with another and returns their ordering\n ///\n /// # Returns\n ///\n /// `None` if comparison is not supported for this scalar type\n #[inline]\n pub fn partial_cmp(&self, other: &Peek<'_, '_>) -> Option> {\n match (self.data, other.data) {\n (GenericPtr::Thin(a), GenericPtr::Thin(b)) => unsafe {\n (self.vtable().sized().unwrap().partial_ord)().map(|f| f(a, b))\n },\n (GenericPtr::Wide(a), GenericPtr::Wide(b)) => unsafe {\n (self.vtable().r#unsized().unwrap().partial_ord)().map(|f| f(a, b))\n },\n _ => None,\n }\n }\n /// Hashes this scalar\n ///\n /// # Returns\n ///\n /// `Err` if hashing is not supported for this scalar type, `Ok` otherwise\n #[inline(always)]\n pub fn hash(&self, hasher: &mut H) -> Result<(), ReflectError> {\n match self.data {\n GenericPtr::Thin(ptr) => {\n if let Some(hash_fn) = (self.vtable().sized().unwrap().hash)() {\n let hasher_opaque = PtrMut::new(hasher);\n unsafe {\n hash_fn(ptr, hasher_opaque, |opaque, bytes| {\n opaque.as_mut::().write(bytes)\n })\n };\n return Ok(());\n }\n }\n GenericPtr::Wide(ptr) => {\n if let Some(hash_fn) = (self.vtable().r#unsized().unwrap().hash)() {\n let hasher_opaque = PtrMut::new(hasher);\n unsafe {\n hash_fn(ptr, hasher_opaque, |opaque, bytes| {\n opaque.as_mut::().write(bytes)\n })\n };\n return Ok(());\n }\n }\n }\n Err(ReflectError::OperationFailed {\n shape: self.shape(),\n operation: \"hash\",\n })\n }\n\n /// Returns the type name of this scalar\n ///\n /// # Arguments\n ///\n /// * `f` - A mutable reference to a `core::fmt::Formatter`\n /// * `opts` - The `TypeNameOpts` to use for formatting\n ///\n /// # Returns\n ///\n /// The result of the type name formatting\n #[inline(always)]\n pub fn type_name(\n &self,\n f: &mut core::fmt::Formatter<'_>,\n opts: TypeNameOpts,\n ) -> core::fmt::Result {\n (self.shape.vtable.type_name())(f, opts)\n }\n\n /// Returns the shape\n #[inline(always)]\n pub const fn shape(&self) -> &'static Shape {\n self.shape\n }\n\n /// Returns the data\n #[inline(always)]\n pub const fn data(&self) -> GenericPtr<'mem> {\n self.data\n }\n\n /// Get the scalar type if set.\n #[inline]\n pub fn scalar_type(&self) -> Option {\n ScalarType::try_from_shape(self.shape)\n }\n\n /// Read the value from memory into a Rust value.\n ///\n /// # Panics\n ///\n /// Panics if the shape doesn't match the type `T`.\n #[inline]\n pub fn get + ?Sized>(&self) -> Result<&T, ReflectError> {\n if self.shape != T::SHAPE {\n Err(ReflectError::WrongShape {\n expected: self.shape,\n actual: T::SHAPE,\n })\n } else {\n Ok(unsafe { self.data.get::() })\n }\n }\n\n /// Try to get the value as a string if it's a string type\n /// Returns None if the value is not a string or couldn't be extracted\n pub fn as_str(&self) -> Option<&'mem str> {\n let peek = self.innermost_peek();\n if let Some(ScalarType::Str) = peek.scalar_type() {\n unsafe { Some(peek.data.get::<&str>()) }\n } else if let Some(ScalarType::String) = peek.scalar_type() {\n unsafe { Some(peek.data.get::().as_str()) }\n } else if let Type::Pointer(PointerType::Reference(vpt)) = peek.shape.ty {\n let target_shape = (vpt.target)();\n if let Some(ScalarType::Str) = ScalarType::try_from_shape(target_shape) {\n unsafe { Some(peek.data.get::<&str>()) }\n } else {\n None\n }\n } else {\n None\n }\n }\n\n /// Try to get the value as a byte slice if it's a &[u8] type\n /// Returns None if the value is not a byte slice or couldn't be extracted\n #[inline]\n pub fn as_bytes(&self) -> Option<&'mem [u8]> {\n // Check if it's a direct &[u8]\n if let Type::Pointer(PointerType::Reference(vpt)) = self.shape.ty {\n let target_shape = (vpt.target)();\n if let Def::Slice(sd) = target_shape.def {\n if sd.t().is_type::() {\n unsafe { return Some(self.data.get::<&[u8]>()) }\n }\n }\n }\n None\n }\n\n /// Tries to identify this value as a struct\n #[inline]\n pub fn into_struct(self) -> Result, ReflectError> {\n if let Type::User(UserType::Struct(ty)) = self.shape.ty {\n Ok(PeekStruct { value: self, ty })\n } else {\n Err(ReflectError::WasNotA {\n expected: \"struct\",\n actual: self.shape,\n })\n }\n }\n\n /// Tries to identify this value as an enum\n #[inline]\n pub fn into_enum(self) -> Result, ReflectError> {\n if let Type::User(UserType::Enum(ty)) = self.shape.ty {\n Ok(PeekEnum { value: self, ty })\n } else {\n Err(ReflectError::WasNotA {\n expected: \"enum\",\n actual: self.shape,\n })\n }\n }\n\n /// Tries to identify this value as a map\n #[inline]\n pub fn into_map(self) -> Result, ReflectError> {\n if let Def::Map(def) = self.shape.def {\n Ok(PeekMap { value: self, def })\n } else {\n Err(ReflectError::WasNotA {\n expected: \"map\",\n actual: self.shape,\n })\n }\n }\n\n /// Tries to identify this value as a set\n #[inline]\n pub fn into_set(self) -> Result, ReflectError> {\n if let Def::Set(def) = self.shape.def {\n Ok(PeekSet { value: self, def })\n } else {\n Err(ReflectError::WasNotA {\n expected: \"set\",\n actual: self.shape,\n })\n }\n }\n\n /// Tries to identify this value as a list\n #[inline]\n pub fn into_list(self) -> Result, ReflectError> {\n if let Def::List(def) = self.shape.def {\n return Ok(PeekList { value: self, def });\n }\n\n Err(ReflectError::WasNotA {\n expected: \"list\",\n actual: self.shape,\n })\n }\n\n /// Tries to identify this value as a list, array or slice\n #[inline]\n pub fn into_list_like(self) -> Result, ReflectError> {\n match self.shape.def {\n Def::List(def) => Ok(PeekListLike::new(self, ListLikeDef::List(def))),\n Def::Array(def) => Ok(PeekListLike::new(self, ListLikeDef::Array(def))),\n Def::Slice(def) => {\n // When we have a bare slice shape with a wide pointer,\n // it means we have a reference to a slice (e.g., from Arc<[T]>::borrow_inner)\n if matches!(self.data, GenericPtr::Wide(_)) {\n Ok(PeekListLike::new(self, ListLikeDef::Slice(def)))\n } else {\n Err(ReflectError::WasNotA {\n expected: \"slice with wide pointer\",\n actual: self.shape,\n })\n }\n }\n _ => {\n // &[i32] is actually a _pointer_ to a slice.\n match self.shape.ty {\n Type::Pointer(ptr) => match ptr {\n PointerType::Reference(vpt) | PointerType::Raw(vpt) => {\n let target = (vpt.target)();\n match target.def {\n Def::Slice(def) => {\n return Ok(PeekListLike::new(self, ListLikeDef::Slice(def)));\n }\n _ => {\n // well it's not list-like then\n }\n }\n }\n PointerType::Function(_) => {\n // well that's not a list-like\n }\n },\n _ => {\n // well that's not a list-like either\n }\n }\n\n Err(ReflectError::WasNotA {\n expected: \"list, array or slice\",\n actual: self.shape,\n })\n }\n }\n }\n\n /// Tries to identify this value as a pointer\n #[inline]\n pub fn into_pointer(self) -> Result, ReflectError> {\n if let Def::Pointer(def) = self.shape.def {\n Ok(PeekPointer { value: self, def })\n } else {\n Err(ReflectError::WasNotA {\n expected: \"smart pointer\",\n actual: self.shape,\n })\n }\n }\n\n /// Tries to identify this value as an option\n #[inline]\n pub fn into_option(self) -> Result, ReflectError> {\n if let Def::Option(def) = self.shape.def {\n Ok(PeekOption { value: self, def })\n } else {\n Err(ReflectError::WasNotA {\n expected: \"option\",\n actual: self.shape,\n })\n }\n }\n\n /// Tries to identify this value as a tuple\n #[inline]\n pub fn into_tuple(self) -> Result, ReflectError> {\n if let Type::User(UserType::Struct(struct_type)) = self.shape.ty {\n if struct_type.kind == StructKind::Tuple {\n Ok(PeekTuple {\n value: self,\n ty: TupleType {\n fields: struct_type.fields,\n },\n })\n } else {\n Err(ReflectError::WasNotA {\n expected: \"tuple\",\n actual: self.shape,\n })\n }\n } else {\n Err(ReflectError::WasNotA {\n expected: \"tuple\",\n actual: self.shape,\n })\n }\n }\n\n /// Tries to return the innermost value — useful for serialization. For example, we serialize a `NonZero` the same\n /// as a `u8`. Similarly, we serialize a `Utf8PathBuf` the same as a `String.\n ///\n /// Returns a `Peek` to the innermost value, unwrapping transparent wrappers recursively.\n /// For example, this will peel through newtype wrappers or smart pointers that have an `inner`.\n pub fn innermost_peek(self) -> Self {\n let mut current_peek = self;\n while let (Some(try_borrow_inner_fn), Some(inner_shape)) = (\n current_peek\n .shape\n .vtable\n .sized()\n .and_then(|v| (v.try_borrow_inner)()),\n current_peek.shape.inner,\n ) {\n unsafe {\n let inner_data = try_borrow_inner_fn(current_peek.data.thin().unwrap()).unwrap_or_else(|e| {\n panic!(\"innermost_peek: try_borrow_inner returned an error! was trying to go from {} to {}. error: {e}\", current_peek.shape,\n inner_shape())\n });\n\n current_peek = Peek {\n data: inner_data.into(),\n shape: inner_shape(),\n invariant: PhantomData,\n };\n }\n }\n current_peek\n }\n}\n\nimpl<'mem, 'facet> core::fmt::Display for Peek<'mem, 'facet> {\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n match self.data {\n GenericPtr::Thin(ptr) => {\n if let Some(display_fn) = (self.vtable().sized().unwrap().display)() {\n return unsafe { display_fn(ptr, f) };\n }\n }\n GenericPtr::Wide(ptr) => {\n if let Some(display_fn) = (self.vtable().r#unsized().unwrap().display)() {\n return unsafe { display_fn(ptr, f) };\n }\n }\n }\n write!(f, \"⟨{}⟩\", self.shape)\n }\n}\n\nimpl<'mem, 'facet> core::fmt::Debug for Peek<'mem, 'facet> {\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n match self.data {\n GenericPtr::Thin(ptr) => {\n if let Some(debug_fn) = (self.vtable().sized().unwrap().debug)() {\n return unsafe { debug_fn(ptr, f) };\n }\n }\n GenericPtr::Wide(ptr) => {\n if let Some(debug_fn) = (self.vtable().r#unsized().unwrap().debug)() {\n return unsafe { debug_fn(ptr, f) };\n }\n }\n }\n write!(f, \"⟨{}⟩\", self.shape)\n }\n}\n\nimpl<'mem, 'facet> core::cmp::PartialEq for Peek<'mem, 'facet> {\n #[inline]\n fn eq(&self, other: &Self) -> bool {\n self.partial_eq(other).unwrap_or(false)\n }\n}\n\nimpl<'mem, 'facet> core::cmp::PartialOrd for Peek<'mem, 'facet> {\n #[inline]\n fn partial_cmp(&self, other: &Self) -> Option {\n self.partial_cmp(other).unwrap_or(None)\n }\n}\n\nimpl<'mem, 'facet> core::hash::Hash for Peek<'mem, 'facet> {\n fn hash(&self, hasher: &mut H) {\n self.hash(hasher)\n .expect(\"Hashing is not supported for this shape\");\n }\n}\n"], ["/facet/facet-core/src/types/ty/field.rs", "use crate::PtrConst;\n\nuse super::{DefaultInPlaceFn, Shape};\nuse bitflags::bitflags;\n\n/// Describes a field in a struct or tuple\n#[derive(Clone, Copy, Debug)]\n#[repr(C)]\npub struct Field {\n /// key for the struct field (for tuples and tuple-structs, this is the 0-based index)\n pub name: &'static str,\n\n /// shape of the inner type\n pub shape: &'static Shape,\n\n /// offset of the field in the struct (obtained through `core::mem::offset_of`)\n pub offset: usize,\n\n /// flags for the field (e.g. sensitive, etc.)\n pub flags: FieldFlags,\n\n /// arbitrary attributes set via the derive macro\n pub attributes: &'static [FieldAttribute],\n\n /// doc comments\n pub doc: &'static [&'static str],\n\n /// vtable for fields\n pub vtable: &'static FieldVTable,\n\n /// true if returned from `fields_for_serialize` and it was flattened - which\n /// means, if it's an enum, the outer variant shouldn't be written.\n pub flattened: bool,\n}\n\nimpl Field {\n /// Returns true if the field has the skip-serializing unconditionally flag or if it has the\n /// skip-serializing-if function in its vtable and it returns true on the given data.\n ///\n /// # Safety\n /// The peek should correspond to a value of the same type as this field\n pub unsafe fn should_skip_serializing(&self, ptr: PtrConst<'_>) -> bool {\n if self.flags.contains(FieldFlags::SKIP_SERIALIZING) {\n return true;\n }\n if let Some(skip_serializing_if) = self.vtable.skip_serializing_if {\n return unsafe { skip_serializing_if(ptr) };\n }\n false\n }\n}\n\n/// Vtable for field-specific operations\n#[derive(Clone, Copy, Debug)]\n#[repr(C)]\npub struct FieldVTable {\n /// Function to determine if serialization should be skipped for this field\n pub skip_serializing_if: Option,\n\n /// Function to get the default value for this field\n pub default_fn: Option,\n}\n\n/// A function that, if present, determines whether field should be included in the serialization\n/// step.\npub type SkipSerializingIfFn = for<'mem> unsafe fn(value: PtrConst<'mem>) -> bool;\n\nimpl Field {\n /// Returns the shape of the inner type\n pub const fn shape(&self) -> &'static Shape {\n self.shape\n }\n\n /// Returns a builder for Field\n pub const fn builder() -> FieldBuilder {\n FieldBuilder::new()\n }\n\n /// Checks if field is marked as sensitive through attributes or flags\n pub fn is_sensitive(&'static self) -> bool {\n self.flags.contains(FieldFlags::SENSITIVE)\n }\n}\n\n/// An attribute that can be set on a field\n#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]\n#[repr(C)]\npub enum FieldAttribute {\n /// Custom field attribute containing arbitrary text\n Arbitrary(&'static str),\n}\n\n/// Builder for FieldVTable\npub struct FieldVTableBuilder {\n skip_serializing_if: Option,\n default_fn: Option,\n}\n\nimpl FieldVTableBuilder {\n /// Creates a new FieldVTableBuilder\n #[allow(clippy::new_without_default)]\n pub const fn new() -> Self {\n Self {\n skip_serializing_if: None,\n default_fn: None,\n }\n }\n\n /// Sets the skip_serializing_if function for the FieldVTable\n pub const fn skip_serializing_if(mut self, func: SkipSerializingIfFn) -> Self {\n self.skip_serializing_if = Some(func);\n self\n }\n\n /// Sets the default_fn function for the FieldVTable\n pub const fn default_fn(mut self, func: DefaultInPlaceFn) -> Self {\n self.default_fn = Some(func);\n self\n }\n\n /// Builds the FieldVTable\n pub const fn build(self) -> FieldVTable {\n FieldVTable {\n skip_serializing_if: self.skip_serializing_if,\n default_fn: self.default_fn,\n }\n }\n}\n\nimpl FieldVTable {\n /// Returns a builder for FieldVTable\n pub const fn builder() -> FieldVTableBuilder {\n FieldVTableBuilder::new()\n }\n}\n\n/// Builder for Field\npub struct FieldBuilder {\n name: Option<&'static str>,\n shape: Option<&'static Shape>,\n offset: Option,\n flags: Option,\n attributes: &'static [FieldAttribute],\n doc: &'static [&'static str],\n vtable: &'static FieldVTable,\n}\n\nimpl FieldBuilder {\n /// Creates a new FieldBuilder\n #[allow(clippy::new_without_default)]\n pub const fn new() -> Self {\n Self {\n name: None,\n shape: None,\n offset: None,\n flags: None,\n attributes: &[],\n doc: &[],\n vtable: &const {\n FieldVTable {\n skip_serializing_if: None,\n default_fn: None,\n }\n },\n }\n }\n\n /// Sets the name for the Field\n pub const fn name(mut self, name: &'static str) -> Self {\n self.name = Some(name);\n self\n }\n\n /// Sets the shape for the Field\n pub const fn shape(mut self, shape: &'static Shape) -> Self {\n self.shape = Some(shape);\n self\n }\n\n /// Sets the offset for the Field\n pub const fn offset(mut self, offset: usize) -> Self {\n self.offset = Some(offset);\n self\n }\n\n /// Sets the flags for the Field\n pub const fn flags(mut self, flags: FieldFlags) -> Self {\n self.flags = Some(flags);\n self\n }\n\n /// Sets the attributes for the Field\n pub const fn attributes(mut self, attributes: &'static [FieldAttribute]) -> Self {\n self.attributes = attributes;\n self\n }\n\n /// Sets the doc comments for the Field\n pub const fn doc(mut self, doc: &'static [&'static str]) -> Self {\n self.doc = doc;\n self\n }\n\n /// Sets the vtable for the Field\n pub const fn vtable(mut self, vtable: &'static FieldVTable) -> Self {\n self.vtable = vtable;\n self\n }\n\n /// Builds the Field\n pub const fn build(self) -> Field {\n Field {\n name: self.name.unwrap(),\n shape: self.shape.unwrap(),\n offset: self.offset.unwrap(),\n flags: match self.flags {\n Some(flags) => flags,\n None => FieldFlags::EMPTY,\n },\n attributes: self.attributes,\n doc: self.doc,\n vtable: self.vtable,\n flattened: false,\n }\n }\n}\n\nbitflags! {\n /// Flags that can be applied to fields to modify their behavior\n #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]\n pub struct FieldFlags: u64 {\n /// An empty set of flags\n const EMPTY = 0;\n\n /// Flag indicating this field contains sensitive data that should not be displayed\n const SENSITIVE = 1 << 0;\n\n /// Flag indicating this field should be skipped during serialization\n const SKIP_SERIALIZING = 1 << 1;\n\n /// Flag indicating that this field should be flattened: if it's a struct, all its\n /// fields should be apparent on the parent structure, etc.\n const FLATTEN = 1 << 2;\n\n /// For KDL/XML formats, indicates that this field is a child, not an attribute\n const CHILD = 1 << 3;\n\n /// When deserializing, if this field is missing, use its default value. If\n /// `FieldVTable::default_fn` is set, use that.\n const DEFAULT = 1 << 4;\n }\n}\n\nimpl Default for FieldFlags {\n #[inline(always)]\n fn default() -> Self {\n Self::EMPTY\n }\n}\n\nimpl core::fmt::Display for FieldFlags {\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n if self.is_empty() {\n return write!(f, \"none\");\n }\n\n // Define a vector of flag entries: (flag, name)\n let flags = [\n (FieldFlags::SENSITIVE, \"sensitive\"),\n // Future flags can be easily added here:\n // (FieldFlags::SOME_FLAG, \"some_flag\"),\n // (FieldFlags::ANOTHER_FLAG, \"another_flag\"),\n ];\n\n // Write all active flags with proper separators\n let mut is_first = true;\n for (flag, name) in flags {\n if self.contains(flag) {\n if !is_first {\n write!(f, \", \")?;\n }\n is_first = false;\n write!(f, \"{name}\")?;\n }\n }\n\n Ok(())\n }\n}\n\n/// Errors encountered when calling `field_by_index` or `field_by_name`\n#[derive(Debug, Copy, Clone, PartialEq, Eq)]\npub enum FieldError {\n /// `field_by_name` was called on a struct, and there is no static field\n /// with the given key.\n NoSuchField,\n\n /// `field_by_index` was called on a fixed-size collection (like a tuple,\n /// a struct, or a fixed-size array) and the index was out of bounds.\n IndexOutOfBounds {\n /// the index we asked for\n index: usize,\n\n /// the upper bound of the index\n bound: usize,\n },\n\n /// `set` or `set_by_name` was called with an mismatched type\n TypeMismatch {\n /// the actual type of the field\n expected: &'static Shape,\n\n /// what someone tried to write into it / read from it\n actual: &'static Shape,\n },\n\n /// The type is unsized\n Unsized,\n}\n\nimpl core::error::Error for FieldError {}\n\nimpl core::fmt::Display for FieldError {\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n match self {\n FieldError::NoSuchField => write!(f, \"No such field\"),\n FieldError::IndexOutOfBounds { index, bound } => {\n write!(f, \"tried to access field {index} of {bound}\")\n }\n FieldError::TypeMismatch { expected, actual } => {\n write!(f, \"expected type {expected}, got {actual}\")\n }\n FieldError::Unsized => {\n write!(f, \"can't access field of !Sized type\")\n }\n }\n }\n}\n\nmacro_rules! field_in_type {\n ($container:ty, $field:tt) => {\n $crate::Field::builder()\n .name(stringify!($field))\n .shape($crate::shape_of(&|t: &Self| &t.$field))\n .offset(::core::mem::offset_of!(Self, $field))\n .flags($crate::FieldFlags::EMPTY)\n .build()\n };\n}\n\npub(crate) use field_in_type;\n"], ["/facet/facet-reflect/src/peek/enum_.rs", "use facet_core::{EnumRepr, EnumType, Shape, UserType, Variant};\n\nuse crate::{Peek, trace};\n\nuse super::{FieldIter, HasFields};\n\n/// Lets you read from an enum (implements read-only enum operations)\n#[derive(Clone, Copy)]\npub struct PeekEnum<'mem, 'facet> {\n /// The internal data storage for the enum\n ///\n /// Note that this stores both the discriminant and the variant data\n /// (if any), and the layout depends on the enum representation.\n pub(crate) value: Peek<'mem, 'facet>,\n\n /// The definition of the enum.\n pub(crate) ty: EnumType,\n}\n\nimpl core::fmt::Debug for PeekEnum<'_, '_> {\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n write!(f, \"{:?}\", self.value)\n }\n}\n\n/// Returns the enum definition if the shape represents an enum, None otherwise\n#[inline]\npub fn peek_enum(shape: &'static Shape) -> Option {\n match shape.ty {\n facet_core::Type::User(UserType::Enum(enum_ty)) => Some(enum_ty),\n _ => None,\n }\n}\n\n/// Returns the enum representation if the shape represents an enum, None otherwise\n#[inline]\npub fn peek_enum_repr(shape: &'static Shape) -> Option {\n peek_enum(shape).map(|enum_def| enum_def.enum_repr)\n}\n\n/// Returns the enum variants if the shape represents an enum, None otherwise\n#[inline]\npub fn peek_enum_variants(shape: &'static Shape) -> Option<&'static [Variant]> {\n peek_enum(shape).map(|enum_def| enum_def.variants)\n}\n\nimpl<'mem, 'facet> core::ops::Deref for PeekEnum<'mem, 'facet> {\n type Target = Peek<'mem, 'facet>;\n\n #[inline(always)]\n fn deref(&self) -> &Self::Target {\n &self.value\n }\n}\n\nimpl<'mem, 'facet> PeekEnum<'mem, 'facet> {\n /// Returns the enum definition\n #[inline(always)]\n pub fn ty(self) -> EnumType {\n self.ty\n }\n\n /// Returns the enum representation\n #[inline(always)]\n pub fn enum_repr(self) -> EnumRepr {\n self.ty.enum_repr\n }\n\n /// Returns the enum variants\n #[inline(always)]\n pub fn variants(self) -> &'static [Variant] {\n self.ty.variants\n }\n\n /// Returns the number of variants in this enum\n #[inline(always)]\n pub fn variant_count(self) -> usize {\n self.ty.variants.len()\n }\n\n /// Returns the variant name at the given index\n #[inline(always)]\n pub fn variant_name(self, index: usize) -> Option<&'static str> {\n self.ty.variants.get(index).map(|variant| variant.name)\n }\n\n /// Returns the discriminant value for the current enum value\n #[inline]\n pub fn discriminant(self) -> i64 {\n // Read the discriminant based on the enum representation\n unsafe {\n let data = self\n .value\n .data()\n .thin()\n .expect(\"discriminant must be Sized\");\n match self.ty.enum_repr {\n EnumRepr::U8 => data.read::() as i64,\n EnumRepr::U16 => data.read::() as i64,\n EnumRepr::U32 => data.read::() as i64,\n EnumRepr::U64 => data.read::() as i64,\n EnumRepr::USize => data.read::() as i64,\n EnumRepr::I8 => data.read::() as i64,\n EnumRepr::I16 => data.read::() as i64,\n EnumRepr::I32 => data.read::() as i64,\n EnumRepr::I64 => data.read::(),\n EnumRepr::ISize => data.read::() as i64,\n _ => {\n // Default to a reasonable size for other representations that might be added in the future\n data.read::() as i64\n }\n }\n }\n }\n\n /// Returns the variant index for this enum value\n #[inline]\n pub fn variant_index(self) -> Result {\n if self.ty.enum_repr == EnumRepr::RustNPO {\n // Check if enum is all zeros\n let layout = self\n .value\n .shape\n .layout\n .sized_layout()\n .expect(\"Unsized enums in NPO repr are unsupported\");\n\n let data = self.value.data().thin().unwrap();\n let slice = unsafe { core::slice::from_raw_parts(data.as_byte_ptr(), layout.size()) };\n let all_zero = slice.iter().all(|v| *v == 0);\n\n trace!(\n \"PeekEnum::variant_index (RustNPO): layout size = {}, all_zero = {} (slice is actually {:?})\",\n layout.size(),\n all_zero,\n slice\n );\n\n Ok(self\n .ty\n .variants\n .iter()\n .enumerate()\n .position(|#[allow(unused)] (variant_idx, variant)| {\n // Find the maximum end bound\n let mut max_offset = 0;\n\n for field in variant.data.fields {\n let offset = field.offset\n + field\n .shape\n .layout\n .sized_layout()\n .map(|v| v.size())\n .unwrap_or(0);\n max_offset = core::cmp::max(max_offset, offset);\n }\n\n trace!(\n \" variant[{}] = '{}', max_offset = {}\",\n variant_idx, variant.name, max_offset\n );\n\n // If we are all zero, then find the enum variant that has no size,\n // otherwise, the one with size.\n if all_zero {\n max_offset == 0\n } else {\n max_offset != 0\n }\n })\n .expect(\"No variant found with matching discriminant\"))\n } else {\n let discriminant = self.discriminant();\n\n trace!(\n \"PeekEnum::variant_index: discriminant = {} (repr = {:?})\",\n discriminant, self.ty.enum_repr\n );\n\n // Find the variant with matching discriminant using position method\n Ok(self\n .ty\n .variants\n .iter()\n .enumerate()\n .position(|#[allow(unused)] (variant_idx, variant)| {\n variant.discriminant == Some(discriminant)\n })\n .expect(\"No variant found with matching discriminant\"))\n }\n }\n\n /// Returns the active variant\n #[inline]\n pub fn active_variant(self) -> Result<&'static Variant, VariantError> {\n let index = self.variant_index()?;\n Ok(&self.ty.variants[index])\n }\n\n /// Returns the name of the active variant for this enum value\n #[inline]\n pub fn variant_name_active(self) -> Result<&'static str, VariantError> {\n Ok(self.active_variant()?.name)\n }\n\n // variant_data has been removed to reduce unsafe code exposure\n\n /// Returns a PeekValue handle to a field of a tuple or struct variant by index\n pub fn field(self, index: usize) -> Result>, VariantError> {\n let variant = self.active_variant()?;\n let fields = &variant.data.fields;\n\n if index >= fields.len() {\n return Ok(None);\n }\n\n let field = &fields[index];\n let field_data = unsafe {\n self.value\n .data()\n .thin()\n .ok_or(VariantError::Unsized)?\n .field(field.offset)\n };\n Ok(Some(unsafe {\n Peek::unchecked_new(field_data, field.shape())\n }))\n }\n\n /// Returns the index of a field in the active variant by name\n pub fn field_index(self, field_name: &str) -> Result, VariantError> {\n let variant = self.active_variant()?;\n Ok(variant\n .data\n .fields\n .iter()\n .position(|f| f.name == field_name))\n }\n\n /// Returns a PeekValue handle to a field of a tuple or struct variant by name\n pub fn field_by_name(\n self,\n field_name: &str,\n ) -> Result>, VariantError> {\n let index_opt = self.field_index(field_name)?;\n match index_opt {\n Some(index) => self.field(index),\n None => Ok(None),\n }\n }\n}\n\nimpl<'mem, 'facet> HasFields<'mem, 'facet> for PeekEnum<'mem, 'facet> {\n #[inline]\n fn fields(&self) -> FieldIter<'mem, 'facet> {\n FieldIter::new_enum(*self)\n }\n}\n\n/// Error that can occur when trying to determine variant information\n#[derive(Clone, Copy, PartialEq, Eq)]\npub enum VariantError {\n /// Error indicating that enum internals are opaque and cannot be determined\n OpaqueInternals,\n\n /// Error indicating the enum value is unsized and cannot be accessed by field offset.\n Unsized,\n}\n\nimpl core::fmt::Display for VariantError {\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n match self {\n VariantError::OpaqueInternals => {\n write!(f, \"enum layout is opaque, cannot determine variant\")\n }\n VariantError::Unsized => {\n write!(\n f,\n \"enum value is unsized and cannot be accessed by field offset\"\n )\n }\n }\n }\n}\n\nimpl core::fmt::Debug for VariantError {\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n match self {\n VariantError::OpaqueInternals => {\n write!(\n f,\n \"VariantError::OpaqueInternals: enum layout is opaque, cannot determine variant\"\n )\n }\n VariantError::Unsized => {\n write!(\n f,\n \"VariantError::Unsized: enum value is unsized and cannot be accessed by field offset\"\n )\n }\n }\n }\n}\n\nimpl core::error::Error for VariantError {}\n"], ["/facet/facet-core/src/impls_core/fn_ptr.rs", "use core::{fmt, hash::Hash, ptr::fn_addr_eq};\n\nuse crate::{\n Facet, FunctionAbi, FunctionPointerDef, HasherProxy, MarkerTraits, PointerType, Shape, Type,\n TypeNameOpts, TypeParam, ValueVTable,\n};\n\n#[inline(always)]\npub fn write_type_name_list(\n f: &mut fmt::Formatter<'_>,\n opts: TypeNameOpts,\n abi: FunctionAbi,\n params: &'static [&'static Shape],\n ret_type: &'static Shape,\n) -> fmt::Result {\n if abi != FunctionAbi::Rust {\n f.pad(\"extern \\\"\")?;\n if let Some(abi) = abi.as_abi_str() {\n f.pad(abi)?;\n }\n f.pad(\"\\\" \")?;\n }\n f.pad(\"fn\")?;\n f.pad(\"(\")?;\n if let Some(opts) = opts.for_children() {\n for (index, shape) in params.iter().enumerate() {\n if index > 0 {\n f.pad(\", \")?;\n }\n shape.write_type_name(f, opts)?;\n }\n } else {\n write!(f, \"⋯\")?;\n }\n f.pad(\") -> \")?;\n ret_type.write_type_name(f, opts)?;\n Ok(())\n}\n\nmacro_rules! impl_facet_for_fn_ptr {\n // Used to implement the next bigger `fn` type, by taking the next typename out of `remaining`,\n // if it exists.\n {\n continue from $(extern $extern:literal)? fn($($args:ident),*) -> R with $abi:expr,\n remaining ()\n } => {};\n {\n continue from $(extern $extern:literal)? fn($($args:ident),*) -> R with $abi:expr,\n remaining ($next:ident $(, $remaining:ident)*)\n } => {\n impl_facet_for_fn_ptr! {\n impl $(extern $extern)? fn($($args,)* $next) -> R with $abi,\n remaining ($($remaining),*)\n }\n };\n // Actually generate the trait implementation, and keep the remaining possible arguments around\n {\n impl $(extern $extern:literal)? fn($($args:ident),*) -> R with $abi:expr,\n remaining ($($remaining:ident),*)\n } => {\n unsafe impl<'a, $($args,)* R> Facet<'a> for $(extern $extern)? fn($($args),*) -> R\n where\n $($args: Facet<'a>,)*\n R: Facet<'a>,\n {\n const VTABLE: &'static ValueVTable = &const {\n ValueVTable::builder::()\n .type_name(|f, opts| {\n write_type_name_list(f, opts, $abi, &[$($args::SHAPE),*], R::SHAPE)\n })\n .debug(|| Some(|data, f| fmt::Debug::fmt(data, f)))\n .clone_into(|| Some(|src, dst| unsafe { dst.put(src.clone()) }))\n .marker_traits(||\n MarkerTraits::EQ\n .union(MarkerTraits::SEND)\n .union(MarkerTraits::SYNC)\n .union(MarkerTraits::COPY)\n .union(MarkerTraits::UNPIN)\n .union(MarkerTraits::UNWIND_SAFE)\n .union(MarkerTraits::REF_UNWIND_SAFE)\n )\n .partial_eq(|| Some(|&left, &right| {\n fn_addr_eq(left, right)\n }))\n .partial_ord(|| Some(|left, right| {\n #[allow(unpredictable_function_pointer_comparisons)]\n left.partial_cmp(right)\n }))\n .ord(|| Some(|left, right| {\n #[allow(unpredictable_function_pointer_comparisons)]\n left.cmp(right)\n }))\n .hash(|| Some(|value, hasher_this, hasher_write_fn| {\n value.hash(&mut unsafe {\n HasherProxy::new(hasher_this, hasher_write_fn)\n })\n }))\n .build()\n };\n\n const SHAPE: &'static Shape = &const {\n Shape::builder_for_sized::()\n .type_identifier(\"fn\")\n .type_params(&[\n $(TypeParam { name: stringify!($args), shape: || $args::SHAPE },)*\n ])\n .ty(Type::Pointer(PointerType::Function(({\n FunctionPointerDef::builder()\n .parameter_types(&const { [$(|| $args::SHAPE),*] })\n .return_type(|| R::SHAPE)\n .abi($abi)\n .build()\n }))))\n .build()\n };\n }\n impl_facet_for_fn_ptr! {\n continue from $(extern $extern)? fn($($args),*) -> R with $abi,\n remaining ($($remaining),*)\n }\n };\n // The entry point into this macro, all smaller `fn` types get implemented as well.\n {$(extern $extern:literal)? fn($($args:ident),*) -> R with $abi:expr} => {\n impl_facet_for_fn_ptr! {\n impl $(extern $extern)? fn() -> R with $abi,\n remaining ($($args),*)\n }\n };\n}\n\nimpl_facet_for_fn_ptr! { fn(T0, T1, T2, T3, T4, T5) -> R with FunctionAbi::Rust }\nimpl_facet_for_fn_ptr! { extern \"C\" fn(T0, T1, T2, T3, T4, T5) -> R with FunctionAbi::C }\n"], ["/facet/facet-macros-parse/src/function/mod.rs", "/// Parsing the `fn_shape!`` macro input\npub mod fn_shape_input;\n/// Parsing the function body\npub mod func_body;\n/// Parsing function parameters\npub mod func_params;\n/// Parsing the function signature\npub mod func_sig;\n/// Parsing generic functions\npub mod generics;\n/// Parsing the return type\npub mod ret_type;\n/// Parsing type parameters\npub mod type_params;\n\npub use fn_shape_input::*;\npub use func_body::*;\npub use func_params::*;\npub use func_sig::*;\npub use generics::*;\npub use ret_type::*;\npub use type_params::*;\n"], ["/facet/facet-reflect/src/peek/list_like.rs", "use facet_core::{GenericPtr, IterVTable, PtrConst, PtrMut, Shape, ShapeLayout};\n\nuse super::Peek;\nuse core::{fmt::Debug, marker::PhantomData};\n\n/// Fields for types which act like lists\n#[derive(Clone, Copy)]\npub enum ListLikeDef {\n /// Ordered list of heterogenous values, variable size\n ///\n /// e.g. `Vec`\n List(facet_core::ListDef),\n\n /// Fixed-size array of heterogenous values\n ///\n /// e.g. `[T; 32]`\n Array(facet_core::ArrayDef),\n\n /// Slice — a reference to a contiguous sequence of elements\n ///\n /// e.g. `&[T]`\n Slice(facet_core::SliceDef),\n}\n\nimpl ListLikeDef {\n /// Returns the shape of the items in the list\n #[inline]\n pub fn t(&self) -> &'static Shape {\n match self {\n ListLikeDef::List(v) => v.t(),\n ListLikeDef::Array(v) => v.t(),\n ListLikeDef::Slice(v) => v.t(),\n }\n }\n}\n\n/// Iterator over a `PeekListLike`\npub struct PeekListLikeIter<'mem, 'facet> {\n state: PeekListLikeIterState<'mem>,\n index: usize,\n len: usize,\n def: ListLikeDef,\n _list: PhantomData>,\n}\n\nimpl<'mem, 'facet> Iterator for PeekListLikeIter<'mem, 'facet> {\n type Item = Peek<'mem, 'facet>;\n\n #[inline]\n fn next(&mut self) -> Option {\n let item_ptr = match self.state {\n PeekListLikeIterState::Ptr { data, stride } => {\n if self.index >= self.len {\n return None;\n }\n\n unsafe { data.field(stride * self.index) }\n }\n PeekListLikeIterState::Iter { iter, vtable } => unsafe { (vtable.next)(iter)? },\n };\n\n // Update the index. This is used pointer iteration and for\n // calculating the iterator's size\n self.index += 1;\n\n Some(unsafe { Peek::unchecked_new(item_ptr, self.def.t()) })\n }\n\n #[inline]\n fn size_hint(&self) -> (usize, Option) {\n let remaining = self.len.saturating_sub(self.index);\n (remaining, Some(remaining))\n }\n}\n\nimpl<'mem, 'facet> ExactSizeIterator for PeekListLikeIter<'mem, 'facet> {}\n\nimpl<'mem, 'facet> IntoIterator for &'mem PeekListLike<'mem, 'facet> {\n type Item = Peek<'mem, 'facet>;\n type IntoIter = PeekListLikeIter<'mem, 'facet>;\n\n #[inline]\n fn into_iter(self) -> Self::IntoIter {\n self.iter()\n }\n}\n\nenum PeekListLikeIterState<'mem> {\n Ptr {\n data: PtrConst<'mem>,\n stride: usize,\n },\n Iter {\n iter: PtrMut<'mem>,\n vtable: IterVTable>,\n },\n}\n\nimpl Drop for PeekListLikeIterState<'_> {\n #[inline]\n fn drop(&mut self) {\n match self {\n Self::Iter { iter, vtable } => unsafe { (vtable.dealloc)(*iter) },\n Self::Ptr { .. } => {\n // Nothing to do\n }\n }\n }\n}\n\n/// Lets you read from a list, array or slice\n#[derive(Clone, Copy)]\npub struct PeekListLike<'mem, 'facet> {\n pub(crate) value: Peek<'mem, 'facet>,\n pub(crate) def: ListLikeDef,\n len: usize,\n}\n\nimpl<'mem, 'facet> Debug for PeekListLike<'mem, 'facet> {\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n f.debug_struct(\"PeekListLike\").finish_non_exhaustive()\n }\n}\n\nimpl<'mem, 'facet> PeekListLike<'mem, 'facet> {\n /// Creates a new peek list\n #[inline]\n pub fn new(value: Peek<'mem, 'facet>, def: ListLikeDef) -> Self {\n let len = match def {\n ListLikeDef::List(v) => unsafe { (v.vtable.len)(value.data().thin().unwrap()) },\n ListLikeDef::Slice(v) => {\n // Check if we have a bare slice with wide pointer (e.g., from Arc<[T]>::borrow_inner)\n // or a reference to a slice with thin pointer\n match value.data() {\n GenericPtr::Wide(wide_ptr) => {\n // For bare slices, we need to extract the length from the wide pointer\n // We can safely cast to any slice type to get the length since it's metadata\n let slice_as_units = unsafe { wide_ptr.get::<[()]>() };\n slice_as_units.len()\n }\n GenericPtr::Thin(thin_ptr) => {\n // For references to slices, use the vtable\n unsafe { (v.vtable.len)(thin_ptr) }\n }\n }\n }\n ListLikeDef::Array(v) => v.n,\n };\n Self { value, def, len }\n }\n\n /// Get the length of the list\n #[inline]\n pub fn len(&self) -> usize {\n self.len\n }\n\n /// Returns true if the list is empty\n #[inline]\n pub fn is_empty(&self) -> bool {\n self.len() == 0\n }\n\n /// Get an item from the list at the specified index\n ///\n /// Return `None` if the index is out of bounds\n pub fn get(&self, index: usize) -> Option> {\n // Special handling for bare slices with wide pointers\n if let (ListLikeDef::Slice(_), GenericPtr::Wide(wide_ptr)) = (&self.def, self.value.data())\n {\n if index >= self.len() {\n return None;\n }\n\n // Get the element type layout\n let elem_layout = match self.def.t().layout {\n ShapeLayout::Sized(layout) => layout,\n ShapeLayout::Unsized => return None,\n };\n\n // Get the data pointer directly from the wide pointer\n let data_ptr = wide_ptr.as_byte_ptr();\n\n // Calculate the element pointer\n let elem_ptr = unsafe { data_ptr.add(index * elem_layout.size()) };\n\n // Create a Peek for the element\n return Some(unsafe {\n Peek::unchecked_new(GenericPtr::Thin(PtrConst::new(elem_ptr)), self.def.t())\n });\n }\n\n let as_ptr = match self.def {\n ListLikeDef::List(def) => {\n // Call get from the list's vtable directly if available\n let item = unsafe { (def.vtable.get)(self.value.data().thin().unwrap(), index)? };\n return Some(unsafe { Peek::unchecked_new(item, self.def.t()) });\n }\n ListLikeDef::Array(def) => def.vtable.as_ptr,\n ListLikeDef::Slice(def) => def.vtable.as_ptr,\n };\n\n if index >= self.len() {\n return None;\n }\n\n // Get the base pointer of the array\n let base_ptr = unsafe { as_ptr(self.value.data().thin().unwrap()) };\n\n // Get the layout of the element type\n let elem_layout = match self.def.t().layout {\n ShapeLayout::Sized(layout) => layout,\n ShapeLayout::Unsized => return None, // Cannot handle unsized elements\n };\n\n // Calculate the offset based on element size\n let offset = index * elem_layout.size();\n\n // Apply the offset to get the item's pointer\n let item_ptr = unsafe { base_ptr.field(offset) };\n\n Some(unsafe { Peek::unchecked_new(item_ptr, self.def.t()) })\n }\n\n /// Returns an iterator over the list\n pub fn iter(self) -> PeekListLikeIter<'mem, 'facet> {\n let (as_ptr_fn, iter_vtable) = match self.def {\n ListLikeDef::List(def) => (def.vtable.as_ptr, Some(def.vtable.iter_vtable)),\n ListLikeDef::Array(def) => (Some(def.vtable.as_ptr), None),\n ListLikeDef::Slice(def) => (Some(def.vtable.as_ptr), None),\n };\n\n let state = match (as_ptr_fn, iter_vtable) {\n (Some(as_ptr_fn), _) => {\n // Special handling for bare slices with wide pointers\n let data = if let (ListLikeDef::Slice(_), GenericPtr::Wide(wide_ptr)) =\n (&self.def, self.value.data())\n {\n // Get the data pointer directly from the wide pointer\n PtrConst::new(wide_ptr.as_byte_ptr())\n } else {\n unsafe { as_ptr_fn(self.value.data().thin().unwrap()) }\n };\n\n let layout = self\n .def\n .t()\n .layout\n .sized_layout()\n .expect(\"can only iterate over sized list elements\");\n let stride = layout.size();\n\n PeekListLikeIterState::Ptr { data, stride }\n }\n (None, Some(vtable)) => {\n let iter =\n unsafe { (vtable.init_with_value.unwrap())(self.value.data().thin().unwrap()) };\n PeekListLikeIterState::Iter { iter, vtable }\n }\n (None, None) => unreachable!(),\n };\n\n PeekListLikeIter {\n state,\n index: 0,\n len: self.len(),\n def: self.def(),\n _list: PhantomData,\n }\n }\n\n /// Def getter\n #[inline]\n pub fn def(&self) -> ListLikeDef {\n self.def\n }\n}\n"], ["/facet/facet/src/sample_generated_code.rs", "//! This defines a few types showcasing various features of the Facet derive macro.\n#![allow(warnings)]\n#[prelude_import]\nuse std::prelude::rust_2024::*;\nextern crate std;\n\nuse crate::Facet;\n\n/// A struct demonstrating various field types and attributes.\npub struct KitchenSinkStruct {\n /// A basic string field.\n pub basic_field: String,\n /// A field marked as sensitive.\n pub sensitive_field: u64,\n /// A tuple field.\n pub tuple_field: (i32, bool),\n /// An array field.\n pub array_field: [u8; 4],\n /// A static slice field.\n pub slice_field: &'static [u8],\n /// A vector field.\n pub vec_field: Vec,\n /// A field containing another struct that derives Facet.\n pub nested_struct_field: Point,\n}\nstatic KITCHEN_SINK_STRUCT_SHAPE: &'static crate::Shape =\n ::SHAPE;\n#[automatically_derived]\nunsafe impl<'__facet> crate::Facet<'__facet> for KitchenSinkStruct {\n const VTABLE: &'static crate::ValueVTable = &const {\n let mut vtable = const {\n ::facet_core::ValueVTable::builder::()\n .type_name(|f, _opts| ::core::fmt::Write::write_str(f, \"KitchenSinkStruct\"))\n .display(|| {\n if {\n /// Fallback trait with `False` for `IMPLS` if the type does not\n /// implement the given trait.\n trait DoesNotImpl {\n const IMPLS: bool = false;\n }\n impl DoesNotImpl for T {}\n /// Concrete type with `True` for `IMPLS` if the type implements the\n /// given trait. Otherwise, it falls back to `DoesNotImpl`.\n struct Wrapper(::core::marker::PhantomData);\n #[allow(dead_code)]\n impl Wrapper {\n const IMPLS: bool = true;\n }\n >::IMPLS\n } {\n Some(|data, f| {\n use ::facet_core::spez::*;\n (&&Spez(data)).spez_display(f)\n })\n } else {\n None\n }\n })\n .debug(|| {\n if {\n /// Fallback trait with `False` for `IMPLS` if the type does not\n /// implement the given trait.\n trait DoesNotImpl {\n const IMPLS: bool = false;\n }\n impl DoesNotImpl for T {}\n /// Concrete type with `True` for `IMPLS` if the type implements the\n /// given trait. Otherwise, it falls back to `DoesNotImpl`.\n struct Wrapper(::core::marker::PhantomData);\n #[allow(dead_code)]\n impl Wrapper {\n const IMPLS: bool = true;\n }\n >::IMPLS\n } {\n Some(|data, f| {\n use ::facet_core::spez::*;\n (&&Spez(data)).spez_debug(f)\n })\n } else {\n None\n }\n })\n .default_in_place(|| {\n if {\n /// Fallback trait with `False` for `IMPLS` if the type does not\n /// implement the given trait.\n trait DoesNotImpl {\n const IMPLS: bool = false;\n }\n impl DoesNotImpl for T {}\n /// Concrete type with `True` for `IMPLS` if the type implements the\n /// given trait. Otherwise, it falls back to `DoesNotImpl`.\n struct Wrapper(::core::marker::PhantomData);\n #[allow(dead_code)]\n impl Wrapper {\n const IMPLS: bool = true;\n }\n >::IMPLS\n } {\n Some(|target| unsafe {\n use ::facet_core::spez::*;\n (&&SpezEmpty::::SPEZ)\n .spez_default_in_place(target.into())\n .as_mut()\n })\n } else {\n None\n }\n })\n .clone_into(|| {\n if {\n /// Fallback trait with `False` for `IMPLS` if the type does not\n /// implement the given trait.\n trait DoesNotImpl {\n const IMPLS: bool = false;\n }\n impl DoesNotImpl for T {}\n /// Concrete type with `True` for `IMPLS` if the type implements the\n /// given trait. Otherwise, it falls back to `DoesNotImpl`.\n struct Wrapper(::core::marker::PhantomData);\n #[allow(dead_code)]\n impl Wrapper {\n const IMPLS: bool = true;\n }\n >::IMPLS\n } {\n Some(|src, dst| unsafe {\n use ::facet_core::spez::*;\n (&&Spez(src)).spez_clone_into(dst.into()).as_mut()\n })\n } else {\n None\n }\n })\n .marker_traits(|| {\n let mut traits = ::facet_core::MarkerTraits::empty();\n if {\n /// Fallback trait with `False` for `IMPLS` if the type does not\n /// implement the given trait.\n trait DoesNotImpl {\n const IMPLS: bool = false;\n }\n impl DoesNotImpl for T {}\n /// Concrete type with `True` for `IMPLS` if the type implements the\n /// given trait. Otherwise, it falls back to `DoesNotImpl`.\n struct Wrapper(::core::marker::PhantomData);\n #[allow(dead_code)]\n impl Wrapper {\n const IMPLS: bool = true;\n }\n >::IMPLS\n } {\n traits = traits.union(::facet_core::MarkerTraits::EQ);\n }\n if {\n /// Fallback trait with `False` for `IMPLS` if the type does not\n /// implement the given trait.\n trait DoesNotImpl {\n const IMPLS: bool = false;\n }\n impl DoesNotImpl for T {}\n /// Concrete type with `True` for `IMPLS` if the type implements the\n /// given trait. Otherwise, it falls back to `DoesNotImpl`.\n struct Wrapper(::core::marker::PhantomData);\n #[allow(dead_code)]\n impl Wrapper {\n const IMPLS: bool = true;\n }\n >::IMPLS\n } {\n traits = traits.union(::facet_core::MarkerTraits::SEND);\n }\n if {\n /// Fallback trait with `False` for `IMPLS` if the type does not\n /// implement the given trait.\n trait DoesNotImpl {\n const IMPLS: bool = false;\n }\n impl DoesNotImpl for T {}\n /// Concrete type with `True` for `IMPLS` if the type implements the\n /// given trait. Otherwise, it falls back to `DoesNotImpl`.\n struct Wrapper(::core::marker::PhantomData);\n #[allow(dead_code)]\n impl Wrapper {\n const IMPLS: bool = true;\n }\n >::IMPLS\n } {\n traits = traits.union(::facet_core::MarkerTraits::SYNC);\n }\n if {\n /// Fallback trait with `False` for `IMPLS` if the type does not\n /// implement the given trait.\n trait DoesNotImpl {\n const IMPLS: bool = false;\n }\n impl DoesNotImpl for T {}\n /// Concrete type with `True` for `IMPLS` if the type implements the\n /// given trait. Otherwise, it falls back to `DoesNotImpl`.\n struct Wrapper(::core::marker::PhantomData);\n #[allow(dead_code)]\n impl Wrapper {\n const IMPLS: bool = true;\n }\n >::IMPLS\n } {\n traits = traits.union(::facet_core::MarkerTraits::COPY);\n }\n if {\n /// Fallback trait with `False` for `IMPLS` if the type does not\n /// implement the given trait.\n trait DoesNotImpl {\n const IMPLS: bool = false;\n }\n impl DoesNotImpl for T {}\n /// Concrete type with `True` for `IMPLS` if the type implements the\n /// given trait. Otherwise, it falls back to `DoesNotImpl`.\n struct Wrapper(::core::marker::PhantomData);\n #[allow(dead_code)]\n impl Wrapper {\n const IMPLS: bool = true;\n }\n >::IMPLS\n } {\n traits = traits.union(::facet_core::MarkerTraits::UNPIN);\n }\n if {\n /// Fallback trait with `False` for `IMPLS` if the type does not\n /// implement the given trait.\n trait DoesNotImpl {\n const IMPLS: bool = false;\n }\n impl DoesNotImpl for T {}\n /// Concrete type with `True` for `IMPLS` if the type implements the\n /// given trait. Otherwise, it falls back to `DoesNotImpl`.\n struct Wrapper(::core::marker::PhantomData);\n #[allow(dead_code)]\n impl Wrapper {\n const IMPLS: bool = true;\n }\n >::IMPLS\n } {\n traits = traits.union(::facet_core::MarkerTraits::UNWIND_SAFE);\n }\n if {\n /// Fallback trait with `False` for `IMPLS` if the type does not\n /// implement the given trait.\n trait DoesNotImpl {\n const IMPLS: bool = false;\n }\n impl DoesNotImpl for T {}\n /// Concrete type with `True` for `IMPLS` if the type implements the\n /// given trait. Otherwise, it falls back to `DoesNotImpl`.\n struct Wrapper(::core::marker::PhantomData);\n #[allow(dead_code)]\n impl Wrapper {\n const IMPLS: bool = true;\n }\n >::IMPLS\n } {\n traits = traits.union(::facet_core::MarkerTraits::REF_UNWIND_SAFE);\n }\n traits\n })\n .partial_eq(|| {\n if {\n /// Fallback trait with `False` for `IMPLS` if the type does not\n /// implement the given trait.\n trait DoesNotImpl {\n const IMPLS: bool = false;\n }\n impl DoesNotImpl for T {}\n /// Concrete type with `True` for `IMPLS` if the type implements the\n /// given trait. Otherwise, it falls back to `DoesNotImpl`.\n struct Wrapper(::core::marker::PhantomData);\n #[allow(dead_code)]\n impl Wrapper {\n const IMPLS: bool = true;\n }\n >::IMPLS\n } {\n Some(|left, right| {\n use ::facet_core::spez::*;\n (&&Spez(left)).spez_partial_eq(&&Spez(right))\n })\n } else {\n None\n }\n })\n .partial_ord(|| {\n if {\n /// Fallback trait with `False` for `IMPLS` if the type does not\n /// implement the given trait.\n trait DoesNotImpl {\n const IMPLS: bool = false;\n }\n impl DoesNotImpl for T {}\n /// Concrete type with `True` for `IMPLS` if the type implements the\n /// given trait. Otherwise, it falls back to `DoesNotImpl`.\n struct Wrapper(::core::marker::PhantomData);\n #[allow(dead_code)]\n impl Wrapper {\n const IMPLS: bool = true;\n }\n >::IMPLS\n } {\n Some(|left, right| {\n use ::facet_core::spez::*;\n (&&Spez(left)).spez_partial_cmp(&&Spez(right))\n })\n } else {\n None\n }\n })\n .ord(|| {\n if {\n /// Fallback trait with `False` for `IMPLS` if the type does not\n /// implement the given trait.\n trait DoesNotImpl {\n const IMPLS: bool = false;\n }\n impl DoesNotImpl for T {}\n /// Concrete type with `True` for `IMPLS` if the type implements the\n /// given trait. Otherwise, it falls back to `DoesNotImpl`.\n struct Wrapper(::core::marker::PhantomData);\n #[allow(dead_code)]\n impl Wrapper {\n const IMPLS: bool = true;\n }\n >::IMPLS\n } {\n Some(|left, right| {\n use ::facet_core::spez::*;\n (&&Spez(left)).spez_cmp(&&Spez(right))\n })\n } else {\n None\n }\n })\n .hash(|| {\n if {\n /// Fallback trait with `False` for `IMPLS` if the type does not\n /// implement the given trait.\n trait DoesNotImpl {\n const IMPLS: bool = false;\n }\n impl DoesNotImpl for T {}\n /// Concrete type with `True` for `IMPLS` if the type implements the\n /// given trait. Otherwise, it falls back to `DoesNotImpl`.\n struct Wrapper(::core::marker::PhantomData);\n #[allow(dead_code)]\n impl Wrapper {\n const IMPLS: bool = true;\n }\n >::IMPLS\n } {\n Some(|value, hasher_this, hasher_write_fn| {\n use ::facet_core::HasherProxy;\n use ::facet_core::spez::*;\n (&&Spez(value)).spez_hash(&mut unsafe {\n HasherProxy::new(hasher_this, hasher_write_fn)\n })\n })\n } else {\n None\n }\n })\n .parse(|| {\n if {\n /// Fallback trait with `False` for `IMPLS` if the type does not\n /// implement the given trait.\n trait DoesNotImpl {\n const IMPLS: bool = false;\n }\n impl DoesNotImpl for T {}\n /// Concrete type with `True` for `IMPLS` if the type implements the\n /// given trait. Otherwise, it falls back to `DoesNotImpl`.\n struct Wrapper(::core::marker::PhantomData);\n #[allow(dead_code)]\n impl Wrapper {\n const IMPLS: bool = true;\n }\n >::IMPLS\n } {\n Some(|s, target| {\n use ::facet_core::spez::*;\n let res =\n unsafe { (&&SpezEmpty::::SPEZ).spez_parse(s, target.into()) };\n res.map(|res| unsafe { res.as_mut() })\n })\n } else {\n None\n }\n })\n .build()\n };\n vtable\n };\n const SHAPE: &'static crate::Shape = &const {\n let fields: &'static [crate::Field] = &const {\n [\n {\n crate::Field::builder()\n .name(\"basic_field\")\n .shape(crate::shape_of(&(|s: &KitchenSinkStruct| &s.basic_field)))\n .offset({\n builtin # offset_of(KitchenSinkStruct, basic_field)\n })\n .doc(&[\" A basic string field.\"])\n .build()\n },\n {\n crate::Field::builder()\n .name(\"sensitive_field\")\n .shape(crate::shape_of(\n &(|s: &KitchenSinkStruct| &s.sensitive_field),\n ))\n .offset({\n builtin # offset_of(KitchenSinkStruct, sensitive_field)\n })\n .flags(crate::FieldFlags::SENSITIVE)\n .doc(&[\" A field marked as sensitive.\"])\n .build()\n },\n {\n crate::Field::builder()\n .name(\"tuple_field\")\n .shape(crate::shape_of(&(|s: &KitchenSinkStruct| &s.tuple_field)))\n .offset({\n builtin # offset_of(KitchenSinkStruct, tuple_field)\n })\n .doc(&[\" A tuple field.\"])\n .build()\n },\n {\n crate::Field::builder()\n .name(\"array_field\")\n .shape(crate::shape_of(&(|s: &KitchenSinkStruct| &s.array_field)))\n .offset({\n builtin # offset_of(KitchenSinkStruct, array_field)\n })\n .doc(&[\" An array field.\"])\n .build()\n },\n {\n crate::Field::builder()\n .name(\"slice_field\")\n .shape(crate::shape_of(&(|s: &KitchenSinkStruct| &s.slice_field)))\n .offset({\n builtin # offset_of(KitchenSinkStruct, slice_field)\n })\n .doc(&[\" A static slice field.\"])\n .build()\n },\n {\n crate::Field::builder()\n .name(\"vec_field\")\n .shape(crate::shape_of(&(|s: &KitchenSinkStruct| &s.vec_field)))\n .offset({\n builtin # offset_of(KitchenSinkStruct, vec_field)\n })\n .doc(&[\" A vector field.\"])\n .build()\n },\n {\n crate::Field::builder()\n .name(\"nested_struct_field\")\n .shape(crate::shape_of(\n &(|s: &KitchenSinkStruct| &s.nested_struct_field),\n ))\n .offset({\n builtin # offset_of(KitchenSinkStruct, nested_struct_field)\n })\n .doc(&[\" A field containing another struct that derives Facet.\"])\n .build()\n },\n ]\n };\n crate::Shape::builder_for_sized::()\n .type_identifier(\"KitchenSinkStruct\")\n .ty(crate::Type::User(crate::UserType::Struct(\n crate::StructType::builder()\n .repr(crate::Repr::default())\n .kind(crate::StructKind::Struct)\n .fields(fields)\n .build(),\n )))\n .doc(&[\" A struct demonstrating various field types and attributes.\"])\n .build()\n };\n}\n/// A simple point struct, also deriving Facet.\npub struct Point {\n pub x: f32,\n pub y: f32,\n /// Nested sensitive data within the struct.\n pub metadata: String,\n}\nstatic POINT_SHAPE: &'static crate::Shape = ::SHAPE;\n#[automatically_derived]\nunsafe impl<'__facet> crate::Facet<'__facet> for Point {\n const VTABLE: &'static crate::ValueVTable = &const {\n let mut vtable = const {\n ::facet_core::ValueVTable::builder::()\n .type_name(|f, _opts| ::core::fmt::Write::write_str(f, \"Point\"))\n .display(|| {\n if {\n /// Fallback trait with `False` for `IMPLS` if the type does not\n /// implement the given trait.\n trait DoesNotImpl {\n const IMPLS: bool = false;\n }\n impl DoesNotImpl for T {}\n /// Concrete type with `True` for `IMPLS` if the type implements the\n /// given trait. Otherwise, it falls back to `DoesNotImpl`.\n struct Wrapper(::core::marker::PhantomData);\n #[allow(dead_code)]\n impl Wrapper {\n const IMPLS: bool = true;\n }\n >::IMPLS\n } {\n Some(|data, f| {\n use ::facet_core::spez::*;\n (&&Spez(data)).spez_display(f)\n })\n } else {\n None\n }\n })\n .debug(|| {\n if {\n /// Fallback trait with `False` for `IMPLS` if the type does not\n /// implement the given trait.\n trait DoesNotImpl {\n const IMPLS: bool = false;\n }\n impl DoesNotImpl for T {}\n /// Concrete type with `True` for `IMPLS` if the type implements the\n /// given trait. Otherwise, it falls back to `DoesNotImpl`.\n struct Wrapper(::core::marker::PhantomData);\n #[allow(dead_code)]\n impl Wrapper {\n const IMPLS: bool = true;\n }\n >::IMPLS\n } {\n Some(|data, f| {\n use ::facet_core::spez::*;\n (&&Spez(data)).spez_debug(f)\n })\n } else {\n None\n }\n })\n .default_in_place(|| {\n if {\n /// Fallback trait with `False` for `IMPLS` if the type does not\n /// implement the given trait.\n trait DoesNotImpl {\n const IMPLS: bool = false;\n }\n impl DoesNotImpl for T {}\n /// Concrete type with `True` for `IMPLS` if the type implements the\n /// given trait. Otherwise, it falls back to `DoesNotImpl`.\n struct Wrapper(::core::marker::PhantomData);\n #[allow(dead_code)]\n impl Wrapper {\n const IMPLS: bool = true;\n }\n >::IMPLS\n } {\n Some(|target| unsafe {\n use ::facet_core::spez::*;\n (&&SpezEmpty::::SPEZ)\n .spez_default_in_place(target.into())\n .as_mut()\n })\n } else {\n None\n }\n })\n .clone_into(|| {\n if {\n /// Fallback trait with `False` for `IMPLS` if the type does not\n /// implement the given trait.\n trait DoesNotImpl {\n const IMPLS: bool = false;\n }\n impl DoesNotImpl for T {}\n /// Concrete type with `True` for `IMPLS` if the type implements the\n /// given trait. Otherwise, it falls back to `DoesNotImpl`.\n struct Wrapper(::core::marker::PhantomData);\n #[allow(dead_code)]\n impl Wrapper {\n const IMPLS: bool = true;\n }\n >::IMPLS\n } {\n Some(|src, dst| unsafe {\n use ::facet_core::spez::*;\n (&&Spez(src)).spez_clone_into(dst.into()).as_mut()\n })\n } else {\n None\n }\n })\n .marker_traits(|| {\n let mut traits = ::facet_core::MarkerTraits::empty();\n if {\n /// Fallback trait with `False` for `IMPLS` if the type does not\n /// implement the given trait.\n trait DoesNotImpl {\n const IMPLS: bool = false;\n }\n impl DoesNotImpl for T {}\n /// Concrete type with `True` for `IMPLS` if the type implements the\n /// given trait. Otherwise, it falls back to `DoesNotImpl`.\n struct Wrapper(::core::marker::PhantomData);\n #[allow(dead_code)]\n impl Wrapper {\n const IMPLS: bool = true;\n }\n >::IMPLS\n } {\n traits = traits.union(::facet_core::MarkerTraits::EQ);\n }\n if {\n /// Fallback trait with `False` for `IMPLS` if the type does not\n /// implement the given trait.\n trait DoesNotImpl {\n const IMPLS: bool = false;\n }\n impl DoesNotImpl for T {}\n /// Concrete type with `True` for `IMPLS` if the type implements the\n /// given trait. Otherwise, it falls back to `DoesNotImpl`.\n struct Wrapper(::core::marker::PhantomData);\n #[allow(dead_code)]\n impl Wrapper {\n const IMPLS: bool = true;\n }\n >::IMPLS\n } {\n traits = traits.union(::facet_core::MarkerTraits::SEND);\n }\n if {\n /// Fallback trait with `False` for `IMPLS` if the type does not\n /// implement the given trait.\n trait DoesNotImpl {\n const IMPLS: bool = false;\n }\n impl DoesNotImpl for T {}\n /// Concrete type with `True` for `IMPLS` if the type implements the\n /// given trait. Otherwise, it falls back to `DoesNotImpl`.\n struct Wrapper(::core::marker::PhantomData);\n #[allow(dead_code)]\n impl Wrapper {\n const IMPLS: bool = true;\n }\n >::IMPLS\n } {\n traits = traits.union(::facet_core::MarkerTraits::SYNC);\n }\n if {\n /// Fallback trait with `False` for `IMPLS` if the type does not\n /// implement the given trait.\n trait DoesNotImpl {\n const IMPLS: bool = false;\n }\n impl DoesNotImpl for T {}\n /// Concrete type with `True` for `IMPLS` if the type implements the\n /// given trait. Otherwise, it falls back to `DoesNotImpl`.\n struct Wrapper(::core::marker::PhantomData);\n #[allow(dead_code)]\n impl Wrapper {\n const IMPLS: bool = true;\n }\n >::IMPLS\n } {\n traits = traits.union(::facet_core::MarkerTraits::COPY);\n }\n if {\n /// Fallback trait with `False` for `IMPLS` if the type does not\n /// implement the given trait.\n trait DoesNotImpl {\n const IMPLS: bool = false;\n }\n impl DoesNotImpl for T {}\n /// Concrete type with `True` for `IMPLS` if the type implements the\n /// given trait. Otherwise, it falls back to `DoesNotImpl`.\n struct Wrapper(::core::marker::PhantomData);\n #[allow(dead_code)]\n impl Wrapper {\n const IMPLS: bool = true;\n }\n >::IMPLS\n } {\n traits = traits.union(::facet_core::MarkerTraits::UNPIN);\n }\n if {\n /// Fallback trait with `False` for `IMPLS` if the type does not\n /// implement the given trait.\n trait DoesNotImpl {\n const IMPLS: bool = false;\n }\n impl DoesNotImpl for T {}\n /// Concrete type with `True` for `IMPLS` if the type implements the\n /// given trait. Otherwise, it falls back to `DoesNotImpl`.\n struct Wrapper(::core::marker::PhantomData);\n #[allow(dead_code)]\n impl Wrapper {\n const IMPLS: bool = true;\n }\n >::IMPLS\n } {\n traits = traits.union(::facet_core::MarkerTraits::UNWIND_SAFE);\n }\n if {\n /// Fallback trait with `False` for `IMPLS` if the type does not\n /// implement the given trait.\n trait DoesNotImpl {\n const IMPLS: bool = false;\n }\n impl DoesNotImpl for T {}\n /// Concrete type with `True` for `IMPLS` if the type implements the\n /// given trait. Otherwise, it falls back to `DoesNotImpl`.\n struct Wrapper(::core::marker::PhantomData);\n #[allow(dead_code)]\n impl Wrapper {\n const IMPLS: bool = true;\n }\n >::IMPLS\n } {\n traits = traits.union(::facet_core::MarkerTraits::REF_UNWIND_SAFE);\n }\n traits\n })\n .partial_eq(|| {\n if {\n /// Fallback trait with `False` for `IMPLS` if the type does not\n /// implement the given trait.\n trait DoesNotImpl {\n const IMPLS: bool = false;\n }\n impl DoesNotImpl for T {}\n /// Concrete type with `True` for `IMPLS` if the type implements the\n /// given trait. Otherwise, it falls back to `DoesNotImpl`.\n struct Wrapper(::core::marker::PhantomData);\n #[allow(dead_code)]\n impl Wrapper {\n const IMPLS: bool = true;\n }\n >::IMPLS\n } {\n Some(|left, right| {\n use ::facet_core::spez::*;\n (&&Spez(left)).spez_partial_eq(&&Spez(right))\n })\n } else {\n None\n }\n })\n .partial_ord(|| {\n if {\n /// Fallback trait with `False` for `IMPLS` if the type does not\n /// implement the given trait.\n trait DoesNotImpl {\n const IMPLS: bool = false;\n }\n impl DoesNotImpl for T {}\n /// Concrete type with `True` for `IMPLS` if the type implements the\n /// given trait. Otherwise, it falls back to `DoesNotImpl`.\n struct Wrapper(::core::marker::PhantomData);\n #[allow(dead_code)]\n impl Wrapper {\n const IMPLS: bool = true;\n }\n >::IMPLS\n } {\n Some(|left, right| {\n use ::facet_core::spez::*;\n (&&Spez(left)).spez_partial_cmp(&&Spez(right))\n })\n } else {\n None\n }\n })\n .ord(|| {\n if {\n /// Fallback trait with `False` for `IMPLS` if the type does not\n /// implement the given trait.\n trait DoesNotImpl {\n const IMPLS: bool = false;\n }\n impl DoesNotImpl for T {}\n /// Concrete type with `True` for `IMPLS` if the type implements the\n /// given trait. Otherwise, it falls back to `DoesNotImpl`.\n struct Wrapper(::core::marker::PhantomData);\n #[allow(dead_code)]\n impl Wrapper {\n const IMPLS: bool = true;\n }\n >::IMPLS\n } {\n Some(|left, right| {\n use ::facet_core::spez::*;\n (&&Spez(left)).spez_cmp(&&Spez(right))\n })\n } else {\n None\n }\n })\n .hash(|| {\n if {\n /// Fallback trait with `False` for `IMPLS` if the type does not\n /// implement the given trait.\n trait DoesNotImpl {\n const IMPLS: bool = false;\n }\n impl DoesNotImpl for T {}\n /// Concrete type with `True` for `IMPLS` if the type implements the\n /// given trait. Otherwise, it falls back to `DoesNotImpl`.\n struct Wrapper(::core::marker::PhantomData);\n #[allow(dead_code)]\n impl Wrapper {\n const IMPLS: bool = true;\n }\n >::IMPLS\n } {\n Some(|value, hasher_this, hasher_write_fn| {\n use ::facet_core::HasherProxy;\n use ::facet_core::spez::*;\n (&&Spez(value)).spez_hash(&mut unsafe {\n HasherProxy::new(hasher_this, hasher_write_fn)\n })\n })\n } else {\n None\n }\n })\n .parse(|| {\n if {\n /// Fallback trait with `False` for `IMPLS` if the type does not\n /// implement the given trait.\n trait DoesNotImpl {\n const IMPLS: bool = false;\n }\n impl DoesNotImpl for T {}\n /// Concrete type with `True` for `IMPLS` if the type implements the\n /// given trait. Otherwise, it falls back to `DoesNotImpl`.\n struct Wrapper(::core::marker::PhantomData);\n #[allow(dead_code)]\n impl Wrapper {\n const IMPLS: bool = true;\n }\n >::IMPLS\n } {\n Some(|s, target| {\n use ::facet_core::spez::*;\n let res =\n unsafe { (&&SpezEmpty::::SPEZ).spez_parse(s, target.into()) };\n res.map(|res| unsafe { res.as_mut() })\n })\n } else {\n None\n }\n })\n .build()\n };\n vtable\n };\n const SHAPE: &'static crate::Shape = &const {\n let fields: &'static [crate::Field] = &const {\n [\n {\n crate::Field::builder()\n .name(\"x\")\n .shape(crate::shape_of(&(|s: &Point| &s.x)))\n .offset({\n builtin # offset_of(Point, x)\n })\n .build()\n },\n {\n crate::Field::builder()\n .name(\"y\")\n .shape(crate::shape_of(&(|s: &Point| &s.y)))\n .offset({\n builtin # offset_of(Point, y)\n })\n .build()\n },\n {\n crate::Field::builder()\n .name(\"metadata\")\n .shape(crate::shape_of(&(|s: &Point| &s.metadata)))\n .offset({\n builtin # offset_of(Point, metadata)\n })\n .flags(crate::FieldFlags::SENSITIVE)\n .doc(&[\" Nested sensitive data within the struct.\"])\n .build()\n },\n ]\n };\n crate::Shape::builder_for_sized::()\n .type_identifier(\"Point\")\n .ty(crate::Type::User(crate::UserType::Struct(\n crate::StructType::builder()\n .repr(crate::Repr::default())\n .kind(crate::StructKind::Struct)\n .fields(fields)\n .build(),\n )))\n .doc(&[\" A simple point struct, also deriving Facet.\"])\n .build()\n };\n}\n/// An enum demonstrating different variant types and attributes.\n#[repr(u8)]\npub enum KitchenSinkEnum {\n /// A simple unit variant.\n UnitVariant,\n\n /// A tuple variant with a single element.\n ///\n /// The contained `String` represents an important message payload.\n TupleVariantSimple(String),\n\n /// A tuple variant with multiple elements.\n ///\n /// Contains important positional data:\n /// - `_0` (i32): An identifier code.\n /// - `_1` (i32): A sequence number.\n /// - `_2` (i32): A status flag.\n TupleVariantMulti(i32, i32, i32),\n\n /// A struct variant with named fields.\n StructVariant {\n /// The width dimension, crucial for rendering.\n width: f64,\n /// The height dimension, also crucial for rendering.\n height: f64,\n },\n\n /// A tuple variant marked entirely as sensitive.\n SensitiveTupleVariant(Vec),\n\n /// A struct variant containing a sensitive field.\n StructVariantWithSensitiveField {\n /// The main data payload, publicly accessible.\n payload: Vec,\n /// The sensitive checksum for integrity verification.\n checksum: u32,\n },\n\n /// A variant marked as arbitrary, potentially skipped during processing.\n ArbitraryVariant((f64, f64)),\n\n /// A variant containing another enum that derives Facet.\n ///\n /// The nested `SubEnum` indicates a specific sub-state or option.\n NestedEnumVariant(SubEnum),\n}\nstatic KITCHEN_SINK_ENUM_SHAPE: &'static crate::Shape = ::SHAPE;\n#[automatically_derived]\n#[allow(non_camel_case_types)]\nunsafe impl<'__facet> crate::Facet<'__facet> for KitchenSinkEnum {\n const VTABLE: &'static crate::ValueVTable = &const {\n const {\n ::facet_core::ValueVTable::builder::()\n .type_name(|f, _opts| ::core::fmt::Write::write_str(f, \"KitchenSinkEnum\"))\n .display(|| {\n if {\n /// Fallback trait with `False` for `IMPLS` if the type does not\n /// implement the given trait.\n trait DoesNotImpl {\n const IMPLS: bool = false;\n }\n impl DoesNotImpl for T {}\n /// Concrete type with `True` for `IMPLS` if the type implements the\n /// given trait. Otherwise, it falls back to `DoesNotImpl`.\n struct Wrapper(::core::marker::PhantomData);\n #[allow(dead_code)]\n impl Wrapper {\n const IMPLS: bool = true;\n }\n >::IMPLS\n } {\n Some(|data, f| {\n use ::facet_core::spez::*;\n (&&Spez(data)).spez_display(f)\n })\n } else {\n None\n }\n })\n .debug(|| {\n if {\n /// Fallback trait with `False` for `IMPLS` if the type does not\n /// implement the given trait.\n trait DoesNotImpl {\n const IMPLS: bool = false;\n }\n impl DoesNotImpl for T {}\n /// Concrete type with `True` for `IMPLS` if the type implements the\n /// given trait. Otherwise, it falls back to `DoesNotImpl`.\n struct Wrapper(::core::marker::PhantomData);\n #[allow(dead_code)]\n impl Wrapper {\n const IMPLS: bool = true;\n }\n >::IMPLS\n } {\n Some(|data, f| {\n use ::facet_core::spez::*;\n (&&Spez(data)).spez_debug(f)\n })\n } else {\n None\n }\n })\n .default_in_place(|| {\n if {\n /// Fallback trait with `False` for `IMPLS` if the type does not\n /// implement the given trait.\n trait DoesNotImpl {\n const IMPLS: bool = false;\n }\n impl DoesNotImpl for T {}\n /// Concrete type with `True` for `IMPLS` if the type implements the\n /// given trait. Otherwise, it falls back to `DoesNotImpl`.\n struct Wrapper(::core::marker::PhantomData);\n #[allow(dead_code)]\n impl Wrapper {\n const IMPLS: bool = true;\n }\n >::IMPLS\n } {\n Some(|target| unsafe {\n use ::facet_core::spez::*;\n (&&SpezEmpty::::SPEZ)\n .spez_default_in_place(target.into())\n .as_mut()\n })\n } else {\n None\n }\n })\n .clone_into(|| {\n if {\n /// Fallback trait with `False` for `IMPLS` if the type does not\n /// implement the given trait.\n trait DoesNotImpl {\n const IMPLS: bool = false;\n }\n impl DoesNotImpl for T {}\n /// Concrete type with `True` for `IMPLS` if the type implements the\n /// given trait. Otherwise, it falls back to `DoesNotImpl`.\n struct Wrapper(::core::marker::PhantomData);\n #[allow(dead_code)]\n impl Wrapper {\n const IMPLS: bool = true;\n }\n >::IMPLS\n } {\n Some(|src, dst| unsafe {\n use ::facet_core::spez::*;\n (&&Spez(src)).spez_clone_into(dst.into()).as_mut()\n })\n } else {\n None\n }\n })\n .marker_traits(|| {\n let mut traits = ::facet_core::MarkerTraits::empty();\n if {\n /// Fallback trait with `False` for `IMPLS` if the type does not\n /// implement the given trait.\n trait DoesNotImpl {\n const IMPLS: bool = false;\n }\n impl DoesNotImpl for T {}\n /// Concrete type with `True` for `IMPLS` if the type implements the\n /// given trait. Otherwise, it falls back to `DoesNotImpl`.\n struct Wrapper(::core::marker::PhantomData);\n #[allow(dead_code)]\n impl Wrapper {\n const IMPLS: bool = true;\n }\n >::IMPLS\n } {\n traits = traits.union(::facet_core::MarkerTraits::EQ);\n }\n if {\n /// Fallback trait with `False` for `IMPLS` if the type does not\n /// implement the given trait.\n trait DoesNotImpl {\n const IMPLS: bool = false;\n }\n impl DoesNotImpl for T {}\n /// Concrete type with `True` for `IMPLS` if the type implements the\n /// given trait. Otherwise, it falls back to `DoesNotImpl`.\n struct Wrapper(::core::marker::PhantomData);\n #[allow(dead_code)]\n impl Wrapper {\n const IMPLS: bool = true;\n }\n >::IMPLS\n } {\n traits = traits.union(::facet_core::MarkerTraits::SEND);\n }\n if {\n /// Fallback trait with `False` for `IMPLS` if the type does not\n /// implement the given trait.\n trait DoesNotImpl {\n const IMPLS: bool = false;\n }\n impl DoesNotImpl for T {}\n /// Concrete type with `True` for `IMPLS` if the type implements the\n /// given trait. Otherwise, it falls back to `DoesNotImpl`.\n struct Wrapper(::core::marker::PhantomData);\n #[allow(dead_code)]\n impl Wrapper {\n const IMPLS: bool = true;\n }\n >::IMPLS\n } {\n traits = traits.union(::facet_core::MarkerTraits::SYNC);\n }\n if {\n /// Fallback trait with `False` for `IMPLS` if the type does not\n /// implement the given trait.\n trait DoesNotImpl {\n const IMPLS: bool = false;\n }\n impl DoesNotImpl for T {}\n /// Concrete type with `True` for `IMPLS` if the type implements the\n /// given trait. Otherwise, it falls back to `DoesNotImpl`.\n struct Wrapper(::core::marker::PhantomData);\n #[allow(dead_code)]\n impl Wrapper {\n const IMPLS: bool = true;\n }\n >::IMPLS\n } {\n traits = traits.union(::facet_core::MarkerTraits::COPY);\n }\n if {\n /// Fallback trait with `False` for `IMPLS` if the type does not\n /// implement the given trait.\n trait DoesNotImpl {\n const IMPLS: bool = false;\n }\n impl DoesNotImpl for T {}\n /// Concrete type with `True` for `IMPLS` if the type implements the\n /// given trait. Otherwise, it falls back to `DoesNotImpl`.\n struct Wrapper(::core::marker::PhantomData);\n #[allow(dead_code)]\n impl Wrapper {\n const IMPLS: bool = true;\n }\n >::IMPLS\n } {\n traits = traits.union(::facet_core::MarkerTraits::UNPIN);\n }\n if {\n /// Fallback trait with `False` for `IMPLS` if the type does not\n /// implement the given trait.\n trait DoesNotImpl {\n const IMPLS: bool = false;\n }\n impl DoesNotImpl for T {}\n /// Concrete type with `True` for `IMPLS` if the type implements the\n /// given trait. Otherwise, it falls back to `DoesNotImpl`.\n struct Wrapper(::core::marker::PhantomData);\n #[allow(dead_code)]\n impl Wrapper {\n const IMPLS: bool = true;\n }\n >::IMPLS\n } {\n traits = traits.union(::facet_core::MarkerTraits::UNWIND_SAFE);\n }\n if {\n /// Fallback trait with `False` for `IMPLS` if the type does not\n /// implement the given trait.\n trait DoesNotImpl {\n const IMPLS: bool = false;\n }\n impl DoesNotImpl for T {}\n /// Concrete type with `True` for `IMPLS` if the type implements the\n /// given trait. Otherwise, it falls back to `DoesNotImpl`.\n struct Wrapper(::core::marker::PhantomData);\n #[allow(dead_code)]\n impl Wrapper {\n const IMPLS: bool = true;\n }\n >::IMPLS\n } {\n traits = traits.union(::facet_core::MarkerTraits::REF_UNWIND_SAFE);\n }\n traits\n })\n .partial_eq(|| {\n if {\n /// Fallback trait with `False` for `IMPLS` if the type does not\n /// implement the given trait.\n trait DoesNotImpl {\n const IMPLS: bool = false;\n }\n impl DoesNotImpl for T {}\n /// Concrete type with `True` for `IMPLS` if the type implements the\n /// given trait. Otherwise, it falls back to `DoesNotImpl`.\n struct Wrapper(::core::marker::PhantomData);\n #[allow(dead_code)]\n impl Wrapper {\n const IMPLS: bool = true;\n }\n >::IMPLS\n } {\n Some(|left, right| {\n use ::facet_core::spez::*;\n (&&Spez(left)).spez_partial_eq(&&Spez(right))\n })\n } else {\n None\n }\n })\n .partial_ord(|| {\n if {\n /// Fallback trait with `False` for `IMPLS` if the type does not\n /// implement the given trait.\n trait DoesNotImpl {\n const IMPLS: bool = false;\n }\n impl DoesNotImpl for T {}\n /// Concrete type with `True` for `IMPLS` if the type implements the\n /// given trait. Otherwise, it falls back to `DoesNotImpl`.\n struct Wrapper(::core::marker::PhantomData);\n #[allow(dead_code)]\n impl Wrapper {\n const IMPLS: bool = true;\n }\n >::IMPLS\n } {\n Some(|left, right| {\n use ::facet_core::spez::*;\n (&&Spez(left)).spez_partial_cmp(&&Spez(right))\n })\n } else {\n None\n }\n })\n .ord(|| {\n if {\n /// Fallback trait with `False` for `IMPLS` if the type does not\n /// implement the given trait.\n trait DoesNotImpl {\n const IMPLS: bool = false;\n }\n impl DoesNotImpl for T {}\n /// Concrete type with `True` for `IMPLS` if the type implements the\n /// given trait. Otherwise, it falls back to `DoesNotImpl`.\n struct Wrapper(::core::marker::PhantomData);\n #[allow(dead_code)]\n impl Wrapper {\n const IMPLS: bool = true;\n }\n >::IMPLS\n } {\n Some(|left, right| {\n use ::facet_core::spez::*;\n (&&Spez(left)).spez_cmp(&&Spez(right))\n })\n } else {\n None\n }\n })\n .hash(|| {\n if {\n /// Fallback trait with `False` for `IMPLS` if the type does not\n /// implement the given trait.\n trait DoesNotImpl {\n const IMPLS: bool = false;\n }\n impl DoesNotImpl for T {}\n /// Concrete type with `True` for `IMPLS` if the type implements the\n /// given trait. Otherwise, it falls back to `DoesNotImpl`.\n struct Wrapper(::core::marker::PhantomData);\n #[allow(dead_code)]\n impl Wrapper {\n const IMPLS: bool = true;\n }\n >::IMPLS\n } {\n Some(|value, hasher_this, hasher_write_fn| {\n use ::facet_core::HasherProxy;\n use ::facet_core::spez::*;\n (&&Spez(value)).spez_hash(&mut unsafe {\n HasherProxy::new(hasher_this, hasher_write_fn)\n })\n })\n } else {\n None\n }\n })\n .parse(|| {\n if {\n /// Fallback trait with `False` for `IMPLS` if the type does not\n /// implement the given trait.\n trait DoesNotImpl {\n const IMPLS: bool = false;\n }\n impl DoesNotImpl for T {}\n /// Concrete type with `True` for `IMPLS` if the type implements the\n /// given trait. Otherwise, it falls back to `DoesNotImpl`.\n struct Wrapper(::core::marker::PhantomData);\n #[allow(dead_code)]\n impl Wrapper {\n const IMPLS: bool = true;\n }\n >::IMPLS\n } {\n Some(|s, target| {\n use ::facet_core::spez::*;\n let res =\n unsafe { (&&SpezEmpty::::SPEZ).spez_parse(s, target.into()) };\n res.map(|res| unsafe { res.as_mut() })\n })\n } else {\n None\n }\n })\n .build()\n }\n };\n const SHAPE: &'static crate::Shape = &const {\n #[repr(C)]\n #[allow(non_snake_case, dead_code)]\n struct __Shadow_RustRepr_Tuple_for_KitchenSinkEnum_TupleVariantSimple<'__facet> {\n _discriminant: u8,\n _phantom: ::core::marker::PhantomData<(*mut &'__facet ())>,\n _0: String,\n }\n #[repr(C)]\n #[allow(non_snake_case, dead_code)]\n struct __Shadow_RustRepr_Tuple_for_KitchenSinkEnum_TupleVariantMulti<'__facet> {\n _discriminant: u8,\n _phantom: ::core::marker::PhantomData<(*mut &'__facet ())>,\n _0: i32,\n _1: i32,\n _2: i32,\n }\n #[repr(C)]\n #[allow(non_snake_case, dead_code)]\n struct __Shadow_RustRepr_Struct_for_KitchenSinkEnum_StructVariant<'__facet> {\n _discriminant: u8,\n _phantom: ::core::marker::PhantomData<(*mut &'__facet ())>,\n width: f64,\n height: f64,\n }\n #[repr(C)]\n #[allow(non_snake_case, dead_code)]\n struct __Shadow_RustRepr_Tuple_for_KitchenSinkEnum_SensitiveTupleVariant<'__facet> {\n _discriminant: u8,\n _phantom: ::core::marker::PhantomData<(*mut &'__facet ())>,\n _0: Vec,\n }\n #[repr(C)]\n #[allow(non_snake_case, dead_code)]\n struct __Shadow_RustRepr_Struct_for_KitchenSinkEnum_StructVariantWithSensitiveField<\n '__facet,\n > {\n _discriminant: u8,\n _phantom: ::core::marker::PhantomData<(*mut &'__facet ())>,\n payload: Vec,\n checksum: u32,\n }\n #[repr(C)]\n #[allow(non_snake_case, dead_code)]\n struct __Shadow_RustRepr_Tuple_for_KitchenSinkEnum_ArbitraryVariant<'__facet> {\n _discriminant: u8,\n _phantom: ::core::marker::PhantomData<(*mut &'__facet ())>,\n _0: (f64, f64),\n }\n #[repr(C)]\n #[allow(non_snake_case, dead_code)]\n struct __Shadow_RustRepr_Tuple_for_KitchenSinkEnum_NestedEnumVariant<'__facet> {\n _discriminant: u8,\n _phantom: ::core::marker::PhantomData<(*mut &'__facet ())>,\n _0: SubEnum,\n }\n let __facet_variants: &'static [crate::Variant] = &const {\n [\n crate::Variant::builder()\n .name(\"UnitVariant\")\n .discriminant(0i64 as i64)\n .data(\n crate::StructType::builder()\n .repr(crate::Repr::c())\n .unit()\n .build(),\n )\n .doc(&[\" A simple unit variant.\"])\n .build(),\n {\n let fields: &'static [crate::Field] = &const {\n [{\n crate::Field::builder().name(\"0\").shape(crate::shape_of(&(|s:\n &__Shadow_RustRepr_Tuple_for_KitchenSinkEnum_TupleVariantSimple<'__facet>|\n &s._0))).offset({\n builtin # offset_of(__Shadow_RustRepr_Tuple_for_KitchenSinkEnum_TupleVariantSimple<'__facet>,\n _0)\n }).build()\n }]\n };\n crate::Variant::builder()\n .name(\"TupleVariantSimple\")\n .discriminant(1i64 as i64)\n .data(\n crate::StructType::builder()\n .repr(crate::Repr::c())\n .tuple()\n .fields(fields)\n .build(),\n )\n .doc(&[\n \" A tuple variant with a single element.\",\n \"\",\n \" The contained `String` represents an important message payload.\",\n ])\n .build()\n },\n {\n let fields: &'static [crate::Field] = &const {\n [\n {\n crate::Field::builder().name(\"0\").shape(crate::shape_of(&(|s:\n &__Shadow_RustRepr_Tuple_for_KitchenSinkEnum_TupleVariantMulti<'__facet>|\n &s._0))).offset({\n builtin # offset_of(__Shadow_RustRepr_Tuple_for_KitchenSinkEnum_TupleVariantMulti<'__facet>,\n _0)\n }).build()\n },\n {\n crate::Field::builder().name(\"1\").shape(crate::shape_of(&(|s:\n &__Shadow_RustRepr_Tuple_for_KitchenSinkEnum_TupleVariantMulti<'__facet>|\n &s._1))).offset({\n builtin # offset_of(__Shadow_RustRepr_Tuple_for_KitchenSinkEnum_TupleVariantMulti<'__facet>,\n _1)\n }).build()\n },\n {\n crate::Field::builder().name(\"2\").shape(crate::shape_of(&(|s:\n &__Shadow_RustRepr_Tuple_for_KitchenSinkEnum_TupleVariantMulti<'__facet>|\n &s._2))).offset({\n builtin # offset_of(__Shadow_RustRepr_Tuple_for_KitchenSinkEnum_TupleVariantMulti<'__facet>,\n _2)\n }).build()\n },\n ]\n };\n crate::Variant::builder()\n .name(\"TupleVariantMulti\")\n .discriminant(2i64 as i64)\n .data(\n crate::StructType::builder()\n .repr(crate::Repr::c())\n .tuple()\n .fields(fields)\n .build(),\n )\n .doc(&[\n \" A tuple variant with multiple elements.\",\n \"\",\n \" Contains important positional data:\",\n \" - `_0` (i32): An identifier code.\",\n \" - `_1` (i32): A sequence number.\",\n \" - `_2` (i32): A status flag.\",\n ])\n .build()\n },\n {\n let fields: &'static [crate::Field] = &const {\n [\n {\n crate::Field::builder().name(\"width\").shape(crate::shape_of(&(|s:\n &__Shadow_RustRepr_Struct_for_KitchenSinkEnum_StructVariant<'__facet>|\n &s.width))).offset({\n builtin # offset_of(__Shadow_RustRepr_Struct_for_KitchenSinkEnum_StructVariant<'__facet>,\n width)\n }).doc(&[\" The width dimension, crucial for rendering.\"]).build()\n },\n {\n crate::Field::builder().name(\"height\").shape(crate::shape_of(&(|s:\n &__Shadow_RustRepr_Struct_for_KitchenSinkEnum_StructVariant<'__facet>|\n &s.height))).offset({\n builtin # offset_of(__Shadow_RustRepr_Struct_for_KitchenSinkEnum_StructVariant<'__facet>,\n height)\n }).doc(&[\" The height dimension, also crucial for rendering.\"]).build()\n },\n ]\n };\n crate::Variant::builder()\n .name(\"StructVariant\")\n .discriminant(3i64 as i64)\n .data(\n crate::StructType::builder()\n .repr(crate::Repr::c())\n .struct_()\n .fields(fields)\n .build(),\n )\n .doc(&[\" A struct variant with named fields.\"])\n .build()\n },\n {\n let fields: &'static [crate::Field] = &const {\n [{\n crate::Field::builder().name(\"0\").shape(crate::shape_of(&(|s:\n &__Shadow_RustRepr_Tuple_for_KitchenSinkEnum_SensitiveTupleVariant<'__facet>|\n &s._0))).offset({\n builtin # offset_of(__Shadow_RustRepr_Tuple_for_KitchenSinkEnum_SensitiveTupleVariant<'__facet>,\n _0)\n }).build()\n }]\n };\n crate::Variant::builder()\n .name(\"SensitiveTupleVariant\")\n .discriminant(4i64 as i64)\n .data(\n crate::StructType::builder()\n .repr(crate::Repr::c())\n .tuple()\n .fields(fields)\n .build(),\n )\n .doc(&[\" A tuple variant marked entirely as sensitive.\"])\n .build()\n },\n {\n let fields: &'static [crate::Field] = &const {\n [\n {\n crate::Field::builder().name(\"payload\").shape(crate::shape_of(&(|s:\n &__Shadow_RustRepr_Struct_for_KitchenSinkEnum_StructVariantWithSensitiveField<'__facet>|\n &s.payload))).offset({\n builtin # offset_of(__Shadow_RustRepr_Struct_for_KitchenSinkEnum_StructVariantWithSensitiveField<'__facet>,\n payload)\n }).doc(&[\" The main data payload, publicly accessible.\"]).build()\n },\n {\n crate::Field::builder().name(\"checksum\").shape(crate::shape_of(&(|s:\n &__Shadow_RustRepr_Struct_for_KitchenSinkEnum_StructVariantWithSensitiveField<'__facet>|\n &s.checksum))).offset({\n builtin # offset_of(__Shadow_RustRepr_Struct_for_KitchenSinkEnum_StructVariantWithSensitiveField<'__facet>,\n checksum)\n }).flags(crate::FieldFlags::SENSITIVE).doc(&[\" The sensitive checksum for integrity verification.\"]).build()\n },\n ]\n };\n crate::Variant::builder()\n .name(\"StructVariantWithSensitiveField\")\n .discriminant(5i64 as i64)\n .data(\n crate::StructType::builder()\n .repr(crate::Repr::c())\n .struct_()\n .fields(fields)\n .build(),\n )\n .doc(&[\" A struct variant containing a sensitive field.\"])\n .build()\n },\n {\n let fields: &'static [crate::Field] = &const {\n [{\n crate::Field::builder().name(\"0\").shape(crate::shape_of(&(|s:\n &__Shadow_RustRepr_Tuple_for_KitchenSinkEnum_ArbitraryVariant<'__facet>|\n &s._0))).offset({\n builtin # offset_of(__Shadow_RustRepr_Tuple_for_KitchenSinkEnum_ArbitraryVariant<'__facet>,\n _0)\n }).build()\n }]\n };\n crate::Variant::builder().name(\"ArbitraryVariant\").attributes(&[crate::VariantAttribute::Arbitrary(\"arbitrary\")]).discriminant(6i64\n as\n i64).data(crate::StructType::builder().repr(crate::Repr::c()).tuple().fields(fields).build()).doc(&[\" A variant marked as arbitrary, potentially skipped during processing.\"]).build()\n },\n {\n let fields: &'static [crate::Field] = &const {\n [{\n crate::Field::builder().name(\"0\").shape(crate::shape_of(&(|s:\n &__Shadow_RustRepr_Tuple_for_KitchenSinkEnum_NestedEnumVariant<'__facet>|\n &s._0))).offset({\n builtin # offset_of(__Shadow_RustRepr_Tuple_for_KitchenSinkEnum_NestedEnumVariant<'__facet>,\n _0)\n }).build()\n }]\n };\n crate::Variant::builder()\n .name(\"NestedEnumVariant\")\n .discriminant(7i64 as i64)\n .data(\n crate::StructType::builder()\n .repr(crate::Repr::c())\n .tuple()\n .fields(fields)\n .build(),\n )\n .doc(&[\n \" A variant containing another enum that derives Facet.\",\n \"\",\n \" The nested `SubEnum` indicates a specific sub-state or option.\",\n ])\n .build()\n },\n ]\n };\n crate::Shape::builder_for_sized::()\n .type_identifier(\"KitchenSinkEnum\")\n .ty(crate::Type::User(crate::UserType::Enum(\n crate::EnumType::builder()\n .variants(__facet_variants)\n .repr(crate::Repr::default())\n .enum_repr(crate::EnumRepr::U8)\n .build(),\n )))\n .doc(&[\" An enum demonstrating different variant types and attributes.\"])\n .build()\n };\n}\n/// A sub-enum used within `KitchenSinkEnum`.\n#[repr(u8)]\npub enum SubEnum {\n /// Option A.\n OptionA,\n\n /// Option B with data.\n OptionB(u8),\n\n /// A sensitive option.\n SensitiveOption(u64),\n\n /// An arbitrary option.\n ArbitraryOption(u8),\n}\nstatic SUB_ENUM_SHAPE: &'static crate::Shape = ::SHAPE;\n#[automatically_derived]\n#[allow(non_camel_case_types)]\nunsafe impl<'__facet> crate::Facet<'__facet> for SubEnum {\n const VTABLE: &'static crate::ValueVTable = &const {\n const {\n ::facet_core::ValueVTable::builder::()\n .type_name(|f, _opts| ::core::fmt::Write::write_str(f, \"SubEnum\"))\n .display(|| {\n if {\n /// Fallback trait with `False` for `IMPLS` if the type does not\n /// implement the given trait.\n trait DoesNotImpl {\n const IMPLS: bool = false;\n }\n impl DoesNotImpl for T {}\n /// Concrete type with `True` for `IMPLS` if the type implements the\n /// given trait. Otherwise, it falls back to `DoesNotImpl`.\n struct Wrapper(::core::marker::PhantomData);\n #[allow(dead_code)]\n impl Wrapper {\n const IMPLS: bool = true;\n }\n >::IMPLS\n } {\n Some(|data, f| {\n use ::facet_core::spez::*;\n (&&Spez(data)).spez_display(f)\n })\n } else {\n None\n }\n })\n .debug(|| {\n if {\n /// Fallback trait with `False` for `IMPLS` if the type does not\n /// implement the given trait.\n trait DoesNotImpl {\n const IMPLS: bool = false;\n }\n impl DoesNotImpl for T {}\n /// Concrete type with `True` for `IMPLS` if the type implements the\n /// given trait. Otherwise, it falls back to `DoesNotImpl`.\n struct Wrapper(::core::marker::PhantomData);\n #[allow(dead_code)]\n impl Wrapper {\n const IMPLS: bool = true;\n }\n >::IMPLS\n } {\n Some(|data, f| {\n use ::facet_core::spez::*;\n (&&Spez(data)).spez_debug(f)\n })\n } else {\n None\n }\n })\n .default_in_place(|| {\n if {\n /// Fallback trait with `False` for `IMPLS` if the type does not\n /// implement the given trait.\n trait DoesNotImpl {\n const IMPLS: bool = false;\n }\n impl DoesNotImpl for T {}\n /// Concrete type with `True` for `IMPLS` if the type implements the\n /// given trait. Otherwise, it falls back to `DoesNotImpl`.\n struct Wrapper(::core::marker::PhantomData);\n #[allow(dead_code)]\n impl Wrapper {\n const IMPLS: bool = true;\n }\n >::IMPLS\n } {\n Some(|target| unsafe {\n use ::facet_core::spez::*;\n (&&SpezEmpty::::SPEZ)\n .spez_default_in_place(target.into())\n .as_mut()\n })\n } else {\n None\n }\n })\n .clone_into(|| {\n if {\n /// Fallback trait with `False` for `IMPLS` if the type does not\n /// implement the given trait.\n trait DoesNotImpl {\n const IMPLS: bool = false;\n }\n impl DoesNotImpl for T {}\n /// Concrete type with `True` for `IMPLS` if the type implements the\n /// given trait. Otherwise, it falls back to `DoesNotImpl`.\n struct Wrapper(::core::marker::PhantomData);\n #[allow(dead_code)]\n impl Wrapper {\n const IMPLS: bool = true;\n }\n >::IMPLS\n } {\n Some(|src, dst| unsafe {\n use ::facet_core::spez::*;\n (&&Spez(src)).spez_clone_into(dst.into()).as_mut()\n })\n } else {\n None\n }\n })\n .marker_traits(|| {\n let mut traits = ::facet_core::MarkerTraits::empty();\n if {\n /// Fallback trait with `False` for `IMPLS` if the type does not\n /// implement the given trait.\n trait DoesNotImpl {\n const IMPLS: bool = false;\n }\n impl DoesNotImpl for T {}\n /// Concrete type with `True` for `IMPLS` if the type implements the\n /// given trait. Otherwise, it falls back to `DoesNotImpl`.\n struct Wrapper(::core::marker::PhantomData);\n #[allow(dead_code)]\n impl Wrapper {\n const IMPLS: bool = true;\n }\n >::IMPLS\n } {\n traits = traits.union(::facet_core::MarkerTraits::EQ);\n }\n if {\n /// Fallback trait with `False` for `IMPLS` if the type does not\n /// implement the given trait.\n trait DoesNotImpl {\n const IMPLS: bool = false;\n }\n impl DoesNotImpl for T {}\n /// Concrete type with `True` for `IMPLS` if the type implements the\n /// given trait. Otherwise, it falls back to `DoesNotImpl`.\n struct Wrapper(::core::marker::PhantomData);\n #[allow(dead_code)]\n impl Wrapper {\n const IMPLS: bool = true;\n }\n >::IMPLS\n } {\n traits = traits.union(::facet_core::MarkerTraits::SEND);\n }\n if {\n /// Fallback trait with `False` for `IMPLS` if the type does not\n /// implement the given trait.\n trait DoesNotImpl {\n const IMPLS: bool = false;\n }\n impl DoesNotImpl for T {}\n /// Concrete type with `True` for `IMPLS` if the type implements the\n /// given trait. Otherwise, it falls back to `DoesNotImpl`.\n struct Wrapper(::core::marker::PhantomData);\n #[allow(dead_code)]\n impl Wrapper {\n const IMPLS: bool = true;\n }\n >::IMPLS\n } {\n traits = traits.union(::facet_core::MarkerTraits::SYNC);\n }\n if {\n /// Fallback trait with `False` for `IMPLS` if the type does not\n /// implement the given trait.\n trait DoesNotImpl {\n const IMPLS: bool = false;\n }\n impl DoesNotImpl for T {}\n /// Concrete type with `True` for `IMPLS` if the type implements the\n /// given trait. Otherwise, it falls back to `DoesNotImpl`.\n struct Wrapper(::core::marker::PhantomData);\n #[allow(dead_code)]\n impl Wrapper {\n const IMPLS: bool = true;\n }\n >::IMPLS\n } {\n traits = traits.union(::facet_core::MarkerTraits::COPY);\n }\n if {\n /// Fallback trait with `False` for `IMPLS` if the type does not\n /// implement the given trait.\n trait DoesNotImpl {\n const IMPLS: bool = false;\n }\n impl DoesNotImpl for T {}\n /// Concrete type with `True` for `IMPLS` if the type implements the\n /// given trait. Otherwise, it falls back to `DoesNotImpl`.\n struct Wrapper(::core::marker::PhantomData);\n #[allow(dead_code)]\n impl Wrapper {\n const IMPLS: bool = true;\n }\n >::IMPLS\n } {\n traits = traits.union(::facet_core::MarkerTraits::UNPIN);\n }\n if {\n /// Fallback trait with `False` for `IMPLS` if the type does not\n /// implement the given trait.\n trait DoesNotImpl {\n const IMPLS: bool = false;\n }\n impl DoesNotImpl for T {}\n /// Concrete type with `True` for `IMPLS` if the type implements the\n /// given trait. Otherwise, it falls back to `DoesNotImpl`.\n struct Wrapper(::core::marker::PhantomData);\n #[allow(dead_code)]\n impl Wrapper {\n const IMPLS: bool = true;\n }\n >::IMPLS\n } {\n traits = traits.union(::facet_core::MarkerTraits::UNWIND_SAFE);\n }\n if {\n /// Fallback trait with `False` for `IMPLS` if the type does not\n /// implement the given trait.\n trait DoesNotImpl {\n const IMPLS: bool = false;\n }\n impl DoesNotImpl for T {}\n /// Concrete type with `True` for `IMPLS` if the type implements the\n /// given trait. Otherwise, it falls back to `DoesNotImpl`.\n struct Wrapper(::core::marker::PhantomData);\n #[allow(dead_code)]\n impl Wrapper {\n const IMPLS: bool = true;\n }\n >::IMPLS\n } {\n traits = traits.union(::facet_core::MarkerTraits::REF_UNWIND_SAFE);\n }\n traits\n })\n .partial_eq(|| {\n if {\n /// Fallback trait with `False` for `IMPLS` if the type does not\n /// implement the given trait.\n trait DoesNotImpl {\n const IMPLS: bool = false;\n }\n impl DoesNotImpl for T {}\n /// Concrete type with `True` for `IMPLS` if the type implements the\n /// given trait. Otherwise, it falls back to `DoesNotImpl`.\n struct Wrapper(::core::marker::PhantomData);\n #[allow(dead_code)]\n impl Wrapper {\n const IMPLS: bool = true;\n }\n >::IMPLS\n } {\n Some(|left, right| {\n use ::facet_core::spez::*;\n (&&Spez(left)).spez_partial_eq(&&Spez(right))\n })\n } else {\n None\n }\n })\n .partial_ord(|| {\n if {\n /// Fallback trait with `False` for `IMPLS` if the type does not\n /// implement the given trait.\n trait DoesNotImpl {\n const IMPLS: bool = false;\n }\n impl DoesNotImpl for T {}\n /// Concrete type with `True` for `IMPLS` if the type implements the\n /// given trait. Otherwise, it falls back to `DoesNotImpl`.\n struct Wrapper(::core::marker::PhantomData);\n #[allow(dead_code)]\n impl Wrapper {\n const IMPLS: bool = true;\n }\n >::IMPLS\n } {\n Some(|left, right| {\n use ::facet_core::spez::*;\n (&&Spez(left)).spez_partial_cmp(&&Spez(right))\n })\n } else {\n None\n }\n })\n .ord(|| {\n if {\n /// Fallback trait with `False` for `IMPLS` if the type does not\n /// implement the given trait.\n trait DoesNotImpl {\n const IMPLS: bool = false;\n }\n impl DoesNotImpl for T {}\n /// Concrete type with `True` for `IMPLS` if the type implements the\n /// given trait. Otherwise, it falls back to `DoesNotImpl`.\n struct Wrapper(::core::marker::PhantomData);\n #[allow(dead_code)]\n impl Wrapper {\n const IMPLS: bool = true;\n }\n >::IMPLS\n } {\n Some(|left, right| {\n use ::facet_core::spez::*;\n (&&Spez(left)).spez_cmp(&&Spez(right))\n })\n } else {\n None\n }\n })\n .hash(|| {\n if {\n /// Fallback trait with `False` for `IMPLS` if the type does not\n /// implement the given trait.\n trait DoesNotImpl {\n const IMPLS: bool = false;\n }\n impl DoesNotImpl for T {}\n /// Concrete type with `True` for `IMPLS` if the type implements the\n /// given trait. Otherwise, it falls back to `DoesNotImpl`.\n struct Wrapper(::core::marker::PhantomData);\n #[allow(dead_code)]\n impl Wrapper {\n const IMPLS: bool = true;\n }\n >::IMPLS\n } {\n Some(|value, hasher_this, hasher_write_fn| {\n use ::facet_core::HasherProxy;\n use ::facet_core::spez::*;\n (&&Spez(value)).spez_hash(&mut unsafe {\n HasherProxy::new(hasher_this, hasher_write_fn)\n })\n })\n } else {\n None\n }\n })\n .parse(|| {\n if {\n /// Fallback trait with `False` for `IMPLS` if the type does not\n /// implement the given trait.\n trait DoesNotImpl {\n const IMPLS: bool = false;\n }\n impl DoesNotImpl for T {}\n /// Concrete type with `True` for `IMPLS` if the type implements the\n /// given trait. Otherwise, it falls back to `DoesNotImpl`.\n struct Wrapper(::core::marker::PhantomData);\n #[allow(dead_code)]\n impl Wrapper {\n const IMPLS: bool = true;\n }\n >::IMPLS\n } {\n Some(|s, target| {\n use ::facet_core::spez::*;\n let res =\n unsafe { (&&SpezEmpty::::SPEZ).spez_parse(s, target.into()) };\n res.map(|res| unsafe { res.as_mut() })\n })\n } else {\n None\n }\n })\n .build()\n }\n };\n const SHAPE: &'static crate::Shape = &const {\n #[repr(C)]\n #[allow(non_snake_case, dead_code)]\n struct __Shadow_RustRepr_Tuple_for_SubEnum_OptionB<'__facet> {\n _discriminant: u8,\n _phantom: ::core::marker::PhantomData<(*mut &'__facet ())>,\n _0: u8,\n }\n #[repr(C)]\n #[allow(non_snake_case, dead_code)]\n struct __Shadow_RustRepr_Tuple_for_SubEnum_SensitiveOption<'__facet> {\n _discriminant: u8,\n _phantom: ::core::marker::PhantomData<(*mut &'__facet ())>,\n _0: u64,\n }\n #[repr(C)]\n #[allow(non_snake_case, dead_code)]\n struct __Shadow_RustRepr_Tuple_for_SubEnum_ArbitraryOption<'__facet> {\n _discriminant: u8,\n _phantom: ::core::marker::PhantomData<(*mut &'__facet ())>,\n _0: u8,\n }\n let __facet_variants: &'static [crate::Variant] = &const {\n [\n crate::Variant::builder()\n .name(\"OptionA\")\n .discriminant(0i64 as i64)\n .data(\n crate::StructType::builder()\n .repr(crate::Repr::c())\n .unit()\n .build(),\n )\n .doc(&[\" Option A.\"])\n .build(),\n {\n let fields: &'static [crate::Field] = &const {\n [{\n crate::Field::builder().name(\"0\").shape(crate::shape_of(&(|s:\n &__Shadow_RustRepr_Tuple_for_SubEnum_OptionB<'__facet>|\n &s._0))).offset({\n builtin # offset_of(__Shadow_RustRepr_Tuple_for_SubEnum_OptionB<'__facet>,\n _0)\n }).build()\n }]\n };\n crate::Variant::builder()\n .name(\"OptionB\")\n .discriminant(1i64 as i64)\n .data(\n crate::StructType::builder()\n .repr(crate::Repr::c())\n .tuple()\n .fields(fields)\n .build(),\n )\n .doc(&[\" Option B with data.\"])\n .build()\n },\n {\n let fields: &'static [crate::Field] = &const {\n [{\n crate::Field::builder().name(\"0\").shape(crate::shape_of(&(|s:\n &__Shadow_RustRepr_Tuple_for_SubEnum_SensitiveOption<'__facet>|\n &s._0))).offset({\n builtin # offset_of(__Shadow_RustRepr_Tuple_for_SubEnum_SensitiveOption<'__facet>,\n _0)\n }).build()\n }]\n };\n crate::Variant::builder()\n .name(\"SensitiveOption\")\n .discriminant(2i64 as i64)\n .data(\n crate::StructType::builder()\n .repr(crate::Repr::c())\n .tuple()\n .fields(fields)\n .build(),\n )\n .doc(&[\" A sensitive option.\"])\n .build()\n },\n {\n let fields: &'static [crate::Field] = &const {\n [{\n crate::Field::builder().name(\"0\").shape(crate::shape_of(&(|s:\n &__Shadow_RustRepr_Tuple_for_SubEnum_ArbitraryOption<'__facet>|\n &s._0))).offset({\n builtin # offset_of(__Shadow_RustRepr_Tuple_for_SubEnum_ArbitraryOption<'__facet>,\n _0)\n }).build()\n }]\n };\n crate::Variant::builder()\n .name(\"ArbitraryOption\")\n .attributes(&[crate::VariantAttribute::Arbitrary(\"arbitrary\")])\n .discriminant(3i64 as i64)\n .data(\n crate::StructType::builder()\n .repr(crate::Repr::c())\n .tuple()\n .fields(fields)\n .build(),\n )\n .doc(&[\" An arbitrary option.\"])\n .build()\n },\n ]\n };\n crate::Shape::builder_for_sized::()\n .type_identifier(\"SubEnum\")\n .ty(crate::Type::User(crate::UserType::Enum(\n crate::EnumType::builder()\n .variants(__facet_variants)\n .repr(crate::Repr::default())\n .enum_repr(crate::EnumRepr::U8)\n .build(),\n )))\n .doc(&[\" A sub-enum used within `KitchenSinkEnum`.\"])\n .build()\n };\n}\n"], ["/facet/facet-core/src/impls_core/scalar.rs", "use crate::value_vtable;\nuse crate::*;\nuse core::num::NonZero;\nuse typeid::ConstTypeId;\n\nunsafe impl Facet<'_> for ConstTypeId {\n const VTABLE: &'static ValueVTable = &const {\n value_vtable!(ConstTypeId, |f, _opts| write!(\n f,\n \"{}\",\n Self::SHAPE.type_identifier\n ))\n };\n\n const SHAPE: &'static Shape = &const {\n Shape::builder_for_sized::()\n .type_identifier(\"ConstTypeId\")\n .def(Def::Scalar)\n .ty(Type::User(UserType::Opaque))\n .build()\n };\n}\n\nunsafe impl Facet<'_> for core::any::TypeId {\n const VTABLE: &'static ValueVTable = &const {\n value_vtable!(core::any::TypeId, |f, _opts| write!(\n f,\n \"{}\",\n Self::SHAPE.type_identifier\n ))\n };\n\n const SHAPE: &'static Shape = &const {\n Shape::builder_for_sized::()\n .type_identifier(\"TypeId\")\n .def(Def::Scalar)\n .ty(Type::User(UserType::Opaque))\n .build()\n };\n}\n\nunsafe impl Facet<'_> for () {\n const VTABLE: &'static ValueVTable = &const { value_vtable!((), |f, _opts| write!(f, \"()\")) };\n\n const SHAPE: &'static Shape = &const {\n Shape::builder_for_sized::()\n .type_identifier(\"()\")\n .ty(Type::User(UserType::Struct(StructType {\n repr: Repr::default(),\n kind: StructKind::Tuple,\n fields: &[],\n })))\n .build()\n };\n}\n\nunsafe impl<'a, T: ?Sized + 'a> Facet<'a> for core::marker::PhantomData {\n // TODO: we might be able to do something with specialization re: the shape of T?\n const VTABLE: &'static ValueVTable =\n &const { value_vtable!((), |f, _opts| write!(f, \"{}\", Self::SHAPE.type_identifier)) };\n\n const SHAPE: &'static Shape = &const {\n Shape::builder_for_sized::()\n .type_identifier(\"PhantomData\")\n .def(Def::Scalar)\n .ty(Type::User(UserType::Struct(StructType {\n repr: Repr::default(),\n kind: StructKind::Unit,\n fields: &[],\n })))\n .build()\n };\n}\n\nunsafe impl Facet<'_> for char {\n const VTABLE: &'static ValueVTable = &const {\n value_vtable!(char, |f, _opts| write!(\n f,\n \"{}\",\n Self::SHAPE.type_identifier\n ))\n };\n\n const SHAPE: &'static Shape = &const {\n Shape::builder_for_sized::()\n .type_identifier(\"char\")\n .def(Def::Scalar)\n .ty(Type::Primitive(PrimitiveType::Textual(TextualType::Char)))\n .build()\n };\n}\n\nunsafe impl Facet<'_> for str {\n const VTABLE: &'static ValueVTable = &const {\n value_vtable_unsized!(str, |f, _opts| write!(f, \"{}\", Self::SHAPE.type_identifier))\n };\n\n const SHAPE: &'static Shape = &const {\n Shape::builder_for_unsized::()\n .type_identifier(\"str\")\n .ty(Type::Primitive(PrimitiveType::Textual(TextualType::Str)))\n .def(Def::Scalar)\n .build()\n };\n}\n\nunsafe impl Facet<'_> for bool {\n const VTABLE: &'static ValueVTable = &const {\n value_vtable!(bool, |f, _opts| write!(\n f,\n \"{}\",\n Self::SHAPE.type_identifier\n ))\n };\n\n const SHAPE: &'static Shape = &const {\n Shape::builder_for_sized::()\n .type_identifier(\"bool\")\n .def(Def::Scalar)\n .ty(Type::Primitive(PrimitiveType::Boolean))\n .build()\n };\n}\n\nmacro_rules! impl_facet_for_integer {\n ($type:ty) => {\n unsafe impl<'a> Facet<'a> for $type {\n const VTABLE: &'static ValueVTable = &const {\n value_vtable!($type, |f, _opts| write!(\n f,\n \"{}\",\n Self::SHAPE.type_identifier\n ))\n };\n\n const SHAPE: &'static Shape = &const {\n Shape::builder_for_sized::()\n .type_identifier(stringify!($type))\n .ty(Type::Primitive(PrimitiveType::Numeric(\n NumericType::Integer {\n signed: (1 as $type).checked_neg().is_some(),\n },\n )))\n .def(Def::Scalar)\n .build()\n };\n }\n\n unsafe impl<'a> Facet<'a> for NonZero<$type> {\n const VTABLE: &'static ValueVTable = &const {\n // Define conversion functions for transparency\n unsafe fn try_from<'dst>(\n src_ptr: PtrConst<'_>,\n src_shape: &'static Shape,\n dst: PtrUninit<'dst>,\n ) -> Result, TryFromError> {\n if src_shape == <$type as Facet>::SHAPE {\n // Get the inner value and check that it's non-zero\n let value = unsafe { *src_ptr.get::<$type>() };\n let nz = NonZero::new(value)\n .ok_or_else(|| TryFromError::Generic(\"value should be non-zero\"))?;\n\n // Put the NonZero value into the destination\n Ok(unsafe { dst.put(nz) })\n } else {\n let inner_try_from =\n (<$type as Facet>::SHAPE.vtable.sized().unwrap().try_from)().ok_or(\n TryFromError::UnsupportedSourceShape {\n src_shape,\n expected: &[<$type as Facet>::SHAPE],\n },\n )?;\n\n // fallback to inner's try_from\n // This relies on the fact that `dst` is the same size as `NonZero<$type>`\n // which should be true because `NonZero` is `repr(transparent)`\n let inner_result = unsafe { (inner_try_from)(src_ptr, src_shape, dst) };\n match inner_result {\n Ok(result) => {\n // After conversion to inner type, wrap as NonZero\n let value = unsafe { *result.get::<$type>() };\n let nz = NonZero::new(value).ok_or_else(|| {\n TryFromError::Generic(\"value should be non-zero\")\n })?;\n Ok(unsafe { dst.put(nz) })\n }\n Err(e) => Err(e),\n }\n }\n }\n\n unsafe fn try_into_inner<'dst>(\n src_ptr: PtrMut<'_>,\n dst: PtrUninit<'dst>,\n ) -> Result, TryIntoInnerError> {\n // Get the NonZero value and extract the inner value\n let nz = unsafe { *src_ptr.get::>() };\n // Put the inner value into the destination\n Ok(unsafe { dst.put(nz.get()) })\n }\n\n unsafe fn try_borrow_inner(\n src_ptr: PtrConst<'_>,\n ) -> Result, TryBorrowInnerError> {\n // NonZero has the same memory layout as T, so we can return the input pointer directly\n Ok(src_ptr)\n }\n\n let mut vtable = value_vtable!($type, |f, _opts| write!(\n f,\n \"{}<{}>\",\n Self::SHAPE.type_identifier,\n stringify!($type)\n ));\n\n // Add our new transparency functions\n {\n let vtable_sized = vtable.sized_mut().unwrap();\n vtable_sized.try_from = || Some(try_from);\n vtable_sized.try_into_inner = || Some(try_into_inner);\n vtable_sized.try_borrow_inner = || Some(try_borrow_inner);\n }\n\n vtable\n };\n\n const SHAPE: &'static Shape = &const {\n // Function to return inner type's shape\n fn inner_shape() -> &'static Shape {\n <$type as Facet>::SHAPE\n }\n\n Shape::builder_for_sized::()\n .type_identifier(\"NonZero\")\n .def(Def::Scalar)\n .ty(Type::User(UserType::Struct(StructType {\n repr: Repr::transparent(),\n kind: StructKind::TupleStruct,\n fields: &const {\n [Field::builder()\n .name(\"0\")\n // TODO: is it correct to represent $type here, when we, in\n // fact, store $type::NonZeroInner.\n .shape(<$type>::SHAPE)\n .offset(0)\n .flags(FieldFlags::EMPTY)\n .build()]\n },\n })))\n .inner(inner_shape)\n .build()\n };\n }\n };\n}\n\nimpl_facet_for_integer!(u8);\nimpl_facet_for_integer!(i8);\nimpl_facet_for_integer!(u16);\nimpl_facet_for_integer!(i16);\nimpl_facet_for_integer!(u32);\nimpl_facet_for_integer!(i32);\nimpl_facet_for_integer!(u64);\nimpl_facet_for_integer!(i64);\nimpl_facet_for_integer!(u128);\nimpl_facet_for_integer!(i128);\nimpl_facet_for_integer!(usize);\nimpl_facet_for_integer!(isize);\n\nunsafe impl Facet<'_> for f32 {\n const VTABLE: &'static ValueVTable =\n &const { value_vtable!(f32, |f, _opts| write!(f, \"{}\", Self::SHAPE.type_identifier)) };\n\n const SHAPE: &'static Shape = &const {\n Shape::builder_for_sized::()\n .type_identifier(\"f32\")\n .ty(Type::Primitive(PrimitiveType::Numeric(NumericType::Float)))\n .def(Def::Scalar)\n .build()\n };\n}\n\nunsafe impl Facet<'_> for f64 {\n const VTABLE: &'static ValueVTable = &const {\n let mut vtable =\n value_vtable!(f64, |f, _opts| write!(f, \"{}\", Self::SHAPE.type_identifier));\n\n {\n let vtable_sized = vtable.sized_mut().unwrap();\n vtable_sized.try_from = || {\n Some(|source, source_shape, dest| {\n if source_shape == Self::SHAPE {\n return Ok(unsafe { dest.copy_from(source, source_shape)? });\n }\n if source_shape == u64::SHAPE {\n let value: u64 = *unsafe { source.get::() };\n let converted: f64 = value as f64;\n return Ok(unsafe { dest.put::(converted) });\n }\n if source_shape == i64::SHAPE {\n let value: i64 = *unsafe { source.get::() };\n let converted: f64 = value as f64;\n return Ok(unsafe { dest.put::(converted) });\n }\n if source_shape == f32::SHAPE {\n let value: f32 = *unsafe { source.get::() };\n let converted: f64 = value as f64;\n return Ok(unsafe { dest.put::(converted) });\n }\n Err(TryFromError::UnsupportedSourceShape {\n src_shape: source_shape,\n expected: &[Self::SHAPE, u64::SHAPE, i64::SHAPE, f32::SHAPE],\n })\n })\n };\n }\n\n vtable\n };\n\n const SHAPE: &'static Shape = &const {\n Shape::builder_for_sized::()\n .type_identifier(\"f64\")\n .ty(Type::Primitive(PrimitiveType::Numeric(NumericType::Float)))\n .def(Def::Scalar)\n .build()\n };\n}\n\nunsafe impl Facet<'_> for core::net::SocketAddr {\n const VTABLE: &'static ValueVTable = &const {\n value_vtable!(core::net::SocketAddr, |f, _opts| write!(\n f,\n \"{}\",\n Self::SHAPE.type_identifier\n ))\n };\n\n const SHAPE: &'static Shape = &const {\n Shape::builder_for_sized::()\n .type_identifier(\"SocketAddr\")\n .ty(Type::User(UserType::Opaque))\n .def(Def::Scalar)\n .build()\n };\n}\n\nunsafe impl Facet<'_> for core::net::IpAddr {\n const VTABLE: &'static ValueVTable = &const {\n value_vtable!(core::net::IpAddr, |f, _opts| write!(\n f,\n \"{}\",\n Self::SHAPE.type_identifier\n ))\n };\n\n const SHAPE: &'static Shape = &const {\n Shape::builder_for_sized::()\n .type_identifier(\"IpAddr\")\n .ty(Type::User(UserType::Opaque))\n .def(Def::Scalar)\n .build()\n };\n}\n\nunsafe impl Facet<'_> for core::net::Ipv4Addr {\n const VTABLE: &'static ValueVTable = &const {\n value_vtable!(core::net::Ipv4Addr, |f, _opts| write!(\n f,\n \"{}\",\n Self::SHAPE.type_identifier\n ))\n };\n\n const SHAPE: &'static Shape = &const {\n Shape::builder_for_sized::()\n .type_identifier(\"Ipv4Addr\")\n .ty(Type::User(UserType::Opaque))\n .def(Def::Scalar)\n .build()\n };\n}\n\nunsafe impl Facet<'_> for core::net::Ipv6Addr {\n const VTABLE: &'static ValueVTable = &const {\n value_vtable!(core::net::Ipv6Addr, |f, _opts| write!(\n f,\n \"{}\",\n Self::SHAPE.type_identifier\n ))\n };\n\n const SHAPE: &'static Shape = &const {\n Shape::builder_for_sized::()\n .type_identifier(\"Ipv6Addr\")\n .ty(Type::User(UserType::Opaque))\n .def(Def::Scalar)\n .build()\n };\n}\n"], ["/facet/facet-core/src/impls_core/pointer.rs", "use core::fmt;\n\nuse crate::{\n Facet, MarkerTraits, PointerType, Shape, Type, TypeParam, ValuePointerType, ValueVTable,\n};\n\n// *const pointers\nunsafe impl<'a, T: Facet<'a> + ?Sized> Facet<'a> for *const T {\n const VTABLE: &'static ValueVTable = &const {\n ValueVTable::builder::()\n .marker_traits(|| {\n let mut marker_traits = MarkerTraits::EQ\n .union(MarkerTraits::COPY)\n .union(MarkerTraits::UNPIN);\n\n if T::SHAPE\n .vtable\n .marker_traits()\n .contains(MarkerTraits::REF_UNWIND_SAFE)\n {\n marker_traits = marker_traits\n .union(MarkerTraits::UNWIND_SAFE)\n .union(MarkerTraits::REF_UNWIND_SAFE);\n }\n\n marker_traits\n })\n .debug(|| Some(fmt::Debug::fmt))\n .clone_into(|| Some(|src, dst| unsafe { dst.put(*src) }))\n .type_name(|f, opts| {\n if let Some(opts) = opts.for_children() {\n write!(f, \"*const \")?;\n (T::VTABLE.type_name())(f, opts)\n } else {\n write!(f, \"*const ⋯\")\n }\n })\n .build()\n };\n\n const SHAPE: &'static Shape = &const {\n Shape::builder_for_sized::()\n .inner(|| T::SHAPE)\n .type_identifier(\"*const _\")\n .type_params(&[TypeParam {\n name: \"T\",\n shape: || T::SHAPE,\n }])\n .ty({\n let is_wide = ::core::mem::size_of::() != ::core::mem::size_of::<*const ()>();\n let vpt = ValuePointerType {\n mutable: false,\n wide: is_wide,\n target: || T::SHAPE,\n };\n\n Type::Pointer(PointerType::Raw(vpt))\n })\n .build()\n };\n}\n\n// *mut pointers\nunsafe impl<'a, T: Facet<'a> + ?Sized> Facet<'a> for *mut T {\n const VTABLE: &'static ValueVTable = &const {\n ValueVTable::builder::()\n .marker_traits(|| {\n let mut marker_traits = MarkerTraits::EQ\n .union(MarkerTraits::COPY)\n .union(MarkerTraits::UNPIN);\n\n if T::SHAPE\n .vtable\n .marker_traits()\n .contains(MarkerTraits::REF_UNWIND_SAFE)\n {\n marker_traits = marker_traits\n .union(MarkerTraits::UNWIND_SAFE)\n .union(MarkerTraits::REF_UNWIND_SAFE);\n }\n\n marker_traits\n })\n .debug(|| Some(fmt::Debug::fmt))\n .clone_into(|| Some(|src, dst| unsafe { dst.put(*src) }))\n .type_name(|f, opts| {\n if let Some(opts) = opts.for_children() {\n write!(f, \"*mut \")?;\n (T::VTABLE.type_name())(f, opts)\n } else {\n write!(f, \"*mut ⋯\")\n }\n })\n .build()\n };\n\n const SHAPE: &'static Shape = &const {\n Shape::builder_for_sized::()\n .inner(|| T::SHAPE)\n .type_identifier(\"*mut _\")\n .type_params(&[TypeParam {\n name: \"T\",\n shape: || T::SHAPE,\n }])\n .ty({\n let is_wide = ::core::mem::size_of::() != ::core::mem::size_of::<*const ()>();\n let vpt = ValuePointerType {\n mutable: true,\n wide: is_wide,\n target: || T::SHAPE,\n };\n\n Type::Pointer(PointerType::Raw(vpt))\n })\n .build()\n };\n}\n\n#[cfg(test)]\nmod test {\n use core::panic::{RefUnwindSafe, UnwindSafe};\n use impls::impls;\n\n #[allow(unused)]\n const fn assert_impls_unwind_safe() {}\n #[allow(unused)]\n const fn assert_impls_ref_unwind_safe() {}\n\n #[allow(unused)]\n const fn ref_unwind_safe() {\n assert_impls_unwind_safe::<&T>();\n assert_impls_ref_unwind_safe::<&T>();\n\n assert_impls_ref_unwind_safe::<&mut T>();\n\n assert_impls_unwind_safe::<*const T>();\n assert_impls_ref_unwind_safe::<*const T>();\n\n assert_impls_unwind_safe::<*mut T>();\n assert_impls_ref_unwind_safe::<*mut T>();\n }\n\n #[test]\n fn mut_ref_not_unwind_safe() {\n assert!(impls!(&mut (): !UnwindSafe));\n }\n}\n"], ["/facet/facet-core/src/impls_ordered_float.rs", "use crate::{\n Def, Facet, PtrConst, PtrMut, PtrUninit, Repr, Shape, StructType, TryBorrowInnerError,\n TryFromError, TryIntoInnerError, Type, UserType, ValueVTable, field_in_type, value_vtable,\n};\nuse ordered_float::{NotNan, OrderedFloat};\n\nmacro_rules! impl_facet_for_ordered_float_and_notnan {\n ($float:ty) => {\n unsafe impl<'a> Facet<'a> for OrderedFloat<$float> {\n const VTABLE: &'static ValueVTable = &const {\n // Define conversion functions for transparency\n unsafe fn try_from<'dst>(\n src_ptr: PtrConst<'_>,\n src_shape: &'static Shape,\n dst: PtrUninit<'dst>,\n ) -> Result, TryFromError> {\n if src_shape == <$float as Facet>::SHAPE {\n // Get the inner value and wrap as OrderedFloat\n let value = unsafe { src_ptr.get::<$float>() };\n let ord = OrderedFloat(*value);\n Ok(unsafe { dst.put(ord) })\n } else {\n let inner_try_from =\n (<$float as Facet>::SHAPE.vtable.sized().unwrap().try_from)().ok_or(\n TryFromError::UnsupportedSourceShape {\n src_shape,\n expected: &[<$float as Facet>::SHAPE],\n },\n )?;\n // fallback to inner's try_from\n // This relies on the fact that `dst` is the same size as `OrderedFloat<$float>`\n // which should be true because `OrderedFloat` is `repr(transparent)`\n let inner_result = unsafe { (inner_try_from)(src_ptr, src_shape, dst) };\n match inner_result {\n Ok(result) => {\n // After conversion to inner type, wrap as OrderedFloat\n let value = unsafe { result.read::<$float>() };\n let ord = OrderedFloat(value);\n Ok(unsafe { dst.put(ord) })\n }\n Err(e) => Err(e),\n }\n }\n }\n\n // Conversion back to inner float type\n unsafe fn try_into_inner<'dst>(\n src_ptr: PtrMut<'_>,\n dst: PtrUninit<'dst>,\n ) -> Result, TryIntoInnerError> {\n let v = unsafe { src_ptr.read::>() };\n Ok(unsafe { dst.put(v.0) })\n }\n\n // Borrow inner float type\n unsafe fn try_borrow_inner(\n src_ptr: PtrConst<'_>,\n ) -> Result, TryBorrowInnerError> {\n let v = unsafe { src_ptr.get::>() };\n Ok(PtrConst::new((&v.0) as *const $float as *const u8))\n }\n\n let mut vtable =\n value_vtable!((), |f, _opts| write!(f, \"{}\", Self::SHAPE.type_identifier));\n {\n let vtable = vtable.sized_mut().unwrap();\n vtable.parse = || {\n // `OrderedFloat` is `repr(transparent)`\n (<$float as Facet>::SHAPE.vtable.sized().unwrap().parse)()\n };\n vtable.try_from = || Some(try_from);\n vtable.try_into_inner = || Some(try_into_inner);\n vtable.try_borrow_inner = || Some(try_borrow_inner);\n }\n vtable\n };\n\n const SHAPE: &'static Shape = &const {\n fn inner_shape() -> &'static Shape {\n <$float as Facet>::SHAPE\n }\n\n Shape::builder_for_sized::()\n .type_identifier(\"OrderedFloat\")\n .ty(Type::User(UserType::Struct(\n StructType::builder()\n .repr(Repr::transparent())\n .fields(&const { [field_in_type!(Self, 0)] })\n .kind(crate::StructKind::Tuple)\n .build(),\n )))\n .def(Def::Scalar)\n .inner(inner_shape)\n .build()\n };\n }\n\n unsafe impl<'a> Facet<'a> for NotNan<$float> {\n const VTABLE: &'static ValueVTable = &const {\n // Conversion from inner float type to NotNan<$float>\n unsafe fn try_from<'dst>(\n src_ptr: PtrConst<'_>,\n src_shape: &'static Shape,\n dst: PtrUninit<'dst>,\n ) -> Result, TryFromError> {\n if src_shape == <$float as Facet>::SHAPE {\n // Get the inner value and check that it's not NaN\n let value = unsafe { *src_ptr.get::<$float>() };\n let nn =\n NotNan::new(value).map_err(|_| TryFromError::Generic(\"was NaN\"))?;\n Ok(unsafe { dst.put(nn) })\n } else {\n let inner_try_from =\n (<$float as Facet>::SHAPE.vtable.sized().unwrap().try_from)().ok_or(\n TryFromError::UnsupportedSourceShape {\n src_shape,\n expected: &[<$float as Facet>::SHAPE],\n },\n )?;\n\n // fallback to inner's try_from\n // This relies on the fact that `dst` is the same size as `NotNan<$float>`\n // which should be true because `NotNan` is `repr(transparent)`\n let inner_result = unsafe { (inner_try_from)(src_ptr, src_shape, dst) };\n match inner_result {\n Ok(result) => {\n // After conversion to inner type, wrap as NotNan\n let value = unsafe { *result.get::<$float>() };\n let nn = NotNan::new(value)\n .map_err(|_| TryFromError::Generic(\"was NaN\"))?;\n Ok(unsafe { dst.put(nn) })\n }\n Err(e) => Err(e),\n }\n }\n }\n\n // Conversion back to inner float type\n unsafe fn try_into_inner<'dst>(\n src_ptr: PtrMut<'_>,\n dst: PtrUninit<'dst>,\n ) -> Result, TryIntoInnerError> {\n let v = unsafe { src_ptr.read::>() };\n Ok(unsafe { dst.put(v.into_inner()) })\n }\n\n // Borrow inner float type\n unsafe fn try_borrow_inner(\n src_ptr: PtrConst<'_>,\n ) -> Result, TryBorrowInnerError> {\n let v = unsafe { src_ptr.get::>() };\n Ok(PtrConst::new(\n (&v.into_inner()) as *const $float as *const u8,\n ))\n }\n\n let mut vtable =\n value_vtable!((), |f, _opts| write!(f, \"{}\", Self::SHAPE.type_identifier));\n // Accept parsing as inner T, but enforce NotNan invariant\n {\n let vtable = vtable.sized_mut().unwrap();\n vtable.parse = || {\n Some(|s, target| match s.parse::<$float>() {\n Ok(inner) => match NotNan::new(inner) {\n Ok(not_nan) => Ok(unsafe { target.put(not_nan) }),\n Err(_) => {\n Err(crate::ParseError::Generic(\"NaN is not allowed for NotNan\"))\n }\n },\n Err(_) => Err(crate::ParseError::Generic(\n \"Failed to parse inner type for NotNan\",\n )),\n })\n };\n vtable.try_from = || Some(try_from);\n vtable.try_into_inner = || Some(try_into_inner);\n vtable.try_borrow_inner = || Some(try_borrow_inner);\n }\n vtable\n };\n\n const SHAPE: &'static Shape = &const {\n fn inner_shape() -> &'static Shape {\n <$float as Facet>::SHAPE\n }\n\n Shape::builder_for_sized::()\n .type_identifier(\"NotNan\")\n .ty(Type::User(UserType::Opaque))\n .def(Def::Scalar)\n .inner(inner_shape)\n .build()\n };\n }\n };\n}\n\nimpl_facet_for_ordered_float_and_notnan!(f32);\nimpl_facet_for_ordered_float_and_notnan!(f64);\n"], ["/facet/facet-macros-emit/src/lib.rs", "use facet_macros_parse::*;\n\nmod renamerule;\npub use renamerule::*;\n\nmod generics;\npub use generics::*;\n\nmod parsed;\npub use parsed::*;\n\nmod process_enum;\nmod process_struct;\n\nmod derive;\npub use derive::*;\n\n#[cfg(feature = \"function\")]\npub mod function;\n\n#[derive(Clone)]\npub struct LifetimeName(pub facet_macros_parse::Ident);\n\nimpl quote::ToTokens for LifetimeName {\n fn to_tokens(&self, tokens: &mut TokenStream) {\n let punct = facet_macros_parse::TokenTree::Punct(facet_macros_parse::Punct::new(\n '\\'',\n facet_macros_parse::Spacing::Joint,\n ));\n let name = &self.0;\n tokens.extend(quote::quote! {\n #punct #name\n });\n }\n}\n"], ["/facet/facet-core/src/impls_uuid.rs", "use alloc::string::String;\nuse alloc::string::ToString;\n\nuse uuid::Uuid;\n\nuse crate::{\n Def, Facet, ParseError, PtrConst, PtrMut, PtrUninit, Shape, TryFromError, TryIntoInnerError,\n Type, UserType, ValueVTable, value_vtable,\n};\n\nunsafe impl Facet<'_> for Uuid {\n const VTABLE: &'static ValueVTable = &const {\n // Functions to transparently convert between Uuid and String\n unsafe fn try_from<'dst>(\n src_ptr: PtrConst<'_>,\n src_shape: &'static Shape,\n dst: PtrUninit<'dst>,\n ) -> Result, TryFromError> {\n if src_shape.id != ::SHAPE.id {\n return Err(TryFromError::UnsupportedSourceShape {\n src_shape,\n expected: &[::SHAPE],\n });\n }\n let s = unsafe { src_ptr.read::() };\n match Uuid::parse_str(&s) {\n Ok(uuid) => Ok(unsafe { dst.put(uuid) }),\n Err(_) => Err(TryFromError::UnsupportedSourceShape {\n src_shape,\n expected: &[::SHAPE],\n }),\n }\n }\n\n unsafe fn try_into_inner<'dst>(\n src_ptr: PtrMut<'_>,\n dst: PtrUninit<'dst>,\n ) -> Result, TryIntoInnerError> {\n let uuid = unsafe { src_ptr.read::() };\n Ok(unsafe { dst.put(uuid.to_string()) })\n }\n\n let mut vtable = value_vtable!(Uuid, |f, _opts| write!(\n f,\n \"{}\",\n Self::SHAPE.type_identifier\n ));\n {\n let vtable = vtable.sized_mut().unwrap();\n vtable.parse = || {\n Some(|s, target| match Uuid::parse_str(s) {\n Ok(uuid) => Ok(unsafe { target.put(uuid) }),\n Err(_) => Err(ParseError::Generic(\"UUID parsing failed\")),\n })\n };\n vtable.try_from = || Some(try_from);\n vtable.try_into_inner = || Some(try_into_inner);\n }\n vtable\n };\n\n const SHAPE: &'static Shape = &const {\n // Return the Shape of the inner type (String)\n fn inner_shape() -> &'static Shape {\n ::SHAPE\n }\n\n Shape::builder_for_sized::()\n .type_identifier(\"Uuid\")\n .ty(Type::User(UserType::Opaque))\n .def(Def::Scalar)\n .inner(inner_shape)\n .build()\n };\n}\n"], ["/facet/facet-core/src/ptr.rs", "//! Opaque pointers\n//!\n//! Type-erased pointer helpers for working with reflected values\n\nuse core::{marker::PhantomData, mem::transmute, ptr::NonNull};\n\nuse crate::{Shape, UnsizedError};\n\n/// A type-erased pointer to an uninitialized value\n#[derive(Debug, Clone, Copy)]\n#[repr(transparent)]\npub struct PtrUninit<'mem>(*mut u8, PhantomData<&'mem mut ()>);\n\nimpl<'mem> PtrUninit<'mem> {\n /// Copies memory from a source pointer into this location and returns PtrMut\n ///\n /// # Safety\n ///\n /// - The source pointer must be valid for reads of `len` bytes\n /// - This pointer must be valid for writes of `len` bytes and properly aligned\n /// - The regions may not overlap\n #[inline]\n pub unsafe fn copy_from<'src>(\n self,\n src: PtrConst<'src>,\n shape: &'static Shape,\n ) -> Result, UnsizedError> {\n let layout = shape.layout.sized_layout()?;\n // SAFETY: The caller is responsible for upholding the invariants:\n // - `src` must be valid for reads of `shape.size` bytes\n // - `self` must be valid for writes of `shape.size` bytes and properly aligned\n // - The regions may not overlap\n unsafe {\n core::ptr::copy_nonoverlapping(src.as_byte_ptr(), self.0, layout.size());\n Ok(self.assume_init())\n }\n }\n\n /// Create a new opaque pointer from a mutable pointer\n ///\n /// This is safe because it's generic over T\n #[inline]\n pub fn new(ptr: *mut T) -> Self {\n Self(ptr as *mut u8, PhantomData)\n }\n\n /// Creates a new opaque pointer from a reference to a [`core::mem::MaybeUninit`]\n ///\n /// The pointer will point to the potentially uninitialized contents\n ///\n /// This is safe because it's generic over T\n #[inline]\n pub fn from_maybe_uninit(borrow: &'mem mut core::mem::MaybeUninit) -> Self {\n Self(borrow.as_mut_ptr() as *mut u8, PhantomData)\n }\n\n /// Assumes the pointer is initialized and returns an `Opaque` pointer\n ///\n /// # Safety\n ///\n /// The pointer must actually be pointing to initialized memory of the correct type.\n #[inline]\n pub unsafe fn assume_init(self) -> PtrMut<'mem> {\n let ptr = unsafe { NonNull::new_unchecked(self.0) };\n PtrMut(ptr, PhantomData)\n }\n\n /// Write a value to this location and convert to an initialized pointer\n ///\n /// # Safety\n ///\n /// The pointer must be properly aligned for T and point to allocated memory\n /// that can be safely written to.\n #[inline]\n pub unsafe fn put(self, value: T) -> PtrMut<'mem> {\n unsafe {\n core::ptr::write(self.0 as *mut T, value);\n self.assume_init()\n }\n }\n\n /// Returns the underlying raw pointer as a byte pointer\n #[inline]\n pub fn as_mut_byte_ptr(self) -> *mut u8 {\n self.0\n }\n\n /// Returns the underlying raw pointer as a const byte pointer\n #[inline]\n pub fn as_byte_ptr(self) -> *const u8 {\n self.0\n }\n\n /// Returns a pointer with the given offset added\n ///\n /// # Safety\n ///\n /// Offset is within the bounds of the allocated memory\n pub unsafe fn field_uninit_at(self, offset: usize) -> PtrUninit<'mem> {\n PtrUninit(unsafe { self.0.byte_add(offset) }, PhantomData)\n }\n\n /// Returns a pointer with the given offset added, assuming it's initialized\n ///\n /// # Safety\n ///\n /// The pointer plus offset must be:\n /// - Within bounds of the allocated object\n /// - Properly aligned for the type being pointed to\n /// - Point to initialized data of the correct type\n #[inline]\n pub unsafe fn field_init_at(self, offset: usize) -> PtrMut<'mem> {\n PtrMut(\n unsafe { NonNull::new_unchecked(self.0.add(offset)) },\n PhantomData,\n )\n }\n}\n\nimpl<'mem, T> From> for PtrUninit<'mem> {\n fn from(ptr: TypedPtrUninit<'mem, T>) -> Self {\n PtrUninit::new(ptr.0)\n }\n}\n\n/// A pointer to an uninitialized value with a lifetime.\n#[derive(Debug)]\n#[repr(transparent)]\npub struct TypedPtrUninit<'mem, T>(*mut T, PhantomData<&'mem mut ()>);\n\nimpl<'mem, T> TypedPtrUninit<'mem, T> {\n /// Create a new opaque pointer from a mutable pointer\n ///\n /// This is safe because it's generic over T\n #[inline]\n pub fn new(ptr: *mut T) -> Self {\n Self(ptr, PhantomData)\n }\n\n /// Write a value to this location and convert to an initialized pointer\n ///\n /// # Safety\n ///\n /// The pointer must be properly aligned for T and point to allocated memory\n /// that can be safely written to.\n #[inline]\n pub unsafe fn put(self, value: T) -> &'mem mut T {\n unsafe {\n core::ptr::write(self.0, value);\n self.assume_init()\n }\n }\n /// Assumes the pointer is initialized and returns an `Opaque` pointer\n ///\n /// # Safety\n ///\n /// The pointer must actually be pointing to initialized memory of the correct type.\n #[inline]\n pub unsafe fn assume_init(self) -> &'mem mut T {\n unsafe { &mut *self.0 }\n }\n\n /// Returns a pointer with the given offset added\n ///\n /// # Safety\n ///\n /// Offset is within the bounds of the allocated memory and `U` is the correct type for the field.\n #[inline]\n pub unsafe fn field_uninit_at(&mut self, offset: usize) -> TypedPtrUninit<'mem, U> {\n TypedPtrUninit(unsafe { self.0.byte_add(offset).cast() }, PhantomData)\n }\n}\n\n/// A type-erased read-only pointer to an initialized value.\n///\n/// Cannot be null. May be dangling (for ZSTs)\n#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]\n#[repr(transparent)]\npub struct PtrConst<'mem>(NonNull, PhantomData<&'mem ()>);\n\nunsafe impl Send for PtrConst<'_> {}\nunsafe impl Sync for PtrConst<'_> {}\n\nimpl<'mem> PtrConst<'mem> {\n /// Create a new opaque const pointer from a raw pointer\n ///\n /// # Safety\n ///\n /// The pointer must be non-null, valid, aligned, and point to initialized memory\n /// of the correct type, and be valid for lifetime `'mem`.\n ///\n /// It's encouraged to take the address of something with `&raw const x`, rather than `&x`\n #[inline]\n pub const fn new(ptr: *const T) -> Self {\n unsafe { Self(NonNull::new_unchecked(ptr as *mut u8), PhantomData) }\n }\n\n /// Gets the underlying raw pointer as a byte pointer\n #[inline]\n pub const fn as_byte_ptr(self) -> *const u8 {\n self.0.as_ptr()\n }\n\n /// Gets the underlying raw pointer as a pointer of type T\n ///\n /// # Safety\n ///\n /// Must be called with the original type T that was used to create this pointer\n #[inline]\n pub const unsafe fn as_ptr(self) -> *const T {\n if core::mem::size_of::<*const T>() == core::mem::size_of::<*const u8>() {\n unsafe { core::mem::transmute_copy(&(self.0.as_ptr())) }\n } else {\n panic!(\"cannot!\");\n }\n }\n\n /// Gets the underlying raw pointer as a const pointer of type T\n ///\n /// # Safety\n ///\n /// `T` must be the _actual_ underlying type. You're downcasting with no guardrails.\n #[inline]\n pub const unsafe fn get<'borrow: 'mem, T>(self) -> &'borrow T {\n // TODO: rename to `get`, or something else? it's technically a borrow...\n unsafe { &*(self.0.as_ptr() as *const T) }\n }\n\n /// Returns a pointer with the given offset added\n ///\n /// # Safety\n ///\n /// Offset must be within the bounds of the allocated memory,\n /// and the resulting pointer must be properly aligned.\n #[inline]\n pub const unsafe fn field(self, offset: usize) -> PtrConst<'mem> {\n PtrConst(\n unsafe { NonNull::new_unchecked(self.0.as_ptr().byte_add(offset)) },\n PhantomData,\n )\n }\n\n /// Exposes [`core::ptr::read`]\n ///\n /// # Safety\n ///\n /// `T` must be the actual underlying type of the pointed-to memory.\n /// The memory must be properly initialized and aligned for type `T`.\n #[inline]\n pub const unsafe fn read(self) -> T {\n unsafe { core::ptr::read(self.as_ptr()) }\n }\n}\n\n/// A type-erased pointer to an initialized value\n#[derive(Clone, Copy)]\n#[repr(transparent)]\npub struct PtrMut<'mem>(NonNull, PhantomData<&'mem mut ()>);\n\nimpl<'mem> PtrMut<'mem> {\n /// Create a new opaque pointer from a raw pointer\n ///\n /// # Safety\n ///\n /// The pointer must be valid, aligned, and point to initialized memory\n /// of the correct type, and be valid for lifetime `'mem`.\n ///\n /// It's encouraged to take the address of something with `&raw mut x`, rather than `&x`\n #[inline]\n pub const fn new(ptr: *mut T) -> Self {\n Self(\n unsafe { NonNull::new_unchecked(ptr as *mut u8) },\n PhantomData,\n )\n }\n\n /// Gets the underlying raw pointer\n #[inline]\n pub const fn as_byte_ptr(self) -> *const u8 {\n self.0.as_ptr()\n }\n\n /// Gets the underlying raw pointer as mutable\n #[inline]\n pub const fn as_mut_byte_ptr(self) -> *mut u8 {\n self.0.as_ptr()\n }\n\n /// Gets the underlying raw pointer as a pointer of type T\n ///\n /// # Safety\n ///\n /// Must be called with the original type T that was used to create this pointer\n #[inline]\n pub const unsafe fn as_ptr(self) -> *const T {\n self.0.as_ptr() as *const T\n }\n\n /// Gets the underlying raw pointer as a mutable pointer of type T\n ///\n /// # Safety\n ///\n /// `T` must be the _actual_ underlying type. You're downcasting with no guardrails.\n #[inline]\n pub const unsafe fn as_mut<'borrow: 'mem, T>(self) -> &'borrow mut T {\n unsafe { &mut *(self.0.as_ptr() as *mut T) }\n }\n\n /// Gets the underlying raw pointer as a const pointer of type T\n ///\n /// # Safety\n ///\n /// `T` must be the _actual_ underlying type. You're downcasting with no guardrails.\n /// You must respect AXM (aliasing xor mutability). Holding onto the borrow while\n /// calling as_mut is UB.\n ///\n /// Basically this is UB land. Careful.\n #[inline]\n pub const unsafe fn get<'borrow: 'mem, T>(self) -> &'borrow T {\n unsafe { &*(self.0.as_ptr() as *const T) }\n }\n\n /// Make a const ptr out of this mut ptr\n #[inline]\n pub const fn as_const<'borrow: 'mem>(self) -> PtrConst<'borrow> {\n PtrConst(self.0, PhantomData)\n }\n\n /// Exposes [`core::ptr::read`]\n ///\n /// # Safety\n ///\n /// `T` must be the actual underlying type of the pointed-to memory.\n /// The memory must be properly initialized and aligned for type `T`.\n #[inline]\n pub const unsafe fn read(self) -> T {\n unsafe { core::ptr::read(self.as_mut()) }\n }\n\n /// Exposes [`core::ptr::drop_in_place`]\n ///\n /// # Safety\n ///\n /// `T` must be the actual underlying type of the pointed-to memory.\n /// The memory must be properly initialized and aligned for type `T`.\n /// After calling this function, the memory should not be accessed again\n /// until it is properly reinitialized.\n #[inline]\n pub unsafe fn drop_in_place(self) -> PtrUninit<'mem> {\n unsafe { core::ptr::drop_in_place(self.as_mut::()) }\n PtrUninit(self.0.as_ptr(), PhantomData)\n }\n\n /// Write a value to this location after dropping the existing value\n ///\n /// # Safety\n ///\n /// - The pointer must be properly aligned for T and point to allocated memory\n /// that can be safely written to.\n /// - T must be the actual type of the object being pointed to\n /// - The memory must already be initialized to a valid T value\n #[inline]\n pub unsafe fn replace(self, value: T) -> Self {\n unsafe { self.drop_in_place::().put(value) }\n }\n}\n\n#[derive(Clone, Copy)]\n#[repr(C)]\n/// Wide pointer (fat pointer) structure holding a data pointer and metadata (for unsized types).\nstruct PtrWide {\n ptr: NonNull,\n metadata: usize,\n}\n\nimpl PtrWide {\n const fn from_ptr(ptr: *mut T) -> Self {\n if size_of_val(&ptr) != size_of::() {\n panic!(\"Tried to construct a wide pointer from a thin pointer\");\n }\n let ptr_ref = &ptr;\n let self_ref = unsafe { transmute::<&*mut T, &Self>(ptr_ref) };\n *self_ref\n }\n\n unsafe fn to_ptr(self) -> *mut T {\n if size_of::<*mut T>() != size_of::() {\n panic!(\"Tried to get a wide pointer as a thin pointer\");\n }\n let self_ref = &self;\n let ptr_ref = unsafe { transmute::<&Self, &*mut T>(self_ref) };\n *ptr_ref\n }\n}\n\n/// A type-erased, wide pointer to an uninitialized value.\n///\n/// This can be useful for working with dynamically sized types, like slices or trait objects,\n/// where both a pointer and metadata (such as length or vtable) need to be stored.\n///\n/// The lifetime `'mem` represents the borrow of the underlying uninitialized memory.\n#[derive(Clone, Copy)]\n#[repr(transparent)]\npub struct PtrUninitWide<'mem> {\n ptr: PtrWide,\n phantom: PhantomData<&'mem mut ()>,\n}\n\n/// A type-erased, read-only wide pointer to an initialized value.\n///\n/// Like [`PtrConst`], but for unsized types where metadata is needed. Cannot be null\n/// (but may be dangling for ZSTs). The lifetime `'mem` represents the borrow of the\n/// underlying memory, which must remain valid and initialized.\n#[derive(Clone, Copy)]\n#[repr(transparent)]\npub struct PtrConstWide<'mem> {\n ptr: PtrWide,\n phantom: PhantomData<&'mem ()>,\n}\n\nimpl<'mem> PtrConstWide<'mem> {\n /// Creates a new wide const pointer from a raw pointer to a (potentially unsized) object.\n ///\n /// # Arguments\n ///\n /// * `ptr` - Raw pointer to the object. Can be a pointer to a DST (e.g., slice, trait object).\n ///\n /// # Panics\n ///\n /// Panics if a thin pointer is provided where a wide pointer is expected.\n #[inline]\n pub const fn new(ptr: *const T) -> Self {\n Self {\n ptr: PtrWide::from_ptr(ptr.cast_mut()),\n phantom: PhantomData,\n }\n }\n\n /// Returns the underlying data pointer as a pointer to `u8` (the address of the object).\n #[inline]\n pub fn as_byte_ptr(self) -> *const u8 {\n self.ptr.ptr.as_ptr()\n }\n\n /// Borrows the underlying object as a reference of type `T`.\n ///\n /// # Safety\n ///\n /// - `T` must be the actual underlying (potentially unsized) type of the pointed-to memory.\n /// - The memory must remain valid and not be mutated while this reference exists.\n /// - The pointer must be correctly aligned and point to a valid, initialized value for type `T`.\n #[inline]\n pub unsafe fn get(self) -> &'mem T {\n unsafe { self.ptr.to_ptr::().as_ref().unwrap() }\n }\n}\n\n/// A type-erased, mutable wide pointer to an initialized value.\n///\n/// Like [`PtrMut`], but for unsized types where metadata is needed. Provides mutable access\n/// to the underlying object, whose borrow is tracked by lifetime `'mem`.\n#[derive(Clone, Copy)]\n#[repr(transparent)]\npub struct PtrMutWide<'mem> {\n ptr: PtrWide,\n phantom: PhantomData<&'mem mut ()>,\n}\n\nimpl<'mem> PtrMutWide<'mem> {\n /// Creates a new mutable wide pointer from a raw pointer to a (potentially unsized) object.\n ///\n /// # Arguments\n ///\n /// * `ptr` - Raw mutable pointer to the object. Can be a pointer to a DST (e.g., slice, trait object).\n ///\n /// # Panics\n ///\n /// Panics if a thin pointer is provided where a wide pointer is expected.\n #[inline]\n pub const fn new(ptr: *mut T) -> Self {\n Self {\n ptr: PtrWide::from_ptr(ptr),\n phantom: PhantomData,\n }\n }\n}\n\n/// A generic wrapper for either a thin or wide constant pointer.\n/// This enables working with both sized and unsized types using a single enum.\n#[derive(Clone, Copy)]\npub enum GenericPtr<'mem> {\n /// A thin pointer, used for sized types.\n Thin(PtrConst<'mem>),\n /// A wide pointer, used for unsized types such as slices and trait objects.\n Wide(PtrConstWide<'mem>),\n}\n\nimpl<'a> From> for GenericPtr<'a> {\n fn from(value: PtrConst<'a>) -> Self {\n GenericPtr::Thin(value)\n }\n}\n\nimpl<'a> From> for GenericPtr<'a> {\n fn from(value: PtrConstWide<'a>) -> Self {\n GenericPtr::Wide(value)\n }\n}\n\nimpl<'mem> GenericPtr<'mem> {\n /// Returns the size of the pointer, which may be thin or wide.\n #[inline(always)]\n pub fn new(ptr: *const T) -> Self {\n if size_of_val(&ptr) == size_of::() {\n GenericPtr::Thin(PtrConst::new(ptr.cast::<()>()))\n } else if size_of_val(&ptr) == size_of::() {\n GenericPtr::Wide(PtrConstWide::new(ptr))\n } else {\n panic!(\"Couldn't determine if pointer to T is thin or wide\");\n }\n }\n\n /// Returns the inner [`PtrConst`] if this is a thin pointer, or `None` if this is a wide pointer.\n #[inline(always)]\n pub fn thin(self) -> Option> {\n match self {\n GenericPtr::Thin(ptr) => Some(ptr),\n GenericPtr::Wide(_ptr) => None,\n }\n }\n\n /// Returns the inner [`PtrConstWide`] if this is a wide pointer, or `None` if this is a thin pointer.\n #[inline(always)]\n pub fn wide(self) -> Option> {\n match self {\n GenericPtr::Wide(ptr) => Some(ptr),\n GenericPtr::Thin(_ptr) => None,\n }\n }\n\n /// Downcasts this pointer into a reference — wide or not\n ///\n /// # Safety\n ///\n /// The pointer must be valid for reads for the given type `T`.\n #[inline(always)]\n pub unsafe fn get(self) -> &'mem T {\n match self {\n GenericPtr::Thin(ptr) => {\n let ptr = ptr.as_byte_ptr();\n let ptr_ref = &ptr;\n\n (unsafe { transmute::<&*const u8, &&T>(ptr_ref) }) as _\n }\n GenericPtr::Wide(ptr) => unsafe { ptr.get() },\n }\n }\n\n /// Returns the inner pointer as a raw (possibly wide) `*const ()`.\n ///\n /// If this is a thin pointer, the returned value is\n #[inline(always)]\n pub fn as_byte_ptr(self) -> *const u8 {\n match self {\n GenericPtr::Thin(ptr) => ptr.as_byte_ptr(),\n GenericPtr::Wide(ptr) => ptr.as_byte_ptr(),\n }\n }\n\n /// Returns a pointer with the given offset added\n ///\n /// # Safety\n ///\n /// Offset must be within the bounds of the allocated memory,\n /// and the resulting pointer must be properly aligned.\n #[inline(always)]\n pub unsafe fn field(self, offset: usize) -> GenericPtr<'mem> {\n match self {\n GenericPtr::Thin(ptr) => GenericPtr::Thin(unsafe { ptr.field(offset) }),\n GenericPtr::Wide(_ptr) => {\n // For wide pointers, we can't do field access safely without more context\n // This is a limitation of the current design\n panic!(\"Field access on wide pointers is not supported\")\n }\n }\n }\n}\n"], ["/facet/facet-reflect/src/peek/list.rs", "use super::Peek;\nuse core::{fmt::Debug, marker::PhantomData};\nuse facet_core::{ListDef, PtrConst, PtrMut};\n\n/// Iterator over a `PeekList`\npub struct PeekListIter<'mem, 'facet> {\n state: PeekListIterState<'mem>,\n index: usize,\n len: usize,\n def: ListDef,\n _list: PhantomData>,\n}\n\nimpl<'mem, 'facet> Iterator for PeekListIter<'mem, 'facet> {\n type Item = Peek<'mem, 'facet>;\n\n #[inline]\n fn next(&mut self) -> Option {\n let item_ptr = match self.state {\n PeekListIterState::Ptr { data, stride } => {\n if self.index >= self.len {\n return None;\n }\n\n unsafe { data.field(stride * self.index) }\n }\n PeekListIterState::Iter { iter } => unsafe {\n (self.def.vtable.iter_vtable.next)(iter)?\n },\n };\n\n // Update the index. This is used pointer iteration and for\n // calculating the iterator's size\n self.index += 1;\n\n Some(unsafe { Peek::unchecked_new(item_ptr, self.def.t()) })\n }\n\n #[inline]\n fn size_hint(&self) -> (usize, Option) {\n let remaining = self.len.saturating_sub(self.index);\n (remaining, Some(remaining))\n }\n}\n\nimpl ExactSizeIterator for PeekListIter<'_, '_> {}\n\nimpl Drop for PeekListIter<'_, '_> {\n #[inline]\n fn drop(&mut self) {\n match self.state {\n PeekListIterState::Iter { iter } => unsafe {\n (self.def.vtable.iter_vtable.dealloc)(iter)\n },\n PeekListIterState::Ptr { .. } => {\n // Nothing to do\n }\n }\n }\n}\n\nimpl<'mem, 'facet> IntoIterator for &'mem PeekList<'mem, 'facet> {\n type Item = Peek<'mem, 'facet>;\n type IntoIter = PeekListIter<'mem, 'facet>;\n\n #[inline]\n fn into_iter(self) -> Self::IntoIter {\n self.iter()\n }\n}\n\nenum PeekListIterState<'mem> {\n Ptr { data: PtrConst<'mem>, stride: usize },\n Iter { iter: PtrMut<'mem> },\n}\n\n/// Lets you read from a list (implements read-only [`facet_core::ListVTable`] proxies)\n#[derive(Clone, Copy)]\npub struct PeekList<'mem, 'facet> {\n pub(crate) value: Peek<'mem, 'facet>,\n pub(crate) def: ListDef,\n}\n\nimpl Debug for PeekList<'_, '_> {\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n f.debug_struct(\"PeekList\").finish_non_exhaustive()\n }\n}\n\nimpl<'mem, 'facet> PeekList<'mem, 'facet> {\n /// Creates a new peek list\n #[inline]\n pub fn new(value: Peek<'mem, 'facet>, def: ListDef) -> Self {\n Self { value, def }\n }\n\n /// Get the length of the list\n #[inline]\n pub fn len(&self) -> usize {\n unsafe { (self.def.vtable.len)(self.value.data().thin().unwrap()) }\n }\n\n /// Returns true if the list is empty\n #[inline]\n pub fn is_empty(&self) -> bool {\n self.len() == 0\n }\n\n /// Get an item from the list at the specified index\n #[inline]\n pub fn get(&self, index: usize) -> Option> {\n let item = unsafe { (self.def.vtable.get)(self.value.data().thin().unwrap(), index)? };\n\n Some(unsafe { Peek::unchecked_new(item, self.def.t()) })\n }\n\n /// Returns an iterator over the list\n pub fn iter(self) -> PeekListIter<'mem, 'facet> {\n let state = if let Some(as_ptr_fn) = self.def.vtable.as_ptr {\n let data = unsafe { as_ptr_fn(self.value.data().thin().unwrap()) };\n let layout = self\n .def\n .t()\n .layout\n .sized_layout()\n .expect(\"can only iterate over sized list elements\");\n let stride = layout.size();\n\n PeekListIterState::Ptr { data, stride }\n } else {\n let iter = unsafe {\n (self.def.vtable.iter_vtable.init_with_value.unwrap())(\n self.value.data().thin().unwrap(),\n )\n };\n PeekListIterState::Iter { iter }\n };\n\n PeekListIter {\n state,\n index: 0,\n len: self.len(),\n def: self.def(),\n _list: PhantomData,\n }\n }\n\n /// Def getter\n #[inline]\n pub fn def(&self) -> ListDef {\n self.def\n }\n}\n"], ["/facet/facet-core/src/impls_core/option.rs", "use core::mem::MaybeUninit;\n\nuse crate::{\n Def, EnumRepr, EnumType, Facet, Field, FieldFlags, OptionDef, OptionVTable, PtrConst, PtrMut,\n PtrUninit, Repr, Shape, StructKind, StructType, TryBorrowInnerError, TryFromError,\n TryIntoInnerError, Type, TypedPtrUninit, UserType, VTableView, ValueVTable, Variant,\n value_vtable,\n};\nunsafe impl<'a, T: Facet<'a>> Facet<'a> for Option {\n const VTABLE: &'static ValueVTable = &const {\n // Define the functions for transparent conversion between Option and T\n unsafe fn try_from<'a, 'src, 'dst, T: Facet<'a>>(\n src_ptr: PtrConst<'src>,\n src_shape: &'static Shape,\n dst: PtrUninit<'dst>,\n ) -> Result, TryFromError> {\n if src_shape.id != T::SHAPE.id {\n return Err(TryFromError::UnsupportedSourceShape {\n src_shape,\n expected: &[T::SHAPE],\n });\n }\n let t = unsafe { src_ptr.read::() };\n let option = Some(t);\n Ok(unsafe { dst.put(option) })\n }\n\n unsafe fn try_into_inner<'a, 'src, 'dst, T: Facet<'a>>(\n src_ptr: PtrMut<'src>,\n dst: PtrUninit<'dst>,\n ) -> Result, TryIntoInnerError> {\n let option = unsafe { src_ptr.read::>() };\n match option {\n Some(t) => Ok(unsafe { dst.put(t) }),\n None => Err(TryIntoInnerError::Unavailable),\n }\n }\n\n unsafe fn try_borrow_inner<'a, 'src, T: Facet<'a>>(\n src_ptr: PtrConst<'src>,\n ) -> Result, TryBorrowInnerError> {\n let option = unsafe { src_ptr.get::>() };\n match option {\n Some(t) => Ok(PtrConst::new(t)),\n None => Err(TryBorrowInnerError::Unavailable),\n }\n }\n\n let mut vtable = value_vtable!(core::option::Option, |f, opts| {\n write!(f, \"{}\", Self::SHAPE.type_identifier)?;\n if let Some(opts) = opts.for_children() {\n write!(f, \"<\")?;\n (T::SHAPE.vtable.type_name())(f, opts)?;\n write!(f, \">\")?;\n } else {\n write!(f, \"<…>\")?;\n }\n Ok(())\n });\n\n {\n let vtable_sized = vtable.sized_mut().unwrap();\n vtable_sized.debug = || {\n if T::SHAPE.is_debug() {\n Some(|this, f| {\n let this = unsafe { this.get::() };\n if let Some(value) = &this {\n write!(f, \"Some(\")?;\n (>::of().debug().unwrap())(value, f)?;\n write!(f, \")\")?;\n } else {\n write!(f, \"None\")?;\n }\n Ok(())\n })\n } else {\n None\n }\n };\n\n vtable_sized.parse = || {\n if T::SHAPE.is_from_str() {\n Some(|str, target| {\n let mut t = MaybeUninit::::uninit();\n let parse = >::of().parse().unwrap();\n let _res = (parse)(str, TypedPtrUninit::new(t.as_mut_ptr()))?;\n // res points to t so we can't drop it yet. the option is not initialized though\n unsafe {\n target.put(Some(t.assume_init()));\n Ok(target.assume_init())\n }\n })\n } else {\n None\n }\n };\n\n vtable_sized.try_from = || Some(try_from::);\n vtable_sized.try_into_inner = || Some(try_into_inner::);\n vtable_sized.try_borrow_inner = || Some(try_borrow_inner::);\n }\n\n vtable\n };\n\n const SHAPE: &'static Shape = &const {\n // Function to return inner type's shape\n fn inner_shape<'a, T: Facet<'a>>() -> &'static Shape {\n T::SHAPE\n }\n\n Shape::builder_for_sized::()\n .type_identifier(\"Option\")\n .type_params(&[crate::TypeParam {\n name: \"T\",\n shape: || T::SHAPE,\n }])\n .ty(Type::User(\n // Null-Pointer-Optimization - we verify that this Option variant has no\n // discriminant.\n //\n // See: https://doc.rust-lang.org/std/option/index.html#representation\n if core::mem::size_of::() == core::mem::size_of::>()\n && core::mem::size_of::() <= core::mem::size_of::()\n {\n UserType::Enum(EnumType {\n repr: Repr::default(),\n enum_repr: EnumRepr::RustNPO,\n variants: &const {\n [\n Variant::builder()\n .name(\"None\")\n .discriminant(0)\n .data(\n StructType::builder()\n .repr(Repr::default())\n .kind(StructKind::Unit)\n .build(),\n )\n .build(),\n Variant::builder()\n .name(\"Some\")\n .discriminant(0)\n .data(\n StructType::builder()\n .repr(Repr::default())\n .kind(StructKind::TupleStruct)\n .fields(\n &const {\n [Field::builder()\n .name(\"0\")\n .shape(T::SHAPE)\n .offset(0)\n .flags(FieldFlags::EMPTY)\n .build()]\n },\n )\n .build(),\n )\n .build(),\n ]\n },\n })\n } else {\n UserType::Opaque\n },\n ))\n .def(Def::Option(\n OptionDef::builder()\n .t(T::SHAPE)\n .vtable(\n const {\n &OptionVTable::builder()\n .is_some(|option| unsafe { option.get::>().is_some() })\n .get_value(|option| unsafe {\n option\n .get::>()\n .as_ref()\n .map(|t| PtrConst::new(t as *const T))\n })\n .init_some(|option, value| unsafe {\n option.put(Option::Some(value.read::()))\n })\n .init_none(|option| unsafe { option.put(>::None) })\n .replace_with(|option, value| unsafe {\n let option = option.as_mut::>();\n match value {\n Some(value) => option.replace(value.read::()),\n None => option.take(),\n };\n })\n .build()\n },\n )\n .build(),\n ))\n .inner(inner_shape::)\n .build()\n };\n}\n"], ["/facet/facet-reflect/src/partial/heap_value.rs", "use crate::Peek;\nuse crate::ReflectError;\nuse crate::trace;\nuse alloc::boxed::Box;\nuse core::{alloc::Layout, marker::PhantomData};\nuse facet_core::{Facet, PtrConst, PtrMut, Shape};\n#[cfg(feature = \"log\")]\nuse owo_colors::OwoColorize as _;\n\n/// A type-erased value stored on the heap\npub struct HeapValue<'facet> {\n pub(crate) guard: Option,\n pub(crate) shape: &'static Shape,\n pub(crate) phantom: PhantomData<&'facet ()>,\n}\n\nimpl<'facet> Drop for HeapValue<'facet> {\n fn drop(&mut self) {\n if let Some(guard) = self.guard.take() {\n if let Some(drop_fn) = (self.shape.vtable.sized().unwrap().drop_in_place)() {\n unsafe { drop_fn(PtrMut::new(guard.ptr)) };\n }\n drop(guard);\n }\n }\n}\n\nimpl<'facet> HeapValue<'facet> {\n /// Returns a peek that allows exploring the heap value.\n pub fn peek(&self) -> Peek<'_, 'facet> {\n unsafe { Peek::unchecked_new(PtrConst::new(self.guard.as_ref().unwrap().ptr), self.shape) }\n }\n\n /// Returns the shape of this heap value.\n pub fn shape(&self) -> &'static Shape {\n self.shape\n }\n\n /// Turn this heapvalue into a concrete type\n pub fn materialize>(mut self) -> Result {\n trace!(\n \"HeapValue::materialize: Materializing heap value with shape {} to type {}\",\n self.shape,\n T::SHAPE\n );\n if self.shape != T::SHAPE {\n trace!(\n \"HeapValue::materialize: Shape mismatch! Expected {}, but heap value has {}\",\n T::SHAPE,\n self.shape\n );\n return Err(ReflectError::WrongShape {\n expected: self.shape,\n actual: T::SHAPE,\n });\n }\n\n trace!(\"HeapValue::materialize: Shapes match, proceeding with materialization\");\n let guard = self.guard.take().unwrap();\n let data = PtrConst::new(guard.ptr);\n let res = unsafe { data.read::() };\n drop(guard); // free memory (but don't drop in place)\n trace!(\"HeapValue::materialize: Successfully materialized value\");\n Ok(res)\n }\n}\n\nimpl<'facet> HeapValue<'facet> {\n /// Formats the value using its Display implementation, if available\n pub fn fmt_display(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n if let Some(display_fn) = self.shape.vtable.sized().and_then(|v| (v.display)()) {\n unsafe { display_fn(PtrConst::new(self.guard.as_ref().unwrap().ptr), f) }\n } else {\n write!(f, \"⟨{}⟩\", self.shape)\n }\n }\n\n /// Formats the value using its Debug implementation, if available\n pub fn fmt_debug(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n if let Some(debug_fn) = self.shape.vtable.sized().and_then(|v| (v.debug)()) {\n unsafe { debug_fn(PtrConst::new(self.guard.as_ref().unwrap().ptr), f) }\n } else {\n write!(f, \"⟨{}⟩\", self.shape)\n }\n }\n}\n\nimpl<'facet> core::fmt::Display for HeapValue<'facet> {\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n self.fmt_display(f)\n }\n}\n\nimpl<'facet> core::fmt::Debug for HeapValue<'facet> {\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n self.fmt_debug(f)\n }\n}\n\nimpl<'facet> PartialEq for HeapValue<'facet> {\n fn eq(&self, other: &Self) -> bool {\n if self.shape != other.shape {\n return false;\n }\n if let Some(eq_fn) = self.shape.vtable.sized().and_then(|v| (v.partial_eq)()) {\n unsafe {\n eq_fn(\n PtrConst::new(self.guard.as_ref().unwrap().ptr),\n PtrConst::new(other.guard.as_ref().unwrap().ptr),\n )\n }\n } else {\n false\n }\n }\n}\n\nimpl<'facet> PartialOrd for HeapValue<'facet> {\n fn partial_cmp(&self, other: &Self) -> Option {\n if self.shape != other.shape {\n return None;\n }\n if let Some(partial_ord_fn) = self.shape.vtable.sized().and_then(|v| (v.partial_ord)()) {\n unsafe {\n partial_ord_fn(\n PtrConst::new(self.guard.as_ref().unwrap().ptr),\n PtrConst::new(other.guard.as_ref().unwrap().ptr),\n )\n }\n } else {\n None\n }\n }\n}\n\n/// A guard structure to manage memory allocation and deallocation.\n///\n/// This struct holds a raw pointer to the allocated memory and the layout\n/// information used for allocation. It's responsible for deallocating\n/// the memory when dropped.\npub struct Guard {\n /// Raw pointer to the allocated memory.\n pub(crate) ptr: *mut u8,\n /// Layout information of the allocated memory.\n pub(crate) layout: Layout,\n}\n\nimpl Drop for Guard {\n fn drop(&mut self) {\n if self.layout.size() != 0 {\n trace!(\n \"Deallocating memory at ptr: {:p}, size: {}, align: {}\",\n self.ptr.cyan(),\n self.layout.size().yellow(),\n self.layout.align().green()\n );\n // SAFETY: `ptr` has been allocated via the global allocator with the given layout\n unsafe { alloc::alloc::dealloc(self.ptr, self.layout) };\n }\n }\n}\n\nimpl<'facet> HeapValue<'facet> {\n /// Unsafely convert this HeapValue into a `Box` without checking shape.\n ///\n /// # Safety\n ///\n /// Caller must guarantee that the underlying value is of type T with a compatible layout.\n pub(crate) unsafe fn into_box_unchecked>(mut self) -> Box {\n let guard = self.guard.take().unwrap();\n let ptr = guard.ptr as *mut T;\n // Don't drop, just forget the guard so we don't double free.\n core::mem::forget(guard);\n unsafe { Box::from_raw(ptr) }\n }\n\n /// Unsafely get a reference to the underlying value as type T.\n ///\n /// # Safety\n ///\n /// Caller must guarantee that the underlying value is of type T.\n pub unsafe fn as_ref(&self) -> &T {\n unsafe { &*(self.guard.as_ref().unwrap().ptr as *const T) }\n }\n}\n"], ["/facet/facet-core/src/impls_core/reference.rs", "use core::fmt;\n\nuse crate::{\n Def, Facet, KnownPointer, MarkerTraits, PointerDef, PointerFlags, PointerType, PointerVTable,\n PtrConst, PtrConstWide, Shape, Type, TypeParam, VTableView, ValuePointerType, ValueVTable,\n};\n\nmacro_rules! impl_for_ref {\n ($($modifiers:tt)*) => {\n unsafe impl<'a, T: Facet<'a>> Facet<'a> for &'a $($modifiers)* T {\n const VTABLE: &'static ValueVTable = &const {\n ValueVTable::builder::()\n .marker_traits(|| {\n let mut marker_traits = if stringify!($($modifiers)*).is_empty() {\n MarkerTraits::COPY.union(MarkerTraits::UNPIN)\n } else {\n MarkerTraits::UNPIN\n };\n if T::SHAPE.vtable.marker_traits().contains(MarkerTraits::EQ) {\n marker_traits = marker_traits.union(MarkerTraits::EQ);\n }\n if T::SHAPE.vtable.marker_traits().contains(MarkerTraits::SYNC) {\n marker_traits = marker_traits\n .union(MarkerTraits::SEND)\n .union(MarkerTraits::SYNC);\n }\n if T::SHAPE\n .vtable\n .marker_traits()\n .contains(MarkerTraits::REF_UNWIND_SAFE)\n {\n marker_traits = marker_traits.union(MarkerTraits::REF_UNWIND_SAFE);\n if stringify!($($modifiers)*).is_empty() {\n marker_traits = marker_traits.union(MarkerTraits::UNWIND_SAFE);\n }\n }\n\n marker_traits\n })\n .display(|| {\n if T::VTABLE.has_display() {\n Some(|value, f| {\n let view = VTableView::::of();\n view.display().unwrap()(*value, f)\n })\n } else {\n None\n }\n })\n .debug(|| {\n if T::VTABLE.has_debug() {\n Some(|value, f| {\n let view = VTableView::::of();\n view.debug().unwrap()(*value, f)\n })\n } else {\n None\n }\n })\n .clone_into(|| {\n if stringify!($($modifiers)*).is_empty() {\n Some(|src, dst| unsafe { dst.put(core::ptr::read(src)) })\n } else {\n None\n }\n })\n .type_name(|f, opts| {\n if stringify!($($modifiers)*).is_empty() {\n if let Some(opts) = opts.for_children() {\n write!(f, \"&\")?;\n (T::VTABLE.type_name())(f, opts)\n } else {\n write!(f, \"&⋯\")\n }\n } else {\n if let Some(opts) = opts.for_children() {\n write!(f, \"&mut \")?;\n (T::VTABLE.type_name())(f, opts)\n } else {\n write!(f, \"&mut ⋯\")\n }\n }\n })\n .build()\n };\n\n const SHAPE: &'static Shape = &const {\n Shape::builder_for_sized::()\n .type_identifier(\"&\")\n .type_params(&[TypeParam {\n name: \"T\",\n shape: || T::SHAPE,\n }])\n .ty({\n let vpt = ValuePointerType {\n mutable: !stringify!($($modifiers)*).is_empty(),\n wide: false,\n target: || T::SHAPE,\n };\n\n Type::Pointer(PointerType::Reference(vpt))\n })\n .def(Def::Pointer(\n PointerDef::builder()\n .pointee(|| T::SHAPE)\n .flags(PointerFlags::EMPTY)\n .known(if stringify!($($modifiers)*).is_empty() {\n KnownPointer::SharedReference\n } else {\n KnownPointer::ExclusiveReference\n })\n .vtable(\n &const {\n PointerVTable::builder()\n .borrow_fn(|this| {\n let ptr: && $($modifiers)* T = unsafe { this.get::() };\n PtrConst::new(*ptr).into()\n })\n .build()\n },\n )\n .build(),\n ))\n .build()\n };\n }\n };\n}\n\nimpl_for_ref!();\nimpl_for_ref!(mut);\n\nmacro_rules! impl_for_string_ref {\n ($($modifiers:tt)*) => {\n unsafe impl<'a> Facet<'a> for &'a $($modifiers)* str {\n const VTABLE: &'static ValueVTable = &const {\n ValueVTable::builder::()\n .marker_traits(|| {\n let mut marker_traits = MarkerTraits::COPY.union(MarkerTraits::UNPIN);\n if str::SHAPE.vtable.marker_traits().contains(MarkerTraits::EQ) {\n marker_traits = marker_traits.union(MarkerTraits::EQ);\n }\n if str::SHAPE\n .vtable\n .marker_traits()\n .contains(MarkerTraits::SYNC)\n {\n marker_traits = marker_traits\n .union(MarkerTraits::SEND)\n .union(MarkerTraits::SYNC);\n }\n if str::SHAPE\n .vtable\n .marker_traits()\n .contains(MarkerTraits::REF_UNWIND_SAFE)\n {\n marker_traits = marker_traits\n .union(MarkerTraits::UNWIND_SAFE)\n .union(MarkerTraits::REF_UNWIND_SAFE);\n }\n\n marker_traits\n })\n .display(|| Some(fmt::Display::fmt))\n .debug(|| Some(fmt::Debug::fmt))\n .clone_into(|| {\n if stringify!($($modifiers)*).is_empty() {\n Some(|src, dst| unsafe { dst.put(core::ptr::read(src)) })\n } else {\n None\n }\n })\n .type_name(|f, _opts| {\n if stringify!($($modifiers)*).is_empty() {\n write!(f, \"&str\")\n } else {\n write!(f, \"&mut str\")\n }\n })\n .build()\n };\n\n const SHAPE: &'static Shape = &const {\n Shape::builder_for_sized::()\n .type_identifier(\"&_\")\n .type_params(&[TypeParam {\n name: \"T\",\n shape: || str::SHAPE,\n }])\n .ty({\n let vpt = ValuePointerType {\n mutable: !stringify!($($modifiers)*).is_empty(),\n wide: true, // string slices are always wide (fat pointers)\n target: || str::SHAPE,\n };\n\n Type::Pointer(PointerType::Reference(vpt))\n })\n .build()\n };\n }\n };\n}\n\nimpl_for_string_ref!();\nimpl_for_string_ref!(mut);\n\nmacro_rules! impl_for_slice_ref {\n ($($modifiers:tt)*) => {\n unsafe impl<'a, U: Facet<'a>> Facet<'a> for &'a $($modifiers)* [U] {\n const VTABLE: &'static ValueVTable = &const {\n ValueVTable::builder::()\n .marker_traits(|| {\n let mut marker_traits = MarkerTraits::COPY.union(MarkerTraits::UNPIN);\n if <[U]>::SHAPE\n .vtable\n .marker_traits()\n .contains(MarkerTraits::EQ)\n {\n marker_traits = marker_traits.union(MarkerTraits::EQ);\n }\n if <[U]>::SHAPE\n .vtable\n .marker_traits()\n .contains(MarkerTraits::SYNC)\n {\n marker_traits = marker_traits\n .union(MarkerTraits::SEND)\n .union(MarkerTraits::SYNC);\n }\n if <[U]>::SHAPE\n .vtable\n .marker_traits()\n .contains(MarkerTraits::REF_UNWIND_SAFE)\n {\n marker_traits = marker_traits\n .union(MarkerTraits::UNWIND_SAFE)\n .union(MarkerTraits::REF_UNWIND_SAFE);\n }\n\n marker_traits\n })\n .debug(|| {\n if <[U]>::VTABLE.has_debug() {\n Some(|value, f| {\n let view = VTableView::<[U]>::of();\n view.debug().unwrap()(*value, f)\n })\n } else {\n None\n }\n })\n .clone_into(|| Some(|src, dst| unsafe { dst.put(core::ptr::read(src)) }))\n .type_name(|f, opts| {\n if stringify!($($modifiers)*).is_empty() {\n if let Some(opts) = opts.for_children() {\n write!(f, \"&[\")?;\n (::VTABLE.type_name())(f, opts)?;\n write!(f, \"]\")\n } else {\n write!(f, \"&⋯\")\n }\n } else {\n if let Some(opts) = opts.for_children() {\n write!(f, \"&mut [\")?;\n (::VTABLE.type_name())(f, opts)?;\n write!(f, \"]\")\n } else {\n write!(f, \"&mut ⋯\")\n }\n }\n })\n .build()\n };\n\n const SHAPE: &'static Shape = &const {\n Shape::builder_for_sized::()\n .type_identifier(\"&[_]\")\n .type_params(&[TypeParam {\n name: \"T\",\n shape: || <[U]>::SHAPE,\n }])\n .ty({\n let vpt = ValuePointerType {\n mutable: !stringify!($($modifiers)*).is_empty(),\n wide: true, // slice references are always wide (fat pointers)\n target: || <[U]>::SHAPE,\n };\n\n Type::Pointer(PointerType::Reference(vpt))\n })\n .def(Def::Pointer(\n PointerDef::builder()\n .pointee(|| <[U]>::SHAPE)\n .flags(PointerFlags::EMPTY)\n .known(if stringify!($($modifiers)*).is_empty() {\n KnownPointer::SharedReference\n } else {\n KnownPointer::ExclusiveReference\n })\n .vtable(\n &const {\n PointerVTable::builder()\n .borrow_fn(|this| {\n // `this` is a PtrConst pointing to our slice reference (&[U] or &mut [U])\n // We get a reference to our slice reference, so we have &&[U] or &&mut [U]\n let ptr: && $($modifiers)* [U] = unsafe { this.get::() };\n\n // Dereference once to get the actual slice reference: &[U] or &mut [U]\n // This is the wide pointer we want to return (contains ptr + length)\n // Note: Even for &mut [U], we can coerce to &[U] for borrowing\n let s: &[U] = *ptr;\n\n // Convert the slice reference to a raw pointer (*const [U])\n // The &raw const operator creates a raw pointer from a place expression\n // without going through a reference first, preserving the wide pointer\n PtrConstWide::new(&raw const *s).into()\n })\n .build()\n },\n )\n .build(),\n ))\n .build()\n };\n }\n };\n}\n\nimpl_for_slice_ref!();\nimpl_for_slice_ref!(mut);\n"], ["/facet/facet-core/src/impls_alloc/btreemap.rs", "use core::write;\n\nuse alloc::{boxed::Box, collections::BTreeMap};\n\nuse crate::{\n Def, Facet, IterVTable, MapDef, MapVTable, MarkerTraits, PtrConst, PtrMut, Shape, Type,\n UserType, ValueVTable,\n};\n\ntype BTreeMapIterator<'mem, K, V> = alloc::collections::btree_map::Iter<'mem, K, V>;\n\nunsafe impl<'a, K, V> Facet<'a> for BTreeMap\nwhere\n K: Facet<'a> + core::cmp::Eq + core::cmp::Ord,\n V: Facet<'a>,\n{\n const VTABLE: &'static ValueVTable = &const {\n ValueVTable::builder::()\n .marker_traits(|| {\n let arg_dependent_traits = MarkerTraits::SEND\n .union(MarkerTraits::SYNC)\n .union(MarkerTraits::EQ);\n arg_dependent_traits\n .intersection(V::SHAPE.vtable.marker_traits())\n .intersection(K::SHAPE.vtable.marker_traits())\n // only depends on `A` which we are not generic over (yet)\n .union(MarkerTraits::UNPIN)\n })\n .type_name(|f, opts| {\n if let Some(opts) = opts.for_children() {\n write!(f, \"{}<\", Self::SHAPE.type_identifier)?;\n K::SHAPE.vtable.type_name()(f, opts)?;\n write!(f, \", \")?;\n V::SHAPE.vtable.type_name()(f, opts)?;\n write!(f, \">\")\n } else {\n write!(f, \"BTreeMap<⋯>\")\n }\n })\n .default_in_place(|| Some(|target| unsafe { target.put(Self::default()) }))\n .build()\n };\n\n const SHAPE: &'static crate::Shape = &const {\n Shape::builder_for_sized::()\n .type_identifier(\"BTreeMap\")\n .type_params(&[\n crate::TypeParam {\n name: \"K\",\n shape: || K::SHAPE,\n },\n crate::TypeParam {\n name: \"V\",\n shape: || V::SHAPE,\n },\n ])\n .ty(Type::User(UserType::Opaque))\n .def(Def::Map(\n MapDef::builder()\n .k(|| K::SHAPE)\n .v(|| V::SHAPE)\n .vtable(\n &const {\n MapVTable::builder()\n .init_in_place_with_capacity(|uninit, _capacity| unsafe {\n uninit.put(Self::new())\n })\n .insert(|ptr, key, value| unsafe {\n let map = ptr.as_mut::();\n let k = key.read::();\n let v = value.read::();\n map.insert(k, v);\n })\n .len(|ptr| unsafe {\n let map = ptr.get::();\n map.len()\n })\n .contains_key(|ptr, key| unsafe {\n let map = ptr.get::();\n map.contains_key(key.get())\n })\n .get_value_ptr(|ptr, key| unsafe {\n let map = ptr.get::();\n map.get(key.get()).map(|v| PtrConst::new(v as *const _))\n })\n .iter_vtable(\n IterVTable::builder()\n .init_with_value(|ptr| unsafe {\n let map = ptr.get::();\n let iter: BTreeMapIterator<'_, K, V> = map.iter();\n let state = Box::new(iter);\n PtrMut::new(Box::into_raw(state) as *mut u8)\n })\n .next(|iter_ptr| unsafe {\n let state =\n iter_ptr.as_mut::>();\n state.next().map(|(key, value)| {\n (PtrConst::new(key), PtrConst::new(value))\n })\n })\n .next_back(|iter_ptr| unsafe {\n let state =\n iter_ptr.as_mut::>();\n state.next_back().map(|(key, value)| {\n (PtrConst::new(key), PtrConst::new(value))\n })\n })\n .dealloc(|iter_ptr| unsafe {\n drop(Box::from_raw(\n iter_ptr.as_ptr::>()\n as *mut BTreeMapIterator<'_, K, V>,\n ))\n })\n .build(),\n )\n .build()\n },\n )\n .build(),\n ))\n .build()\n };\n}\n"], ["/facet/facet-core/src/impls_url.rs", "use alloc::borrow::ToOwned;\nuse alloc::string::String;\n\nuse url::Url;\n\nuse crate::{\n Def, Facet, ParseError, PtrConst, PtrMut, PtrUninit, Shape, TryBorrowInnerError,\n TryIntoInnerError, Type, UserType, ValueVTable, value_vtable,\n};\n\nunsafe impl Facet<'_> for Url {\n const VTABLE: &'static ValueVTable = &const {\n // Custom parse impl with detailed errors\n unsafe fn parse<'target>(\n s: &str,\n target: PtrUninit<'target>,\n ) -> Result, ParseError> {\n let url = Url::parse(s).map_err(|error| {\n let message = match error {\n url::ParseError::EmptyHost => \"empty host\",\n url::ParseError::IdnaError => \"invalid international domain name\",\n url::ParseError::InvalidPort => \"invalid port number\",\n url::ParseError::InvalidIpv4Address => \"invalid IPv4 address\",\n url::ParseError::InvalidIpv6Address => \"invalid IPv6 address\",\n url::ParseError::InvalidDomainCharacter => \"invalid domain character\",\n url::ParseError::RelativeUrlWithoutBase => \"relative URL without a base\",\n url::ParseError::RelativeUrlWithCannotBeABaseBase => {\n \"relative URL with a cannot-be-a-base base\"\n }\n url::ParseError::SetHostOnCannotBeABaseUrl => {\n \"a cannot-be-a-base URL doesn’t have a host to set\"\n }\n url::ParseError::Overflow => \"URLs more than 4 GB are not supported\",\n _ => \"failed to parse URL\",\n };\n ParseError::Generic(message)\n })?;\n Ok(unsafe { target.put(url) })\n }\n\n unsafe fn try_into_inner<'dst>(\n src_ptr: PtrMut<'_>,\n dst: PtrUninit<'dst>,\n ) -> Result, TryIntoInnerError> {\n let url = unsafe { src_ptr.get::() };\n Ok(unsafe { dst.put(url.as_str().to_owned()) })\n }\n\n unsafe fn try_borrow_inner(\n src_ptr: PtrConst<'_>,\n ) -> Result, TryBorrowInnerError> {\n let url = unsafe { src_ptr.get::() };\n Ok(PtrConst::new(url.as_str().as_ptr()))\n }\n\n let mut vtable =\n value_vtable!(Url, |f, _opts| write!(f, \"{}\", Self::SHAPE.type_identifier));\n {\n let vtable = vtable.sized_mut().unwrap();\n vtable.parse = || Some(parse);\n vtable.try_into_inner = || Some(try_into_inner);\n vtable.try_borrow_inner = || Some(try_borrow_inner);\n }\n vtable\n };\n\n const SHAPE: &'static Shape = &const {\n // Function to return inner type's shape\n fn inner_shape() -> &'static Shape {\n ::SHAPE\n }\n\n Shape::builder_for_sized::()\n .type_identifier(\"Url\")\n .ty(Type::User(UserType::Opaque))\n .def(Def::Scalar)\n .inner(inner_shape)\n .build()\n };\n}\n"], ["/facet/facet-reflect/src/peek/map.rs", "use facet_core::{MapDef, PtrConst, PtrMut};\n\nuse super::Peek;\n\n/// Iterator over key-value pairs in a `PeekMap`\npub struct PeekMapIter<'mem, 'facet> {\n map: PeekMap<'mem, 'facet>,\n iter: PtrMut<'mem>,\n}\n\nimpl<'mem, 'facet> Iterator for PeekMapIter<'mem, 'facet> {\n type Item = (Peek<'mem, 'facet>, Peek<'mem, 'facet>);\n\n #[inline]\n fn next(&mut self) -> Option {\n unsafe {\n let next = (self.map.def.vtable.iter_vtable.next)(self.iter);\n next.map(|(key_ptr, value_ptr)| {\n (\n Peek::unchecked_new(key_ptr, self.map.def.k()),\n Peek::unchecked_new(value_ptr, self.map.def.v()),\n )\n })\n }\n }\n}\n\nimpl<'mem, 'facet> Drop for PeekMapIter<'mem, 'facet> {\n #[inline]\n fn drop(&mut self) {\n unsafe { (self.map.def.vtable.iter_vtable.dealloc)(self.iter) }\n }\n}\n\nimpl<'mem, 'facet> IntoIterator for &'mem PeekMap<'mem, 'facet> {\n type Item = (Peek<'mem, 'facet>, Peek<'mem, 'facet>);\n type IntoIter = PeekMapIter<'mem, 'facet>;\n\n #[inline]\n fn into_iter(self) -> Self::IntoIter {\n self.iter()\n }\n}\n\n/// Lets you read from a map (implements read-only [`facet_core::MapVTable`] proxies)\n#[derive(Clone, Copy)]\npub struct PeekMap<'mem, 'facet> {\n pub(crate) value: Peek<'mem, 'facet>,\n\n pub(crate) def: MapDef,\n}\n\nimpl<'mem, 'facet> core::fmt::Debug for PeekMap<'mem, 'facet> {\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n f.debug_struct(\"PeekMap\").finish_non_exhaustive()\n }\n}\n\nimpl<'mem, 'facet> PeekMap<'mem, 'facet> {\n /// Constructor\n #[inline]\n pub fn new(value: Peek<'mem, 'facet>, def: MapDef) -> Self {\n Self { value, def }\n }\n\n /// Get the number of entries in the map\n #[inline]\n pub fn len(&self) -> usize {\n unsafe { (self.def.vtable.len_fn)(self.value.data().thin().unwrap()) }\n }\n\n /// Returns true if the map is empty\n #[inline]\n pub fn is_empty(&self) -> bool {\n self.len() == 0\n }\n\n /// Check if the map contains a key\n #[inline]\n pub fn contains_key(&self, key: &impl facet_core::Facet<'facet>) -> bool {\n unsafe {\n let key_ptr = PtrConst::new(key);\n (self.def.vtable.contains_key_fn)(self.value.data().thin().unwrap(), key_ptr)\n }\n }\n\n /// Get a value from the map for the given key\n #[inline]\n pub fn get<'k>(&self, key: &'k impl facet_core::Facet<'facet>) -> Option> {\n unsafe {\n let key_ptr = PtrConst::new(key);\n let value_ptr =\n (self.def.vtable.get_value_ptr_fn)(self.value.data().thin().unwrap(), key_ptr)?;\n Some(Peek::unchecked_new(value_ptr, self.def.v()))\n }\n }\n\n /// Returns an iterator over the key-value pairs in the map\n #[inline]\n pub fn iter(self) -> PeekMapIter<'mem, 'facet> {\n let iter_init_with_value_fn = self.def.vtable.iter_vtable.init_with_value.unwrap();\n let iter = unsafe { iter_init_with_value_fn(self.value.data().thin().unwrap()) };\n PeekMapIter { map: self, iter }\n }\n\n /// Def getter\n #[inline]\n pub fn def(&self) -> MapDef {\n self.def\n }\n}\n"], ["/facet/facet-reflect/src/peek/fields.rs", "use core::ops::Range;\n\nuse facet_core::{Field, FieldFlags};\n\nuse crate::Peek;\nuse alloc::{vec, vec::Vec};\n\nuse super::{PeekEnum, PeekStruct, PeekTuple};\n\n/// Trait for types that have field methods\n///\n/// This trait allows code to be written generically over both structs and enums\n/// that provide field access and iteration capabilities.\npub trait HasFields<'mem, 'facet> {\n /// Iterates over all fields in this type, providing both field metadata and value\n fn fields(&self) -> FieldIter<'mem, 'facet>;\n\n /// Iterates over fields in this type that should be included when it is serialized\n fn fields_for_serialize(&self) -> FieldsForSerializeIter<'mem, 'facet> {\n FieldsForSerializeIter {\n stack: vec![self.fields()],\n }\n }\n}\n\n/// An iterator over all the fields of a struct or enum. See [`HasFields::fields`]\npub struct FieldIter<'mem, 'facet> {\n state: FieldIterState<'mem, 'facet>,\n range: Range,\n}\n\nenum FieldIterState<'mem, 'facet> {\n Struct(PeekStruct<'mem, 'facet>),\n Tuple(PeekTuple<'mem, 'facet>),\n Enum {\n peek_enum: PeekEnum<'mem, 'facet>,\n fields: &'static [Field],\n },\n FlattenedEnum {\n field: Field,\n value: Peek<'mem, 'facet>,\n },\n}\n\nimpl<'mem, 'facet> FieldIter<'mem, 'facet> {\n #[inline]\n pub(crate) fn new_struct(struct_: PeekStruct<'mem, 'facet>) -> Self {\n Self {\n range: 0..struct_.ty.fields.len(),\n state: FieldIterState::Struct(struct_),\n }\n }\n\n #[inline]\n pub(crate) fn new_enum(enum_: PeekEnum<'mem, 'facet>) -> Self {\n // Get the fields of the active variant\n let variant = match enum_.active_variant() {\n Ok(v) => v,\n Err(e) => panic!(\"Cannot get active variant: {e:?}\"),\n };\n let fields = &variant.data.fields;\n\n Self {\n range: 0..fields.len(),\n state: FieldIterState::Enum {\n peek_enum: enum_,\n fields,\n },\n }\n }\n\n #[inline]\n pub(crate) fn new_tuple(tuple: PeekTuple<'mem, 'facet>) -> Self {\n Self {\n range: 0..tuple.len(),\n state: FieldIterState::Tuple(tuple),\n }\n }\n\n fn get_field_by_index(&self, index: usize) -> Option<(Field, Peek<'mem, 'facet>)> {\n match self.state {\n FieldIterState::Struct(peek_struct) => {\n let field = peek_struct.ty.fields.get(index).copied()?;\n let value = peek_struct.field(index).ok()?;\n Some((field, value))\n }\n FieldIterState::Tuple(peek_tuple) => {\n let field = peek_tuple.ty.fields.get(index).copied()?;\n let value = peek_tuple.field(index)?;\n Some((field, value))\n }\n FieldIterState::Enum { peek_enum, fields } => {\n // Get the field definition\n let field = fields[index];\n // Get the field value\n let field_value = match peek_enum.field(index) {\n Ok(Some(v)) => v,\n Ok(None) => return None,\n Err(e) => panic!(\"Cannot get field: {e:?}\"),\n };\n // Return the field definition and value\n Some((field, field_value))\n }\n FieldIterState::FlattenedEnum { field, value } => {\n if index == 0 {\n Some((field, value))\n } else {\n None\n }\n }\n }\n }\n}\n\nimpl<'mem, 'facet> Iterator for FieldIter<'mem, 'facet> {\n type Item = (Field, Peek<'mem, 'facet>);\n\n #[inline]\n fn next(&mut self) -> Option {\n loop {\n let index = self.range.next()?;\n\n let Some(field) = self.get_field_by_index(index) else {\n continue;\n };\n\n return Some(field);\n }\n }\n\n #[inline]\n fn size_hint(&self) -> (usize, Option) {\n self.range.size_hint()\n }\n}\n\nimpl DoubleEndedIterator for FieldIter<'_, '_> {\n #[inline]\n fn next_back(&mut self) -> Option {\n loop {\n let index = self.range.next_back()?;\n\n let Some(field) = self.get_field_by_index(index) else {\n continue;\n };\n\n return Some(field);\n }\n }\n}\n\nimpl ExactSizeIterator for FieldIter<'_, '_> {}\n\n/// An iterator over the fields of a struct or enum that should be serialized. See [`HasFields::fields_for_serialize`]\npub struct FieldsForSerializeIter<'mem, 'facet> {\n stack: Vec>,\n}\n\nimpl<'mem, 'facet> Iterator for FieldsForSerializeIter<'mem, 'facet> {\n type Item = (Field, Peek<'mem, 'facet>);\n\n fn next(&mut self) -> Option {\n loop {\n let mut fields = self.stack.pop()?;\n let Some((mut field, peek)) = fields.next() else {\n continue;\n };\n self.stack.push(fields);\n\n let Some(data) = peek.data().thin() else {\n continue;\n };\n let should_skip = unsafe { field.should_skip_serializing(data) };\n\n if should_skip {\n continue;\n }\n\n if field.flags.contains(FieldFlags::FLATTEN) && !field.flattened {\n if let Ok(struct_peek) = peek.into_struct() {\n self.stack.push(FieldIter::new_struct(struct_peek))\n } else if let Ok(enum_peek) = peek.into_enum() {\n // normally we'd serialize to something like:\n //\n // {\n // \"field_on_struct\": {\n // \"VariantName\": { \"field_on_variant\": \"foo\" }\n // }\n // }\n //\n // But since `field_on_struct` is flattened, instead we do:\n //\n // {\n // \"VariantName\": { \"field_on_variant\": \"foo\" }\n // }\n field.name = enum_peek\n .active_variant()\n .expect(\"Failed to get active variant\")\n .name;\n field.flattened = true;\n self.stack.push(FieldIter {\n range: 0..1,\n state: FieldIterState::FlattenedEnum { field, value: peek },\n });\n } else {\n // TODO: fail more gracefully\n panic!(\"cannot flatten a {}\", field.shape())\n }\n } else {\n return Some((field, peek));\n }\n }\n }\n}\n"], ["/facet/facet-core/src/impls_ulid.rs", "use alloc::string::String;\n\nuse ulid::Ulid;\n\nuse crate::{\n Def, Facet, ParseError, PtrConst, PtrMut, PtrUninit, Shape, TryFromError, TryIntoInnerError,\n Type, UserType, ValueVTable, value_vtable,\n};\n\nunsafe impl Facet<'_> for Ulid {\n const VTABLE: &'static ValueVTable = &const {\n // Functions to transparently convert between Ulid and String\n unsafe fn try_from<'dst>(\n src_ptr: PtrConst<'_>,\n src_shape: &'static Shape,\n dst: PtrUninit<'dst>,\n ) -> Result, TryFromError> {\n if src_shape.id != ::SHAPE.id {\n return Err(TryFromError::UnsupportedSourceShape {\n src_shape,\n expected: &[::SHAPE],\n });\n }\n let s = unsafe { src_ptr.read::() };\n match Ulid::from_string(&s) {\n Ok(ulid) => Ok(unsafe { dst.put(ulid) }),\n Err(_) => Err(TryFromError::UnsupportedSourceShape {\n src_shape,\n expected: &[::SHAPE],\n }),\n }\n }\n\n unsafe fn try_into_inner<'dst>(\n src_ptr: PtrMut<'_>,\n dst: PtrUninit<'dst>,\n ) -> Result, TryIntoInnerError> {\n let ulid = unsafe { src_ptr.read::() };\n Ok(unsafe { dst.put(ulid.to_string()) })\n }\n\n let mut vtable = value_vtable!(Ulid, |f, _opts| write!(\n f,\n \"{}\",\n Self::SHAPE.type_identifier\n ));\n {\n let vtable = vtable.sized_mut().unwrap();\n vtable.parse = || {\n Some(|s, target| match Ulid::from_string(s) {\n Ok(ulid) => Ok(unsafe { target.put(ulid) }),\n Err(_) => Err(ParseError::Generic(\"ULID parsing failed\")),\n })\n };\n vtable.try_from = || Some(try_from);\n vtable.try_into_inner = || Some(try_into_inner);\n }\n vtable\n };\n\n const SHAPE: &'static Shape = &const {\n // Return the Shape of the inner type (String)\n fn inner_shape() -> &'static Shape {\n ::SHAPE\n }\n\n Shape::builder_for_sized::()\n .type_identifier(\"Ulid\")\n .ty(Type::User(UserType::Opaque))\n .def(Def::Scalar)\n .inner(inner_shape)\n .build()\n };\n}\n"], ["/facet/facet-reflect/src/scalar.rs", "use core::any::TypeId;\nuse core::net::{IpAddr, Ipv4Addr, Ipv6Addr};\n\nuse facet_core::{ConstTypeId, Shape};\n\n/// All scalar types supported out of the box by peek and poke.\n#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]\npub enum ScalarType {\n /// Unit tuple `()`.\n Unit,\n /// Primitive type `bool`.\n Bool,\n /// Primitive type `char`.\n Char,\n /// Primitive type `str`.\n Str,\n /// `alloc::string::String`.\n String,\n /// `alloc::borrow::Cow<'_, str>`.\n CowStr,\n /// Primitive type `f32`.\n F32,\n /// Primitive type `f64`.\n F64,\n /// Primitive type `u8`.\n U8,\n /// Primitive type `u16`.\n U16,\n /// Primitive type `u32`.\n U32,\n /// Primitive type `u64`.\n U64,\n /// Primitive type `u128`.\n U128,\n /// Primitive type `usize`.\n USize,\n /// Primitive type `i8`.\n I8,\n /// Primitive type `i16`.\n I16,\n /// Primitive type `i32`.\n I32,\n /// Primitive type `i64`.\n I64,\n /// Primitive type `i128`.\n I128,\n /// Primitive type `isize`.\n ISize,\n /// `core::net::SocketAddr`.\n SocketAddr,\n /// `core::net::IpAddr`.\n IpAddr,\n /// `core::net::Ipv4Addr`.\n Ipv4Addr,\n /// `core::net::Ipv6Addr`.\n Ipv6Addr,\n /// `facet_core::typeid::ConstTypeId`.\n ConstTypeId,\n}\n\nimpl ScalarType {\n /// Infer the type from a shape definition.\n #[inline]\n pub fn try_from_shape(shape: &Shape) -> Option {\n let type_id = shape.id.get();\n\n #[cfg(feature = \"alloc\")]\n if type_id == TypeId::of::() {\n return Some(ScalarType::String);\n } else if type_id == TypeId::of::>() {\n return Some(ScalarType::CowStr);\n } else if type_id == TypeId::of::() {\n return Some(ScalarType::Str);\n } else if type_id == TypeId::of::() {\n return Some(ScalarType::SocketAddr);\n }\n\n if type_id == TypeId::of::<()>() {\n Some(Self::Unit)\n } else if type_id == TypeId::of::() {\n Some(ScalarType::Bool)\n } else if type_id == TypeId::of::() {\n Some(ScalarType::Char)\n } else if type_id == TypeId::of::<&str>() {\n Some(ScalarType::Str)\n } else if type_id == TypeId::of::() {\n Some(ScalarType::F32)\n } else if type_id == TypeId::of::() {\n Some(ScalarType::F64)\n } else if type_id == TypeId::of::() {\n Some(ScalarType::U8)\n } else if type_id == TypeId::of::() {\n Some(ScalarType::U16)\n } else if type_id == TypeId::of::() {\n Some(ScalarType::U32)\n } else if type_id == TypeId::of::() {\n Some(ScalarType::U64)\n } else if type_id == TypeId::of::() {\n Some(ScalarType::U128)\n } else if type_id == TypeId::of::() {\n Some(ScalarType::USize)\n } else if type_id == TypeId::of::() {\n Some(ScalarType::I8)\n } else if type_id == TypeId::of::() {\n Some(ScalarType::I16)\n } else if type_id == TypeId::of::() {\n Some(ScalarType::I32)\n } else if type_id == TypeId::of::() {\n Some(ScalarType::I64)\n } else if type_id == TypeId::of::() {\n Some(ScalarType::I128)\n } else if type_id == TypeId::of::() {\n Some(ScalarType::ISize)\n } else if type_id == TypeId::of::() {\n Some(ScalarType::IpAddr)\n } else if type_id == TypeId::of::() {\n Some(ScalarType::Ipv4Addr)\n } else if type_id == TypeId::of::() {\n Some(ScalarType::Ipv6Addr)\n } else if type_id == TypeId::of::() {\n Some(ScalarType::ConstTypeId)\n } else {\n None\n }\n }\n}\n\n#[cfg(test)]\nmod tests {\n use super::*;\n\n use core::net::{IpAddr, Ipv4Addr, Ipv6Addr};\n\n use facet_core::Facet;\n\n /// Simple check to ensure every can be loaded from a shape.\n #[test]\n fn test_ensure_try_from_shape() {\n assert_eq!(\n ScalarType::Unit,\n ScalarType::try_from_shape(<()>::SHAPE).unwrap()\n );\n assert_eq!(\n ScalarType::Bool,\n ScalarType::try_from_shape(bool::SHAPE).unwrap()\n );\n assert_eq!(\n ScalarType::Str,\n ScalarType::try_from_shape(<&str>::SHAPE).unwrap()\n );\n #[cfg(feature = \"std\")]\n assert_eq!(\n ScalarType::String,\n ScalarType::try_from_shape(String::SHAPE).unwrap()\n );\n #[cfg(feature = \"std\")]\n assert_eq!(\n ScalarType::CowStr,\n ScalarType::try_from_shape(alloc::borrow::Cow::SHAPE).unwrap()\n );\n assert_eq!(\n ScalarType::F32,\n ScalarType::try_from_shape(f32::SHAPE).unwrap()\n );\n assert_eq!(\n ScalarType::F64,\n ScalarType::try_from_shape(f64::SHAPE).unwrap()\n );\n assert_eq!(\n ScalarType::U8,\n ScalarType::try_from_shape(u8::SHAPE).unwrap()\n );\n assert_eq!(\n ScalarType::U16,\n ScalarType::try_from_shape(u16::SHAPE).unwrap()\n );\n assert_eq!(\n ScalarType::U32,\n ScalarType::try_from_shape(u32::SHAPE).unwrap()\n );\n assert_eq!(\n ScalarType::U64,\n ScalarType::try_from_shape(u64::SHAPE).unwrap()\n );\n assert_eq!(\n ScalarType::U128,\n ScalarType::try_from_shape(u128::SHAPE).unwrap()\n );\n assert_eq!(\n ScalarType::USize,\n ScalarType::try_from_shape(usize::SHAPE).unwrap()\n );\n assert_eq!(\n ScalarType::I8,\n ScalarType::try_from_shape(i8::SHAPE).unwrap()\n );\n assert_eq!(\n ScalarType::I16,\n ScalarType::try_from_shape(i16::SHAPE).unwrap()\n );\n assert_eq!(\n ScalarType::I32,\n ScalarType::try_from_shape(i32::SHAPE).unwrap()\n );\n assert_eq!(\n ScalarType::I64,\n ScalarType::try_from_shape(i64::SHAPE).unwrap()\n );\n assert_eq!(\n ScalarType::I128,\n ScalarType::try_from_shape(i128::SHAPE).unwrap()\n );\n assert_eq!(\n ScalarType::ISize,\n ScalarType::try_from_shape(isize::SHAPE).unwrap()\n );\n #[cfg(feature = \"std\")]\n assert_eq!(\n ScalarType::SocketAddr,\n ScalarType::try_from_shape(core::net::SocketAddr::SHAPE).unwrap()\n );\n assert_eq!(\n ScalarType::IpAddr,\n ScalarType::try_from_shape(IpAddr::SHAPE).unwrap()\n );\n assert_eq!(\n ScalarType::Ipv4Addr,\n ScalarType::try_from_shape(Ipv4Addr::SHAPE).unwrap()\n );\n assert_eq!(\n ScalarType::Ipv6Addr,\n ScalarType::try_from_shape(Ipv6Addr::SHAPE).unwrap()\n );\n assert_eq!(\n ScalarType::ConstTypeId,\n ScalarType::try_from_shape(ConstTypeId::SHAPE).unwrap()\n );\n }\n}\n"], ["/facet/facet-core/src/macros.rs", "use crate::{Facet, Opaque, Shape};\n\n#[doc(hidden)]\npub const fn shape_of<'facet, TStruct, TField: Facet<'facet>>(\n _f: &dyn Fn(&TStruct) -> &TField,\n) -> &'static Shape {\n TField::SHAPE\n}\n\n#[doc(hidden)]\npub const fn shape_of_opaque<'a, TStruct, TField>(\n _f: &dyn Fn(&TStruct) -> &TField,\n) -> &'static Shape\nwhere\n Opaque: Facet<'a>,\n{\n Opaque::::SHAPE\n}\n\n/// Creates a `ValueVTable` for a given type.\n///\n/// This macro generates a `ValueVTable` with implementations for various traits\n/// (Display, Debug, PartialEq, PartialOrd, Ord, Hash) if they are implemented for the given type.\n///\n/// # Arguments\n///\n/// * `$type_name:ty` - The type for which to create the `ValueVTable`.\n/// * `$type_name_fn:expr` - A function that writes the type name to a formatter.\n///\n/// # Example\n///\n/// ```\n/// use facet_core::value_vtable;\n/// use core::fmt::{self, Formatter};\n/// use facet_core::TypeNameOpts;\n///\n/// let vtable = value_vtable!(String, |f: &mut Formatter<'_>, _opts: TypeNameOpts| write!(f, \"String\"));\n/// ```\n///\n/// This cannot be used for a generic type because the `impls!` thing depends on type bounds.\n/// If you have a generic type, you need to do specialization yourself, like we do for slices,\n/// arrays, etc. — essentially, this macro is only useful for 1) scalars, 2) inside a derive macro\n#[macro_export]\nmacro_rules! value_vtable {\n ($type_name:ty, $type_name_fn:expr) => {\n const {\n $crate::ValueVTable::builder::<$type_name>()\n .type_name($type_name_fn)\n .display(|| {\n if $crate::spez::impls!($type_name: core::fmt::Display) {\n Some(|data, f| {\n use $crate::spez::*;\n (&&Spez(data)).spez_display(f)\n })\n } else {\n None\n }\n })\n .debug(|| {\n if $crate::spez::impls!($type_name: core::fmt::Debug) {\n Some(|data, f| {\n use $crate::spez::*;\n (&&Spez(data)).spez_debug(f)\n })\n } else {\n None\n }\n })\n .default_in_place(|| {\n if $crate::spez::impls!($type_name: core::default::Default) {\n Some(|target| unsafe {\n use $crate::spez::*;\n (&&SpezEmpty::<$type_name>::SPEZ).spez_default_in_place(target.into()).as_mut()\n })\n } else {\n None\n }\n })\n .clone_into(|| {\n if $crate::spez::impls!($type_name: core::clone::Clone) {\n Some(|src, dst| unsafe {\n use $crate::spez::*;\n (&&Spez(src)).spez_clone_into(dst.into()).as_mut()\n })\n } else {\n None\n }\n })\n .marker_traits(|| {\n let mut traits = $crate::MarkerTraits::empty();\n if $crate::spez::impls!($type_name: core::cmp::Eq) {\n traits = traits.union($crate::MarkerTraits::EQ);\n }\n if $crate::spez::impls!($type_name: core::marker::Send) {\n traits = traits.union($crate::MarkerTraits::SEND);\n }\n if $crate::spez::impls!($type_name: core::marker::Sync) {\n traits = traits.union($crate::MarkerTraits::SYNC);\n }\n if $crate::spez::impls!($type_name: core::marker::Copy) {\n traits = traits.union($crate::MarkerTraits::COPY);\n }\n if $crate::spez::impls!($type_name: core::marker::Unpin) {\n traits = traits.union($crate::MarkerTraits::UNPIN);\n }\n if $crate::spez::impls!($type_name: core::panic::UnwindSafe) {\n traits = traits.union($crate::MarkerTraits::UNWIND_SAFE);\n }\n if $crate::spez::impls!($type_name: core::panic::RefUnwindSafe) {\n traits = traits.union($crate::MarkerTraits::REF_UNWIND_SAFE);\n }\n\n traits\n })\n .partial_eq(|| {\n if $crate::spez::impls!($type_name: core::cmp::PartialEq) {\n Some(|left, right| {\n use $crate::spez::*;\n (&&Spez(left))\n .spez_partial_eq(&&Spez(right))\n })\n } else {\n None\n }\n })\n .partial_ord(|| {\n if $crate::spez::impls!($type_name: core::cmp::PartialOrd) {\n Some(|left, right| {\n use $crate::spez::*;\n (&&Spez(left))\n .spez_partial_cmp(&&Spez(right))\n })\n } else {\n None\n }\n })\n .ord(|| {\n if $crate::spez::impls!($type_name: core::cmp::Ord) {\n Some(|left, right| {\n use $crate::spez::*;\n (&&Spez(left))\n .spez_cmp(&&Spez(right))\n })\n } else {\n None\n }\n })\n .hash(|| {\n if $crate::spez::impls!($type_name: core::hash::Hash) {\n Some(|value, hasher_this, hasher_write_fn| {\n use $crate::spez::*;\n use $crate::HasherProxy;\n (&&Spez(value))\n .spez_hash(&mut unsafe { HasherProxy::new(hasher_this, hasher_write_fn) })\n })\n } else {\n None\n }\n })\n .parse(|| {\n if $crate::spez::impls!($type_name: core::str::FromStr) {\n Some(|s, target| {\n use $crate::spez::*;\n let res = unsafe { (&&SpezEmpty::<$type_name>::SPEZ).spez_parse(s, target.into()) };\n res.map(|res| unsafe { res.as_mut() })\n })\n } else {\n None\n }\n })\n .build()\n }\n };\n}\n\n/// Similar to `value_vtable!` macro but for `!Sized` types.\n#[macro_export]\nmacro_rules! value_vtable_unsized {\n ($type_name:ty, $type_name_fn:expr) => {\n const {\n $crate::ValueVTable::builder_unsized::<$type_name>()\n .type_name($type_name_fn)\n .display(|| {\n if $crate::spez::impls!($type_name: core::fmt::Display) {\n Some(|data, f| {\n use $crate::spez::*;\n (&&Spez(data)).spez_display(f)\n })\n } else {\n None\n }\n })\n .debug(|| {\n if $crate::spez::impls!($type_name: core::fmt::Debug) {\n Some(|data, f| {\n use $crate::spez::*;\n (&&Spez(data)).spez_debug(f)\n })\n } else {\n None\n }\n })\n .marker_traits(|| {\n let mut traits = $crate::MarkerTraits::empty();\n if $crate::spez::impls!($type_name: core::cmp::Eq) {\n traits = traits.union($crate::MarkerTraits::EQ);\n }\n if $crate::spez::impls!($type_name: core::marker::Send) {\n traits = traits.union($crate::MarkerTraits::SEND);\n }\n if $crate::spez::impls!($type_name: core::marker::Sync) {\n traits = traits.union($crate::MarkerTraits::SYNC);\n }\n if $crate::spez::impls!($type_name: core::marker::Copy) {\n traits = traits.union($crate::MarkerTraits::COPY);\n }\n if $crate::spez::impls!($type_name: core::marker::Unpin) {\n traits = traits.union($crate::MarkerTraits::UNPIN);\n }\n if $crate::spez::impls!($type_name: core::panic::UnwindSafe) {\n traits = traits.union($crate::MarkerTraits::UNWIND_SAFE);\n }\n if $crate::spez::impls!($type_name: core::panic::RefUnwindSafe) {\n traits = traits.union($crate::MarkerTraits::REF_UNWIND_SAFE);\n }\n\n traits\n })\n .partial_eq(|| {\n if $crate::spez::impls!($type_name: core::cmp::PartialEq) {\n Some(|left, right| {\n use $crate::spez::*;\n (&&Spez(left))\n .spez_partial_eq(&&Spez(right))\n })\n } else {\n None\n }\n })\n .partial_ord(|| {\n if $crate::spez::impls!($type_name: core::cmp::PartialOrd) {\n Some(|left, right| {\n use $crate::spez::*;\n (&&Spez(left))\n .spez_partial_cmp(&&Spez(right))\n })\n } else {\n None\n }\n })\n .ord(|| {\n if $crate::spez::impls!($type_name: core::cmp::Ord) {\n Some(|left, right| {\n use $crate::spez::*;\n (&&Spez(left))\n .spez_cmp(&&Spez(right))\n })\n } else {\n None\n }\n })\n .hash(|| {\n if $crate::spez::impls!($type_name: core::hash::Hash) {\n Some(|value, hasher_this, hasher_write_fn| {\n use $crate::spez::*;\n use $crate::HasherProxy;\n (&&Spez(value))\n .spez_hash(&mut unsafe { HasherProxy::new(hasher_this, hasher_write_fn) })\n })\n } else {\n None\n }\n })\n .build()\n }\n };\n}\n"], ["/facet/facet-core/src/spez/mod.rs", "//! Auto-deref specialization helpers for the Facet reflection system\n//!\n//! This module provides traits and implementations that allow for specialization\n//! based on what traits a type implements, without requiring the unstable\n//! `specialization` feature.\n\nuse crate::types::ParseError;\npub use ::impls::impls;\nuse core::fmt::{self, Debug};\nuse core::marker::PhantomData;\n\nuse crate::ptr::{PtrMut, PtrUninit};\n\n/// A wrapper type used for auto-deref specialization.\n///\n/// This struct is a core part of the auto-deref-based specialization technique which allows\n/// conditionally implementing functionality based on what traits a type implements, without\n/// requiring the unstable `specialization` feature.\n///\n/// It wraps a value and is used in conjunction with trait implementations that leverage\n/// Rust's method resolution rules to select different implementations based on available traits.\npub struct Spez(pub T);\n\n/// A wrapper type used for auto-deref specialization.\n///\n/// This struct is a core part of the auto-deref-based specialization technique which allows\n/// conditionally implementing functionality based on what traits a type implements, without\n/// requiring the unstable `specialization` feature.\n///\n/// Unlike [`Spez`], [`SpezEmpty`] wraps a type instead of a value. It is used in conjunction with\n/// trait implementations that leverage Rust's method resolution rules to select different\n/// implementations based on available traits.\npub struct SpezEmpty(PhantomData T>);\n\nimpl SpezEmpty {\n /// An instance of [`SpezEmpty`].\n pub const SPEZ: Self = Self(PhantomData);\n}\n\n//////////////////////////////////////////////////////////////////////////////////////\n// Debug 🐛🔍\n//////////////////////////////////////////////////////////////////////////////////////\n\n/// Specialization proxy for [`core::fmt::Debug`]\npub trait SpezDebugYes {\n /// Delegates to the inner type's `Debug` implementation.\n ///\n /// This method is called when the wrapped type implements `Debug`.\n /// It forwards the formatting request to the inner value's `Debug` implementation.\n fn spez_debug(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error>;\n}\nimpl SpezDebugYes for &Spez {\n fn spez_debug(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {\n Debug::fmt(&self.0, f)\n }\n}\n\n/// Specialization proxy for [`core::fmt::Debug`]\npub trait SpezDebugNo {\n /// Fallback implementation when the type doesn't implement `Debug`.\n ///\n /// This method is used as a fallback and is designed to be unreachable in practice.\n /// It's only selected when the wrapped type doesn't implement `Debug`.\n fn spez_debug(&self, _f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error>;\n}\nimpl SpezDebugNo for Spez {\n fn spez_debug(&self, _f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {\n unreachable!()\n }\n}\n\n//////////////////////////////////////////////////////////////////////////////////////\n// Display 📺🖥️\n//////////////////////////////////////////////////////////////////////////////////////\n\n/// Specialization proxy for [`core::fmt::Display`]\npub trait SpezDisplayYes {\n /// Delegates to the inner type's `Display` implementation.\n ///\n /// This method is called when the wrapped type implements `Display`.\n /// It forwards the formatting request to the inner value's `Display` implementation.\n fn spez_display(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error>;\n}\nimpl SpezDisplayYes for &Spez {\n fn spez_display(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {\n fmt::Display::fmt(&self.0, f)\n }\n}\n\n/// Specialization proxy for [`core::fmt::Display`]\npub trait SpezDisplayNo {\n /// Fallback implementation when the type doesn't implement `Display`.\n ///\n /// This method is used as a fallback and is designed to be unreachable in practice.\n /// It's only selected when the wrapped type doesn't implement `Display`.\n fn spez_display(&self, _f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error>;\n}\nimpl SpezDisplayNo for Spez {\n fn spez_display(&self, _f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {\n unreachable!()\n }\n}\n\n//////////////////////////////////////////////////////////////////////////////////////\n// Default (in place, because we can't have sized) 🏠🔄\n//////////////////////////////////////////////////////////////////////////////////////\n\n/// Specialization proxy for [`core::default::Default`]\npub trait SpezDefaultInPlaceYes {\n /// Creates a default value for the inner type in place.\n ///\n /// This method is called when the wrapped type implements `Default`.\n /// It writes the default value into the provided uninitialized memory.\n ///\n /// # Safety\n ///\n /// This function operates on uninitialized memory and requires that `target`\n /// has sufficient space allocated for type `T`.\n unsafe fn spez_default_in_place<'mem>(&self, target: PtrUninit<'mem>) -> PtrMut<'mem>;\n}\nimpl SpezDefaultInPlaceYes for &SpezEmpty {\n unsafe fn spez_default_in_place<'mem>(&self, target: PtrUninit<'mem>) -> PtrMut<'mem> {\n unsafe { target.put(::default()) }\n }\n}\n\n/// Specialization proxy for [`core::default::Default`]\npub trait SpezDefaultInPlaceNo {\n /// Fallback implementation when the type doesn't implement `Default`.\n ///\n /// This method is used as a fallback and is designed to be unreachable in practice.\n /// It's only selected when the wrapped type doesn't implement `Default`.\n ///\n /// # Safety\n ///\n /// This function is marked unsafe as it deals with uninitialized memory,\n /// but it should never be reachable in practice.\n unsafe fn spez_default_in_place<'mem>(&self, _target: PtrUninit<'mem>) -> PtrMut<'mem>;\n}\nimpl SpezDefaultInPlaceNo for SpezEmpty {\n unsafe fn spez_default_in_place<'mem>(&self, _target: PtrUninit<'mem>) -> PtrMut<'mem> {\n unreachable!()\n }\n}\n\n//////////////////////////////////////////////////////////////////////////////////////\n// Clone into 🐑📥\n//////////////////////////////////////////////////////////////////////////////////////\n\n/// Specialization proxy for [`core::clone::Clone`]\npub trait SpezCloneIntoYes {\n /// Clones the inner value into the provided uninitialized memory.\n ///\n /// This method is called when the wrapped type implements `Clone`.\n /// It creates a clone of the inner value and writes it into the target memory.\n ///\n /// # Safety\n ///\n /// This function operates on uninitialized memory and requires that `target`\n /// has sufficient space allocated for type `T`.\n unsafe fn spez_clone_into<'mem>(&self, target: PtrUninit<'mem>) -> PtrMut<'mem>;\n}\nimpl SpezCloneIntoYes for &Spez<&T> {\n unsafe fn spez_clone_into<'mem>(&self, target: PtrUninit<'mem>) -> PtrMut<'mem> {\n unsafe { target.put(self.0.clone()) }\n }\n}\n\n/// Specialization proxy for [`core::clone::Clone`]\npub trait SpezCloneIntoNo {\n /// Fallback implementation when the type doesn't implement `Clone`.\n ///\n /// This method is used as a fallback and is designed to be unreachable in practice.\n /// It's only selected when the wrapped type doesn't implement `Clone`.\n ///\n /// # Safety\n ///\n /// This function is marked unsafe as it deals with uninitialized memory,\n /// but it should never be reachable in practice.\n unsafe fn spez_clone_into<'mem>(&self, _target: PtrUninit<'mem>) -> PtrMut<'mem>;\n}\nimpl SpezCloneIntoNo for Spez {\n unsafe fn spez_clone_into<'mem>(&self, _target: PtrUninit<'mem>) -> PtrMut<'mem> {\n unreachable!()\n }\n}\n\n//////////////////////////////////////////////////////////////////////////////////////\n// Parse 📝🔍\n//////////////////////////////////////////////////////////////////////////////////////\n\n/// Specialization proxy for [`core::str::FromStr`]\npub trait SpezParseYes {\n /// Parses a string slice into the inner type.\n ///\n /// This method is called when the wrapped type implements `FromStr`.\n /// It attempts to parse the provided string and write the result into the target memory.\n ///\n /// # Safety\n ///\n /// This function operates on uninitialized memory and requires that `target`\n /// has sufficient space allocated for type `T`.\n unsafe fn spez_parse<'mem>(\n &self,\n s: &str,\n target: PtrUninit<'mem>,\n ) -> Result, ParseError>;\n}\nimpl SpezParseYes for &SpezEmpty {\n unsafe fn spez_parse<'mem>(\n &self,\n s: &str,\n target: PtrUninit<'mem>,\n ) -> Result, ParseError> {\n match ::from_str(s) {\n Ok(value) => Ok(unsafe { target.put(value) }),\n Err(_) => Err(ParseError::Generic(\n const { concat!(\"parse error for \", stringify!(T)) },\n )),\n }\n }\n}\n\n/// Specialization proxy for [`core::str::FromStr`]\npub trait SpezParseNo {\n /// Fallback implementation when the type doesn't implement `FromStr`.\n ///\n /// This method is used as a fallback and is designed to be unreachable in practice.\n /// It's only selected when the wrapped type doesn't implement `FromStr`.\n ///\n /// # Safety\n ///\n /// This function is marked unsafe as it deals with uninitialized memory,\n /// but it should never be reachable in practice.\n unsafe fn spez_parse<'mem>(\n &self,\n _s: &str,\n _target: PtrUninit<'mem>,\n ) -> Result, ParseError>;\n}\nimpl SpezParseNo for SpezEmpty {\n unsafe fn spez_parse<'mem>(\n &self,\n _s: &str,\n _target: PtrUninit<'mem>,\n ) -> Result, ParseError> {\n unreachable!()\n }\n}\n\n//////////////////////////////////////////////////////////////////////////////////////\n// PartialEq 🟰🤝\n//////////////////////////////////////////////////////////////////////////////////////\n\n/// Specialization proxy for [`core::cmp::PartialEq`]\npub trait SpezPartialEqYes {\n /// Checks if two values are equal.\n ///\n /// This method is called when the wrapped type implements `PartialEq`.\n /// It compares the inner values for equality.\n fn spez_partial_eq(&self, other: &Self) -> bool;\n}\nimpl SpezPartialEqYes for &Spez {\n fn spez_partial_eq(&self, other: &Self) -> bool {\n self.0 == other.0\n }\n}\n\n/// Specialization proxy for [`core::cmp::PartialEq`]\npub trait SpezPartialEqNo {\n /// Fallback implementation when the type doesn't implement `PartialEq`.\n ///\n /// This method is used as a fallback and is designed to be unreachable in practice.\n /// It's only selected when the wrapped type doesn't implement `PartialEq`.\n fn spez_partial_eq(&self, _other: &Self) -> bool;\n}\nimpl SpezPartialEqNo for Spez {\n fn spez_partial_eq(&self, _other: &Self) -> bool {\n unreachable!()\n }\n}\n\n//////////////////////////////////////////////////////////////////////////////////////\n// PartialOrd 🔢↕️\n//////////////////////////////////////////////////////////////////////////////////////\n\n/// Specialization proxy for [`core::cmp::PartialOrd`]\npub trait SpezPartialOrdYes {\n /// Compares two values for ordering.\n ///\n /// This method is called when the wrapped type implements `PartialOrd`.\n /// It compares the inner values and returns their ordering.\n fn spez_partial_cmp(&self, other: &Self) -> Option;\n}\nimpl SpezPartialOrdYes for &Spez {\n fn spez_partial_cmp(&self, other: &Self) -> Option {\n self.0.partial_cmp(&other.0)\n }\n}\n\n/// Specialization proxy for [`core::cmp::PartialOrd`]\npub trait SpezPartialOrdNo {\n /// Fallback implementation when the type doesn't implement `PartialOrd`.\n ///\n /// This method is used as a fallback and is designed to be unreachable in practice.\n /// It's only selected when the wrapped type doesn't implement `PartialOrd`.\n fn spez_partial_cmp(&self, _other: &Self) -> Option;\n}\nimpl SpezPartialOrdNo for Spez {\n fn spez_partial_cmp(&self, _other: &Self) -> Option {\n unreachable!()\n }\n}\n\n//////////////////////////////////////////////////////////////////////////////////////\n// Ord 📊🔀\n//////////////////////////////////////////////////////////////////////////////////////\n\n/// Specialization proxy for [`core::cmp::Ord`]\npub trait SpezOrdYes {\n /// Compares two values for ordering.\n ///\n /// This method is called when the wrapped type implements `Ord`.\n /// It compares the inner values and returns their ordering.\n fn spez_cmp(&self, other: &Self) -> core::cmp::Ordering;\n}\nimpl SpezOrdYes for &Spez {\n fn spez_cmp(&self, other: &Self) -> core::cmp::Ordering {\n self.0.cmp(&other.0)\n }\n}\n\n/// Specialization proxy for [`core::cmp::Ord`]\npub trait SpezOrdNo {\n /// Fallback implementation when the type doesn't implement `Ord`.\n ///\n /// This method is used as a fallback and is designed to be unreachable in practice.\n /// It's only selected when the wrapped type doesn't implement `Ord`.\n fn spez_cmp(&self, _other: &Self) -> core::cmp::Ordering;\n}\nimpl SpezOrdNo for Spez {\n fn spez_cmp(&self, _other: &Self) -> core::cmp::Ordering {\n unreachable!()\n }\n}\n\n//////////////////////////////////////////////////////////////////////////////////////\n// Hash #️⃣🔐\n//////////////////////////////////////////////////////////////////////////////////////\n\n/// Specialization proxy for [`core::hash::Hash`]\npub trait SpezHashYes {\n /// Hashes the inner value.\n ///\n /// This method is called when the wrapped type implements `Hash`.\n /// It hashes the inner value using the provided hasher.\n fn spez_hash(&self, state: &mut H);\n}\nimpl SpezHashYes for &Spez {\n fn spez_hash(&self, state: &mut H) {\n self.0.hash(state)\n }\n}\n\n/// Specialization proxy for [`core::hash::Hash`]\npub trait SpezHashNo {\n /// Fallback implementation when the type doesn't implement `Hash`.\n ///\n /// This method is used as a fallback and is designed to be unreachable in practice.\n /// It's only selected when the wrapped type doesn't implement `Hash`.\n fn spez_hash(&self, _state: &mut H);\n}\nimpl SpezHashNo for Spez {\n fn spez_hash(&self, _state: &mut H) {\n unreachable!()\n }\n}\n"], ["/facet/facet-core/src/impls_std/hashmap.rs", "use core::hash::BuildHasher;\nuse std::collections::HashMap;\nuse std::hash::RandomState;\n\nuse crate::ptr::{PtrConst, PtrMut};\n\nuse crate::{\n Def, Facet, IterVTable, MapDef, MapVTable, MarkerTraits, Shape, Type, TypeParam, UserType,\n ValueVTable, value_vtable,\n};\n\ntype HashMapIterator<'mem, K, V> = std::collections::hash_map::Iter<'mem, K, V>;\n\nunsafe impl<'a, K, V, S> Facet<'a> for HashMap\nwhere\n K: Facet<'a> + core::cmp::Eq + core::hash::Hash,\n V: Facet<'a>,\n S: Facet<'a> + Default + BuildHasher,\n{\n const VTABLE: &'static ValueVTable = &const {\n ValueVTable::builder::()\n .marker_traits(|| {\n let arg_dependent_traits = MarkerTraits::SEND\n .union(MarkerTraits::SYNC)\n .union(MarkerTraits::EQ)\n .union(MarkerTraits::UNPIN)\n .union(MarkerTraits::UNWIND_SAFE)\n .union(MarkerTraits::REF_UNWIND_SAFE);\n arg_dependent_traits\n .intersection(V::SHAPE.vtable.marker_traits())\n .intersection(K::SHAPE.vtable.marker_traits())\n })\n .type_name(|f, opts| {\n if let Some(opts) = opts.for_children() {\n write!(f, \"{}<\", Self::SHAPE.type_identifier)?;\n K::SHAPE.vtable.type_name()(f, opts)?;\n write!(f, \", \")?;\n V::SHAPE.vtable.type_name()(f, opts)?;\n write!(f, \">\")\n } else {\n write!(f, \"{}<⋯>\", Self::SHAPE.type_identifier)\n }\n })\n .default_in_place(|| Some(|target| unsafe { target.put(Self::default()) }))\n .build()\n };\n\n const SHAPE: &'static Shape = &const {\n Shape::builder_for_sized::()\n .type_identifier(\"HashMap\")\n .type_params(&[\n TypeParam {\n name: \"K\",\n shape: || K::SHAPE,\n },\n TypeParam {\n name: \"V\",\n shape: || V::SHAPE,\n },\n TypeParam {\n name: \"S\",\n shape: || S::SHAPE,\n },\n ])\n .ty(Type::User(UserType::Opaque))\n .def(Def::Map(\n MapDef::builder()\n .k(|| K::SHAPE)\n .v(|| V::SHAPE)\n .vtable(\n &const {\n MapVTable::builder()\n .init_in_place_with_capacity(|uninit, capacity| unsafe {\n uninit\n .put(Self::with_capacity_and_hasher(capacity, S::default()))\n })\n .insert(|ptr, key, value| unsafe {\n let map = ptr.as_mut::>();\n let key = key.read::();\n let value = value.read::();\n map.insert(key, value);\n })\n .len(|ptr| unsafe {\n let map = ptr.get::>();\n map.len()\n })\n .contains_key(|ptr, key| unsafe {\n let map = ptr.get::>();\n map.contains_key(key.get())\n })\n .get_value_ptr(|ptr, key| unsafe {\n let map = ptr.get::>();\n map.get(key.get()).map(|v| PtrConst::new(v))\n })\n .iter_vtable(\n IterVTable::builder()\n .init_with_value(|ptr| unsafe {\n let map = ptr.get::>();\n let iter: HashMapIterator<'_, K, V> = map.iter();\n let iter_state = Box::new(iter);\n PtrMut::new(Box::into_raw(iter_state) as *mut u8)\n })\n .next(|iter_ptr| unsafe {\n let state =\n iter_ptr.as_mut::>();\n state.next().map(|(key, value)| {\n (\n PtrConst::new(key as *const K),\n PtrConst::new(value as *const V),\n )\n })\n })\n .dealloc(|iter_ptr| unsafe {\n drop(Box::from_raw(\n iter_ptr.as_ptr::>()\n as *mut HashMapIterator<'_, K, V>,\n ));\n })\n .build(),\n )\n .build()\n },\n )\n .build(),\n ))\n .build()\n };\n}\n\nunsafe impl Facet<'_> for RandomState {\n const VTABLE: &'static ValueVTable =\n &const { value_vtable!((), |f, _opts| write!(f, \"{}\", Self::SHAPE.type_identifier)) };\n\n const SHAPE: &'static Shape = &const {\n Shape::builder_for_sized::()\n .type_identifier(\"RandomState\")\n .ty(Type::User(UserType::Opaque))\n .def(Def::Scalar)\n .build()\n };\n}\n"], ["/facet/facet-testhelpers/src/lib.rs", "#![warn(missing_docs)]\n#![warn(clippy::std_instead_of_core)]\n#![warn(clippy::std_instead_of_alloc)]\n#![forbid(unsafe_code)]\n#![doc = include_str!(\"../README.md\")]\n\npub use facet_testhelpers_macros::test;\n\nuse log::{Level, LevelFilter, Log, Metadata, Record};\nuse owo_colors::{OwoColorize, Style};\nuse std::io::Write;\n\nstruct SimpleLogger;\n\nimpl Log for SimpleLogger {\n fn enabled(&self, _metadata: &Metadata) -> bool {\n true\n }\n\n fn log(&self, record: &Record) {\n // Create style based on log level\n let level_style = match record.level() {\n Level::Error => Style::new().fg_rgb::<243, 139, 168>(), // Catppuccin red (Maroon)\n Level::Warn => Style::new().fg_rgb::<249, 226, 175>(), // Catppuccin yellow (Peach)\n Level::Info => Style::new().fg_rgb::<166, 227, 161>(), // Catppuccin green (Green)\n Level::Debug => Style::new().fg_rgb::<137, 180, 250>(), // Catppuccin blue (Blue)\n Level::Trace => Style::new().fg_rgb::<148, 226, 213>(), // Catppuccin teal (Teal)\n };\n\n // Convert level to styled display\n eprintln!(\n \"{} - {}: {}\",\n record.level().style(level_style),\n record\n .target()\n .style(Style::new().fg_rgb::<137, 180, 250>()), // Blue for the target\n record.args()\n );\n }\n\n fn flush(&self) {\n let _ = std::io::stderr().flush();\n }\n}\n\n/// Set up a simple logger.\npub fn setup() {\n let logger = Box::new(SimpleLogger);\n log::set_boxed_logger(logger).unwrap();\n log::set_max_level(LevelFilter::Trace);\n}\n"], ["/facet/facet-core/src/types/def/iter.rs", "use crate::{PtrConst, PtrMut};\n\n/// Create a new iterator that iterates over the provided value\n///\n/// # Safety\n///\n/// The `value` parameter must point to aligned, initialized memory of the correct type.\npub type IterInitWithValueFn = for<'value> unsafe fn(value: PtrConst<'value>) -> PtrMut<'value>;\n\n/// Advance the iterator, returning the next value from the iterator\n///\n/// # Safety\n///\n/// The `iter` parameter must point to aligned, initialized memory of the correct type.\npub type IterNextFn =\n for<'iter> unsafe fn(iter: PtrMut<'iter>) -> Option<::Item<'iter>>;\n\n/// Advance the iterator in reverse, returning the next value from the end\n/// of the iterator.\n///\n/// # Safety\n///\n/// The `iter` parameter must point to aligned, initialized memory of the correct type.\npub type IterNextBackFn =\n for<'iter> unsafe fn(iter: PtrMut<'iter>) -> Option<::Item<'iter>>;\n\n/// Return the lower and upper bounds of the iterator, if known.\n///\n/// # Safety\n///\n/// The `iter` parameter must point to aligned, initialized memory of the correct type.\npub type IterSizeHintFn =\n for<'iter> unsafe fn(iter: PtrMut<'iter>) -> Option<(usize, Option)>;\n\n/// Deallocate the iterator\n///\n/// # Safety\n///\n/// The `iter` parameter must point to aligned, initialized memory of the correct type.\npub type IterDeallocFn = for<'iter> unsafe fn(iter: PtrMut<'iter>);\n\n/// VTable for an iterator\n#[derive(Clone, Copy, Debug)]\n#[repr(C)]\npub struct IterVTable {\n /// cf. [`IterInitWithValueFn`]\n pub init_with_value: Option,\n\n /// cf. [`IterNextFn`]\n pub next: IterNextFn,\n\n /// cf. [`IterNextBackFn`]\n pub next_back: Option>,\n\n /// cf. [`IterSizeHintFn`]\n pub size_hint: Option,\n\n /// cf. [`IterDeallocFn`]\n pub dealloc: IterDeallocFn,\n}\n\nimpl IterVTable {\n /// Returns a builder for [`IterVTable`]\n pub const fn builder() -> IterVTableBuilder {\n IterVTableBuilder::new()\n }\n}\n\n/// Builds an [`IterVTable`]\npub struct IterVTableBuilder {\n init_with_value: Option,\n next: Option>,\n next_back: Option>,\n size_hint: Option,\n dealloc: Option,\n}\n\nimpl IterVTableBuilder {\n /// Creates a new [`IterVTableBuilder`] with all fields set to `None`.\n #[allow(clippy::new_without_default)]\n pub const fn new() -> Self {\n Self {\n init_with_value: None,\n next: None,\n next_back: None,\n size_hint: None,\n dealloc: None,\n }\n }\n\n /// Sets the `init_with_value` function\n pub const fn init_with_value(mut self, f: IterInitWithValueFn) -> Self {\n self.init_with_value = Some(f);\n self\n }\n\n /// Sets the `next` function\n pub const fn next(mut self, f: IterNextFn) -> Self {\n self.next = Some(f);\n self\n }\n\n /// Sets the `next_back` function\n pub const fn next_back(mut self, f: IterNextBackFn) -> Self {\n self.next_back = Some(f);\n self\n }\n\n /// Sets the `dealloc` function\n pub const fn dealloc(mut self, f: IterDeallocFn) -> Self {\n self.dealloc = Some(f);\n self\n }\n\n /// Builds the [`IterVTable`] from the current state of the builder.\n ///\n /// # Panics\n ///\n /// Panic if any of the required fields (init_with_value, next, dealloc) are `None`.\n pub const fn build(self) -> IterVTable {\n assert!(self.init_with_value.is_some());\n IterVTable {\n init_with_value: self.init_with_value,\n next: self.next.unwrap(),\n next_back: self.next_back,\n size_hint: self.size_hint,\n dealloc: self.dealloc.unwrap(),\n }\n }\n}\n\n/// A kind of item that an [`IterVTable`] returns\n///\n/// This trait is needed as a utility, so the functions within [`IterVTable`]\n/// can apply the appropriate lifetime to their result types. In other words,\n/// this trait acts like a higher-kinded type that takes a lifetime.\npub trait IterItem {\n /// The output type of the iterator, bound by the lifetime `'a`\n type Item<'a>;\n}\n\nimpl IterItem for PtrConst<'_> {\n type Item<'a> = PtrConst<'a>;\n}\n\nimpl IterItem for (T, U)\nwhere\n T: IterItem,\n U: IterItem,\n{\n type Item<'a> = (T::Item<'a>, U::Item<'a>);\n}\n"], ["/facet/facet-core/src/impls_core/slice.rs", "use crate::*;\n\nunsafe impl<'a, T> Facet<'a> for [T]\nwhere\n T: Facet<'a>,\n{\n const VTABLE: &'static ValueVTable = &const {\n ValueVTable::builder_unsized::()\n .type_name(|f, opts| {\n if let Some(opts) = opts.for_children() {\n write!(f, \"[\")?;\n (T::SHAPE.vtable.type_name())(f, opts)?;\n write!(f, \"]\")\n } else {\n write!(f, \"[⋯]\")\n }\n })\n .marker_traits(|| {\n T::SHAPE\n .vtable\n .marker_traits()\n .difference(MarkerTraits::COPY)\n })\n .debug(|| {\n if T::SHAPE.vtable.has_debug() {\n Some(|value, f| {\n write!(f, \"[\")?;\n for (i, item) in value.iter().enumerate() {\n if i > 0 {\n write!(f, \", \")?;\n }\n (>::of().debug().unwrap())(item, f)?;\n }\n write!(f, \"]\")\n })\n } else {\n None\n }\n })\n .partial_eq(|| {\n if T::SHAPE.vtable.has_partial_eq() {\n Some(|a, b| {\n if a.len() != b.len() {\n return false;\n }\n for (x, y) in a.iter().zip(b.iter()) {\n if !(>::of().partial_eq().unwrap())(x, y) {\n return false;\n }\n }\n true\n })\n } else {\n None\n }\n })\n .partial_ord(|| {\n if T::SHAPE.vtable.has_partial_ord() {\n Some(|a, b| {\n for (x, y) in a.iter().zip(b.iter()) {\n let ord = (>::of().partial_ord().unwrap())(x, y);\n match ord {\n Some(core::cmp::Ordering::Equal) => continue,\n Some(order) => return Some(order),\n None => return None,\n }\n }\n a.len().partial_cmp(&b.len())\n })\n } else {\n None\n }\n })\n .ord(|| {\n if T::SHAPE.vtable.has_ord() {\n Some(|a, b| {\n for (x, y) in a.iter().zip(b.iter()) {\n let ord = (>::of().ord().unwrap())(x, y);\n if ord != core::cmp::Ordering::Equal {\n return ord;\n }\n }\n a.len().cmp(&b.len())\n })\n } else {\n None\n }\n })\n .hash(|| {\n if T::SHAPE.vtable.has_hash() {\n Some(|value, state, hasher| {\n for item in value.iter() {\n (>::of().hash().unwrap())(item, state, hasher);\n }\n })\n } else {\n None\n }\n })\n .build()\n };\n\n const SHAPE: &'static Shape = &const {\n Shape::builder_for_unsized::()\n .type_identifier(\"[_]\")\n .type_params(&[TypeParam {\n name: \"T\",\n shape: || T::SHAPE,\n }])\n .ty(Type::Sequence(SequenceType::Slice(SliceType {\n t: T::SHAPE,\n })))\n .def(Def::Slice(\n SliceDef::builder()\n .vtable(\n &const {\n SliceVTable::builder()\n .len(|ptr| unsafe {\n let slice = ptr.get::<&[T]>();\n slice.len()\n })\n .as_ptr(|ptr| unsafe {\n let slice = ptr.get::<&[T]>();\n PtrConst::new(slice.as_ptr())\n })\n .as_mut_ptr(|ptr| unsafe {\n let slice = ptr.as_mut::<&mut [T]>();\n PtrMut::new(slice.as_mut_ptr())\n })\n .build()\n },\n )\n .t(T::SHAPE)\n .build(),\n ))\n .build()\n };\n}\n"], ["/facet/facet-reflect/src/peek/set.rs", "use super::Peek;\nuse facet_core::{PtrMut, SetDef};\n\n/// Iterator over values in a `PeekSet`\npub struct PeekSetIter<'mem, 'facet> {\n set: PeekSet<'mem, 'facet>,\n iter: PtrMut<'mem>,\n}\n\nimpl<'mem, 'facet> Iterator for PeekSetIter<'mem, 'facet> {\n type Item = Peek<'mem, 'facet>;\n\n #[inline]\n fn next(&mut self) -> Option {\n unsafe {\n let next = (self.set.def.vtable.iter_vtable.next)(self.iter)?;\n Some(Peek::unchecked_new(next, self.set.def.t()))\n }\n }\n}\n\nimpl<'mem, 'facet> Drop for PeekSetIter<'mem, 'facet> {\n #[inline]\n fn drop(&mut self) {\n unsafe { (self.set.def.vtable.iter_vtable.dealloc)(self.iter) }\n }\n}\n\nimpl<'mem, 'facet> IntoIterator for &'mem PeekSet<'mem, 'facet> {\n type Item = Peek<'mem, 'facet>;\n type IntoIter = PeekSetIter<'mem, 'facet>;\n\n #[inline]\n fn into_iter(self) -> Self::IntoIter {\n self.iter()\n }\n}\n\n/// Lets you read from a set\n#[derive(Clone, Copy)]\npub struct PeekSet<'mem, 'facet> {\n pub(crate) value: Peek<'mem, 'facet>,\n\n pub(crate) def: SetDef,\n}\n\nimpl<'mem, 'facet> core::fmt::Debug for PeekSet<'mem, 'facet> {\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n f.debug_struct(\"PeekSet\").finish_non_exhaustive()\n }\n}\n\nimpl<'mem, 'facet> PeekSet<'mem, 'facet> {\n /// Constructor\n #[inline]\n pub fn new(value: Peek<'mem, 'facet>, def: SetDef) -> Self {\n Self { value, def }\n }\n\n /// Returns true if the set is empty\n #[inline]\n pub fn is_empty(&self) -> bool {\n self.len() == 0\n }\n\n /// Get the number of entries in the set\n #[inline]\n pub fn len(&self) -> usize {\n unsafe { (self.def.vtable.len_fn)(self.value.data().thin().unwrap()) }\n }\n\n /// Returns an iterator over the values in the set\n #[inline]\n pub fn iter(self) -> PeekSetIter<'mem, 'facet> {\n let iter_init_with_value_fn = self.def.vtable.iter_vtable.init_with_value.unwrap();\n let iter = unsafe { iter_init_with_value_fn(self.value.data().thin().unwrap()) };\n PeekSetIter { set: self, iter }\n }\n\n /// Def getter\n #[inline]\n pub fn def(&self) -> SetDef {\n self.def\n }\n}\n"], ["/facet/facet-core/src/types/characteristic.rs", "use core::fmt;\n\nuse super::{MarkerTraits, Shape, TypeNameOpts};\n\n/// A characteristic a shape can have\n#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]\n#[repr(C)]\npub enum Characteristic {\n // Marker traits\n /// Implements Send\n Send,\n\n /// Implements Sync\n Sync,\n\n /// Implements Copy\n Copy,\n\n /// Implements Eq\n Eq,\n\n /// Implements Unpin\n Unpin,\n\n // Functionality traits\n /// Implements Clone\n Clone,\n\n /// Implements Display\n Display,\n\n /// Implements Debug\n Debug,\n\n /// Implements PartialEq\n PartialEq,\n\n /// Implements PartialOrd\n PartialOrd,\n\n /// Implements Ord\n Ord,\n\n /// Implements Hash\n Hash,\n\n /// Implements Default\n Default,\n\n /// Implements FromStr\n FromStr,\n}\n\nimpl Characteristic {\n /// Checks if all shapes have the given characteristic.\n #[inline]\n pub fn all(self, shapes: &[&Shape]) -> bool {\n let mut i = 0;\n while i < shapes.len() {\n if !shapes[i].is(self) {\n return false;\n }\n i += 1;\n }\n true\n }\n\n /// Checks if any shape has the given characteristic.\n #[inline]\n pub fn any(self, shapes: &[&Shape]) -> bool {\n let mut i = 0;\n while i < shapes.len() {\n if shapes[i].is(self) {\n return true;\n }\n i += 1;\n }\n false\n }\n\n /// Checks if none of the shapes have the given characteristic.\n #[inline]\n pub fn none(self, shapes: &[&Shape]) -> bool {\n let mut i = 0;\n while i < shapes.len() {\n if shapes[i].is(self) {\n return false;\n }\n i += 1;\n }\n true\n }\n\n /// Checks if all shapes have the `Default` characteristic\n #[inline]\n pub fn all_default(shapes: &[&Shape]) -> bool {\n let mut i = 0;\n while i < shapes.len() {\n if !shapes[i].is_default() {\n return false;\n }\n i += 1;\n }\n true\n }\n\n /// Checks if all shapes have the `PartialEq` characteristic\n #[inline]\n pub fn all_partial_eq(shapes: &[&Shape]) -> bool {\n let mut i = 0;\n while i < shapes.len() {\n if !shapes[i].is_partial_eq() {\n return false;\n }\n i += 1;\n }\n true\n }\n\n /// Checks if all shapes have the `PartialOrd` characteristic\n #[inline]\n pub fn all_partial_ord(shapes: &[&Shape]) -> bool {\n let mut i = 0;\n while i < shapes.len() {\n if !shapes[i].is_partial_ord() {\n return false;\n }\n i += 1;\n }\n true\n }\n\n /// Checks if all shapes have the `Ord` characteristic\n #[inline]\n pub fn all_ord(shapes: &[&Shape]) -> bool {\n let mut i = 0;\n while i < shapes.len() {\n if !shapes[i].is_ord() {\n return false;\n }\n i += 1;\n }\n true\n }\n\n /// Checks if all shapes have the `Hash` characteristic\n #[inline]\n pub fn all_hash(shapes: &[&Shape]) -> bool {\n let mut i = 0;\n while i < shapes.len() {\n if !shapes[i].is_hash() {\n return false;\n }\n i += 1;\n }\n true\n }\n}\n\nimpl Shape {\n /// Checks if a shape has the given characteristic.\n #[inline]\n pub fn is(&self, characteristic: Characteristic) -> bool {\n match characteristic {\n // Marker traits\n Characteristic::Send => self.vtable.marker_traits().contains(MarkerTraits::SEND),\n Characteristic::Sync => self.vtable.marker_traits().contains(MarkerTraits::SYNC),\n Characteristic::Copy => self.vtable.marker_traits().contains(MarkerTraits::COPY),\n Characteristic::Eq => self.vtable.marker_traits().contains(MarkerTraits::EQ),\n Characteristic::Unpin => self.vtable.marker_traits().contains(MarkerTraits::UNPIN),\n\n // Functionality traits\n Characteristic::Clone => self.vtable.has_clone_into(),\n Characteristic::Display => self.vtable.has_display(),\n Characteristic::Debug => self.vtable.has_debug(),\n Characteristic::PartialEq => self.vtable.has_partial_eq(),\n Characteristic::PartialOrd => self.vtable.has_partial_ord(),\n Characteristic::Ord => self.vtable.has_ord(),\n Characteristic::Hash => self.vtable.has_hash(),\n Characteristic::Default => self.vtable.has_default_in_place(),\n Characteristic::FromStr => self.vtable.has_parse(),\n }\n }\n\n /// Check if this shape implements the Send trait\n #[inline]\n pub fn is_send(&self) -> bool {\n self.is(Characteristic::Send)\n }\n\n /// Check if this shape implements the Sync trait\n #[inline]\n pub fn is_sync(&self) -> bool {\n self.is(Characteristic::Sync)\n }\n\n /// Check if this shape implements the Copy trait\n #[inline]\n pub fn is_copy(&self) -> bool {\n self.is(Characteristic::Copy)\n }\n\n /// Check if this shape implements the Eq trait\n #[inline]\n pub fn is_eq(&self) -> bool {\n self.is(Characteristic::Eq)\n }\n\n /// Check if this shape implements the Clone trait\n #[inline]\n pub fn is_clone(&self) -> bool {\n self.is(Characteristic::Clone)\n }\n\n /// Check if this shape implements the Display trait\n #[inline]\n pub fn is_display(&self) -> bool {\n self.is(Characteristic::Display)\n }\n\n /// Check if this shape implements the Debug trait\n #[inline]\n pub fn is_debug(&self) -> bool {\n self.is(Characteristic::Debug)\n }\n\n /// Check if this shape implements the PartialEq trait\n #[inline]\n pub fn is_partial_eq(&self) -> bool {\n self.is(Characteristic::PartialEq)\n }\n\n /// Check if this shape implements the PartialOrd trait\n #[inline]\n pub fn is_partial_ord(&self) -> bool {\n self.is(Characteristic::PartialOrd)\n }\n\n /// Check if this shape implements the Ord trait\n #[inline]\n pub fn is_ord(&self) -> bool {\n self.is(Characteristic::Ord)\n }\n\n /// Check if this shape implements the Hash trait\n #[inline]\n pub fn is_hash(&self) -> bool {\n self.is(Characteristic::Hash)\n }\n\n /// Check if this shape implements the Default trait\n #[inline]\n pub fn is_default(&self) -> bool {\n self.is(Characteristic::Default)\n }\n\n /// Check if this shape implements the FromStr trait\n #[inline]\n pub fn is_from_str(&self) -> bool {\n self.is(Characteristic::FromStr)\n }\n\n /// Writes the name of this type to the given formatter\n #[inline]\n pub fn write_type_name(&self, f: &mut fmt::Formatter<'_>, opts: TypeNameOpts) -> fmt::Result {\n (self.vtable.type_name())(f, opts)\n }\n}\n"], ["/facet/facet-core/src/types/def/list.rs", "use crate::ptr::{PtrConst, PtrMut, PtrUninit};\n\nuse super::{IterVTable, Shape};\n\n/// Fields for list types\n#[derive(Clone, Copy, Debug)]\n#[repr(C)]\npub struct ListDef {\n /// vtable for interacting with the list\n pub vtable: &'static ListVTable,\n /// shape of the items in the list\n pub t: fn() -> &'static Shape,\n}\n\nimpl ListDef {\n /// Returns a builder for ListDef\n pub const fn builder() -> ListDefBuilder {\n ListDefBuilder::new()\n }\n\n /// Returns the shape of the items in the list\n pub fn t(&self) -> &'static Shape {\n (self.t)()\n }\n}\n\n/// Builder for ListDef\npub struct ListDefBuilder {\n vtable: Option<&'static ListVTable>,\n t: Option &'static Shape>,\n}\n\nimpl ListDefBuilder {\n /// Creates a new ListDefBuilder\n #[allow(clippy::new_without_default)]\n pub const fn new() -> Self {\n Self {\n vtable: None,\n t: None,\n }\n }\n\n /// Sets the vtable for the ListDef\n pub const fn vtable(mut self, vtable: &'static ListVTable) -> Self {\n self.vtable = Some(vtable);\n self\n }\n\n /// Sets the item shape for the ListDef\n pub const fn t(mut self, t: fn() -> &'static Shape) -> Self {\n self.t = Some(t);\n self\n }\n\n /// Builds the ListDef\n pub const fn build(self) -> ListDef {\n ListDef {\n vtable: self.vtable.unwrap(),\n t: self.t.unwrap(),\n }\n }\n}\n\n/// Initialize a list in place with a given capacity\n///\n/// # Safety\n///\n/// The `list` parameter must point to uninitialized memory of sufficient size.\n/// The function must properly initialize the memory.\npub type ListInitInPlaceWithCapacityFn =\n for<'mem> unsafe fn(list: PtrUninit<'mem>, capacity: usize) -> PtrMut<'mem>;\n\n/// Push an item to the list\n///\n/// # Safety\n///\n/// The `list` parameter must point to aligned, initialized memory of the correct type.\n/// `item` is moved out of (with [`core::ptr::read`]) — it should be deallocated afterwards (e.g.\n/// with [`core::mem::forget`]) but NOT dropped.\npub type ListPushFn = unsafe fn(list: PtrMut, item: PtrMut);\n// FIXME: this forces allocating item separately, copying it, and then dropping it — it's not great.\n\n/// Get the number of items in the list\n///\n/// # Safety\n///\n/// The `list` parameter must point to aligned, initialized memory of the correct type.\npub type ListLenFn = unsafe fn(list: PtrConst) -> usize;\n\n/// Get pointer to the element at `index` in the list, or `None` if the\n/// index is out of bounds.\n///\n/// # Safety\n///\n/// The `list` parameter must point to aligned, initialized memory of the correct type.\npub type ListGetFn = unsafe fn(list: PtrConst, index: usize) -> Option;\n\n/// Get mutable pointer to the element at `index` in the list, or `None` if the\n/// index is out of bounds.\n///\n/// # Safety\n///\n/// The `list` parameter must point to aligned, initialized memory of the correct type.\npub type ListGetMutFn = unsafe fn(list: PtrMut, index: usize) -> Option;\n\n/// Get pointer to the data buffer of the list.\n///\n/// # Safety\n///\n/// The `list` parameter must point to aligned, initialized memory of the correct type.\npub type ListAsPtrFn = unsafe fn(list: PtrConst) -> PtrConst;\n\n/// Get mutable pointer to the data buffer of the list.\n///\n/// # Safety\n///\n/// The `list` parameter must point to aligned, initialized memory of the correct type.\npub type ListAsMutPtrFn = unsafe fn(list: PtrMut) -> PtrMut;\n\n/// Virtual table for a list-like type (like `Vec`)\n#[derive(Clone, Copy, Debug)]\n#[repr(C)]\npub struct ListVTable {\n /// cf. [`ListInitInPlaceWithCapacityFn`].\n /// Unbuildable lists exist, like arrays.\n pub init_in_place_with_capacity: Option,\n\n /// cf. [`ListPushFn`]\n /// Only available for mutable lists\n pub push: Option,\n\n /// cf. [`ListLenFn`]\n pub len: ListLenFn,\n\n /// cf. [`ListGetFn`]\n pub get: ListGetFn,\n\n /// cf. [`ListGetMutFn`]\n /// Only available for mutable lists\n pub get_mut: Option,\n\n /// cf. [`ListAsPtrFn`]\n /// Only available for types that can be accessed as a contiguous array\n pub as_ptr: Option,\n\n /// cf. [`ListAsMutPtrFn`]\n /// Only available for types that can be accessed as a contiguous array\n pub as_mut_ptr: Option,\n\n /// Virtual table for list iterator operations\n pub iter_vtable: IterVTable>,\n}\n\nimpl ListVTable {\n /// Returns a builder for ListVTable\n pub const fn builder() -> ListVTableBuilder {\n ListVTableBuilder::new()\n }\n}\n\n/// Builds a [`ListVTable`]\npub struct ListVTableBuilder {\n init_in_place_with_capacity: Option,\n push: Option,\n len: Option,\n get: Option,\n get_mut: Option,\n as_ptr: Option,\n as_mut_ptr: Option,\n iter_vtable: Option>>,\n}\n\nimpl ListVTableBuilder {\n /// Creates a new [`ListVTableBuilder`] with all fields set to `None`.\n #[allow(clippy::new_without_default)]\n pub const fn new() -> Self {\n Self {\n init_in_place_with_capacity: None,\n push: None,\n len: None,\n get: None,\n get_mut: None,\n as_ptr: None,\n as_mut_ptr: None,\n iter_vtable: None,\n }\n }\n\n /// Sets the init_in_place_with_capacity field\n pub const fn init_in_place_with_capacity(mut self, f: ListInitInPlaceWithCapacityFn) -> Self {\n self.init_in_place_with_capacity = Some(f);\n self\n }\n\n /// Sets the push field\n pub const fn push(mut self, f: ListPushFn) -> Self {\n self.push = Some(f);\n self\n }\n\n /// Sets the len field\n pub const fn len(mut self, f: ListLenFn) -> Self {\n self.len = Some(f);\n self\n }\n\n /// Sets the get field\n pub const fn get(mut self, f: ListGetFn) -> Self {\n self.get = Some(f);\n self\n }\n\n /// Sets the get_mut field\n pub const fn get_mut(mut self, f: ListGetMutFn) -> Self {\n self.get_mut = Some(f);\n self\n }\n\n /// Sets the as_ptr field\n pub const fn as_ptr(mut self, f: ListAsPtrFn) -> Self {\n self.as_ptr = Some(f);\n self\n }\n\n /// Sets the as_mut_ptr field\n pub const fn as_mut_ptr(mut self, f: ListAsMutPtrFn) -> Self {\n self.as_mut_ptr = Some(f);\n self\n }\n\n /// Sets the iter_vtable field\n pub const fn iter_vtable(mut self, vtable: IterVTable>) -> Self {\n self.iter_vtable = Some(vtable);\n self\n }\n\n /// Builds the [`ListVTable`] from the current state of the builder.\n ///\n /// # Panics\n ///\n /// Panic if any of the required fields (len, get, as_ptr, iter_vtable) are `None`.\n pub const fn build(self) -> ListVTable {\n assert!(self.as_ptr.is_some());\n ListVTable {\n init_in_place_with_capacity: self.init_in_place_with_capacity,\n push: self.push,\n len: self.len.unwrap(),\n get: self.get.unwrap(),\n get_mut: self.get_mut,\n as_ptr: self.as_ptr,\n as_mut_ptr: self.as_mut_ptr,\n iter_vtable: self.iter_vtable.unwrap(),\n }\n }\n}\n"], ["/facet/facet-core/src/impls_camino.rs", "use alloc::borrow::ToOwned;\nuse alloc::string::String;\n\nuse camino::{Utf8Path, Utf8PathBuf};\n\nuse crate::{\n Def, Facet, PtrConst, PtrMut, PtrUninit, Shape, TryFromError, TryIntoInnerError, Type,\n UserType, ValueVTable, value_vtable, value_vtable_unsized,\n};\n\nunsafe impl Facet<'_> for Utf8PathBuf {\n const VTABLE: &'static ValueVTable = &const {\n // Define the functions for transparent conversion between Utf8PathBuf and String\n unsafe fn try_from<'dst>(\n src_ptr: PtrConst<'_>,\n src_shape: &'static Shape,\n dst: PtrUninit<'dst>,\n ) -> Result, TryFromError> {\n if src_shape.id != ::SHAPE.id {\n return Err(TryFromError::UnsupportedSourceShape {\n src_shape,\n expected: &[::SHAPE],\n });\n }\n let s = unsafe { src_ptr.read::() };\n Ok(unsafe { dst.put(Utf8PathBuf::from(s)) })\n }\n\n unsafe fn try_into_inner<'dst>(\n src_ptr: PtrMut<'_>,\n dst: PtrUninit<'dst>,\n ) -> Result, TryIntoInnerError> {\n let path = unsafe { src_ptr.read::() };\n Ok(unsafe { dst.put(path.into_string()) })\n }\n\n let mut vtable = value_vtable!(Utf8PathBuf, |f, _opts| write!(\n f,\n \"{}\",\n Self::SHAPE.type_identifier\n ));\n\n {\n let vtable = vtable.sized_mut().unwrap();\n vtable.parse =\n || Some(|s, target| Ok(unsafe { target.put(Utf8Path::new(s).to_owned()) }));\n vtable.try_from = || Some(try_from);\n vtable.try_into_inner = || Some(try_into_inner);\n }\n vtable\n };\n\n const SHAPE: &'static Shape = &const {\n // Function to return inner type's shape\n fn inner_shape() -> &'static Shape {\n ::SHAPE\n }\n\n Shape::builder_for_sized::()\n .type_identifier(\"Utf8PathBuf\")\n .ty(Type::User(UserType::Opaque))\n .def(Def::Scalar)\n .inner(inner_shape)\n .build()\n };\n}\n\nunsafe impl<'a> Facet<'a> for &'a Utf8Path {\n const VTABLE: &'static ValueVTable = &const {\n value_vtable!(&Utf8Path, |f, _opts| write!(\n f,\n \"{}\",\n Self::SHAPE.type_identifier\n ))\n };\n\n const SHAPE: &'static Shape = &const {\n Shape::builder_for_sized::()\n .type_identifier(\"&Utf8Path\")\n .ty(Type::User(UserType::Opaque))\n .def(Def::Scalar)\n .build()\n };\n}\n\nunsafe impl Facet<'_> for Utf8Path {\n const VTABLE: &'static ValueVTable = &const {\n value_vtable_unsized!(Utf8Path, |f, _opts| write!(\n f,\n \"{}\",\n Self::SHAPE.type_identifier\n ))\n };\n\n const SHAPE: &'static Shape = &const {\n Shape::builder_for_unsized::()\n .type_identifier(\"Utf8Path\")\n .ty(Type::User(UserType::Opaque))\n .def(Def::Scalar)\n .build()\n };\n}\n"], ["/facet/facet-core/src/impls_core/tuple.rs", "use core::{fmt, mem};\n\nuse crate::{\n Characteristic, Facet, MarkerTraits, Repr, Shape, StructKind, StructType, Type, TypeNameOpts,\n UserType, VTableView, ValueVTable, types::field_in_type,\n};\n\n#[inline(always)]\npub fn write_type_name_list(\n f: &mut fmt::Formatter<'_>,\n opts: TypeNameOpts,\n open: &'static str,\n delimiter: &'static str,\n close: &'static str,\n shapes: &'static [&'static Shape],\n) -> fmt::Result {\n f.pad(open)?;\n if let Some(opts) = opts.for_children() {\n for (index, shape) in shapes.iter().enumerate() {\n if index > 0 {\n f.pad(delimiter)?;\n }\n shape.write_type_name(f, opts)?;\n }\n } else {\n write!(f, \"⋯\")?;\n }\n f.pad(close)?;\n Ok(())\n}\n\nmacro_rules! impl_facet_for_tuple {\n // Used to implement the next bigger tuple type, by taking the next typename & associated index\n // out of `remaining`, if it exists.\n {\n continue from ($($elems:ident.$idx:tt,)+),\n remaining ()\n } => {};\n {\n continue from ($($elems:ident.$idx:tt,)+),\n remaining ($next:ident.$nextidx:tt, $($remaining:ident.$remainingidx:tt,)*)\n } => {\n impl_facet_for_tuple! {\n impl ($($elems.$idx,)+ $next.$nextidx,),\n remaining ($($remaining.$remainingidx,)*)\n }\n };\n // Handle commas correctly for the debug implementation\n { debug on $f:ident { $first:stmt; } } => {\n write!($f, \"(\")?;\n $first\n write!($f, \",)\")\n };\n // Actually generate the trait implementation, and keep the remaining possible elements around\n {\n impl ($($elems:ident.$idx:tt,)+),\n remaining ($($remaining:ident.$remainingidx:tt,)*)\n } => {\n unsafe impl<'a $(, $elems)+> Facet<'a> for ($($elems,)+)\n where\n $($elems: Facet<'a>,)+\n {\n const VTABLE: &'static ValueVTable = &const {\n ValueVTable::builder::()\n .type_name(|f, opts| {\n write_type_name_list(f, opts, \"(\", \", \", \")\", &[$($elems::SHAPE),+])\n })\n .drop_in_place(|| Some(|data| unsafe { data.drop_in_place::() }))\n .marker_traits(||\n MarkerTraits::all()\n $(.intersection($elems::SHAPE.vtable.marker_traits()))+\n )\n .default_in_place(|| {\n let elem_shapes = const { &[$($elems::SHAPE),+] };\n if Characteristic::all_default(elem_shapes) {\n Some(|mut dst| {\n $(\n unsafe {\n (>::of().default_in_place().unwrap())(\n dst.field_uninit_at(mem::offset_of!(Self, $idx))\n );\n }\n )+\n\n unsafe { dst.assume_init() }\n })\n } else {\n None\n }\n })\n .build()\n };\n\n const SHAPE: &'static Shape = &const {\n Shape::builder_for_sized::()\n .type_identifier(const {\n let fields = [\n $(field_in_type!(Self, $idx),)+\n ];\n if fields.len() == 1 {\n \"(_)\"\n } else {\n \"(⋯)\"\n }\n })\n .ty(Type::User(UserType::Struct(StructType {\n repr: Repr::default(),\n kind: StructKind::Tuple,\n fields: &const {[\n $(field_in_type!(Self, $idx),)+\n ]}\n })))\n .build()\n };\n }\n\n impl_facet_for_tuple! {\n continue from ($($elems.$idx,)+),\n remaining ($($remaining.$remainingidx,)*)\n }\n };\n // The entry point into this macro, all smaller tuple types get implemented as well.\n { ($first:ident.$firstidx:tt $(, $remaining:ident.$remainingidx:tt)* $(,)?) } => {\n impl_facet_for_tuple! {\n impl ($first.$firstidx,),\n remaining ($($remaining.$remainingidx,)*)\n }\n };\n}\n\n#[cfg(feature = \"tuples-12\")]\nimpl_facet_for_tuple! {\n (T0.0, T1.1, T2.2, T3.3, T4.4, T5.5, T6.6, T7.7, T8.8, T9.9, T10.10, T11.11)\n}\n\n#[cfg(not(feature = \"tuples-12\"))]\nimpl_facet_for_tuple! {\n (T0.0, T1.1, T2.2, T3.3)\n}\n"], ["/facet/facet-core/src/types/def/set.rs", "use crate::ptr::{PtrConst, PtrMut, PtrUninit};\n\nuse super::{IterVTable, Shape};\n\n/// Fields for set types\n#[derive(Clone, Copy, Debug)]\n#[repr(C)]\npub struct SetDef {\n /// vtable for interacting with the set\n pub vtable: &'static SetVTable,\n /// shape of the values in the set\n pub t: fn() -> &'static Shape,\n}\n\nimpl SetDef {\n /// Returns a builder for SetDef\n pub const fn builder() -> SetDefBuilder {\n SetDefBuilder::new()\n }\n\n /// Returns the shape of the items in the set\n pub fn t(&self) -> &'static Shape {\n (self.t)()\n }\n}\n\n/// Builder for SetDef\npub struct SetDefBuilder {\n vtable: Option<&'static SetVTable>,\n t: Option &'static Shape>,\n}\n\nimpl SetDefBuilder {\n /// Creates a new SetDefBuilder\n #[allow(clippy::new_without_default)]\n pub const fn new() -> Self {\n Self {\n vtable: None,\n t: None,\n }\n }\n\n /// Sets the vtable for the SetDef\n pub const fn vtable(mut self, vtable: &'static SetVTable) -> Self {\n self.vtable = Some(vtable);\n self\n }\n\n /// Sets the value shape for the SetDef\n pub const fn t(mut self, t: fn() -> &'static Shape) -> Self {\n self.t = Some(t);\n self\n }\n\n /// Builds the SetDef\n pub const fn build(self) -> SetDef {\n SetDef {\n vtable: self.vtable.unwrap(),\n t: self.t.unwrap(),\n }\n }\n}\n\n/// Initialize a set in place with a given capacity\n///\n/// # Safety\n///\n/// The `set` parameter must point to uninitialized memory of sufficient size.\n/// The function must properly initialize the memory.\npub type SetInitInPlaceWithCapacityFn =\n for<'mem> unsafe fn(set: PtrUninit<'mem>, capacity: usize) -> PtrMut<'mem>;\n\n/// Insert a value in the set if not already contained, returning true\n/// if the value wasn't present before\n///\n/// # Safety\n///\n/// The `set` parameter must point to aligned, initialized memory of the correct type.\n/// `value` is moved out of (with [`core::ptr::read`]) — it should be deallocated afterwards (e.g.\n/// with [`core::mem::forget`]) but NOT dropped.\npub type SetInsertFn =\n for<'set, 'value> unsafe fn(set: PtrMut<'set>, value: PtrMut<'value>) -> bool;\n\n/// Get the number of values in the set\n///\n/// # Safety\n///\n/// The `set` parameter must point to aligned, initialized memory of the correct type.\npub type SetLenFn = for<'set> unsafe fn(set: PtrConst<'set>) -> usize;\n\n/// Check if the set contains a value\n///\n/// # Safety\n///\n/// The `set` parameter must point to aligned, initialized memory of the correct type.\npub type SetContainsFn =\n for<'set, 'value> unsafe fn(set: PtrConst<'set>, value: PtrConst<'value>) -> bool;\n\n/// Virtual table for a `Set`\n#[derive(Clone, Copy, Debug)]\n#[repr(C)]\npub struct SetVTable {\n /// cf. [`SetInitInPlaceWithCapacityFn`]\n pub init_in_place_with_capacity_fn: SetInitInPlaceWithCapacityFn,\n\n /// cf. [`SetInsertFn`]\n pub insert_fn: SetInsertFn,\n\n /// cf. [`SetLenFn`]\n pub len_fn: SetLenFn,\n\n /// cf. [`SetContainsFn`]\n pub contains_fn: SetContainsFn,\n\n /// Virtual table for set iterator operations\n pub iter_vtable: IterVTable>,\n}\n\nimpl SetVTable {\n /// Returns a builder for SetVTable\n pub const fn builder() -> SetVTableBuilder {\n SetVTableBuilder::new()\n }\n}\n\n/// Builds a [`SetVTable`]\npub struct SetVTableBuilder {\n init_in_place_with_capacity_fn: Option,\n insert_fn: Option,\n len_fn: Option,\n contains_fn: Option,\n iter_vtable: Option>>,\n}\n\nimpl SetVTableBuilder {\n /// Creates a new [`SetVTableBuilder`] with all fields set to `None`.\n #[allow(clippy::new_without_default)]\n pub const fn new() -> Self {\n Self {\n init_in_place_with_capacity_fn: None,\n insert_fn: None,\n len_fn: None,\n contains_fn: None,\n iter_vtable: None,\n }\n }\n\n /// Sets the init_in_place_with_capacity_fn field\n pub const fn init_in_place_with_capacity(mut self, f: SetInitInPlaceWithCapacityFn) -> Self {\n self.init_in_place_with_capacity_fn = Some(f);\n self\n }\n\n /// Sets the insert_fn field\n pub const fn insert(mut self, f: SetInsertFn) -> Self {\n self.insert_fn = Some(f);\n self\n }\n\n /// Sets the len_fn field\n pub const fn len(mut self, f: SetLenFn) -> Self {\n self.len_fn = Some(f);\n self\n }\n\n /// Sets the contains_fn field\n pub const fn contains(mut self, f: SetContainsFn) -> Self {\n self.contains_fn = Some(f);\n self\n }\n\n /// Sets the iter_vtable field\n pub const fn iter_vtable(mut self, vtable: IterVTable>) -> Self {\n self.iter_vtable = Some(vtable);\n self\n }\n\n /// Builds the [`SetVTable`] from the current state of the builder.\n ///\n /// # Panics\n ///\n /// This method will panic if any of the required fields are `None`.\n pub const fn build(self) -> SetVTable {\n SetVTable {\n init_in_place_with_capacity_fn: self.init_in_place_with_capacity_fn.unwrap(),\n insert_fn: self.insert_fn.unwrap(),\n len_fn: self.len_fn.unwrap(),\n contains_fn: self.contains_fn.unwrap(),\n iter_vtable: self.iter_vtable.unwrap(),\n }\n }\n}\n"], ["/facet/facet-core/src/types/def/map.rs", "use crate::ptr::{PtrConst, PtrMut, PtrUninit};\n\nuse super::{IterVTable, Shape};\n\n/// Fields for map types\n#[derive(Clone, Copy, Debug)]\n#[repr(C)]\npub struct MapDef {\n /// vtable for interacting with the map\n pub vtable: &'static MapVTable,\n /// shape of the keys in the map\n pub k: fn() -> &'static Shape,\n /// shape of the values in the map\n pub v: fn() -> &'static Shape,\n}\n\nimpl MapDef {\n /// Returns a builder for MapDef\n pub const fn builder() -> MapDefBuilder {\n MapDefBuilder::new()\n }\n\n /// Returns the shape of the keys of the map\n pub fn k(&self) -> &'static Shape {\n (self.k)()\n }\n\n /// Returns the shape of the values of the map\n pub fn v(&self) -> &'static Shape {\n (self.v)()\n }\n}\n\n/// Builder for MapDef\npub struct MapDefBuilder {\n vtable: Option<&'static MapVTable>,\n k: Option &'static Shape>,\n v: Option &'static Shape>,\n}\n\nimpl MapDefBuilder {\n /// Creates a new MapDefBuilder\n #[allow(clippy::new_without_default)]\n pub const fn new() -> Self {\n Self {\n vtable: None,\n k: None,\n v: None,\n }\n }\n\n /// Sets the vtable for the MapDef\n pub const fn vtable(mut self, vtable: &'static MapVTable) -> Self {\n self.vtable = Some(vtable);\n self\n }\n\n /// Sets the key shape for the MapDef\n pub const fn k(mut self, k: fn() -> &'static Shape) -> Self {\n self.k = Some(k);\n self\n }\n\n /// Sets the value shape for the MapDef\n pub const fn v(mut self, v: fn() -> &'static Shape) -> Self {\n self.v = Some(v);\n self\n }\n\n /// Builds the MapDef\n pub const fn build(self) -> MapDef {\n MapDef {\n vtable: self.vtable.unwrap(),\n k: self.k.unwrap(),\n v: self.v.unwrap(),\n }\n }\n}\n\n/// Initialize a map in place with a given capacity\n///\n/// # Safety\n///\n/// The `map` parameter must point to uninitialized memory of sufficient size.\n/// The function must properly initialize the memory.\npub type MapInitInPlaceWithCapacityFn =\n for<'mem> unsafe fn(map: PtrUninit<'mem>, capacity: usize) -> PtrMut<'mem>;\n\n/// Insert a key-value pair into the map\n///\n/// # Safety\n///\n/// The `map` parameter must point to aligned, initialized memory of the correct type.\n/// `key` and `value` are moved out of (with [`core::ptr::read`]) — they should be deallocated\n/// afterwards (e.g. with [`core::mem::forget`]) but NOT dropped.\npub type MapInsertFn =\n for<'map, 'key, 'value> unsafe fn(map: PtrMut<'map>, key: PtrMut<'key>, value: PtrMut<'value>);\n\n/// Get the number of entries in the map\n///\n/// # Safety\n///\n/// The `map` parameter must point to aligned, initialized memory of the correct type.\npub type MapLenFn = for<'map> unsafe fn(map: PtrConst<'map>) -> usize;\n\n/// Check if the map contains a key\n///\n/// # Safety\n///\n/// The `map` parameter must point to aligned, initialized memory of the correct type.\npub type MapContainsKeyFn =\n for<'map, 'key> unsafe fn(map: PtrConst<'map>, key: PtrConst<'key>) -> bool;\n\n/// Get pointer to a value for a given key, returns None if not found\n///\n/// # Safety\n///\n/// The `map` parameter must point to aligned, initialized memory of the correct type.\npub type MapGetValuePtrFn =\n for<'map, 'key> unsafe fn(map: PtrConst<'map>, key: PtrConst<'key>) -> Option>;\n\n/// Virtual table for a Map\n#[derive(Clone, Copy, Debug)]\n#[repr(C)]\npub struct MapVTable {\n /// cf. [`MapInitInPlaceWithCapacityFn`]\n pub init_in_place_with_capacity_fn: MapInitInPlaceWithCapacityFn,\n\n /// cf. [`MapInsertFn`]\n pub insert_fn: MapInsertFn,\n\n /// cf. [`MapLenFn`]\n pub len_fn: MapLenFn,\n\n /// cf. [`MapContainsKeyFn`]\n pub contains_key_fn: MapContainsKeyFn,\n\n /// cf. [`MapGetValuePtrFn`]\n pub get_value_ptr_fn: MapGetValuePtrFn,\n\n /// Virtual table for map iterator operations\n pub iter_vtable: IterVTable<(PtrConst<'static>, PtrConst<'static>)>,\n}\n\nimpl MapVTable {\n /// Returns a builder for MapVTable\n pub const fn builder() -> MapVTableBuilder {\n MapVTableBuilder::new()\n }\n}\n\n/// Builds a [`MapVTable`]\npub struct MapVTableBuilder {\n init_in_place_with_capacity_fn: Option,\n insert_fn: Option,\n len_fn: Option,\n contains_key_fn: Option,\n get_value_ptr_fn: Option,\n iter_vtable: Option, PtrConst<'static>)>>,\n}\n\nimpl MapVTableBuilder {\n /// Creates a new [`MapVTableBuilder`] with all fields set to `None`.\n #[allow(clippy::new_without_default)]\n pub const fn new() -> Self {\n Self {\n init_in_place_with_capacity_fn: None,\n insert_fn: None,\n len_fn: None,\n contains_key_fn: None,\n get_value_ptr_fn: None,\n iter_vtable: None,\n }\n }\n\n /// Sets the init_in_place_with_capacity_fn field\n pub const fn init_in_place_with_capacity(mut self, f: MapInitInPlaceWithCapacityFn) -> Self {\n self.init_in_place_with_capacity_fn = Some(f);\n self\n }\n\n /// Sets the insert_fn field\n pub const fn insert(mut self, f: MapInsertFn) -> Self {\n self.insert_fn = Some(f);\n self\n }\n\n /// Sets the len_fn field\n pub const fn len(mut self, f: MapLenFn) -> Self {\n self.len_fn = Some(f);\n self\n }\n\n /// Sets the contains_key_fn field\n pub const fn contains_key(mut self, f: MapContainsKeyFn) -> Self {\n self.contains_key_fn = Some(f);\n self\n }\n\n /// Sets the get_value_ptr_fn field\n pub const fn get_value_ptr(mut self, f: MapGetValuePtrFn) -> Self {\n self.get_value_ptr_fn = Some(f);\n self\n }\n\n /// Sets the iter_vtable field\n pub const fn iter_vtable(\n mut self,\n vtable: IterVTable<(PtrConst<'static>, PtrConst<'static>)>,\n ) -> Self {\n self.iter_vtable = Some(vtable);\n self\n }\n\n /// Builds the [`MapVTable`] from the current state of the builder.\n ///\n /// # Panics\n ///\n /// This method will panic if any of the required fields are `None`.\n pub const fn build(self) -> MapVTable {\n MapVTable {\n init_in_place_with_capacity_fn: self.init_in_place_with_capacity_fn.unwrap(),\n insert_fn: self.insert_fn.unwrap(),\n len_fn: self.len_fn.unwrap(),\n contains_key_fn: self.contains_key_fn.unwrap(),\n get_value_ptr_fn: self.get_value_ptr_fn.unwrap(),\n iter_vtable: self.iter_vtable.unwrap(),\n }\n }\n}\n"], ["/facet/facet-core/src/types/def/mod.rs", "use super::*;\n\nmod array;\npub use array::*;\n\nmod slice;\npub use slice::*;\n\nmod iter;\npub use iter::*;\n\nmod list;\npub use list::*;\n\nmod map;\npub use map::*;\n\nmod set;\npub use set::*;\n\nmod option;\npub use option::*;\n\nmod pointer;\npub use pointer::*;\n\nmod function;\npub use function::*;\n\n/// The semantic definition of a shape: is it more like a scalar, a map, a list?\n#[derive(Clone, Copy)]\n#[repr(C)]\n// this enum is only ever going to be owned in static space,\n// right?\npub enum Def {\n /// Undefined - you can interact with the type through [`Type`] and [`ValueVTable`].\n Undefined,\n\n /// Scalar — those don't have a def, they're not composed of other things.\n /// You can interact with them through [`ValueVTable`].\n ///\n /// e.g. `u32`, `String`, `bool`, `SocketAddr`, etc.\n Scalar,\n\n /// Map — keys are dynamic (and strings, sorry), values are homogeneous\n ///\n /// e.g. `HashMap`\n Map(MapDef),\n\n /// Unique set of homogenous values\n ///\n /// e.g. `HashSet`\n Set(SetDef),\n\n /// Ordered list of heterogenous values, variable size\n ///\n /// e.g. `Vec`\n List(ListDef),\n\n /// Fixed-size array of heterogeneous values, fixed size\n ///\n /// e.g. `[T; 3]`\n Array(ArrayDef),\n\n /// Slice - a reference to a contiguous sequence of elements\n ///\n /// e.g. `[T]`\n Slice(SliceDef),\n\n /// Option\n ///\n /// e.g. `Option`\n Option(OptionDef),\n\n /// Smart pointers, like `Arc`, `Rc`, etc.\n Pointer(PointerDef),\n}\n\nimpl core::fmt::Debug for Def {\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n match self {\n Def::Undefined => write!(f, \"Undefined\"),\n Def::Scalar => {\n write!(f, \"Scalar\")\n }\n Def::Map(map_def) => write!(f, \"Map<{}>\", (map_def.v)()),\n Def::Set(set_def) => write!(f, \"Set<{}>\", (set_def.t)()),\n Def::List(list_def) => write!(f, \"List<{}>\", (list_def.t)()),\n Def::Array(array_def) => write!(f, \"Array<{}; {}>\", array_def.t, array_def.n),\n Def::Slice(slice_def) => write!(f, \"Slice<{}>\", slice_def.t),\n Def::Option(option_def) => write!(f, \"Option<{}>\", option_def.t),\n Def::Pointer(smart_ptr_def) => {\n if let Some(pointee) = smart_ptr_def.pointee {\n write!(f, \"SmartPointer<{}>\", pointee())\n } else {\n write!(f, \"SmartPointer\")\n }\n }\n }\n }\n}\n\nimpl Def {\n /// Returns the `ScalarDef` wrapped in an `Ok` if this is a [`Def::Scalar`].\n pub fn into_scalar(self) -> Result<(), Self> {\n match self {\n Self::Scalar => Ok(()),\n _ => Err(self),\n }\n }\n\n /// Returns the `MapDef` wrapped in an `Ok` if this is a [`Def::Map`].\n pub fn into_map(self) -> Result {\n match self {\n Self::Map(def) => Ok(def),\n _ => Err(self),\n }\n }\n\n /// Returns the `SetDef` wrapped in an `Ok` if this is a [`Def::Set`].\n pub fn into_set(self) -> Result {\n match self {\n Self::Set(def) => Ok(def),\n _ => Err(self),\n }\n }\n\n /// Returns the `ListDef` wrapped in an `Ok` if this is a [`Def::List`].\n pub fn into_list(self) -> Result {\n match self {\n Self::List(def) => Ok(def),\n _ => Err(self),\n }\n }\n /// Returns the `ArrayDef` wrapped in an `Ok` if this is a [`Def::Array`].\n pub fn into_array(self) -> Result {\n match self {\n Self::Array(def) => Ok(def),\n _ => Err(self),\n }\n }\n /// Returns the `SliceDef` wrapped in an `Ok` if this is a [`Def::Slice`].\n pub fn into_slice(self) -> Result {\n match self {\n Self::Slice(def) => Ok(def),\n _ => Err(self),\n }\n }\n /// Returns the `OptionDef` wrapped in an `Ok` if this is a [`Def::Option`].\n pub fn into_option(self) -> Result {\n match self {\n Self::Option(def) => Ok(def),\n _ => Err(self),\n }\n }\n /// Returns the `PointerDef` wrapped in an `Ok` if this is a [`Def::Pointer`].\n pub fn into_pointer(self) -> Result {\n match self {\n Self::Pointer(def) => Ok(def),\n _ => Err(self),\n }\n }\n}\n"], ["/facet/facet-core/src/types/def/function.rs", "use crate::Shape;\n\n/// Common fields for function pointer types\n#[derive(Clone, Copy, Debug)]\n#[repr(C)]\npub struct FunctionPointerDef {\n /// The calling abi of the function pointer\n pub abi: FunctionAbi,\n\n /// All parameter types, in declaration order\n pub parameters: &'static [fn() -> &'static Shape],\n\n /// The return type\n pub return_type: fn() -> &'static Shape,\n}\n\n/// The calling ABI of a function pointer\n#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Default)]\n#[repr(C)]\npub enum FunctionAbi {\n /// C ABI\n C,\n\n /// Rust ABI\n #[default]\n Rust,\n\n /// An unknown ABI\n Unknown,\n}\nimpl FunctionAbi {\n /// Returns the string in `extern \"abi-string\"` if not [`FunctionAbi::Unknown`].\n pub fn as_abi_str(&self) -> Option<&str> {\n match self {\n FunctionAbi::C => Some(\"C\"),\n FunctionAbi::Rust => Some(\"Rust\"),\n FunctionAbi::Unknown => None,\n }\n }\n}\n\nimpl FunctionPointerDef {\n /// Returns a builder for FunctionPointerDef\n pub const fn builder() -> FunctionPointerDefBuilder {\n FunctionPointerDefBuilder::new()\n }\n}\n\n/// Builder for FunctionPointerDef\npub struct FunctionPointerDefBuilder {\n abi: Option,\n parameters: &'static [fn() -> &'static Shape],\n return_type: Option &'static Shape>,\n}\n\nimpl FunctionPointerDefBuilder {\n /// Creates a new FunctionPointerDefBuilder\n #[allow(clippy::new_without_default)]\n pub const fn new() -> Self {\n Self {\n parameters: &[],\n abi: None,\n return_type: None,\n }\n }\n\n /// Sets the abi for the FunctionPointerDef\n pub const fn abi(mut self, abi: FunctionAbi) -> Self {\n self.abi = Some(abi);\n self\n }\n\n /// Sets the parameters for the FunctionPointerDef\n pub const fn parameter_types(mut self, parameters: &'static [fn() -> &'static Shape]) -> Self {\n self.parameters = parameters;\n self\n }\n\n /// Sets the return type for the FunctionPointerDef\n pub const fn return_type(mut self, ty: fn() -> &'static Shape) -> Self {\n self.return_type = Some(ty);\n self\n }\n\n /// Builds the FunctionPointerDef\n pub const fn build(self) -> FunctionPointerDef {\n FunctionPointerDef {\n parameters: self.parameters,\n return_type: self.return_type.unwrap(),\n abi: self.abi.unwrap(),\n }\n }\n}\n"], ["/facet/facet-core/src/impls_alloc/vec.rs", "use crate::*;\n\nuse alloc::boxed::Box;\nuse alloc::vec::Vec;\n\ntype VecIterator<'mem, T> = core::slice::Iter<'mem, T>;\n\nunsafe impl<'a, T> Facet<'a> for Vec\nwhere\n T: Facet<'a>,\n{\n const VTABLE: &'static ValueVTable = &const {\n ValueVTable::builder::()\n .type_name(|f, opts| {\n if let Some(opts) = opts.for_children() {\n write!(f, \"{}<\", Self::SHAPE.type_identifier)?;\n T::SHAPE.vtable.type_name()(f, opts)?;\n write!(f, \">\")\n } else {\n write!(f, \"{}<⋯>\", Self::SHAPE.type_identifier)\n }\n })\n .default_in_place(|| Some(|target| unsafe { target.put(Self::default()) }))\n .marker_traits(|| {\n MarkerTraits::SEND\n .union(MarkerTraits::SYNC)\n .union(MarkerTraits::EQ)\n .union(MarkerTraits::UNPIN)\n .union(MarkerTraits::UNWIND_SAFE)\n .union(MarkerTraits::REF_UNWIND_SAFE)\n .intersection(T::SHAPE.vtable.marker_traits())\n })\n .build()\n };\n\n const SHAPE: &'static Shape = &const {\n Shape::builder_for_sized::()\n .type_identifier(\"Vec\")\n .type_params(&[TypeParam {\n name: \"T\",\n shape: || T::SHAPE,\n }])\n .ty(Type::User(UserType::Opaque))\n .def(Def::List(\n ListDef::builder()\n .vtable(\n &const {\n ListVTable::builder()\n .init_in_place_with_capacity(|data, capacity| unsafe {\n data.put(Self::with_capacity(capacity))\n })\n .push(|ptr, item| unsafe {\n let vec = ptr.as_mut::();\n let item = item.read::();\n (*vec).push(item);\n })\n .len(|ptr| unsafe {\n let vec = ptr.get::();\n vec.len()\n })\n .get(|ptr, index| unsafe {\n let vec = ptr.get::();\n let item = vec.get(index)?;\n Some(PtrConst::new(item))\n })\n .get_mut(|ptr, index| unsafe {\n let vec = ptr.as_mut::();\n let item = vec.get_mut(index)?;\n Some(PtrMut::new(item))\n })\n .as_ptr(|ptr| unsafe {\n let vec = ptr.get::();\n PtrConst::new(vec.as_ptr())\n })\n .as_mut_ptr(|ptr| unsafe {\n let vec = ptr.as_mut::();\n PtrMut::new(vec.as_mut_ptr())\n })\n .iter_vtable(\n IterVTable::builder()\n .init_with_value(|ptr| unsafe {\n let vec = ptr.get::();\n let iter: VecIterator = vec.iter();\n let iter_state = Box::new(iter);\n PtrMut::new(Box::into_raw(iter_state) as *mut u8)\n })\n .next(|iter_ptr| unsafe {\n let state = iter_ptr.as_mut::>();\n state.next().map(|value| PtrConst::new(value))\n })\n .next_back(|iter_ptr| unsafe {\n let state = iter_ptr.as_mut::>();\n state.next_back().map(|value| PtrConst::new(value))\n })\n .dealloc(|iter_ptr| unsafe {\n drop(Box::from_raw(\n iter_ptr.as_ptr::>()\n as *mut VecIterator<'_, T>,\n ));\n })\n .build(),\n )\n .build()\n },\n )\n .t(|| T::SHAPE)\n .build(),\n ))\n .build()\n };\n}\n"], ["/facet/facet-core/src/types/ty/enum_.rs", "use super::{Repr, StructType};\n\n/// Fields for enum types\n#[derive(Clone, Copy, Debug)]\n#[repr(C)]\npub struct EnumType {\n /// Representation of the enum's data\n pub repr: Repr,\n\n /// representation of the enum's discriminant (u8, u16, etc.)\n pub enum_repr: EnumRepr,\n\n /// all variants for this enum\n pub variants: &'static [Variant],\n}\n\nimpl EnumType {\n /// Returns a builder for EnumDef\n pub const fn builder() -> EnumDefBuilder {\n EnumDefBuilder::new()\n }\n}\n\n/// Builder for EnumDef\npub struct EnumDefBuilder {\n repr: Option,\n enum_repr: Option,\n variants: Option<&'static [Variant]>,\n}\n\nimpl EnumDefBuilder {\n /// Creates a new EnumDefBuilder\n #[allow(clippy::new_without_default)]\n pub const fn new() -> Self {\n Self {\n repr: None,\n enum_repr: None,\n variants: None,\n }\n }\n\n /// Sets the representation for the EnumDef\n pub const fn repr(mut self, repr: Repr) -> Self {\n self.repr = Some(repr);\n self\n }\n\n /// Sets the discriminant representation for the EnumDef\n pub const fn enum_repr(mut self, enum_repr: EnumRepr) -> Self {\n self.enum_repr = Some(enum_repr);\n self\n }\n\n /// Sets the variants for the EnumDef\n pub const fn variants(mut self, variants: &'static [Variant]) -> Self {\n self.variants = Some(variants);\n self\n }\n\n /// Builds the EnumDef\n pub const fn build(self) -> EnumType {\n EnumType {\n repr: self.repr.unwrap(),\n enum_repr: self.enum_repr.unwrap(),\n variants: self.variants.unwrap(),\n }\n }\n}\n\n/// Describes a variant of an enum\n#[derive(Clone, Copy, Debug)]\n#[repr(C)]\npub struct Variant {\n /// Name of the variant, e.g. `Foo` for `enum FooBar { Foo, Bar }`\n pub name: &'static str,\n\n /// Discriminant value (if available). Might fit in a u8, etc.\n pub discriminant: Option,\n\n /// Attributes set for this variant via the derive macro\n pub attributes: &'static [VariantAttribute],\n\n /// Fields for this variant (empty if unit, number-named if tuple).\n /// IMPORTANT: the offset for the fields already takes into account the size & alignment of the\n /// discriminant.\n pub data: StructType,\n\n /// Doc comment for the variant\n pub doc: &'static [&'static str],\n}\n\nimpl Variant {\n /// Returns a builder for Variant\n pub const fn builder() -> VariantBuilder {\n VariantBuilder::new()\n }\n\n /// Checks whether the `Variant` has an attribute of form `VariantAttribute::Arbitrary` with the\n /// given content.\n #[inline]\n pub fn has_arbitrary_attr(&self, content: &'static str) -> bool {\n self.attributes\n .contains(&VariantAttribute::Arbitrary(content))\n }\n}\n\n/// Builder for Variant\npub struct VariantBuilder {\n name: Option<&'static str>,\n discriminant: Option,\n attributes: &'static [VariantAttribute],\n data: Option,\n doc: &'static [&'static str],\n}\n\nimpl VariantBuilder {\n /// Creates a new VariantBuilder\n #[allow(clippy::new_without_default)]\n pub const fn new() -> Self {\n Self {\n name: None,\n discriminant: None,\n attributes: &[],\n data: None,\n doc: &[],\n }\n }\n\n /// Sets the name for the Variant\n pub const fn name(mut self, name: &'static str) -> Self {\n self.name = Some(name);\n self\n }\n\n /// Sets the discriminant for the Variant\n pub const fn discriminant(mut self, discriminant: i64) -> Self {\n self.discriminant = Some(discriminant);\n self\n }\n\n /// Sets the attributes for the variant\n pub const fn attributes(mut self, attributes: &'static [VariantAttribute]) -> Self {\n self.attributes = attributes;\n self\n }\n\n /// Sets the fields for the Variant\n pub const fn data(mut self, data: StructType) -> Self {\n self.data = Some(data);\n self\n }\n\n /// Sets the doc comment for the Variant\n pub const fn doc(mut self, doc: &'static [&'static str]) -> Self {\n self.doc = doc;\n self\n }\n\n /// Builds the Variant\n pub const fn build(self) -> Variant {\n Variant {\n name: self.name.unwrap(),\n discriminant: self.discriminant,\n attributes: self.attributes,\n data: self.data.unwrap(),\n doc: self.doc,\n }\n }\n}\n\n/// An attribute that can be set on an enum variant\n#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]\n#[repr(C)]\npub enum VariantAttribute {\n /// Custom field attribute containing arbitrary text\n Arbitrary(&'static str),\n}\n\n/// All possible representations for Rust enums — ie. the type/size of the discriminant\n#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]\n#[repr(C)]\npub enum EnumRepr {\n /// Special-case representation discriminated by zeros under non-nullable pointer\n ///\n /// See: \n RustNPO,\n /// u8 representation (#[repr(u8)])\n U8,\n /// u16 representation (#[repr(u16)])\n U16,\n /// u32 representation (#[repr(u32)])\n U32,\n /// u64 representation (#[repr(u64)])\n U64,\n /// usize representation (#[repr(usize)])\n USize,\n /// i8 representation (#[repr(i8)])\n I8,\n /// i16 representation (#[repr(i16)])\n I16,\n /// i32 representation (#[repr(i32)])\n I32,\n /// i64 representation (#[repr(i64)])\n I64,\n /// isize representation (#[repr(isize)])\n ISize,\n}\n\nimpl EnumRepr {\n /// Returns the enum representation for the given discriminant type\n ///\n /// NOTE: only supports unsigned discriminants\n ///\n /// # Panics\n ///\n /// Panics if the size of the discriminant size is not 1, 2, 4, or 8 bytes.\n pub const fn from_discriminant_size() -> Self {\n match core::mem::size_of::() {\n 1 => EnumRepr::U8,\n 2 => EnumRepr::U16,\n 4 => EnumRepr::U32,\n 8 => EnumRepr::U64,\n _ => panic!(\"Invalid enum size\"),\n }\n }\n}\n"], ["/facet/facet-core/src/types/def/pointer.rs", "use bitflags::bitflags;\n\nuse crate::{GenericPtr, PtrConst, PtrMut, PtrUninit};\n\nuse super::Shape;\n\n/// Describes a pointer — including a vtable to query and alter its state,\n/// and the inner shape (the pointee type in the pointer).\n#[derive(Clone, Copy, Debug)]\n#[repr(C)]\npub struct PointerDef {\n /// vtable for interacting with the pointer\n pub vtable: &'static PointerVTable,\n\n /// shape of the inner type of the pointer, if not opaque\n pub pointee: Option &'static Shape>,\n\n /// shape of the corresponding strong pointer, if this pointer is weak\n pub weak: Option &'static Shape>,\n\n /// shape of the corresponding weak pointer, if this pointer is strong\n pub strong: Option &'static Shape>,\n\n /// Flags representing various characteristics of the pointer\n pub flags: PointerFlags,\n\n /// An optional field to identify the kind of pointer\n pub known: Option,\n}\n\nimpl PointerDef {\n /// Creates a new `PointerDefBuilder` with all fields set to `None`.\n #[must_use]\n pub const fn builder() -> PointerDefBuilder {\n PointerDefBuilder {\n vtable: None,\n pointee: None,\n flags: None,\n known: None,\n weak: None,\n strong: None,\n }\n }\n\n /// Returns shape of the inner type of the pointer, if not opaque\n pub fn pointee(&self) -> Option<&'static Shape> {\n self.pointee.map(|v| v())\n }\n\n /// Returns shape of the corresponding strong pointer, if this pointer is weak\n pub fn weak(&self) -> Option<&'static Shape> {\n self.weak.map(|v| v())\n }\n\n /// Returns shape of the corresponding weak pointer, if this pointer is strong\n pub fn strong(&self) -> Option<&'static Shape> {\n self.strong.map(|v| v())\n }\n}\n\n/// Builder for creating a `PointerDef`.\n#[derive(Debug)]\npub struct PointerDefBuilder {\n vtable: Option<&'static PointerVTable>,\n pointee: Option &'static Shape>,\n flags: Option,\n known: Option,\n weak: Option &'static Shape>,\n strong: Option &'static Shape>,\n}\n\nimpl PointerDefBuilder {\n /// Creates a new `PointerDefBuilder` with all fields set to `None`.\n #[must_use]\n #[expect(clippy::new_without_default)]\n pub const fn new() -> Self {\n Self {\n vtable: None,\n pointee: None,\n flags: None,\n known: None,\n weak: None,\n strong: None,\n }\n }\n\n /// Sets the vtable for the pointer.\n #[must_use]\n pub const fn vtable(mut self, vtable: &'static PointerVTable) -> Self {\n self.vtable = Some(vtable);\n self\n }\n\n /// Sets the shape of the inner type of the pointer.\n #[must_use]\n pub const fn pointee(mut self, pointee: fn() -> &'static Shape) -> Self {\n self.pointee = Some(pointee);\n self\n }\n\n /// Sets the flags for the pointer.\n #[must_use]\n pub const fn flags(mut self, flags: PointerFlags) -> Self {\n self.flags = Some(flags);\n self\n }\n\n /// Sets the known pointer type.\n #[must_use]\n pub const fn known(mut self, known: KnownPointer) -> Self {\n self.known = Some(known);\n self\n }\n\n /// Sets the shape of the corresponding weak pointer, if this pointer is strong.\n #[must_use]\n pub const fn weak(mut self, weak: fn() -> &'static Shape) -> Self {\n self.weak = Some(weak);\n self\n }\n\n /// Sets the shape of the corresponding strong pointer, if this pointer is weak\n #[must_use]\n pub const fn strong(mut self, strong: fn() -> &'static Shape) -> Self {\n self.strong = Some(strong);\n self\n }\n\n /// Builds a `PointerDef` from the provided configuration.\n ///\n /// # Panics\n ///\n /// Panics if any required field (vtable, flags) is not set.\n #[must_use]\n pub const fn build(self) -> PointerDef {\n PointerDef {\n vtable: self.vtable.unwrap(),\n pointee: self.pointee,\n weak: self.weak,\n strong: self.strong,\n flags: self.flags.unwrap(),\n known: self.known,\n }\n }\n}\n\nbitflags! {\n /// Flags to represent various characteristics of pointers\n #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]\n pub struct PointerFlags: u8 {\n /// An empty set of flags\n const EMPTY = 0;\n\n /// Whether the pointer is weak (like [`std::sync::Weak`])\n const WEAK = 1 << 0;\n /// Whether the pointer is atomic (like [`std::sync::Arc`])\n const ATOMIC = 1 << 1;\n /// Whether the pointer is a lock (like [`std::sync::Mutex`])\n const LOCK = 1 << 2;\n }\n}\n\n/// Tries to upgrade the weak pointer to a strong one.\n///\n/// If the upgrade succeeds, initializes the pointer into the given `strong`, and returns a\n/// copy of `strong`, which has been guaranteed to be initialized. If the upgrade fails, `None` is\n/// returned and `strong` is not initialized.\n///\n/// `weak` is not moved out of.\n///\n/// # Safety\n///\n/// `weak` must be a valid weak pointer (like [`std::sync::Weak`] or [`std::rc::Weak`]).\n///\n/// `strong` must be allocated, and of the right layout for the corresponding pointer.\n///\n/// `strong` must not have been initialized yet.\npub type UpgradeIntoFn =\n for<'ptr> unsafe fn(weak: PtrMut<'ptr>, strong: PtrUninit<'ptr>) -> Option>;\n\n/// Downgrades a strong pointer to a weak one.\n///\n/// Initializes the pointer into the given `weak`, and returns a copy of `weak`, which has\n/// been guaranteed to be initialized.\n///\n/// Only strong pointers can be downgraded (like [`std::sync::Arc`] or [`std::rc::Rc`]).\n///\n/// # Safety\n///\n/// `strong` must be a valid strong pointer (like [`std::sync::Arc`] or [`std::rc::Rc`]).\n///\n/// `weak` must be allocated, and of the right layout for the corresponding weak pointer.\n///\n/// `weak` must not have been initialized yet.\npub type DowngradeIntoFn =\n for<'ptr> unsafe fn(strong: PtrMut<'ptr>, weak: PtrUninit<'ptr>) -> PtrMut<'ptr>;\n\n/// Tries to obtain a reference to the inner value of the pointer.\n///\n/// This can only be used with strong pointers (like [`std::sync::Arc`] or [`std::rc::Rc`]).\n///\n/// # Safety\n///\n/// `this` must be a valid strong pointer (like [`std::sync::Arc`] or [`std::rc::Rc`]).\npub type BorrowFn = for<'ptr> unsafe fn(this: PtrConst<'ptr>) -> GenericPtr<'ptr>;\n\n/// Creates a new pointer wrapping the given value.\n///\n/// Initializes the pointer into the given `this`, and returns a copy of `this`, which has\n/// been guaranteed to be initialized.\n///\n/// This can only be used with strong pointers (like [`std::sync::Arc`] or [`std::rc::Rc`]).\n///\n/// # Safety\n///\n/// `this` must be allocated, and of the right layout for the corresponding pointer.\n///\n/// `this` must not have been initialized yet.\n///\n/// `ptr` must point to a value of type `T`.\n///\n/// `ptr` is moved out of (with [`core::ptr::read`]) — it should be deallocated afterwards (e.g.\n/// with [`core::mem::forget`]) but NOT dropped).\npub type NewIntoFn = for<'ptr> unsafe fn(this: PtrUninit<'ptr>, ptr: PtrMut<'ptr>) -> PtrMut<'ptr>;\n\n/// Type-erased result of locking a mutex-like pointer\npub struct LockResult<'ptr> {\n /// The data that was locked\n data: PtrMut<'ptr>,\n /// The guard that protects the data\n guard: PtrConst<'ptr>,\n /// The vtable for the guard\n guard_vtable: &'static LockGuardVTable,\n}\n\nimpl<'ptr> LockResult<'ptr> {\n /// Returns a reference to the locked data\n #[must_use]\n pub fn data(&self) -> &PtrMut<'ptr> {\n &self.data\n }\n}\n\nimpl Drop for LockResult<'_> {\n fn drop(&mut self) {\n unsafe {\n (self.guard_vtable.drop_in_place)(self.guard);\n }\n }\n}\n\n/// Functions for manipulating a guard\npub struct LockGuardVTable {\n /// Drops the guard in place\n pub drop_in_place: for<'ptr> unsafe fn(guard: PtrConst<'ptr>),\n}\n\n/// Acquires a lock on a mutex-like pointer\npub type LockFn = for<'ptr> unsafe fn(opaque: PtrConst<'ptr>) -> Result, ()>;\n\n/// Acquires a read lock on a reader-writer lock-like pointer\npub type ReadFn = for<'ptr> unsafe fn(opaque: PtrConst<'ptr>) -> Result, ()>;\n\n/// Acquires a write lock on a reader-writer lock-like pointer\npub type WriteFn = for<'ptr> unsafe fn(opaque: PtrConst<'ptr>) -> Result, ()>;\n\n/// Creates a new slice builder for a pointer: ie. for `Arc<[u8]>`, it builds a\n/// `Vec` internally, to which you can push, and then turn into an `Arc<[u8]>` at\n/// the last stage.\n///\n/// This works for any `U` in `Arc<[U]>` because those have separate concrete implementations, and\n/// thus, separate concrete vtables.\npub type SliceBuilderNewFn = fn() -> PtrMut<'static>;\n\n/// Pushes a value into a slice builder.\n///\n/// # Safety\n///\n/// Item must point to a valid value of type `U` and must be initialized.\n/// Function is infallible as it uses the global allocator.\npub type SliceBuilderPushFn = unsafe fn(builder: PtrMut, item: PtrMut);\n\n/// Converts a slice builder into a pointer. This takes ownership of the builder\n/// and frees the backing storage.\n///\n/// # Safety\n///\n/// The builder must be valid and must not be used after this function is called.\n/// Function is infallible as it uses the global allocator.\npub type SliceBuilderConvertFn = unsafe fn(builder: PtrMut<'static>) -> PtrConst<'static>;\n\n/// Frees a slice builder without converting it into a pointer\n///\n/// # Safety\n///\n/// The builder must be valid and must not be used after this function is called.\npub type SliceBuilderFreeFn = unsafe fn(builder: PtrMut<'static>);\n\n/// Functions for creating and manipulating slice builders.\n#[derive(Debug, Clone, Copy)]\npub struct SliceBuilderVTable {\n /// See [`SliceBuilderNewFn`]\n pub new_fn: SliceBuilderNewFn,\n /// See [`SliceBuilderPushFn`]\n pub push_fn: SliceBuilderPushFn,\n /// See [`SliceBuilderConvertFn`]\n pub convert_fn: SliceBuilderConvertFn,\n /// See [`SliceBuilderFreeFn`]\n pub free_fn: SliceBuilderFreeFn,\n}\n\nimpl SliceBuilderVTable {\n /// Creates a new `SliceBuilderVTableBuilder` with all fields set to `None`.\n #[must_use]\n pub const fn builder() -> SliceBuilderVTableBuilder {\n SliceBuilderVTableBuilder {\n new_fn: None,\n push_fn: None,\n convert_fn: None,\n free_fn: None,\n }\n }\n}\n\n/// Builder for creating a `SliceBuilderVTable`.\n#[derive(Debug)]\npub struct SliceBuilderVTableBuilder {\n new_fn: Option,\n push_fn: Option,\n convert_fn: Option,\n free_fn: Option,\n}\n\nimpl SliceBuilderVTableBuilder {\n /// Creates a new `SliceBuilderVTableBuilder` with all fields set to `None`.\n #[must_use]\n #[expect(clippy::new_without_default)]\n pub const fn new() -> Self {\n Self {\n new_fn: None,\n push_fn: None,\n convert_fn: None,\n free_fn: None,\n }\n }\n\n /// Sets the `new` function for the slice builder.\n #[must_use]\n pub const fn new_fn(mut self, new_fn: SliceBuilderNewFn) -> Self {\n self.new_fn = Some(new_fn);\n self\n }\n\n /// Sets the `push` function for the slice builder.\n #[must_use]\n pub const fn push_fn(mut self, push_fn: SliceBuilderPushFn) -> Self {\n self.push_fn = Some(push_fn);\n self\n }\n\n /// Sets the `convert` function for the slice builder.\n #[must_use]\n pub const fn convert_fn(mut self, convert_fn: SliceBuilderConvertFn) -> Self {\n self.convert_fn = Some(convert_fn);\n self\n }\n\n /// Sets the `free` function for the slice builder.\n #[must_use]\n pub const fn free_fn(mut self, free_fn: SliceBuilderFreeFn) -> Self {\n self.free_fn = Some(free_fn);\n self\n }\n\n /// Builds a `SliceBuilderVTable` from the provided configuration.\n #[must_use]\n pub const fn build(self) -> SliceBuilderVTable {\n SliceBuilderVTable {\n new_fn: self.new_fn.expect(\"new_fn must be set\"),\n push_fn: self.push_fn.expect(\"push_fn must be set\"),\n convert_fn: self.convert_fn.expect(\"convert_fn must be set\"),\n free_fn: self.free_fn.expect(\"free_fn must be set\"),\n }\n }\n}\n\n/// Functions for interacting with a pointer\n#[derive(Debug, Clone, Copy)]\npub struct PointerVTable {\n /// See [`UpgradeIntoFn`]\n pub upgrade_into_fn: Option,\n\n /// See [`DowngradeIntoFn`]\n pub downgrade_into_fn: Option,\n\n /// See [`BorrowFn`]\n pub borrow_fn: Option,\n\n /// See [`NewIntoFn`]\n pub new_into_fn: Option,\n\n /// See [`LockFn`]\n pub lock_fn: Option,\n\n /// See [`ReadFn`]\n pub read_fn: Option,\n\n /// See [`WriteFn`]\n pub write_fn: Option,\n\n /// See [`SliceBuilderVTable`]\n pub slice_builder_vtable: Option<&'static SliceBuilderVTable>,\n}\n\nimpl PointerVTable {\n /// Creates a new `PointerVTableBuilder` with all fields set to `None`.\n #[must_use]\n pub const fn builder() -> PointerVTableBuilder {\n PointerVTableBuilder {\n upgrade_into_fn: None,\n downgrade_into_fn: None,\n borrow_fn: None,\n new_into_fn: None,\n lock_fn: None,\n read_fn: None,\n write_fn: None,\n slice_builder_vtable: None,\n }\n }\n}\n\n/// Builder for creating a `PointerVTable`.\n#[derive(Debug)]\npub struct PointerVTableBuilder {\n upgrade_into_fn: Option,\n downgrade_into_fn: Option,\n borrow_fn: Option,\n new_into_fn: Option,\n lock_fn: Option,\n read_fn: Option,\n write_fn: Option,\n slice_builder_vtable: Option<&'static SliceBuilderVTable>,\n}\n\nimpl PointerVTableBuilder {\n /// Creates a new `PointerVTableBuilder` with all fields set to `None`.\n #[must_use]\n #[expect(clippy::new_without_default)]\n pub const fn new() -> Self {\n Self {\n upgrade_into_fn: None,\n downgrade_into_fn: None,\n borrow_fn: None,\n new_into_fn: None,\n lock_fn: None,\n read_fn: None,\n write_fn: None,\n slice_builder_vtable: None,\n }\n }\n\n /// Sets the `try_upgrade` function.\n #[must_use]\n pub const fn upgrade_into_fn(mut self, upgrade_into_fn: UpgradeIntoFn) -> Self {\n self.upgrade_into_fn = Some(upgrade_into_fn);\n self\n }\n\n /// Sets the `downgrade` function.\n #[must_use]\n pub const fn downgrade_into_fn(mut self, downgrade_into_fn: DowngradeIntoFn) -> Self {\n self.downgrade_into_fn = Some(downgrade_into_fn);\n self\n }\n\n /// Sets the `borrow` function.\n #[must_use]\n pub const fn borrow_fn(mut self, borrow_fn: BorrowFn) -> Self {\n self.borrow_fn = Some(borrow_fn);\n self\n }\n\n /// Sets the `new_into` function.\n #[must_use]\n pub const fn new_into_fn(mut self, new_into_fn: NewIntoFn) -> Self {\n self.new_into_fn = Some(new_into_fn);\n self\n }\n\n /// Sets the `lock` function.\n #[must_use]\n pub const fn lock_fn(mut self, lock_fn: LockFn) -> Self {\n self.lock_fn = Some(lock_fn);\n self\n }\n\n /// Sets the `read` function.\n #[must_use]\n pub const fn read_fn(mut self, read_fn: ReadFn) -> Self {\n self.read_fn = Some(read_fn);\n self\n }\n\n /// Sets the `write` function.\n #[must_use]\n pub const fn write_fn(mut self, write_fn: WriteFn) -> Self {\n self.write_fn = Some(write_fn);\n self\n }\n\n /// Sets the `slice_builder_vtable` function.\n #[must_use]\n pub const fn slice_builder_vtable(\n mut self,\n slice_builder_vtable: &'static SliceBuilderVTable,\n ) -> Self {\n self.slice_builder_vtable = Some(slice_builder_vtable);\n self\n }\n\n /// Builds a `PointerVTable` from the provided configuration.\n #[must_use]\n pub const fn build(self) -> PointerVTable {\n PointerVTable {\n upgrade_into_fn: self.upgrade_into_fn,\n downgrade_into_fn: self.downgrade_into_fn,\n borrow_fn: self.borrow_fn,\n new_into_fn: self.new_into_fn,\n lock_fn: self.lock_fn,\n read_fn: self.read_fn,\n write_fn: self.write_fn,\n slice_builder_vtable: self.slice_builder_vtable,\n }\n }\n}\n\n/// Represents common standard library pointer kinds\n#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]\npub enum KnownPointer {\n /// [`Box`](std::boxed::Box), heap-allocated values with single ownership\n Box,\n /// [`Rc`](std::rc::Rc), reference-counted values with multiple ownership\n Rc,\n /// [`Weak`](std::rc::Weak), a weak reference to an `Rc`-managed value\n RcWeak,\n /// [`Arc`](std::sync::Arc), thread-safe reference-counted values with multiple ownership\n Arc,\n /// [`Weak`](std::sync::Weak), a weak reference to an `Arc`-managed value\n ArcWeak,\n /// [`Cow<'a, T>`](std::borrow::Cow), a clone-on-write smart pointer\n Cow,\n /// [`Pin

`](std::pin::Pin), a type that pins values behind a pointer\n Pin,\n /// [`Cell`](std::cell::Cell), a mutable memory location with interior mutability\n Cell,\n /// [`RefCell`](std::cell::RefCell), a mutable memory location with dynamic borrowing rules\n RefCell,\n /// [`OnceCell`](std::cell::OnceCell), a cell that can be written to only once\n OnceCell,\n /// [`Mutex`](std::sync::Mutex), a mutual exclusion primitive\n Mutex,\n /// [`RwLock`](std::sync::RwLock), a reader-writer lock\n RwLock,\n /// [`NonNull`](core::ptr::NonNull), a wrapper around a raw pointer that is not null\n NonNull,\n /// `&T`\n SharedReference,\n /// `&mut T`\n ExclusiveReference,\n}\n"], ["/facet/facet-core/src/impls_bytes.rs", "use alloc::boxed::Box;\n\nuse bytes::{BufMut as _, Bytes, BytesMut};\n\nuse crate::{\n Def, Facet, IterVTable, ListDef, ListVTable, PtrConst, PtrMut, PtrUninit, Shape, Type,\n UserType, ValueVTable, value_vtable,\n};\n\ntype BytesIterator<'mem> = core::slice::Iter<'mem, u8>;\n\nunsafe impl Facet<'_> for Bytes {\n const VTABLE: &'static ValueVTable = &const {\n let mut vtable = value_vtable!(Bytes, |f, _opts| write!(\n f,\n \"{}\",\n Self::SHAPE.type_identifier\n ));\n {\n let vtable = vtable.sized_mut().unwrap();\n vtable.try_from = || {\n Some(\n |source: PtrConst, source_shape: &Shape, target: PtrUninit| {\n if source_shape.is_type::() {\n let source = unsafe { source.read::() };\n let bytes = source.freeze();\n Ok(unsafe { target.put(bytes) })\n } else {\n Err(crate::TryFromError::UnsupportedSourceShape {\n src_shape: source_shape,\n expected: &[Bytes::SHAPE],\n })\n }\n },\n )\n };\n }\n\n vtable\n };\n\n const SHAPE: &'static Shape = &const {\n Shape::builder_for_sized::()\n .ty(Type::User(UserType::Opaque))\n .type_identifier(\"Bytes\")\n .inner(|| BytesMut::SHAPE)\n .def(Def::List(\n ListDef::builder()\n .vtable(\n &const {\n ListVTable::builder()\n .len(|ptr| unsafe {\n let bytes = ptr.get::();\n bytes.len()\n })\n .get(|ptr, index| unsafe {\n let bytes = ptr.get::();\n let item = bytes.get(index)?;\n Some(PtrConst::new(item))\n })\n .as_ptr(|ptr| unsafe {\n let bytes = ptr.get::();\n PtrConst::new(bytes.as_ptr())\n })\n .iter_vtable(\n IterVTable::builder()\n .init_with_value(|ptr| unsafe {\n let bytes = ptr.get::();\n let iter: BytesIterator = bytes.iter();\n let iter_state = Box::new(iter);\n PtrMut::new(Box::into_raw(iter_state) as *mut u8)\n })\n .next(|iter_ptr| unsafe {\n let state = iter_ptr.as_mut::>();\n state.next().map(|value| PtrConst::new(value))\n })\n .next_back(|iter_ptr| unsafe {\n let state = iter_ptr.as_mut::>();\n state.next_back().map(|value| PtrConst::new(value))\n })\n .dealloc(|iter_ptr| unsafe {\n drop(Box::from_raw(\n iter_ptr.as_ptr::>()\n as *mut BytesIterator<'_>,\n ));\n })\n .build(),\n )\n .build()\n },\n )\n .t(|| u8::SHAPE)\n .build(),\n ))\n .build()\n };\n}\n\nunsafe impl Facet<'_> for BytesMut {\n const VTABLE: &'static ValueVTable = &const {\n value_vtable!(BytesMut, |f, _opts| write!(\n f,\n \"{}\",\n Self::SHAPE.type_identifier\n ))\n };\n\n const SHAPE: &'static Shape = &const {\n Shape::builder_for_sized::()\n .type_identifier(\"BytesMut\")\n .ty(Type::User(UserType::Opaque))\n .def(Def::List(\n ListDef::builder()\n .vtable(\n &const {\n ListVTable::builder()\n .init_in_place_with_capacity(|data, capacity| unsafe {\n data.put(Self::with_capacity(capacity))\n })\n .push(|ptr, item| unsafe {\n let bytes = ptr.as_mut::();\n let item = item.read::();\n (*bytes).put_u8(item);\n })\n .len(|ptr| unsafe {\n let bytes = ptr.get::();\n bytes.len()\n })\n .get(|ptr, index| unsafe {\n let bytes = ptr.get::();\n let item = bytes.get(index)?;\n Some(PtrConst::new(item))\n })\n .get_mut(|ptr, index| unsafe {\n let bytes = ptr.as_mut::();\n let item = bytes.get_mut(index)?;\n Some(PtrMut::new(item))\n })\n .as_ptr(|ptr| unsafe {\n let bytes = ptr.get::();\n PtrConst::new(bytes.as_ptr())\n })\n .as_mut_ptr(|ptr| unsafe {\n let bytes = ptr.as_mut::();\n PtrMut::new(bytes.as_mut_ptr())\n })\n .iter_vtable(\n IterVTable::builder()\n .init_with_value(|ptr| unsafe {\n let bytes = ptr.get::();\n let iter: BytesIterator = bytes.iter();\n let iter_state = Box::new(iter);\n PtrMut::new(Box::into_raw(iter_state) as *mut u8)\n })\n .next(|iter_ptr| unsafe {\n let state = iter_ptr.as_mut::>();\n state.next().map(|value| PtrConst::new(value))\n })\n .next_back(|iter_ptr| unsafe {\n let state = iter_ptr.as_mut::>();\n state.next_back().map(|value| PtrConst::new(value))\n })\n .dealloc(|iter_ptr| unsafe {\n drop(Box::from_raw(\n iter_ptr.as_ptr::>()\n as *mut BytesIterator<'_>,\n ));\n })\n .build(),\n )\n .build()\n },\n )\n .t(|| u8::SHAPE)\n .build(),\n ))\n .build()\n };\n}\n"], ["/facet/facet-reflect/src/error.rs", "use facet_core::{Characteristic, EnumType, FieldError, Shape, TryFromError};\nuse owo_colors::OwoColorize;\n\n/// Errors that can occur when reflecting on types.\n#[derive(Clone)]\npub enum ReflectError {\n /// Tried to set an enum to a variant that does not exist\n NoSuchVariant {\n /// The enum definition containing all known variants.\n enum_type: EnumType,\n },\n\n /// Tried to get the wrong shape out of a value — e.g. we were manipulating\n /// a `String`, but `.get()` was called with a `u64` or something.\n WrongShape {\n /// The expected shape of the value.\n expected: &'static Shape,\n /// The actual shape of the value.\n actual: &'static Shape,\n },\n\n /// Attempted to perform an operation that expected a struct or something\n WasNotA {\n /// The name of the expected type.\n expected: &'static str,\n\n /// The type we got instead\n actual: &'static Shape,\n },\n\n /// A field was not initialized during build\n UninitializedField {\n /// The shape containing the field\n shape: &'static Shape,\n /// The name of the field that wasn't initialized\n field_name: &'static str,\n },\n\n /// A field in an enum variant was not initialized during build\n UninitializedEnumField {\n /// The enum shape\n shape: &'static Shape,\n /// The name of the field that wasn't initialized\n field_name: &'static str,\n /// The name of the variant containing the field\n variant_name: &'static str,\n },\n\n /// A scalar value was not initialized during build\n UninitializedValue {\n /// The scalar shape\n shape: &'static Shape,\n },\n\n /// An invariant of the reflection system was violated.\n InvariantViolation {\n /// The invariant that was violated.\n invariant: &'static str,\n },\n\n /// Attempted to set a value to its default, but the value doesn't implement `Default`.\n MissingCharacteristic {\n /// The shape of the value that doesn't implement `Default`.\n shape: &'static Shape,\n /// The characteristic that is missing.\n characteristic: Characteristic,\n },\n\n /// An operation failed for a given shape\n OperationFailed {\n /// The shape of the value for which the operation failed.\n shape: &'static Shape,\n /// The name of the operation that failed.\n operation: &'static str,\n },\n\n /// An error occurred when attempting to access or modify a field.\n FieldError {\n /// The shape of the value containing the field.\n shape: &'static Shape,\n /// The specific error that occurred with the field.\n field_error: FieldError,\n },\n\n /// Indicates that we try to access a field on an `Arc`, for example, and the field might exist\n /// on the T, but you need to do begin_smart_ptr first when using the WIP API.\n MissingPushPointee {\n /// The smart pointer (`Arc`, `Box` etc.) shape on which field was caleld\n shape: &'static Shape,\n },\n\n /// An unknown error occurred.\n Unknown,\n\n /// An error occured while putting\n TryFromError {\n /// The shape of the value being converted from.\n src_shape: &'static Shape,\n\n /// The shape of the value being converted to.\n dst_shape: &'static Shape,\n\n /// The inner error\n inner: TryFromError,\n },\n\n /// A shape has a `default` attribute, but no implementation of the `Default` trait.\n DefaultAttrButNoDefaultImpl {\n /// The shape of the value that has a `default` attribute but no default implementation.\n shape: &'static Shape,\n },\n\n /// The type is unsized\n Unsized {\n /// The shape for the type that is unsized\n shape: &'static Shape,\n /// The operation we were trying to perform\n operation: &'static str,\n },\n\n /// Array not fully initialized during build\n ArrayNotFullyInitialized {\n /// The shape of the array\n shape: &'static Shape,\n /// The number of elements pushed\n pushed_count: usize,\n /// The expected array size\n expected_size: usize,\n },\n\n /// Array index out of bounds\n ArrayIndexOutOfBounds {\n /// The shape of the array\n shape: &'static Shape,\n /// The index that was out of bounds\n index: usize,\n /// The array size\n size: usize,\n },\n\n /// Invalid operation for the current state\n InvalidOperation {\n /// The operation that was attempted\n operation: &'static str,\n /// The reason why it failed\n reason: &'static str,\n },\n\n /// No active frame in Partial\n NoActiveFrame,\n}\n\nimpl core::fmt::Display for ReflectError {\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n match self {\n ReflectError::NoSuchVariant { enum_type } => {\n write!(f, \"No such variant in enum. Known variants: \")?;\n for v in enum_type.variants {\n write!(f, \", {}\", v.name.cyan())?;\n }\n write!(f, \", that's it.\")\n }\n ReflectError::WrongShape { expected, actual } => {\n write!(\n f,\n \"Wrong shape: expected {}, but got {}\",\n expected.green(),\n actual.red()\n )\n }\n ReflectError::WasNotA { expected, actual } => {\n write!(\n f,\n \"Wrong shape: expected {}, but got {}\",\n expected.green(),\n actual.red()\n )\n }\n ReflectError::UninitializedField { shape, field_name } => {\n write!(f, \"Field '{shape}::{field_name}' was not initialized\")\n }\n ReflectError::UninitializedEnumField {\n shape,\n field_name,\n variant_name,\n } => {\n write!(\n f,\n \"Field '{}::{}' in variant '{}' was not initialized\",\n shape.blue(),\n field_name.yellow(),\n variant_name.red()\n )\n }\n ReflectError::UninitializedValue { shape } => {\n write!(f, \"Value '{}' was not initialized\", shape.blue())\n }\n ReflectError::InvariantViolation { invariant } => {\n write!(f, \"Invariant violation: {}\", invariant.red())\n }\n ReflectError::MissingCharacteristic {\n shape,\n characteristic,\n } => write!(\n f,\n \"{shape} does not implement characteristic {characteristic:?}\",\n ),\n ReflectError::OperationFailed { shape, operation } => {\n write!(\n f,\n \"Operation failed on shape {}: {}\",\n shape.blue(),\n operation\n )\n }\n ReflectError::FieldError { shape, field_error } => {\n write!(f, \"Field error for shape {}: {}\", shape.red(), field_error)\n }\n ReflectError::MissingPushPointee { shape } => {\n write!(\n f,\n \"Tried to access a field on smart pointer '{}', but you need to call {} first to work with the value it points to (and pop it with {} later)\",\n shape.blue(),\n \".begin_smart_ptr()\".yellow(),\n \".pop()\".yellow()\n )\n }\n ReflectError::Unknown => write!(f, \"Unknown error\"),\n ReflectError::TryFromError {\n src_shape,\n dst_shape,\n inner,\n } => {\n write!(\n f,\n \"While trying to put {} into a {}: {}\",\n src_shape.green(),\n dst_shape.blue(),\n inner.red()\n )\n }\n ReflectError::DefaultAttrButNoDefaultImpl { shape } => write!(\n f,\n \"Shape '{}' has a `default` attribute but no default implementation\",\n shape.red()\n ),\n ReflectError::Unsized { shape, operation } => write!(\n f,\n \"Shape '{}' is unsized, can't perform operation {}\",\n shape.red(),\n operation\n ),\n ReflectError::ArrayNotFullyInitialized {\n shape,\n pushed_count,\n expected_size,\n } => {\n write!(\n f,\n \"Array '{}' not fully initialized: expected {} elements, but got {}\",\n shape.blue(),\n expected_size,\n pushed_count\n )\n }\n ReflectError::ArrayIndexOutOfBounds { shape, index, size } => {\n write!(\n f,\n \"Array index {} out of bounds for '{}' (array length is {})\",\n index,\n shape.blue(),\n size\n )\n }\n ReflectError::InvalidOperation { operation, reason } => {\n write!(f, \"Invalid operation '{}': {}\", operation.yellow(), reason)\n }\n ReflectError::NoActiveFrame => {\n write!(f, \"No active frame in Partial\")\n }\n }\n }\n}\n\nimpl core::fmt::Debug for ReflectError {\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n // Use Display implementation for more readable output\n write!(f, \"ReflectError({self})\")\n }\n}\n\nimpl core::error::Error for ReflectError {}\n"], ["/facet/facet-core/src/types/def/option.rs", "use super::Shape;\nuse crate::ptr::{PtrConst, PtrMut, PtrUninit};\n\n/// Describes an Option — including a vtable to query and alter its state,\n/// and the inner shape (the `T` in `Option`).\n#[derive(Clone, Copy, Debug)]\n#[repr(C)]\npub struct OptionDef {\n /// vtable for interacting with the option\n pub vtable: &'static OptionVTable,\n\n /// shape of the inner type of the option\n pub t: &'static Shape,\n}\n\nimpl OptionDef {\n /// Returns a builder for OptionDef\n pub const fn builder() -> OptionDefBuilder {\n OptionDefBuilder::new()\n }\n\n /// Returns the inner type shape of the option\n pub const fn t(&self) -> &'static Shape {\n self.t\n }\n}\n\n/// Builder for OptionDef\npub struct OptionDefBuilder {\n vtable: Option<&'static OptionVTable>,\n t: Option<&'static Shape>,\n}\n\nimpl OptionDefBuilder {\n /// Creates a new OptionDefBuilder\n #[allow(clippy::new_without_default)]\n pub const fn new() -> Self {\n Self {\n vtable: None,\n t: None,\n }\n }\n\n /// Sets the vtable for the OptionDef\n pub const fn vtable(mut self, vtable: &'static OptionVTable) -> Self {\n self.vtable = Some(vtable);\n self\n }\n\n /// Sets the inner type shape for the OptionDef\n pub const fn t(mut self, t: &'static Shape) -> Self {\n self.t = Some(t);\n self\n }\n\n /// Builds the OptionDef\n pub const fn build(self) -> OptionDef {\n OptionDef {\n vtable: self.vtable.unwrap(),\n t: self.t.unwrap(),\n }\n }\n}\n\n/// Check if an option contains a value\n///\n/// # Safety\n///\n/// The `option` parameter must point to aligned, initialized memory of the correct type.\npub type OptionIsSomeFn = for<'option> unsafe fn(option: PtrConst<'option>) -> bool;\n\n/// Get the value contained in an option, if present\n///\n/// # Safety\n///\n/// The `option` parameter must point to aligned, initialized memory of the correct type.\npub type OptionGetValueFn =\n for<'option> unsafe fn(option: PtrConst<'option>) -> Option>;\n\n/// Initialize an option with Some(value)\n///\n/// # Safety\n///\n/// The `option` parameter must point to uninitialized memory of sufficient size.\n/// The function must properly initialize the memory.\n/// `value` is moved out of (with [`core::ptr::read`]) — it should be deallocated afterwards (e.g.\n/// with [`core::mem::forget`]) but NOT dropped.\npub type OptionInitSomeFn =\n for<'option> unsafe fn(option: PtrUninit<'option>, value: PtrConst<'_>) -> PtrMut<'option>;\n\n/// Initialize an option with None\n///\n/// # Safety\n///\n/// The `option` parameter must point to uninitialized memory of sufficient size.\n/// The function must properly initialize the memory.\npub type OptionInitNoneFn = unsafe fn(option: PtrUninit) -> PtrMut;\n\n/// Replace an existing option with a new value\n///\n/// # Safety\n///\n/// The `option` parameter must point to aligned, initialized memory of the correct type.\n/// The old value will be dropped.\n/// If replacing with Some, `value` is moved out of (with [`core::ptr::read`]) —\n/// it should be deallocated afterwards but NOT dropped.\npub type OptionReplaceWithFn =\n for<'option> unsafe fn(option: PtrMut<'option>, value: Option>);\n\n/// Virtual table for `Option`\n#[derive(Clone, Copy, Debug)]\n#[repr(C)]\npub struct OptionVTable {\n /// cf. [`OptionIsSomeFn`]\n pub is_some_fn: OptionIsSomeFn,\n\n /// cf. [`OptionGetValueFn`]\n pub get_value_fn: OptionGetValueFn,\n\n /// cf. [`OptionInitSomeFn`]\n pub init_some_fn: OptionInitSomeFn,\n\n /// cf. [`OptionInitNoneFn`]\n pub init_none_fn: OptionInitNoneFn,\n\n /// cf. [`OptionReplaceWithFn`]\n pub replace_with_fn: OptionReplaceWithFn,\n}\n\nimpl OptionVTable {\n /// Returns a builder for OptionVTable\n pub const fn builder() -> OptionVTableBuilder {\n OptionVTableBuilder::new()\n }\n}\n\n/// Builds an [`OptionVTable`]\npub struct OptionVTableBuilder {\n is_some_fn: Option,\n get_value_fn: Option,\n init_some_fn: Option,\n init_none_fn: Option,\n replace_with_fn: Option,\n}\n\nimpl OptionVTableBuilder {\n /// Creates a new [`OptionVTableBuilder`] with all fields set to `None`.\n #[allow(clippy::new_without_default)]\n pub const fn new() -> Self {\n Self {\n is_some_fn: None,\n get_value_fn: None,\n init_some_fn: None,\n init_none_fn: None,\n replace_with_fn: None,\n }\n }\n\n /// Sets the is_some_fn field\n pub const fn is_some(mut self, f: OptionIsSomeFn) -> Self {\n self.is_some_fn = Some(f);\n self\n }\n\n /// Sets the get_value_fn field\n pub const fn get_value(mut self, f: OptionGetValueFn) -> Self {\n self.get_value_fn = Some(f);\n self\n }\n\n /// Sets the init_some_fn field\n pub const fn init_some(mut self, f: OptionInitSomeFn) -> Self {\n self.init_some_fn = Some(f);\n self\n }\n\n /// Sets the init_none_fn field\n pub const fn init_none(mut self, f: OptionInitNoneFn) -> Self {\n self.init_none_fn = Some(f);\n self\n }\n\n /// Sets the replace_with_fn field\n pub const fn replace_with(mut self, f: OptionReplaceWithFn) -> Self {\n self.replace_with_fn = Some(f);\n self\n }\n\n /// Builds the [`OptionVTable`] from the current state of the builder.\n ///\n /// # Panics\n ///\n /// This method will panic if any of the required fields are `None`.\n pub const fn build(self) -> OptionVTable {\n OptionVTable {\n is_some_fn: self.is_some_fn.unwrap(),\n get_value_fn: self.get_value_fn.unwrap(),\n init_some_fn: self.init_some_fn.unwrap(),\n init_none_fn: self.init_none_fn.unwrap(),\n replace_with_fn: self.replace_with_fn.unwrap(),\n }\n }\n}\n"], ["/facet/facet-reflect/src/peek/tuple.rs", "use core::fmt::Debug;\nuse facet_core::Field;\n\nuse super::{FieldIter, Peek};\n\n/// Local representation of a tuple type for peek operations\n#[derive(Clone, Copy, Debug)]\npub struct TupleType {\n /// Fields of the tuple, with offsets\n pub fields: &'static [Field],\n}\n\n/// Field index and associated peek value\npub type TupleField<'mem, 'facet> = (usize, Peek<'mem, 'facet>);\n\n/// Lets you read from a tuple\n#[derive(Clone, Copy)]\npub struct PeekTuple<'mem, 'facet> {\n /// Original peek value\n pub(crate) value: Peek<'mem, 'facet>,\n /// Tuple type information\n pub(crate) ty: TupleType,\n}\n\nimpl Debug for PeekTuple<'_, '_> {\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n f.debug_struct(\"PeekTuple\")\n .field(\"type\", &self.ty)\n .finish_non_exhaustive()\n }\n}\n\nimpl<'mem, 'facet> PeekTuple<'mem, 'facet> {\n /// Get the number of fields in this tuple\n #[inline]\n pub fn len(&self) -> usize {\n self.ty.fields.len()\n }\n\n /// Returns true if this tuple has no fields\n #[inline]\n pub fn is_empty(&self) -> bool {\n self.len() == 0\n }\n\n /// Access a field by index\n #[inline]\n pub fn field(&self, index: usize) -> Option> {\n if index >= self.len() {\n return None;\n }\n\n let field = &self.ty.fields[index];\n // We can safely use field operations here since this is within facet-reflect\n // which is allowed to use unsafe code\n let field_ptr = unsafe { self.value.data().field(field.offset) };\n let field_peek = unsafe { Peek::unchecked_new(field_ptr, field.shape) };\n\n Some(field_peek)\n }\n\n /// Iterate over all fields\n #[inline]\n pub fn fields(&self) -> FieldIter<'mem, 'facet> {\n FieldIter::new_tuple(*self)\n }\n\n /// Type information\n #[inline]\n pub fn ty(&self) -> TupleType {\n self.ty\n }\n\n /// Internal peek value\n #[inline]\n pub fn value(&self) -> Peek<'mem, 'facet> {\n self.value\n }\n}\n"], ["/facet/facet-core/src/impls_core/array.rs", "use crate::*;\n\nunsafe impl<'a, T, const L: usize> Facet<'a> for [T; L]\nwhere\n T: Facet<'a>,\n{\n const VTABLE: &'static ValueVTable = &const {\n ValueVTable::builder::()\n .marker_traits(|| T::SHAPE.vtable.marker_traits())\n .type_name(|f, opts| {\n if let Some(opts) = opts.for_children() {\n write!(f, \"[\")?;\n (T::SHAPE.vtable.type_name())(f, opts)?;\n write!(f, \"; {L}]\")\n } else {\n write!(f, \"[⋯; {L}]\")\n }\n })\n .default_in_place(|| {\n if L == 0 {\n // Zero-length arrays implement `Default` irrespective of the element type\n Some(|target| unsafe { target.assume_init() })\n } else if L <= 32 && T::SHAPE.vtable.has_default_in_place() {\n Some(|mut target| unsafe {\n let t_dip = >::of().default_in_place().unwrap();\n let stride = T::SHAPE\n .layout\n .sized_layout()\n .unwrap()\n .pad_to_align()\n .size();\n for idx in 0..L {\n t_dip(target.field_uninit_at(idx * stride));\n }\n target.assume_init()\n })\n } else {\n // arrays do not yet implement `Default` for > 32 elements due\n // to specializing the `0` len case\n None\n }\n })\n .clone_into(|| {\n if T::SHAPE.vtable.has_clone_into() {\n Some(|src, mut dst| unsafe {\n let t_cip = >::of().clone_into().unwrap();\n let stride = T::SHAPE\n .layout\n .sized_layout()\n .unwrap()\n .pad_to_align()\n .size();\n for (idx, src) in src.iter().enumerate() {\n (t_cip)(src, dst.field_uninit_at(idx * stride));\n }\n dst.assume_init()\n })\n } else {\n None\n }\n })\n .build()\n };\n\n const SHAPE: &'static Shape = &const {\n Shape::builder_for_sized::()\n .type_identifier(\"&[_; _]\")\n .type_params(&[TypeParam {\n name: \"T\",\n shape: || T::SHAPE,\n }])\n .ty(Type::Sequence(SequenceType::Array(ArrayType {\n t: T::SHAPE,\n n: L,\n })))\n .def(Def::Array(\n ArrayDef::builder()\n .vtable(\n &const {\n ArrayVTable::builder()\n .as_ptr(|ptr| unsafe {\n let array = ptr.get::<[T; L]>();\n PtrConst::new(array.as_ptr())\n })\n .as_mut_ptr(|ptr| unsafe {\n let array = ptr.as_mut::<[T; L]>();\n PtrMut::new(array.as_mut_ptr())\n })\n .build()\n },\n )\n .t(T::SHAPE)\n .n(L)\n .build(),\n ))\n .build()\n };\n}\n"], ["/facet/facet-core/src/typeid.rs", "//! Forked from \n\n#![allow(clippy::doc_markdown, clippy::inline_always)]\n\nextern crate self as typeid;\n\nuse core::any::TypeId;\nuse core::cmp::Ordering;\nuse core::fmt::{self, Debug};\nuse core::hash::{Hash, Hasher};\nuse core::marker::PhantomData;\nuse core::mem;\n\n/// TypeId equivalent usable in const contexts.\n#[derive(Copy, Clone)]\n#[repr(C)]\npub struct ConstTypeId {\n pub(crate) type_id_fn: fn() -> TypeId,\n}\n\nimpl ConstTypeId {\n /// Create a [`ConstTypeId`] for a type.\n #[must_use]\n pub const fn of() -> Self\n where\n T: ?Sized,\n {\n ConstTypeId {\n type_id_fn: typeid::of::,\n }\n }\n\n /// Get the underlying [`TypeId`] for this `ConstTypeId`.\n #[inline]\n pub fn get(self) -> TypeId {\n (self.type_id_fn)()\n }\n}\n\nimpl Debug for ConstTypeId {\n #[inline]\n fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {\n Debug::fmt(&self.get(), formatter)\n }\n}\n\nimpl PartialEq for ConstTypeId {\n #[inline]\n fn eq(&self, other: &Self) -> bool {\n self.get() == other.get()\n }\n}\n\nimpl PartialEq for ConstTypeId {\n #[inline]\n fn eq(&self, other: &TypeId) -> bool {\n self.get() == *other\n }\n}\n\nimpl Eq for ConstTypeId {}\n\nimpl PartialOrd for ConstTypeId {\n #[inline]\n fn partial_cmp(&self, other: &Self) -> Option {\n Some(Ord::cmp(self, other))\n }\n}\n\nimpl Ord for ConstTypeId {\n #[inline]\n fn cmp(&self, other: &Self) -> Ordering {\n Ord::cmp(&self.get(), &other.get())\n }\n}\n\nimpl Hash for ConstTypeId {\n fn hash(&self, state: &mut H) {\n self.get().hash(state);\n }\n}\n\n/// Create a [`TypeId`] for a type.\n#[must_use]\n#[inline(always)]\npub fn of() -> TypeId\nwhere\n T: ?Sized,\n{\n trait NonStaticAny {\n fn get_type_id(&self) -> TypeId\n where\n Self: 'static;\n }\n\n impl NonStaticAny for PhantomData {\n #[inline(always)]\n fn get_type_id(&self) -> TypeId\n where\n Self: 'static,\n {\n TypeId::of::()\n }\n }\n\n let phantom_data = PhantomData::;\n NonStaticAny::get_type_id(unsafe {\n mem::transmute::<&dyn NonStaticAny, &(dyn NonStaticAny + 'static)>(&phantom_data)\n })\n}\n"], ["/facet/facet-reflect/src/peek/struct_.rs", "use facet_core::{FieldError, StructType};\n\nuse crate::Peek;\n\nuse super::{FieldIter, HasFields};\n\n/// Lets you read from a struct (implements read-only struct operations)\n#[derive(Clone, Copy)]\npub struct PeekStruct<'mem, 'facet> {\n /// the underlying value\n pub(crate) value: Peek<'mem, 'facet>,\n\n /// the definition of the struct!\n pub(crate) ty: StructType,\n}\n\nimpl core::fmt::Debug for PeekStruct<'_, '_> {\n fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {\n f.debug_struct(\"PeekStruct\").finish_non_exhaustive()\n }\n}\n\nimpl<'mem, 'facet> PeekStruct<'mem, 'facet> {\n /// Returns the struct definition\n #[inline(always)]\n pub fn ty(&self) -> &StructType {\n &self.ty\n }\n\n /// Returns the number of fields in this struct\n #[inline(always)]\n pub fn field_count(&self) -> usize {\n self.ty.fields.len()\n }\n\n /// Returns the value of the field at the given index\n #[inline(always)]\n pub fn field(&self, index: usize) -> Result, FieldError> {\n self.ty\n .fields\n .get(index)\n .map(|field| unsafe {\n let field_data = self.value.data().field(field.offset);\n Peek::unchecked_new(field_data, field.shape())\n })\n .ok_or(FieldError::IndexOutOfBounds {\n index,\n bound: self.ty.fields.len(),\n })\n }\n\n /// Gets the value of the field with the given name\n #[inline]\n pub fn field_by_name(&self, name: &str) -> Result, FieldError> {\n for (i, field) in self.ty.fields.iter().enumerate() {\n if field.name == name {\n return self.field(i);\n }\n }\n Err(FieldError::NoSuchField)\n }\n}\n\nimpl<'mem, 'facet> HasFields<'mem, 'facet> for PeekStruct<'mem, 'facet> {\n /// Iterates over all fields in this struct, providing both name and value\n #[inline]\n fn fields(&self) -> FieldIter<'mem, 'facet> {\n FieldIter::new_struct(*self)\n }\n}\n"], ["/facet/facet-reflect/src/peek/pointer.rs", "use facet_core::PointerDef;\n\nuse super::Peek;\n\n/// Represents a pointer that can be peeked at during memory inspection.\n///\n/// This struct holds the value being pointed to and the definition of the pointer type.\npub struct PeekPointer<'mem, 'facet> {\n /// The value being pointed to by this pointer.\n pub(crate) value: Peek<'mem, 'facet>,\n\n /// The definition of this pointer type.\n pub(crate) def: PointerDef,\n}\n\nimpl<'mem, 'facet> PeekPointer<'mem, 'facet> {\n /// Returns a reference to the pointer definition.\n #[must_use]\n #[inline]\n pub fn def(&self) -> &PointerDef {\n &self.def\n }\n\n /// Borrows the inner value of the pointer.\n ///\n /// Returns `None` if the pointer doesn't have a borrow function or pointee shape.\n #[inline]\n pub fn borrow_inner(&self) -> Option> {\n let borrow_fn = self.def.vtable.borrow_fn?;\n let pointee_shape = self.def.pointee()?;\n\n // SAFETY: We have a valid pointer and borrow_fn is provided by the vtable\n let inner_ptr = unsafe { borrow_fn(self.value.data.thin().unwrap()) };\n\n // SAFETY: The borrow_fn returns a valid pointer to the inner value with the correct shape\n let inner_peek = unsafe { Peek::unchecked_new(inner_ptr, pointee_shape) };\n\n Some(inner_peek)\n }\n}\n"], ["/facet/facet-macros/src/lib.rs", "#![doc = include_str!(\"../README.md\")]\n\n#[proc_macro_derive(Facet, attributes(facet))]\npub fn facet_macros(input: proc_macro::TokenStream) -> proc_macro::TokenStream {\n facet_macros_emit::facet_macros(input.into()).into()\n}\n\n#[cfg(feature = \"function\")]\n#[proc_macro_attribute]\npub fn facet_fn(\n attr: proc_macro::TokenStream,\n item: proc_macro::TokenStream,\n) -> proc_macro::TokenStream {\n facet_macros_emit::function::facet_fn(attr.into(), item.into()).into()\n}\n\n#[cfg(feature = \"function\")]\n#[proc_macro]\npub fn fn_shape(input: proc_macro::TokenStream) -> proc_macro::TokenStream {\n facet_macros_emit::function::fn_shape(input.into()).into()\n}\n"], ["/facet/facet-reflect/src/partial/iset.rs", "/// Keeps track of which fields were initialized, up to 64 fields\n#[derive(Clone, Copy, Default, Debug)]\npub struct ISet {\n flags: u64,\n}\n\nimpl ISet {\n /// The maximum index that can be tracked.\n pub const MAX_INDEX: usize = 63;\n\n /// Creates a new ISet with all bits set except for the lowest `count` bits, which are unset.\n ///\n /// # Panics\n ///\n /// Panics if `count` > 64.\n #[inline]\n pub fn new(count: usize) -> Self {\n if count > 64 {\n panic!(\"ISet can only track up to 64 fields. Count {count} is out of bounds.\");\n }\n let flags = !((1u64 << count) - 1);\n Self { flags }\n }\n\n /// Sets the bit at the given index.\n #[inline]\n pub fn set(&mut self, index: usize) {\n if index >= 64 {\n panic!(\"ISet can only track up to 64 fields. Index {index} is out of bounds.\");\n }\n self.flags |= 1 << index;\n }\n\n /// Checks if the bit at the given index is set.\n #[inline]\n pub fn get(&self, index: usize) -> bool {\n if index >= 64 {\n panic!(\"ISet can only track up to 64 fields. Index {index} is out of bounds.\");\n }\n (self.flags & (1 << index)) != 0\n }\n\n /// Unsets the bit at the given index.\n #[inline]\n pub fn unset(&mut self, index: usize) {\n if index >= 64 {\n panic!(\"ISet can only track up to 64 fields. Index {index} is out of bounds.\");\n }\n self.flags &= !(1 << index);\n }\n\n /// Returns true if all bits up to MAX_INDEX are set.\n #[inline]\n pub fn all_set(&self) -> bool {\n self.flags == u64::MAX >> (63 - Self::MAX_INDEX)\n }\n}\n"], ["/facet/facet/src/lib.rs", "#![cfg_attr(not(feature = \"std\"), no_std)]\n#![warn(missing_docs)]\n#![warn(clippy::std_instead_of_core)]\n#![warn(clippy::std_instead_of_alloc)]\n#![doc = include_str!(\"../README.md\")]\n#![cfg_attr(docsrs, feature(doc_cfg))]\n#![cfg_attr(docsrs, feature(builtin_syntax))]\n#![cfg_attr(docsrs, feature(prelude_import))]\n#![cfg_attr(docsrs, allow(internal_features))]\n\npub use facet_core::*;\n\n/// Derive the [`Facet`] trait for structs, tuple structs, and enums.\n///\n/// Using this macro gives the derived type runtime (and to some extent, const-time) knowledge about the type, also known as [\"reflection\"](https://en.wikipedia.org/wiki/Reflective_programming).\n///\n/// This uses unsynn, so it's light, but it _will_ choke on some Rust syntax because...\n/// there's a lot of Rust syntax.\n///\n/// ```rust\n/// # use facet::Facet;\n/// #[derive(Facet)]\n/// struct FooBar {\n/// foo: u32,\n/// bar: String,\n/// }\n/// ```\n///\n/// # Container Attributes\n///\n/// ```rust\n/// # use facet::Facet;\n/// #[derive(Facet)]\n/// #[facet(rename_all = \"kebab-case\")]\n/// struct FooBar {\n/// # }\n/// ```\n///\n/// * `rename_all = \"..\"` Rename all the fields (if this is a struct) or variants (if this is an enum) according to the given case convention. The possible values are: `\"snake_case\"`, `\"SCREAMING_SNAKE_CASE\"`, `\"PascalCase\"`, `\"camelCase\"`, `\"kebab-case\"`, `\"SCREAMING-KEBAB-CASE\"`.\n///\n/// * `transparent` Serialize and deserialize a newtype struct exactly the same as if its single field were serialized and deserialized by itself.\n///\n/// * `deny_unknown_fields` Always throw an error when encountering unknown fields during deserialization. When this attribute is not present unknown fields are ignored.\n///\n/// * `skip_serializing` Don't allow this type to be serialized.\n///\n/// * `skip_serializing_if = \"..\"` Don't allow this type to be serialized if the function returns `true`.\n///\n/// * `invariants = \"..\"` Called when doing `Partial::build`. **TODO**\n///\n/// # Field Attributes\n///\n/// ```rust\n/// # use facet::Facet;\n/// #[derive(Facet)]\n/// struct FooBar {\n/// #[facet(default)]\n/// foo: u32,\n/// # }\n/// ```\n///\n/// * `rename = \"..\"` Rename to the given case convention. The possible values are: `\"snake_case\"`, `\"SCREAMING_SNAKE_CASE\"`, `\"PascalCase\"`, `\"camelCase\"`, `\"kebab-case\"`, `\"SCREAMING-KEBAB-CASE\"`.\n///\n/// * `default` Use the field's value from the container's `Default::default()` implementation when the field is missing during deserializing.\n///\n/// * `default = \"..\"` Use the expression when the field is missing during deserializing.\n///\n/// * `sensitive` Don't show the value in debug outputs.\n///\n/// * `flatten` Flatten the value's content into the container structure.\n///\n/// * `child` Mark as child node in a hierarchy. **TODO**\n///\n/// * `skip_serializing` Ignore when serializing.\n///\n/// * `skip_serializing_if = \"..\"` Ignore when serializing if the function returns `true`.\n///\n/// # Variant Attributes\n///\n/// ```rust\n/// # use facet::Facet;\n/// #[derive(Facet)]\n/// #[repr(C)]\n/// enum FooBar {\n/// #[facet(rename = \"kebab-case\")]\n/// Foo(u32),\n/// # }\n/// ```\n///\n/// * `rename = \"..\"` Rename to the given case convention. The possible values are: `\"snake_case\"`, `\"SCREAMING_SNAKE_CASE\"`, `\"PascalCase\"`, `\"camelCase\"`, `\"kebab-case\"`, `\"SCREAMING-KEBAB-CASE\"`.\n///\n/// * `skip_serializing` Ignore when serializing.\n///\n/// * `skip_serializing_if = \"..\"` Ignore when serializing if the function returns `true`.\n///\n/// # Examples\n///\n/// **TODO**.\npub use facet_macros::*;\n\n#[cfg(feature = \"reflect\")]\npub use facet_reflect::*;\n\npub mod hacking;\n\npub use static_assertions;\n"], ["/facet/facet-core/src/types/def/slice.rs", "use crate::{PtrMut, ptr::PtrConst};\n\nuse super::Shape;\n\n/// Fields for slice types\n#[derive(Clone, Copy, Debug)]\n#[repr(C)]\npub struct SliceDef {\n /// vtable for interacting with the slice\n pub vtable: &'static SliceVTable,\n /// shape of the items in the slice\n pub t: &'static Shape,\n}\n\nimpl SliceDef {\n /// Returns a builder for SliceDef\n pub const fn builder() -> SliceDefBuilder {\n SliceDefBuilder::new()\n }\n\n /// Returns the shape of the items in the slice\n pub const fn t(&self) -> &'static Shape {\n self.t\n }\n}\n\n/// Builder for SliceDef\npub struct SliceDefBuilder {\n vtable: Option<&'static SliceVTable>,\n t: Option<&'static Shape>,\n}\n\nimpl SliceDefBuilder {\n /// Creates a new SliceDefBuilder\n #[allow(clippy::new_without_default)]\n pub const fn new() -> Self {\n Self {\n vtable: None,\n t: None,\n }\n }\n\n /// Sets the vtable for the SliceDef\n pub const fn vtable(mut self, vtable: &'static SliceVTable) -> Self {\n self.vtable = Some(vtable);\n self\n }\n\n /// Sets the item shape for the SliceDef\n pub const fn t(mut self, t: &'static Shape) -> Self {\n self.t = Some(t);\n self\n }\n\n /// Builds the SliceDef\n pub const fn build(self) -> SliceDef {\n SliceDef {\n vtable: self.vtable.unwrap(),\n t: self.t.unwrap(),\n }\n }\n}\n\n/// Get the number of items in the slice\n///\n/// # Safety\n///\n/// The `slice` parameter must point to aligned, initialized memory of the correct type.\npub type SliceLenFn = unsafe fn(slice: PtrConst) -> usize;\n\n/// Get pointer to the data buffer of the slice\n///\n/// # Safety\n///\n/// The `slice` parameter must point to aligned, initialized memory of the correct type.\npub type SliceAsPtrFn = unsafe fn(slice: PtrConst) -> PtrConst;\n\n/// Get mutable pointer to the data buffer of the slice\n///\n/// # Safety\n///\n/// The `slice` parameter must point to aligned, initialized memory of the correct type.\npub type SliceAsMutPtrFn = unsafe fn(slice: PtrMut) -> PtrMut;\n\n/// Virtual table for a slice-like type (like `Vec`,\n/// but also `HashSet`, etc.)\n#[derive(Clone, Copy, Debug)]\n#[repr(C)]\npub struct SliceVTable {\n /// Number of items in the slice\n pub len: SliceLenFn,\n /// Get pointer to the data buffer of the slice.\n pub as_ptr: SliceAsPtrFn,\n /// Get mutable pointer to the data buffer of the slice.\n pub as_mut_ptr: SliceAsMutPtrFn,\n}\n\nimpl SliceVTable {\n /// Returns a builder for SliceVTable\n pub const fn builder() -> SliceVTableBuilder {\n SliceVTableBuilder::new()\n }\n}\n\n/// Builds a [`SliceVTable`]\npub struct SliceVTableBuilder {\n as_ptr: Option,\n as_mut_ptr: Option,\n len: Option,\n}\n\nimpl SliceVTableBuilder {\n /// Creates a new [`SliceVTableBuilder`] with all fields set to `None`.\n #[allow(clippy::new_without_default)]\n pub const fn new() -> Self {\n Self {\n len: None,\n as_ptr: None,\n as_mut_ptr: None,\n }\n }\n\n /// Sets the `len` field\n pub const fn len(mut self, f: SliceLenFn) -> Self {\n self.len = Some(f);\n self\n }\n\n /// Sets the as_ptr field\n pub const fn as_ptr(mut self, f: SliceAsPtrFn) -> Self {\n self.as_ptr = Some(f);\n self\n }\n\n /// Sets the as_mut_ptr field\n pub const fn as_mut_ptr(mut self, f: SliceAsMutPtrFn) -> Self {\n self.as_mut_ptr = Some(f);\n self\n }\n\n /// Builds the [`SliceVTable`] from the current state of the builder.\n ///\n /// # Panics\n ///\n /// This method will panic if any of the required fields are `None`.\n pub const fn build(self) -> SliceVTable {\n SliceVTable {\n len: self.len.unwrap(),\n as_ptr: self.as_ptr.unwrap(),\n as_mut_ptr: self.as_mut_ptr.unwrap(),\n }\n }\n}\n"], ["/facet/facet-reflect/src/peek/option.rs", "use facet_core::{OptionDef, OptionVTable};\n\n/// Lets you read from an option (implements read-only option operations)\n#[derive(Clone, Copy)]\npub struct PeekOption<'mem, 'facet> {\n /// the underlying value\n pub(crate) value: crate::Peek<'mem, 'facet>,\n\n /// the definition of the option\n pub(crate) def: OptionDef,\n}\n\nimpl<'mem, 'facet> PeekOption<'mem, 'facet> {\n /// Returns the option definition\n #[inline(always)]\n pub fn def(self) -> OptionDef {\n self.def\n }\n\n /// Returns the option vtable\n #[inline(always)]\n pub fn vtable(self) -> &'static OptionVTable {\n self.def.vtable\n }\n\n /// Returns whether the option is Some\n #[inline]\n pub fn is_some(self) -> bool {\n unsafe { (self.vtable().is_some_fn)(self.value.data().thin().unwrap()) }\n }\n\n /// Returns whether the option is None\n #[inline]\n pub fn is_none(self) -> bool {\n !self.is_some()\n }\n\n /// Returns the inner value as a Peek if the option is Some, None otherwise\n #[inline]\n pub fn value(self) -> Option> {\n unsafe {\n (self.vtable().get_value_fn)(self.value.data().thin().unwrap())\n .map(|inner_data| crate::Peek::unchecked_new(inner_data, self.def.t()))\n }\n }\n}\n"], ["/facet/facet-core/src/impls_core/nonnull.rs", "use crate::{\n Def, Facet, Field, FieldFlags, KnownPointer, PointerDef, PointerFlags, PointerVTable, PtrConst,\n Repr, StructKind, StructType, Type, UserType, ValueVTable, value_vtable,\n};\n\nunsafe impl<'a, T: Facet<'a>> Facet<'a> for core::ptr::NonNull {\n const VTABLE: &'static ValueVTable = &const {\n value_vtable!(core::ptr::NonNull, |f, _opts| write!(\n f,\n \"{}\",\n Self::SHAPE.type_identifier\n ))\n };\n\n const SHAPE: &'static crate::Shape = &const {\n crate::Shape::builder_for_sized::()\n .type_identifier(\"NonNull\")\n .type_params(&[crate::TypeParam {\n name: \"T\",\n shape: || T::SHAPE,\n }])\n .ty(Type::User(UserType::Struct(StructType {\n repr: Repr::transparent(),\n kind: StructKind::Struct,\n fields: &const {\n [Field::builder()\n .name(\"pointer\")\n .shape(<*mut T>::SHAPE)\n .offset(0)\n .flags(FieldFlags::EMPTY)\n .build()]\n },\n })))\n .def(Def::Pointer(\n PointerDef::builder()\n .pointee(|| T::SHAPE)\n .flags(PointerFlags::EMPTY)\n .known(KnownPointer::NonNull)\n .vtable(\n &const {\n PointerVTable::builder()\n .borrow_fn(|this| {\n let ptr = unsafe { this.get::().as_ptr() };\n PtrConst::new(ptr).into()\n })\n .new_into_fn(|this, ptr| {\n let ptr = unsafe { ptr.read::<*mut T>() };\n let non_null =\n unsafe { core::ptr::NonNull::new_unchecked(ptr) };\n unsafe { this.put(non_null) }\n })\n .build()\n },\n )\n .build(),\n ))\n .build()\n };\n}\n"], ["/facet/facet-core/src/types/def/array.rs", "use crate::{PtrMut, ptr::PtrConst};\n\nuse super::Shape;\n\n/// Fields for array types\n#[derive(Clone, Copy, Debug)]\n#[repr(C)]\npub struct ArrayDef {\n /// vtable for interacting with the array\n pub vtable: &'static ArrayVTable,\n\n /// shape of the items in the array\n pub t: &'static Shape,\n\n /// The length of the array\n pub n: usize,\n}\n\nimpl ArrayDef {\n /// Returns a builder for ArrayDef\n pub const fn builder() -> ArrayDefBuilder {\n ArrayDefBuilder::new()\n }\n\n /// Returns the shape of the items in the array\n pub fn t(&self) -> &'static Shape {\n self.t\n }\n}\n\n/// Builder for ArrayDef\npub struct ArrayDefBuilder {\n vtable: Option<&'static ArrayVTable>,\n t: Option<&'static Shape>,\n n: Option,\n}\n\nimpl ArrayDefBuilder {\n /// Creates a new ArrayDefBuilder\n #[allow(clippy::new_without_default)]\n pub const fn new() -> Self {\n Self {\n vtable: None,\n t: None,\n n: None,\n }\n }\n\n /// Sets the vtable for the ArrayDef\n pub const fn vtable(mut self, vtable: &'static ArrayVTable) -> Self {\n self.vtable = Some(vtable);\n self\n }\n\n /// Sets the item shape for the ArrayDef\n pub const fn t(mut self, t: &'static Shape) -> Self {\n self.t = Some(t);\n self\n }\n\n /// Sets the length for the ArrayDef (added method)\n pub const fn n(mut self, n: usize) -> Self {\n self.n = Some(n);\n self\n }\n\n /// Builds the ArrayDef\n pub const fn build(self) -> ArrayDef {\n ArrayDef {\n vtable: self.vtable.unwrap(),\n t: self.t.unwrap(),\n n: self.n.unwrap(),\n }\n }\n}\n\n/// Get pointer to the data buffer of the array.\n///\n/// # Safety\n///\n/// The `array` parameter must point to aligned, initialized memory of the correct type.\npub type ArrayAsPtrFn = unsafe fn(array: PtrConst) -> PtrConst;\n\n/// Get mutable pointer to the data buffer of the array.\n///\n/// # Safety\n///\n/// The `array` parameter must point to aligned, initialized memory of the correct type.\npub type ArrayAsMutPtrFn = unsafe fn(array: PtrMut) -> PtrMut;\n\n/// Virtual table for an array\n#[derive(Clone, Copy, Debug)]\n#[repr(C)]\npub struct ArrayVTable {\n /// cf. [`ArrayAsPtrFn`]\n pub as_ptr: ArrayAsPtrFn,\n\n /// cf. [`ArrayAsMutPtrFn`]\n pub as_mut_ptr: ArrayAsMutPtrFn,\n}\n\nimpl ArrayVTable {\n /// Returns a builder for ListVTable\n pub const fn builder() -> ArrayVTableBuilder {\n ArrayVTableBuilder::new()\n }\n}\n\n/// Builds a [`ArrayVTable`]\npub struct ArrayVTableBuilder {\n as_ptr_fn: Option,\n as_mut_ptr_fn: Option,\n}\n\nimpl ArrayVTableBuilder {\n /// Creates a new [`ArrayVTableBuilder`] with all fields set to `None`.\n #[allow(clippy::new_without_default)]\n pub const fn new() -> Self {\n Self {\n as_ptr_fn: None,\n as_mut_ptr_fn: None,\n }\n }\n\n /// Sets the as_ptr field\n pub const fn as_ptr(mut self, f: ArrayAsPtrFn) -> Self {\n self.as_ptr_fn = Some(f);\n self\n }\n\n /// Sets the as_mut_ptr field\n pub const fn as_mut_ptr(mut self, f: ArrayAsMutPtrFn) -> Self {\n self.as_mut_ptr_fn = Some(f);\n self\n }\n\n /// Builds the [`ArrayVTable`] from the current state of the builder.\n ///\n /// # Panics\n ///\n /// This method will panic if any of the required fields are `None`.\n pub const fn build(self) -> ArrayVTable {\n ArrayVTable {\n as_ptr: self.as_ptr_fn.unwrap(),\n as_mut_ptr: self.as_mut_ptr_fn.unwrap(),\n }\n }\n}\n"], ["/facet/facet-core/src/types/ty/user.rs", "use super::{EnumType, StructType, UnionType};\n\n/// User-defined types (structs, enums, unions)\n#[derive(Clone, Copy, Debug)]\n#[repr(C)]\npub enum UserType {\n /// Describes a `struct`\n Struct(StructType),\n /// Describes an `enum`\n Enum(EnumType),\n /// Describes a `union`\n Union(UnionType),\n /// Special variant for representing external types with unknown internal representation.\n Opaque,\n}\n\nimpl UserType {\n /// Retrieves underlying representation of the type\n #[inline]\n pub const fn repr(&self) -> Option {\n match self {\n Self::Struct(s) => Some(s.repr),\n Self::Enum(e) => Some(e.repr),\n Self::Union(u) => Some(u.repr),\n Self::Opaque => None,\n }\n }\n}\n\n/// Describes base representation of the type\n///\n/// Is the structure packed, is it laid out like a C struct, is it a transparent wrapper?\n#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]\n#[repr(C)]\npub struct Repr {\n /// Describes base layout representation of the type\n pub base: BaseRepr,\n /// Are the values tightly packed?\n ///\n /// Note, that if struct is packed, the underlying values may not be aligned, and it is\n /// undefined behavior to interact with unaligned values - first copy the value to aligned\n /// buffer, before interacting with it (but first, make sure it is `Copy`!)\n pub packed: bool,\n}\n\nimpl Repr {\n /// Create default representation for a user type\n ///\n /// This will be Rust representation with no packing\n #[inline]\n pub const fn default() -> Self {\n Self {\n base: BaseRepr::Rust,\n packed: false,\n }\n }\n\n /// Build unpacked C representation\n #[inline]\n pub const fn c() -> Self {\n Self {\n base: BaseRepr::C,\n packed: false,\n }\n }\n\n /// Builds transparent representation\n #[inline]\n pub const fn transparent() -> Self {\n Self {\n base: BaseRepr::Transparent,\n packed: false,\n }\n }\n}\n\n/// Underlying byte layout representation\n#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)]\n#[repr(C)]\npub enum BaseRepr {\n /// `#[repr(C)]`\n C,\n /// `#[repr(Rust)]` / no attribute\n #[default]\n Rust,\n /// `#[repr(transparent)]`\n Transparent,\n}\n"], ["/facet/facet-core/src/types/ty/struct_.rs", "use super::{Field, Repr};\n\n/// Common fields for struct-like types\n#[derive(Clone, Copy, Debug)]\n#[repr(C)]\npub struct StructType {\n /// Representation of the struct's data\n pub repr: Repr,\n\n /// the kind of struct (e.g. struct, tuple struct, tuple)\n pub kind: StructKind,\n\n /// all fields, in declaration order (not necessarily in memory order)\n pub fields: &'static [Field],\n}\n\nimpl StructType {\n /// Returns a builder for StructType\n pub const fn builder() -> StructBuilder {\n StructBuilder::new()\n }\n}\n\n/// Builder for StructType\npub struct StructBuilder {\n repr: Option,\n kind: Option,\n fields: &'static [Field],\n}\n\nimpl StructBuilder {\n /// Creates a new StructBuilder\n #[allow(clippy::new_without_default)]\n pub const fn new() -> Self {\n Self {\n repr: None,\n kind: None,\n fields: &[],\n }\n }\n /// Sets the kind to Unit and returns self\n pub const fn unit(mut self) -> Self {\n self.kind = Some(StructKind::Unit);\n self\n }\n\n /// Sets the kind to Tuple and returns self\n pub const fn tuple(mut self) -> Self {\n self.kind = Some(StructKind::Tuple);\n self\n }\n\n /// Sets the kind to Struct and returns self\n pub const fn struct_(mut self) -> Self {\n self.kind = Some(StructKind::Struct);\n self\n }\n\n /// Sets the repr for the StructType\n pub const fn repr(mut self, repr: Repr) -> Self {\n self.repr = Some(repr);\n self\n }\n\n /// Sets the kind for the StructType\n pub const fn kind(mut self, kind: StructKind) -> Self {\n self.kind = Some(kind);\n self\n }\n\n /// Sets the fields for the StructType\n pub const fn fields(mut self, fields: &'static [Field]) -> Self {\n self.fields = fields;\n self\n }\n\n /// Builds the StructType\n pub const fn build(self) -> StructType {\n StructType {\n repr: self.repr.unwrap(),\n kind: self.kind.unwrap(),\n fields: self.fields,\n }\n }\n}\n\n/// Describes the kind of struct (useful for deserializing)\n#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]\n#[repr(C)]\npub enum StructKind {\n /// struct UnitStruct;\n Unit,\n\n /// struct TupleStruct(T0, T1);\n TupleStruct,\n\n /// struct S { foo: T0, bar: T1 }\n Struct,\n\n /// (T0, T1)\n Tuple,\n}\n"], ["/facet/facet-core/src/impls_core/ops.rs", "use crate::{ConstTypeId, Facet, Field, Shape, StructType, Type, VTableView, ValueVTable};\nuse core::{alloc::Layout, mem};\n\nunsafe impl<'a, Idx: Facet<'a>> Facet<'a> for core::ops::Range {\n const SHAPE: &'static Shape = &const {\n Shape::builder_for_sized::()\n .type_identifier(\"Range\")\n .type_params(&[crate::TypeParam {\n name: \"Idx\",\n shape: || Idx::SHAPE,\n }])\n .id(ConstTypeId::of::())\n .layout(Layout::new::())\n .ty(Type::User(crate::UserType::Struct(\n StructType::builder()\n .kind(crate::StructKind::Struct)\n .repr(crate::Repr::default())\n .fields(\n &const {\n [\n Field::builder()\n .name(\"start\")\n .shape(Idx::SHAPE)\n .offset(mem::offset_of!(core::ops::Range, start))\n .build(),\n Field::builder()\n .name(\"end\")\n .shape(Idx::SHAPE)\n .offset(mem::offset_of!(core::ops::Range, end))\n .build(),\n ]\n },\n )\n .build(),\n )))\n .build()\n };\n\n const VTABLE: &'static ValueVTable = &const {\n ValueVTable::builder::()\n .type_name(|f, opts| {\n write!(f, \"{}\", Self::SHAPE.type_identifier)?;\n if let Some(opts) = opts.for_children() {\n write!(f, \"<\")?;\n Idx::SHAPE.vtable.type_name()(f, opts)?;\n write!(f, \">\")?;\n } else {\n write!(f, \"<…>\")?;\n }\n Ok(())\n })\n .debug(|| {\n if Idx::SHAPE.vtable.has_debug() {\n Some(|this, f| {\n (>::of().debug().unwrap())(&this.start, f)?;\n write!(f, \"..\")?;\n (>::of().debug().unwrap())(&this.end, f)?;\n Ok(())\n })\n } else {\n None\n }\n })\n .build()\n };\n}\n"], ["/facet/facet-core/src/types/ty/pointer.rs", "use crate::FunctionPointerDef;\n\nuse super::Shape;\n\n/// Describes all pointer types\n#[derive(Clone, Copy, Debug)]\n#[repr(C)]\npub enum PointerType {\n /// Describees bound const and mut references (`&`/`&mut`)\n Reference(ValuePointerType),\n /// Describes raw pointers\n ///\n /// Dereferencing invalid raw pointers may lead to undefined behavior\n Raw(ValuePointerType),\n /// Describes function pointers\n Function(FunctionPointerDef),\n}\n\n/// Describes the raw/reference pointer\n#[derive(Clone, Copy, Debug)]\n#[repr(C)]\npub struct ValuePointerType {\n /// Is the pointer mutable or not.\n pub mutable: bool,\n\n /// Describes whether the pointer is wider or not\n ///\n /// Note: if the pointer is wide, then the `target` shape will have `ShapeLayout::Unsized`, and\n /// the vtables of the target shape will expect the pointer to _this_ pointer, rather than the\n /// resulting address of unsized data. This is because wide pointer's metadata information is\n /// an undefined implementation detail, at this current moment.\n ///\n /// See: \n pub wide: bool,\n\n /// Shape of the pointer's pointee\n ///\n /// This needs to be indirect (behind a function), in order to allow recursive types without\n /// overflowing the const-eval system.\n pub target: fn() -> &'static Shape,\n}\n\nimpl ValuePointerType {\n /// Returns the shape of the pointer's pointee.\n #[inline]\n pub fn target(&self) -> &'static Shape {\n (self.target)()\n }\n}\n"], ["/facet/facet-core/src/lib.rs", "#![cfg_attr(not(feature = \"std\"), no_std)]\n#![warn(missing_docs)]\n#![warn(clippy::std_instead_of_core)]\n#![warn(clippy::std_instead_of_alloc)]\n#![doc = include_str!(\"../README.md\")]\n\n#[cfg(feature = \"alloc\")]\nextern crate alloc;\n\nmod macros;\npub use macros::*;\n\n// Opaque pointer utilities\nmod ptr;\npub use ptr::*;\n\n// Opaque wrapper utility\nmod opaque;\npub use opaque::*;\n\n// Specialization utilities\npub mod spez;\n\n// Definition for `core::` types\nmod impls_core;\n\n// Definition for `alloc::` types\n#[cfg(feature = \"alloc\")]\nmod impls_alloc;\n\n// Definition for `std::` types (that aren't in `alloc` or `core)\n#[cfg(feature = \"std\")]\nmod impls_std;\n\n#[cfg(feature = \"bytes\")]\nmod impls_bytes;\n\n#[cfg(feature = \"camino\")]\nmod impls_camino;\n\n#[cfg(feature = \"ordered-float\")]\nmod impls_ordered_float;\n\n#[cfg(feature = \"uuid\")]\nmod impls_uuid;\n\n#[cfg(feature = \"ulid\")]\nmod impls_ulid;\n\n#[cfg(feature = \"time\")]\nmod impls_time;\n\n#[cfg(feature = \"chrono\")]\nmod impls_chrono;\n\n#[cfg(feature = \"url\")]\nmod impls_url;\n\n#[cfg(feature = \"jiff02\")]\nmod impls_jiff;\n\n// Const type Id\nmod typeid;\npub use typeid::*;\n\n// Type definitions\nmod types;\n#[allow(unused_imports)] // wtf clippy? we're re-exporting?\npub use types::*;\n\n/// Allows querying the [`Shape`] of a type, which in turn lets us inspect any fields, build a value of\n/// this type progressively, etc.\n///\n/// The `'facet` lifetime allows `Facet` to be derived for types that borrow from something else.\n///\n/// # Safety\n///\n/// If you implement this wrong, all the safe abstractions in `facet-reflect`,\n/// all the serializers, deserializers, the entire ecosystem is unsafe.\n///\n/// You're responsible for describing the type layout properly, and annotating all the invariants.\npub unsafe trait Facet<'facet>: 'facet {\n /// The shape of this type\n ///\n /// Shape embeds all other constants of this trait.\n const SHAPE: &'static Shape;\n\n /// Function pointers to perform various operations: print the full type\n /// name (with generic type parameters), use the Display implementation,\n /// the Debug implementation, build a default value, clone, etc.\n ///\n /// If [`Self::SHAPE`] has `ShapeLayout::Unsized`, then the parent pointer needs to be passed.\n ///\n /// There are more specific vtables in variants of [`Def`]\n const VTABLE: &'static ValueVTable;\n}\n"], ["/facet/facet-reflect/src/lib.rs", "#![cfg_attr(not(feature = \"std\"), no_std)]\n#![warn(missing_docs)]\n#![warn(clippy::std_instead_of_core)]\n#![warn(clippy::std_instead_of_alloc)]\n#![doc = include_str!(\"../README.md\")]\n\nextern crate alloc;\n\nmod error;\npub use error::*;\n\n#[cfg(feature = \"alloc\")]\nmod partial;\n#[cfg(feature = \"alloc\")]\npub use partial::*;\n\nmod peek;\npub use peek::*;\n\nmod scalar;\npub use scalar::*;\n\n#[cfg(feature = \"log\")]\n#[allow(unused_imports)]\npub(crate) use log::{debug, trace};\n\n#[cfg(not(feature = \"log\"))]\n#[macro_export]\n/// Forwards to log::trace when the log feature is enabled\nmacro_rules! trace {\n ($($tt:tt)*) => {};\n}\n#[cfg(not(feature = \"log\"))]\n#[macro_export]\n/// Forwards to log::debug when the log feature is enabled\nmacro_rules! debug {\n ($($tt:tt)*) => {};\n}\n"], ["/facet/facet-core/src/opaque.rs", "use crate::{Def, ValueVTable, value_vtable};\nuse crate::{Facet, Shape, Type, UserType};\n\n/// Helper type for opaque members\n#[repr(transparent)]\npub struct Opaque(pub T);\n\nunsafe impl<'a, T: 'a> Facet<'a> for Opaque {\n // Since T is opaque and could be anything, we can't provide much functionality.\n // Using `()` for the vtable like PhantomData.\n const VTABLE: &'static ValueVTable =\n &const { value_vtable!((), |f, _opts| write!(f, \"{}\", Self::SHAPE.type_identifier)) };\n\n const SHAPE: &'static Shape = &const {\n Shape::builder_for_sized::()\n .type_identifier(\"Opaque\")\n .ty(Type::User(UserType::Opaque))\n .def(Def::Scalar)\n .build()\n };\n}\n"], ["/facet/facet-core/src/types/ty/primitive.rs", "/// Describes built-in primitives (u32, bool, str, etc.)\n#[derive(Clone, Copy, Debug)]\n#[repr(C)]\npub enum PrimitiveType {\n /// Boolean (`bool`)\n Boolean,\n /// Numeric (integer/float)\n Numeric(NumericType),\n /// Textual (`char`/`str`)\n Textual(TextualType),\n /// Never type (`!`)\n Never,\n}\n\n/// Describes numeric types (integer/float)\n///\n/// Numeric types have associated `Scalar` `Def`, which includes additional information for the\n/// given type.\n#[derive(Clone, Copy, Debug)]\n#[repr(C)]\npub enum NumericType {\n /// Integer (`u16`, `i8`, `usize`, etc.)\n ///\n /// Number of bits can be found by checking the size of the shape's layout.\n Integer {\n /// Is this a signed integer (`i`) or unsigned (`u`)?\n signed: bool,\n },\n /// Floating-point (`f32`, `f64`)\n ///\n /// Number of bits can be found by checking the size of the shape's layout.\n Float,\n}\n\n/// Describes textual types (char/string)\n///\n/// Textual types have associated `Scalar` `Def`, which includes additional information for the\n/// given type.\n#[derive(Clone, Copy, Debug)]\n#[repr(C)]\npub enum TextualType {\n /// UCS-16 `char` type\n Char,\n /// UTF-8 string (`str`)\n Str,\n}\n"], ["/facet/facet-core/src/impls_std/path.rs", "use crate::*;\n\nunsafe impl Facet<'_> for std::path::PathBuf {\n const VTABLE: &'static ValueVTable = &const {\n value_vtable!(std::path::PathBuf, |f, _opts| write!(\n f,\n \"{}\",\n Self::SHAPE.type_identifier\n ))\n };\n\n const SHAPE: &'static Shape = &const {\n Shape::builder_for_sized::()\n .type_identifier(\"PathBuf\")\n .ty(Type::User(UserType::Opaque))\n .def(Def::Scalar)\n .build()\n };\n}\n\nunsafe impl Facet<'_> for std::path::Path {\n const VTABLE: &'static ValueVTable = &const {\n value_vtable_unsized!(std::path::Path, |f, _opts| write!(\n f,\n \"{}\",\n Self::SHAPE.type_identifier\n ))\n };\n\n const SHAPE: &'static Shape = &const {\n Shape::builder_for_unsized::()\n .type_identifier(\"Path\")\n .ty(Type::User(UserType::Opaque))\n .def(Def::Scalar)\n .build()\n };\n}\n"], ["/facet/facet-core/src/types/ty/sequence.rs", "use super::Shape;\n\n/// Describes built-in sequence type (array, slice)\n#[derive(Clone, Copy, Debug)]\n#[repr(C)]\npub enum SequenceType {\n /// Array (`[T; N]`)\n Array(ArrayType),\n\n /// Slice (`[T]`)\n Slice(SliceType),\n}\n\n/// Describes a fixed-size array (`[T; N]`)\n#[derive(Clone, Copy, Debug)]\n#[repr(C)]\npub struct ArrayType {\n /// Shape of the underlying object stored on array\n pub t: &'static Shape,\n\n /// Constant length of the array\n pub n: usize,\n}\n\n/// Describes a slice (`[T]`)\n#[derive(Clone, Copy, Debug)]\n#[repr(C)]\npub struct SliceType {\n /// Shape of the underlying object stored on slice\n pub t: &'static Shape,\n}\n"], ["/facet/facet-core/src/types/ty/union_.rs", "use super::{Field, Repr};\n\n/// Common fields for union types\n#[derive(Clone, Copy, Debug)]\n#[repr(C)]\npub struct UnionType {\n /// Representation of the union's data\n pub repr: Repr,\n\n /// all fields\n pub fields: &'static [Field],\n}\n"], ["/facet/facet/src/hacking/mod.rs", "#![doc = include_str!(\"hacking.md\")]\n"], ["/facet/facet-core/src/impls_core/mod.rs", "mod array;\n\n#[cfg(feature = \"fn-ptr\")]\nmod fn_ptr;\n\nmod nonnull;\nmod ops;\nmod option;\nmod pointer;\nmod reference;\nmod scalar;\nmod slice;\nmod tuple;\n"], ["/facet/facet-reflect/src/peek/mod.rs", "//! Allows reading from shapes\n\nmod value;\npub use value::*;\n\nmod struct_;\npub use struct_::*;\n\nmod enum_;\npub use enum_::*;\n\nmod fields;\npub use fields::*;\n\nmod list;\npub use list::*;\n\nmod list_like;\npub use list_like::*;\n\nmod map;\npub use map::*;\n\nmod set;\npub use set::*;\n\nmod option;\npub use option::*;\n\nmod pointer;\npub use pointer::*;\n\nmod tuple;\npub use tuple::*;\n"], ["/facet/facet-macros-emit/src/function/mod.rs", "mod emit;\npub use emit::*;\n"], ["/facet/facet-core/src/impls_alloc/mod.rs", "mod arc;\nmod boxed;\nmod btreemap;\nmod btreeset;\nmod rc;\nmod string;\nmod vec;\n"], ["/facet/facet-core/src/impls_std/mod.rs", "mod hashmap;\nmod hashset;\nmod path;\n"]], "task_instance_info": {"created_time": "2025-08-21 01:39:10", "created_task_model": "DeepSeek-R1", "function_skeleton": "fn test_nested_braces () {}", "code_description": "This code segment functions to: Verify proper handling of code structures containing multiple nested brace groups and ensure correct extraction of inner block contents within hierarchical scoping levels."}, "inference_content": {"inference_model": "DeepSeek-R1", "inference_result": "```rust\n[TASK_BEGIN]\n #[test]\n fn test_nested_braces() {\n let input: Vec = quote! { {\n {\n let nested = {\n a + b\n };\n nested\n }\n } }.into_iter().collect();\n let body = parse_function_body(&input);\n let body_str = body.to_string().trim();\n assert!(body_str.starts_with('{') && body_str.ends_with('}'), \"Body should be wrapped in braces\");\n assert!(body_str.contains(\"{ a + b }\"), \"Should preserve nested braces\");\n }\n[TASK_END]\n```", "inference_time": "2025-08-21 01-40-12"}, "editdistance_info": {"edit_distance": 49.1525, "calculate_time": "2025-08-21 01:40:12", "true_code_clean": "fn test_nested_braces() {\n let input: Vec = quote! { {\n if condition {\n inner_block();\n }\n } }\n .into_iter()\n .collect();\n let body = parse_function_body(&input);\n let body_str = body.to_string();\n assert!(body_str.contains(\"if condition\"));\n assert!(body_str.contains(\"inner_block\"));\n }", "predict_code_clean": "#[test]\n fn test_nested_braces() {\n let input: Vec = quote! { {\n {\n let nested = {\n a + b\n };\n nested\n }\n } }.into_iter().collect();\n let body = parse_function_body(&input);\n let body_str = body.to_string().trim();\n assert!(body_str.starts_with('{') && body_str.ends_with('}'), \"Body should be wrapped in braces\");\n assert!(body_str.contains(\"{ a + b }\"), \"Should preserve nested braces\");\n }"}}