pub enum WireId<'a> {
Number(i64),
Text(Cow<'a, str>),
}Expand description
A JSON-RPC id as it appears on the wire, borrowed from the frame buffer.
A number is copied out — it is a Copy i64, so that arm never allocates.
A string is a Cow: borrowed straight out of the buffer when it has no
escape, and owned only when it does.
§Why a Cow and not a &str
serde_json will not hand back a borrowed &str for a string containing an
escape — "a\"b" has to be unescaped, and unescaping means allocating, so
the parse fails rather than lie about the borrow. An id containing an escape
is perfectly legal JSON and a peer can send one, so a bare &'a str here
would reject a request that must be answered.
The price is that WireId is no longer Copy, which propagates to
Envelope and Routed. That is the right trade: a Copy derive on a type
that cannot represent a valid id is not a saving, it is a bug waiting to
compile. The common case — an unescaped uuid or a small integer — still
allocates nothing.
§The lossy-looking to_json
to_json re-escapes rather than splicing the original raw
text, so a string id that was sent escaped comes back escaped in the same
way. That is what makes the response’s id parse to the value the peer sent.
Variants§
Number(i64)
A numeric id.
Text(Cow<'a, str>)
A string id, borrowed from the buffer unless it needed unescaping.
Implementations§
Source§impl<'a> WireId<'a>
impl<'a> WireId<'a>
Sourcepub fn to_owned(&self) -> WireId<'static>
pub fn to_owned(&self) -> WireId<'static>
This id, owned.
A handler can outlive the frame it was invoked for — a tool that asks its peer a question keeps running while the request that called it is being answered — so an id borrowed from a request body has to become an owned one before it crosses into anything longer-lived than that body.
Sourcepub fn from_raw(value: &'a RawValue) -> Result<Self, WireIdError>
pub fn from_raw(value: &'a RawValue) -> Result<Self, WireIdError>
Parses an id from its raw JSON, borrowed.
The spec allows a number or a string and nothing else, so null,
true, an array, and a fractional number are all rejected. A
fractional number is rejected rather than truncated: 1.5 is not id
1, and quietly rounding it would make two different ids collide.
§Errors
WireIdError::NotAnId if the value is not a number or a string.
WireIdError::NotAnInteger if the number has a fractional part.
Sourcepub const fn text(value: &'a str) -> Self
pub const fn text(value: &'a str) -> Self
A borrowed string id.
Does not allocate. The type is a Cow only because an id containing a
JSON escape cannot be borrowed out of the buffer; a caller that already
holds a &str never pays for that.