Skip to main content

ProtoString

Trait ProtoString 

Source
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-written Debug impl on message structs, and for clear() (which resets the field to Default rather than relying on a String-specific clear, since a substituted type may be immutable).
  • Send + Sync — so a message owning such a field stays Send + Sync; without this bound an exotic string type could silently make every containing message thread-unsafe.
  • Deref<Target = str> and AsRef<str> — generated code borrows the field as &str by plain reference coercion (&self.field where encode_string / string_encoded_len expect &str), so the representation must Deref to str; 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 uses decode_length_delimited, whose default calls from_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:

  • Default is the empty string — generated clear() resets to Default::default() and implicit-presence encoding skips empty values, so a non-empty Default silently drops or corrupts cleared fields.
  • Deref, AsRef, and the constructors observe the same content — encoding borrows via Deref / AsRef and the view / reflect paths read the same way; if they disagree, a value encodes differently than it reads back.
  • from_wire and any decode_length_delimited override are value-equivalent to From<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 to From::from(s.to_owned()) — an override exists only to skip the intermediate String, 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 repeated element or map slot needs codegen-emitted ReflectElement / ReflectMapKey impls (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 serde outside non-optional singular fields. A custom string in an optional, repeated, map, or oneof field uses its own serde, so it must implement Serialize / Deserialize (and, for an external type, enable its serde feature). Non-optional singular custom strings use the proto_string with-module and need no serde impl.
  • A map key needs Hash + Eq (default / HashMap container) or Ord (map_type(BTreeMap)); the bound is enforced at the generated field type.
  • No Arbitrary impl required. Under generate_arbitrary, codegen attaches a generic builder to a custom string field, and to a map field with a custom string key or value.

Required Methods§

Source

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§

Source

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.

Source

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".

Implementations on Foreign Types§

Source§

impl ProtoString for String

Source§

fn from_wire(payload: WirePayload<'_>) -> Result<Self, DecodeError>

Implementors§