rpc-io 0.4.0

JSON-RPC 2.0 engine for LSP, MCP, and service APIs: Content-Length and newline framings, a sans-IO core, blocking and async adapters, bounded non-blocking output, and hostile-input hardening.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
//! [`Raw`]: validated JSON kept as text, and [`Json`]: a value to send, built
//! or raw.

use alloc::{borrow::Cow, string::String};
use core::{
    fmt,
    hash::{Hash, Hasher},
};

use jsonx_lib::{DuplicateKeys, Kind, Parser, RawValue, Value};

/// One JSON value kept as its exact, validated source text.
///
/// This is how `params` and `result` travel through the crate without being
/// decoded: an incoming message is validated once and its `params` handed to
/// the handler as a slice of the message (`Raw<'a>` borrows), to be parsed
/// only if and when the handler wants it. In the other direction, a `Raw`
/// passes pre-serialized JSON through unchanged, so forwarding a value costs a
/// copy, not a parse and a re-serialization.
///
/// A `Raw` always holds exactly one complete JSON value with no surrounding
/// whitespace: the constructors validate, and the crate builds them only from
/// text it has validated.
///
/// # Examples
///
/// ```
/// use rpc_io::Raw;
///
/// let raw = Raw::new(r#" {"line": 3} "#)?;
/// assert_eq!(raw.as_str(), r#"{"line": 3}"#);
/// assert_eq!(raw.parse()?["line"], 3);
/// assert!(Raw::new("{").is_err());
/// # Ok::<(), rpc_io::jsonx::Error>(())
/// ```
///
/// Raws compare and hash by their text.
#[derive(Clone)]
pub struct Raw<'a>(Repr<'a>);

