pub trait ProtoString:
Clone
+ PartialEq
+ Default
+ Debug
+ Send
+ Sync
+ Deref<Target = str>
+ AsRef<str>
+ From<String> {
// Required method
fn from_wire(payload: WirePayload<'_>) -> Result<Self, DecodeError>;
// Provided methods
fn copy_from_str(value: &str) -> Self { ... }
fn decode_length_delimited(
payload: &mut FieldPayload<impl Buf>,
) -> Result<Self, DecodeError> { ... }
}Expand description
The bound generated code places on the Rust type used for a proto string
field.
buffa implements it for the default String. Select another representation
with buffa_build’s string_type / string_type_custom. There is
intentionally no blanket impl, and a foreign type cannot implement this
trait (orphan rule) — wrap it in a local newtype that implements the trait;
see examples/custom-types in the buffa repository for the canonical
template (and buffa-smolstr in the same repository for a self-contained
smol_str newtype).
The bounds are exactly what generated code requires of a string field:
from_wire(the required method, below) — the binary decode constructor.Clone + PartialEq + Default + Debug— for the#[derive(...)]and the hand-writtenDebugimpl on message structs, and forclear()(which resets the field toDefaultrather than relying on aString-specificclear, since a substituted type may be immutable).Send + Sync— so a message owning such a field staysSend + Sync; without this bound an exotic string type could silently make every containing message thread-unsafe.Deref<Target = str>andAsRef<str>— generated code borrows the field as&strby plain reference coercion (&self.fieldwhereencode_string/string_encoded_lenexpect&str), so the representation mustDereftostr;AsRef<str>is also required for the call sites that ask for it explicitly.From<String>— constructs fields from owned JSON strings, text-format parsing, and proto2 defaults.copy_from_str— copies borrowed JSON strings in non-optional singular fields, and the text of string view fields of custom representations, into owned storage. Binary decoding usesdecode_length_delimited, whose default callsfrom_wire.
For the default String representation every conversion is the identity, so
the generic path costs nothing relative to the specialized one.
§Contract
The bounds are structural and cannot capture these invariants; an implementation must uphold them:
Defaultis the empty string — generatedclear()resets toDefault::default()and implicit-presence encoding skips empty values, so a non-emptyDefaultsilently drops or corrupts cleared fields.Deref,AsRef, and the constructors observe the same content — encoding borrows viaDeref/AsRefand the view / reflect paths read the same way; if they disagree, a value encodes differently than it reads back.from_wireand anydecode_length_delimitedoverride are value-equivalent toFrom<String>/copy_from_str— binary decode uses them while JSON / text / view→owned use the other constructors, so a representation must not transform the text (e.g. case-fold) in one path but not the other.copy_from_str(s)is value-equivalent toFrom::from(s.to_owned())— an override exists only to skip the intermediateString, so it must not change the resulting value.
§Limitations
The requirements below depend on where the custom string appears. See the user guide’s “String and bytes field representations” section for the full table.
- Must be crate-local. A custom type in a
repeatedelement ormapslot needs codegen-emittedReflectElement/ReflectMapKeyimpls (for vtable reflection), which the orphan rule permits only when the type is local to the generating crate. A foreign custom type in those positions fails to compile — wrap it in a crate-local newtype. - JSON needs native
serdeoutside non-optional singular fields. A custom string in an optional, repeated, map, or oneof field uses its ownserde, so it must implementSerialize/Deserialize(and, for an external type, enable itsserdefeature). Non-optional singular custom strings use theproto_stringwith-module and need noserdeimpl. - A
mapkey needsHash + Eq(default /HashMapcontainer) orOrd(map_type(BTreeMap)); the bound is enforced at the generated field type. - No
Arbitraryimpl required. Undergenerate_arbitrary, codegen attaches a generic builder to a custom string field, and to amapfield with a custom string key or value.
Required Methods§
Sourcefn from_wire(payload: WirePayload<'_>) -> Result<Self, DecodeError>
fn from_wire(payload: WirePayload<'_>) -> Result<Self, DecodeError>
Construct the representation from a decoded string field’s wire payload.
This is the decode constructor: it owns the validation/ownership choice,
so a representation can borrow-and-inline a short string (no transient
heap allocation) or validate UTF-8 only when it must. Validate-and-borrow
with WirePayload::to_str (which uses buffa’s UTF-8 validator and so
picks up the fast-utf8 feature), or read raw bytes with
WirePayload::as_slice. There is
intentionally no blanket impl — every representation provides its own
optimal from_wire; From<String> and Self::copy_from_str remain
for ordinary JSON, text, and view→owned paths. Selected JSON policies
call their policy deserializer, and guarded arbitrary construction calls
from_wire directly with borrowed input. Binary decode calls from_wire
through the default
decode_length_delimited; a type that
overrides that method still provides from_wire for direct callers.
§Errors
Returns DecodeError::InvalidUtf8 if the payload is not valid UTF-8. A
representation that enforces additional invariants can reject the value
with DecodeError::Custom (carrying a static reason), or return any
other DecodeError variant.
Provided Methods§
Sourcefn copy_from_str(value: &str) -> Self
fn copy_from_str(value: &str) -> Self
Copy text into storage that does not borrow from value.
The default constructs a String and passes it to From<String>.
Unlike From<&str>, this method does not tie the result’s lifetime to
the input, so a type can retain a separate borrowing From<&str>
implementation.
Override it if the type stores short strings inline or shares them. The
default cannot call From<&str>, so a type with a cheaper
borrowed-text constructor that does not override this method pays the
intermediate String allocation wherever generated code copies borrowed
text: view-to-owned conversion of singular, optional, repeated, map and
oneof string fields, and JSON deserialization of non-optional singular
fields. The values are unchanged; only the cost differs.
#[derive(buffa_remote_derive::ProtoString)] forwards this method to
the remote type’s From<&str>, so derived types are already covered.
Sourcefn decode_length_delimited(
payload: &mut FieldPayload<impl Buf>,
) -> Result<Self, DecodeError>
fn decode_length_delimited( payload: &mut FieldPayload<impl Buf>, ) -> Result<Self, DecodeError>
Decode one field payload, given exactly the bytes of that field.
Generated code and decode_string_to call this after reading the field’s length
prefix and checking it against the input, so payload holds exactly
that field and payload.remaining() is its validated length. The
default passes a WirePayload to Self::from_wire.
Override it when the representation must also control temporary
allocations, for example to copy a fragmented field straight into
storage that is wiped on drop rather than through an intermediate
Bytes.
An override must accept and reject exactly the payloads that
from_wire does, including rejecting invalid UTF-8, and produce an equal value. Bytes it leaves
unread are skipped. The opaque FieldPayload exposes only bounded
Buf operations; its limit and underlying buffer cannot be accessed.
§Errors
Returns the representation’s error for a rejected payload. On error the input position is unspecified: a decode error aborts the whole decode.
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety".