macro_rules! register_value_string_codec {
(id = $id:expr, codec = $codec:ty, value = $value:ty, input = $input:ty $(,)?) => { ... };
(id = $id:expr, codec = $codec:ty, value = $value:ty $(,)?) => { ... };
}Expand description
Registers a default-constructible bidirectional string codec.
The macro must be invoked at module scope; it defines the descriptor, a
registration function, and an inventory submission in an anonymous const.
The id must be a constant expression. Use a literal, constant, or
const fn result; a runtime function call cannot define a static ID.
The encoder and decoder error types must implement Error + Send + Sync + 'static, as required by crate::ValueStringCodecDescriptor::of.
Without input, the encoder input type is value. The optional input
form selects a borrowed view of the owned value type for encoding; the
descriptor still accepts and decodes the owned value type.
§Examples
A registry-only example with a local codec:
use core::convert::Infallible;
use qubit_codec::{ValueDecoder, ValueEncoder, ValueStringCodecRegistry};
use qubit_codec::register_value_string_codec;
#[derive(Default)]
struct TextCodec;
impl ValueEncoder<String> for TextCodec {
type Output = String;
type Error = Infallible;
fn encode(&mut self, value: &String) -> Result<String, Infallible> { Ok(value.clone()) }
}
impl ValueDecoder<str> for TextCodec {
type Output = String;
type Error = Infallible;
fn decode(&mut self, input: &str) -> Result<String, Infallible> { Ok(input.to_owned()) }
}
register_value_string_codec!(id = "example.text", codec = TextCodec, value = String);
let registry = ValueStringCodecRegistry::try_global().unwrap();
let descriptor = registry.get("example.text").unwrap().descriptor();
let encoded = descriptor.encode(&String::from("hello")).unwrap();
assert_eq!("hello", encoded);
let decoded = descriptor.decode(&encoded).unwrap();
assert_eq!("hello", *decoded.downcast::<String>().unwrap());An invalid ID fails during macro expansion:
register_value_string_codec!(id = "invalid-id", codec = TextCodec, value = String);A runtime ID cannot initialize the static registration:
fn runtime_id() -> &'static str { "example.text" }
register_value_string_codec!(id = runtime_id(), codec = TextCodec, value = String);