/// How a [`Raw`] holds its text.
#[derive(Clone)]
enum Repr<'a> {
    /// Validated by jsonx-lib, in a read or by its writer: written into a
    /// `ToJson` value as it is, with no second scan.
    Checked(RawValue<'a>),
    /// Text the crate validated or wrote itself, outside a `RawValue`
    /// (message buffers, `serde` output): written into a `ToJson` value after
    /// a validation pass, since jsonx-lib's writer takes raw text only as a
    /// `RawValue`.
    Text(Cow<'a, str>),
}

impl<'a> Raw<'a> {
    /// `null`.
    pub const NULL: Raw<'static> = Raw(Repr::Text(Cow::Borrowed("null")));

    /// Validates `text` as one JSON value (the default `jsonx_lib` budgets)
    /// and keeps it, minus surrounding whitespace, as a borrowed slice.
    ///
    /// # Errors
    ///
    /// The `jsonx_lib::Error` for text that is not exactly one JSON value.
    ///
    /// # Examples
    ///
    /// ```
    /// let raw = rpc_io::Raw::new("[1, 2]")?;
    /// assert_eq!(raw.as_str(), "[1, 2]");
    /// # Ok::<(), rpc_io::jsonx::Error>(())
    /// ```
    pub fn new(text: &'a str) -> Result<Self, jsonx_lib::Error> {
        Self::new_with(text, &Parser::new())
    }

    /// As [`new`](Raw::new), with `parser`'s budgets.
    ///
    /// # Errors
    ///
    /// The `jsonx_lib::Error` for text that is not exactly one JSON value
    /// within `parser`'s limits.
    ///
    /// # Examples
    ///
    /// ```
    /// use rpc_io::jsonx::{Limits, Parser};
    ///
    /// let shallow = Parser::new().limits(Limits::new().with_max_depth(1));
    /// assert!(rpc_io::Raw::new_with("[1]", &shallow).is_ok());
    /// assert!(rpc_io::Raw::new_with("[[1]]", &shallow).is_err());
    /// ```
    pub fn new_with(text: &'a str, parser: &Parser) -> Result<Self, jsonx_lib::Error> {
        // Syntax and budgets only: whether a repeated key is acceptable is
        // for whoever parses the value (`parse_with`'s policy).
        let mut reader = parser.duplicate_keys(DuplicateKeys::KeepAll).reader(text);
        match reader.read_raw_value()? {
            Some(value) => {
                reader.finish()?;
                Ok(Raw(Repr::Checked(value)))
            }
            // `read_raw_value` finds no value only in input that holds none,
            // which the parser refuses with the precise error.
            None => parser.parse(text).map(|_| Raw::trusted(text.trim())),
        }
    }

    /// Validates an owned string as one JSON value, as [`new`](Raw::new).
    ///
    /// # Errors
    ///
    /// The `jsonx_lib::Error` for text that is not exactly one JSON value.
    ///
    /// # Examples
    ///
    /// ```
    /// let raw = rpc_io::Raw::from_string(String::from("true"))?;
    /// assert_eq!(raw.as_str(), "true");
    /// # Ok::<(), rpc_io::jsonx::Error>(())
    /// ```
    pub fn from_string(text: String) -> Result<Raw<'static>, jsonx_lib::Error> {
        let value = Raw::new(&text)?;
        if value.as_str().len() == text.len() {
            // Validated just now: kept without a copy.
            Ok(Raw::trusted_owned(text))
        } else {
            Ok(value.into_owned())
        }
    }

    /// Serializes `value` (compact JSON).
    ///
    /// # Examples
    ///
    /// ```
    /// use rpc_io::jsonx::json;
    ///
    /// let raw = rpc_io::Raw::from_value(&json!({ "ok": true }));
    /// assert_eq!(raw.as_str(), r#"{"ok":true}"#);
    /// ```
    #[must_use]
    pub fn from_value(value: &Value<'_>) -> Raw<'static> {
        Raw(Repr::Checked(RawValue::encode(value)))
    }

    /// Wraps text the crate has already validated as one JSON value.
    #[inline]
    pub(crate) const fn trusted(text: &'a str) -> Self {
        Raw(Repr::Text(Cow::Borrowed(text)))
    }

    /// Wraps an owned string the crate wrote itself as one JSON value.
    #[inline]
    pub(crate) const fn trusted_owned(text: String) -> Raw<'static> {
        Raw(Repr::Text(Cow::Owned(text)))
    }

    /// Wraps a value jsonx-lib validated.
    #[inline]
    pub(crate) const fn checked(value: RawValue<'a>) -> Self {
        Raw(Repr::Checked(value))
    }

    /// The `RawValue`, when the text is held as one.
    #[inline]
    pub(crate) fn raw_value(&self) -> Option<&RawValue<'a>> {
        match &self.0 {
            Repr::Checked(value) => Some(value),
            Repr::Text(_) => None,
        }
    }

    /// The JSON text.
    ///
    /// # Examples
    ///
    /// ```
    /// assert_eq!(rpc_io::Raw::NULL.as_str(), "null");
    /// ```
    #[inline]
    #[must_use]
    pub fn as_str(&self) -> &str {
        match &self.0 {
            Repr::Checked(value) => value.as_str(),
            Repr::Text(text) => text,
        }
    }

    /// The kind of value, read from its first byte without parsing.
    ///
    /// # Examples
    ///
    /// ```
    /// use rpc_io::jsonx::Kind;
    ///
    /// assert_eq!(rpc_io::Raw::new("[]")?.kind(), Kind::Array);
    /// assert_eq!(rpc_io::Raw::new("-1.5")?.kind(), Kind::Number);
    /// # Ok::<(), rpc_io::jsonx::Error>(())
    /// ```
    #[must_use]
    pub fn kind(&self) -> Kind {
        kind_of(self.as_str())
    }

    /// Parses the text into a [`Value`] that borrows from it, with the default
    /// `jsonx_lib` budgets and duplicate keys refused.
    ///
    /// # Errors
    ///
    /// The `jsonx_lib::Error` for a value over the default budgets (the text
    /// itself is always valid JSON), or with a duplicate key.
    ///
    /// # Examples
    ///
    /// ```
    /// let raw = rpc_io::Raw::new(r#"{"a": [1, "two"]}"#)?;
    /// assert_eq!(raw.parse()?["a"][1], "two");
    /// # Ok::<(), rpc_io::jsonx::Error>(())
    /// ```
    pub fn parse(&self) -> Result<Value<'_>, jsonx_lib::Error> {
        self.parse_with(&Parser::new())
    }

    /// Parses the text with `parser`'s budgets and duplicate-key policy.
    ///
    /// # Errors
    ///
    /// The `jsonx_lib::Error` for a value over `parser`'s budgets, or that its
    /// duplicate-key policy refuses.
    ///
    /// # Examples
    ///
    /// ```
    /// use rpc_io::jsonx::{DuplicateKeys, Parser};
    ///
    /// let raw = rpc_io::Raw::new(r#"{"a": 1, "a": 2}"#)?;
    /// assert!(raw.parse().is_err());
    /// let last = Parser::new().duplicate_keys(DuplicateKeys::Last);
    /// assert_eq!(raw.parse_with(&last)?["a"], 2);
    /// # Ok::<(), rpc_io::jsonx::Error>(())
    /// ```
    pub fn parse_with(&self, parser: &Parser) -> Result<Value<'_>, jsonx_lib::Error> {
        parser.parse(self.as_str())
    }

    /// Copies borrowed text so the value can outlive its message.
    ///
    /// # Examples
    ///
    /// ```
    /// let text = String::from("[1]");
    /// let raw: rpc_io::Raw<'static> = rpc_io::Raw::new(&text)?.into_owned();
    /// drop(text);
    /// assert_eq!(raw.as_str(), "[1]");
    /// # Ok::<(), rpc_io::jsonx::Error>(())
    /// ```
    #[must_use]
    pub fn into_owned(self) -> Raw<'static> {
        Raw(match self.0 {
            Repr::Checked(value) => Repr::Checked(value.into_owned()),
            Repr::Text(text) => Repr::Text(Cow::Owned(text.into_owned())),
        })
    }

    /// A borrowed view of this value's text, for writing it.
    #[inline]
    pub(crate) fn reborrow(&self) -> Raw<'_> {
        Raw::trusted(self.as_str())
    }
}

