mysten_common/rpc_format/
format.rs

1// Copyright (c) Mysten Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4use crate::rpc_format::Meter;
5use crate::rpc_format::MeterError;
6
7/// A trait for serializing values into some nested structured representation that supports
8/// `null`, `bool`, numbers, strings, vectors, and maps (e.g. JSON or Protobuf).
9///
10/// Formats decide both the output shape and how each output operation is charged against a meter.
11pub trait Format: Sized {
12    type Vec: Default;
13    type Map: Default;
14
15    fn is_null(&self) -> bool;
16    fn is_bool(&self) -> bool;
17    fn is_number(&self) -> bool;
18    fn is_string(&self) -> bool;
19    fn is_array(&self) -> bool;
20    fn is_object(&self) -> bool;
21
22    fn as_bool(&self) -> Option<bool>;
23    fn as_string(&self) -> Option<&str>;
24    fn as_array(&self) -> Option<&Self::Vec>;
25    fn as_object(&self) -> Option<&Self::Map>;
26
27    /// Write a `null` value.
28    fn null<M: Meter>(meter: &mut M) -> Result<Self, MeterError>;
29
30    /// Write a `true` or `false` value.
31    fn bool<M: Meter>(meter: &mut M, value: bool) -> Result<Self, MeterError>;
32
33    /// Write a numeric value that fits in a `u32`.
34    fn number<M: Meter>(meter: &mut M, value: u32) -> Result<Self, MeterError>;
35
36    /// Write a string value.
37    fn string<M: Meter>(meter: &mut M, value: String) -> Result<Self, MeterError>;
38
39    /// Write a completed vector.
40    fn vec<M: Meter>(meter: &mut M, value: Self::Vec) -> Result<Self, MeterError>;
41
42    /// Write a completed key-value map.
43    fn map<M: Meter>(meter: &mut M, value: Self::Map) -> Result<Self, MeterError>;
44
45    /// Add an element to a vector.
46    fn vec_push_element<M: Meter>(
47        meter: &mut M,
48        vec: &mut Self::Vec,
49        val: Self,
50    ) -> Result<(), MeterError>;
51
52    /// Add a key-value pair to a map.
53    fn map_push_field<M: Meter>(
54        meter: &mut M,
55        map: &mut Self::Map,
56        key: String,
57        val: Self,
58    ) -> Result<(), MeterError>;
59}