impl PartialEq for Raw<'_> {
    fn eq(&self, other: &Self) -> bool {
        self.as_str() == other.as_str()
    }
}

impl Eq for Raw<'_> {}

impl Hash for Raw<'_> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.as_str().hash(state);
    }
}

/// The kind of the JSON value whose text starts `text`.
pub(crate) fn kind_of(text: &str) -> Kind {
    match text.as_bytes().first() {
        Some(b'{') => Kind::Object,
        Some(b'[') => Kind::Array,
        Some(b'"') => Kind::String,
        Some(b't' | b'f') => Kind::Bool,
        Some(b'n') => Kind::Null,
        _ => Kind::Number,
    }
}

impl fmt::Display for Raw<'_> {
    /// Writes the JSON text.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl fmt::Debug for Raw<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// A JSON value to send: built as a [`Value`], or already serialized as a
/// [`Raw`].
///
/// Everything that sends JSON (params of requests and notifications, results,
/// error data) takes `impl Into<Json>`, so a `Value` from
/// [`json!`](jsonx_lib::json), anything that converts into a `Value` (numbers,
/// strings, booleans, `()` for `null`), or a `Raw` can be passed directly.
///
/// # Examples
///
/// ```
/// use rpc_io::jsonx::json;
/// use rpc_io::{Json, Raw};
///
/// assert_eq!(Json::from(json!([1, 2])).to_string(), "[1,2]");
/// assert_eq!(Json::from(42).to_string(), "42");
/// assert_eq!(Json::from(()).to_string(), "null");
/// assert_eq!(Json::from(Raw::new(r#"{"a": 1}"#)?).to_string(), r#"{"a": 1}"#);
/// # Ok::<(), rpc_io::jsonx::Error>(())
/// ```
#[derive(Clone, PartialEq)]
pub enum Json<'a> {
    /// A value, serialized when it is sent.
    Value(Value<'a>),
    /// Text sent as it is.
    Raw(Raw<'a>),
}

impl Json<'_> {
    /// The kind of value.
    ///
    /// # Examples
    ///
    /// ```
    /// use rpc_io::jsonx::Kind;
    ///
    /// assert_eq!(rpc_io::Json::from(true).kind(), Kind::Bool);
    /// ```
    #[must_use]
    pub fn kind(&self) -> Kind {
        match self {
            Json::Value(value) => value.kind(),
            Json::Raw(raw) => raw.kind(),
        }
    }

    /// Copies everything borrowed.
    ///
    /// # Examples
    ///
    /// ```
    /// let text = String::from("a");
    /// let owned: rpc_io::Json<'static> = rpc_io::Json::from(text.as_str()).into_owned();
    /// drop(text);
    /// assert_eq!(owned.to_string(), r#""a""#);
    /// ```
    #[must_use]
    pub fn into_owned(self) -> Json<'static> {
        match self {
            Json::Value(value) => Json::Value(value.into_owned()),
            Json::Raw(raw) => Json::Raw(raw.into_owned()),
        }
    }

    /// Appends the value as compact JSON (raw text as it is).
    pub(crate) fn write(&self, out: &mut String) {
        match self {
            Json::Value(value) => jsonx_lib::write_value(out, value),
            Json::Raw(raw) => out.push_str(raw.as_str()),
        }
    }

    /// The value as a `Raw`, serializing a built value.
    pub(crate) fn into_raw(self) -> Raw<'static> {
        match self {
            Json::Value(value) => Raw::checked(RawValue::encode(&value)),
            Json::Raw(raw) => raw.into_owned(),
        }
    }
}

impl<'a, T: Into<Value<'a>>> From<T> for Json<'a> {
    #[inline]
    fn from(value: T) -> Self {
        Json::Value(value.into())
    }
}

impl<'a> From<Raw<'a>> for Json<'a> {
    #[inline]
    fn from(raw: Raw<'a>) -> Self {
        Json::Raw(raw)
    }
}

impl fmt::Display for Json<'_> {
    /// Writes compact JSON.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Json::Value(value) => fmt::Display::fmt(value, f),
            Json::Raw(raw) => f.write_str(raw.as_str()),
        }
    }
}

impl fmt::Debug for Json<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(self, f)
    }
}

#[cfg(test)]
#[allow(clippy::panic)]
mod tests {
    use super::*;

    #[test]
    fn test_new_trims_and_validates() {
        assert_eq!(Raw::new("\t null \n").map(|r| r.kind()), Ok(Kind::Null));
        assert!(Raw::new("").is_err());
        assert!(Raw::new("   ").is_err());
        assert!(Raw::new("1 2").is_err());
        assert!(Raw::new("[1,]").is_err());
    }

    #[test]
    fn test_from_string_keeps_or_trims() {
        let kept = Raw::from_string(String::from("[1]"));
        assert_eq!(kept.as_ref().map(Raw::as_str), Ok("[1]"));
        let trimmed = Raw::from_string(String::from(" [1] "));
        assert_eq!(trimmed.as_ref().map(Raw::as_str), Ok("[1]"));
    }

    #[test]
    fn test_kind_of_every_kind() {
        for (text, kind) in [
            ("{}", Kind::Object),
            ("[]", Kind::Array),
            ("\"\"", Kind::String),
            ("true", Kind::Bool),
            ("false", Kind::Bool),
            ("null", Kind::Null),
            ("-0", Kind::Number),
        ] {
            assert_eq!(kind_of(text), kind, "{text}");
        }
    }
}