Skip to main content

Json

Enum Json 

Source
pub enum Json {
    Null,
    Bool(bool),
    Int(i64),
    Float(f64),
    Str(String),
    Array(Vec<Json>),
    Object(Vec<(String, Json)>),
}
Expand description

A JSON value.

Variants§

§

Null

§

Bool(bool)

§

Int(i64)

§

Float(f64)

§

Str(String)

§

Array(Vec<Json>)

§

Object(Vec<(String, Json)>)

Implementations§

Source§

impl Json

Source

pub fn object() -> Json

An empty object.

Source

pub fn array() -> Json

An empty array.

Source

pub fn is_null(&self) -> bool

Source

pub fn as_str(&self) -> Option<&str>

Examples found in repository?
examples/example_server.rs (line 86)
56fn build() -> Server {
57    let mut s = Server::new();
58    s.set_info("rcp-example", "1.0.0");
59    s.advertise(
60        Capability::Embed,
61        obj(&[("dimensions", (DIM as i64).into()), ("modes", vec![Json::from("dense")].into())]),
62    );
63    s.advertise(
64        Capability::Retrieve,
65        obj(&[
66            ("maxK", 100.into()),
67            ("modes", vec![Json::from("dense")].into()),
68            ("citations", true.into()),
69        ]),
70    );
71    s.advertise(
72        Capability::Graph,
73        obj(&[("ops", vec![Json::from("local"), Json::from("global")].into())]),
74    );
75
76    s.on(Method::EMBED, |params| {
77        // Accept `inputs` (preferred, spec §7.3) or the legacy `texts` synonym.
78        let items = params
79            .get("inputs")
80            .or_else(|| params.get("texts"))
81            .and_then(|v| v.as_array())
82            .cloned()
83            .unwrap_or_default();
84        let vectors: Vec<Json> = items
85            .iter()
86            .filter_map(|x| x.as_str())
87            .map(|t| Json::from(embed_one(t)))
88            .collect();
89        Ok(obj(&[("vectors", Json::Array(vectors)), ("dimensions", (DIM as i64).into())]))
90    });
91
92    s.on(Method::RETRIEVE, |params| {
93        let q = params.get_str("query").unwrap_or("");
94        let k = params.get("k").and_then(|v| v.as_i64()).unwrap_or(10).max(0) as usize;
95        Ok(obj(&[("hits", search(q, k))]))
96    });
97
98    s.on(Method::GRAPH, |params| {
99        let op = params.get_str("op").unwrap_or("local");
100        match op {
101            "local" => {
102                let q = params.get_str("query").unwrap_or("");
103                let k = params.get("k").and_then(|v| v.as_i64()).unwrap_or(5).max(0) as usize;
104                Ok(obj(&[("hits", search(q, k))]))
105            }
106            "global" => Ok(obj(&[
107                ("summary", "a global community summary would go here".into()),
108                ("communities", 1.into()),
109            ])),
110            other => Ok(obj(&[("op", other.into()), ("note", "unimplemented".into())])),
111        }
112    });
113
114    s
115}
Source

pub fn as_i64(&self) -> Option<i64>

Examples found in repository?
examples/example_server.rs (line 94)
56fn build() -> Server {
57    let mut s = Server::new();
58    s.set_info("rcp-example", "1.0.0");
59    s.advertise(
60        Capability::Embed,
61        obj(&[("dimensions", (DIM as i64).into()), ("modes", vec![Json::from("dense")].into())]),
62    );
63    s.advertise(
64        Capability::Retrieve,
65        obj(&[
66            ("maxK", 100.into()),
67            ("modes", vec![Json::from("dense")].into()),
68            ("citations", true.into()),
69        ]),
70    );
71    s.advertise(
72        Capability::Graph,
73        obj(&[("ops", vec![Json::from("local"), Json::from("global")].into())]),
74    );
75
76    s.on(Method::EMBED, |params| {
77        // Accept `inputs` (preferred, spec §7.3) or the legacy `texts` synonym.
78        let items = params
79            .get("inputs")
80            .or_else(|| params.get("texts"))
81            .and_then(|v| v.as_array())
82            .cloned()
83            .unwrap_or_default();
84        let vectors: Vec<Json> = items
85            .iter()
86            .filter_map(|x| x.as_str())
87            .map(|t| Json::from(embed_one(t)))
88            .collect();
89        Ok(obj(&[("vectors", Json::Array(vectors)), ("dimensions", (DIM as i64).into())]))
90    });
91
92    s.on(Method::RETRIEVE, |params| {
93        let q = params.get_str("query").unwrap_or("");
94        let k = params.get("k").and_then(|v| v.as_i64()).unwrap_or(10).max(0) as usize;
95        Ok(obj(&[("hits", search(q, k))]))
96    });
97
98    s.on(Method::GRAPH, |params| {
99        let op = params.get_str("op").unwrap_or("local");
100        match op {
101            "local" => {
102                let q = params.get_str("query").unwrap_or("");
103                let k = params.get("k").and_then(|v| v.as_i64()).unwrap_or(5).max(0) as usize;
104                Ok(obj(&[("hits", search(q, k))]))
105            }
106            "global" => Ok(obj(&[
107                ("summary", "a global community summary would go here".into()),
108                ("communities", 1.into()),
109            ])),
110            other => Ok(obj(&[("op", other.into()), ("note", "unimplemented".into())])),
111        }
112    });
113
114    s
115}
Source

pub fn as_f64(&self) -> Option<f64>

Source

pub fn as_bool(&self) -> Option<bool>

Source

pub fn as_array(&self) -> Option<&Vec<Json>>

Examples found in repository?
examples/example_server.rs (line 81)
56fn build() -> Server {
57    let mut s = Server::new();
58    s.set_info("rcp-example", "1.0.0");
59    s.advertise(
60        Capability::Embed,
61        obj(&[("dimensions", (DIM as i64).into()), ("modes", vec![Json::from("dense")].into())]),
62    );
63    s.advertise(
64        Capability::Retrieve,
65        obj(&[
66            ("maxK", 100.into()),
67            ("modes", vec![Json::from("dense")].into()),
68            ("citations", true.into()),
69        ]),
70    );
71    s.advertise(
72        Capability::Graph,
73        obj(&[("ops", vec![Json::from("local"), Json::from("global")].into())]),
74    );
75
76    s.on(Method::EMBED, |params| {
77        // Accept `inputs` (preferred, spec §7.3) or the legacy `texts` synonym.
78        let items = params
79            .get("inputs")
80            .or_else(|| params.get("texts"))
81            .and_then(|v| v.as_array())
82            .cloned()
83            .unwrap_or_default();
84        let vectors: Vec<Json> = items
85            .iter()
86            .filter_map(|x| x.as_str())
87            .map(|t| Json::from(embed_one(t)))
88            .collect();
89        Ok(obj(&[("vectors", Json::Array(vectors)), ("dimensions", (DIM as i64).into())]))
90    });
91
92    s.on(Method::RETRIEVE, |params| {
93        let q = params.get_str("query").unwrap_or("");
94        let k = params.get("k").and_then(|v| v.as_i64()).unwrap_or(10).max(0) as usize;
95        Ok(obj(&[("hits", search(q, k))]))
96    });
97
98    s.on(Method::GRAPH, |params| {
99        let op = params.get_str("op").unwrap_or("local");
100        match op {
101            "local" => {
102                let q = params.get_str("query").unwrap_or("");
103                let k = params.get("k").and_then(|v| v.as_i64()).unwrap_or(5).max(0) as usize;
104                Ok(obj(&[("hits", search(q, k))]))
105            }
106            "global" => Ok(obj(&[
107                ("summary", "a global community summary would go here".into()),
108                ("communities", 1.into()),
109            ])),
110            other => Ok(obj(&[("op", other.into()), ("note", "unimplemented".into())])),
111        }
112    });
113
114    s
115}
Source

pub fn as_object(&self) -> Option<&Vec<(String, Json)>>

Examples found in repository?
examples/example_client.rs (line 22)
8fn main() -> Result<(), rcp::RcpError> {
9    // The example_server binary sits next to this one in target/.../examples/.
10    let exe = std::env::current_exe().expect("current exe");
11    let server = exe.parent().unwrap().join("example_server");
12    let server = server.to_string_lossy().to_string();
13
14    let mut c = rcp::connect_stdio(&[server.as_str()])?;
15
16    println!(
17        "connected to {} v{} (RCP/{})",
18        c.server().get_str("name").unwrap_or("?"),
19        c.server().get_str("version").unwrap_or("?"),
20        c.protocol_version()
21    );
22    if let Some(caps) = c.capabilities().as_object() {
23        let keys: Vec<&str> = caps.iter().map(|(k, _)| k.as_str()).collect();
24        println!("capabilities: {:?}", keys);
25    }
26
27    if c.supports(Capability::Embed) {
28        let vecs = c.embed(&["hello world"], None)?;
29        println!("embed      -> {} vector(s), dim={}", vecs.len(), vecs[0].len());
30    }
31
32    if c.supports(Capability::Retrieve) {
33        println!("retrieve   ->");
34        for h in c.retrieve("landmark in the French capital", 2)? {
35            let snippet: String = h.text.chars().take(48).collect();
36            println!("   {}  score={:.3}  {}", h.id, h.score, snippet);
37        }
38    }
39
40    if c.supports(Capability::Graph) {
41        let g = c.graph("global", Some(rcp::obj(&[("query", "anything".into())])))?;
42        println!("graph      -> {}", g);
43    }
44
45    c.shutdown();
46    Ok(())
47}
Source

pub fn get(&self, key: &str) -> Option<&Json>

Look up a key in an object (returns None for non-objects).

Examples found in repository?
examples/example_server.rs (line 79)
56fn build() -> Server {
57    let mut s = Server::new();
58    s.set_info("rcp-example", "1.0.0");
59    s.advertise(
60        Capability::Embed,
61        obj(&[("dimensions", (DIM as i64).into()), ("modes", vec![Json::from("dense")].into())]),
62    );
63    s.advertise(
64        Capability::Retrieve,
65        obj(&[
66            ("maxK", 100.into()),
67            ("modes", vec![Json::from("dense")].into()),
68            ("citations", true.into()),
69        ]),
70    );
71    s.advertise(
72        Capability::Graph,
73        obj(&[("ops", vec![Json::from("local"), Json::from("global")].into())]),
74    );
75
76    s.on(Method::EMBED, |params| {
77        // Accept `inputs` (preferred, spec §7.3) or the legacy `texts` synonym.
78        let items = params
79            .get("inputs")
80            .or_else(|| params.get("texts"))
81            .and_then(|v| v.as_array())
82            .cloned()
83            .unwrap_or_default();
84        let vectors: Vec<Json> = items
85            .iter()
86            .filter_map(|x| x.as_str())
87            .map(|t| Json::from(embed_one(t)))
88            .collect();
89        Ok(obj(&[("vectors", Json::Array(vectors)), ("dimensions", (DIM as i64).into())]))
90    });
91
92    s.on(Method::RETRIEVE, |params| {
93        let q = params.get_str("query").unwrap_or("");
94        let k = params.get("k").and_then(|v| v.as_i64()).unwrap_or(10).max(0) as usize;
95        Ok(obj(&[("hits", search(q, k))]))
96    });
97
98    s.on(Method::GRAPH, |params| {
99        let op = params.get_str("op").unwrap_or("local");
100        match op {
101            "local" => {
102                let q = params.get_str("query").unwrap_or("");
103                let k = params.get("k").and_then(|v| v.as_i64()).unwrap_or(5).max(0) as usize;
104                Ok(obj(&[("hits", search(q, k))]))
105            }
106            "global" => Ok(obj(&[
107                ("summary", "a global community summary would go here".into()),
108                ("communities", 1.into()),
109            ])),
110            other => Ok(obj(&[("op", other.into()), ("note", "unimplemented".into())])),
111        }
112    });
113
114    s
115}
Source

pub fn contains_key(&self, key: &str) -> bool

Source

pub fn get_str(&self, key: &str) -> Option<&str>

Convenience: the string at key, if present and a string.

Examples found in repository?
examples/example_client.rs (line 18)
8fn main() -> Result<(), rcp::RcpError> {
9    // The example_server binary sits next to this one in target/.../examples/.
10    let exe = std::env::current_exe().expect("current exe");
11    let server = exe.parent().unwrap().join("example_server");
12    let server = server.to_string_lossy().to_string();
13
14    let mut c = rcp::connect_stdio(&[server.as_str()])?;
15
16    println!(
17        "connected to {} v{} (RCP/{})",
18        c.server().get_str("name").unwrap_or("?"),
19        c.server().get_str("version").unwrap_or("?"),
20        c.protocol_version()
21    );
22    if let Some(caps) = c.capabilities().as_object() {
23        let keys: Vec<&str> = caps.iter().map(|(k, _)| k.as_str()).collect();
24        println!("capabilities: {:?}", keys);
25    }
26
27    if c.supports(Capability::Embed) {
28        let vecs = c.embed(&["hello world"], None)?;
29        println!("embed      -> {} vector(s), dim={}", vecs.len(), vecs[0].len());
30    }
31
32    if c.supports(Capability::Retrieve) {
33        println!("retrieve   ->");
34        for h in c.retrieve("landmark in the French capital", 2)? {
35            let snippet: String = h.text.chars().take(48).collect();
36            println!("   {}  score={:.3}  {}", h.id, h.score, snippet);
37        }
38    }
39
40    if c.supports(Capability::Graph) {
41        let g = c.graph("global", Some(rcp::obj(&[("query", "anything".into())])))?;
42        println!("graph      -> {}", g);
43    }
44
45    c.shutdown();
46    Ok(())
47}
More examples
Hide additional examples
examples/example_server.rs (line 93)
56fn build() -> Server {
57    let mut s = Server::new();
58    s.set_info("rcp-example", "1.0.0");
59    s.advertise(
60        Capability::Embed,
61        obj(&[("dimensions", (DIM as i64).into()), ("modes", vec![Json::from("dense")].into())]),
62    );
63    s.advertise(
64        Capability::Retrieve,
65        obj(&[
66            ("maxK", 100.into()),
67            ("modes", vec![Json::from("dense")].into()),
68            ("citations", true.into()),
69        ]),
70    );
71    s.advertise(
72        Capability::Graph,
73        obj(&[("ops", vec![Json::from("local"), Json::from("global")].into())]),
74    );
75
76    s.on(Method::EMBED, |params| {
77        // Accept `inputs` (preferred, spec §7.3) or the legacy `texts` synonym.
78        let items = params
79            .get("inputs")
80            .or_else(|| params.get("texts"))
81            .and_then(|v| v.as_array())
82            .cloned()
83            .unwrap_or_default();
84        let vectors: Vec<Json> = items
85            .iter()
86            .filter_map(|x| x.as_str())
87            .map(|t| Json::from(embed_one(t)))
88            .collect();
89        Ok(obj(&[("vectors", Json::Array(vectors)), ("dimensions", (DIM as i64).into())]))
90    });
91
92    s.on(Method::RETRIEVE, |params| {
93        let q = params.get_str("query").unwrap_or("");
94        let k = params.get("k").and_then(|v| v.as_i64()).unwrap_or(10).max(0) as usize;
95        Ok(obj(&[("hits", search(q, k))]))
96    });
97
98    s.on(Method::GRAPH, |params| {
99        let op = params.get_str("op").unwrap_or("local");
100        match op {
101            "local" => {
102                let q = params.get_str("query").unwrap_or("");
103                let k = params.get("k").and_then(|v| v.as_i64()).unwrap_or(5).max(0) as usize;
104                Ok(obj(&[("hits", search(q, k))]))
105            }
106            "global" => Ok(obj(&[
107                ("summary", "a global community summary would go here".into()),
108                ("communities", 1.into()),
109            ])),
110            other => Ok(obj(&[("op", other.into()), ("note", "unimplemented".into())])),
111        }
112    });
113
114    s
115}
Source

pub fn insert(&mut self, key: &str, value: impl Into<Json>) -> &mut Self

Insert or replace key in an object. Converts Null into an object.

Source

pub fn push(&mut self, value: impl Into<Json>) -> &mut Self

Push onto an array. Converts Null into an array.

Source

pub fn dump(&self) -> String

Serialize to a compact JSON string (no whitespace).

Source

pub fn parse(text: &str) -> Result<Json, String>

Parse a JSON string.

Trait Implementations§

Source§

impl Clone for Json

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Json

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for Json

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl From<&String> for Json

Source§

fn from(s: &String) -> Json

Converts to this type from the input type.
Source§

impl From<&str> for Json

Source§

fn from(s: &str) -> Json

Converts to this type from the input type.
Source§

impl From<String> for Json

Source§

fn from(s: String) -> Json

Converts to this type from the input type.
Source§

impl<T: Into<Json>> From<Vec<T>> for Json

Source§

fn from(v: Vec<T>) -> Json

Converts to this type from the input type.
Source§

impl From<bool> for Json

Source§

fn from(b: bool) -> Json

Converts to this type from the input type.
Source§

impl From<f64> for Json

Source§

fn from(f: f64) -> Json

Converts to this type from the input type.
Source§

impl From<i32> for Json

Source§

fn from(n: i32) -> Json

Converts to this type from the input type.
Source§

impl From<i64> for Json

Source§

fn from(n: i64) -> Json

Converts to this type from the input type.
Source§

impl From<usize> for Json

Source§

fn from(n: usize) -> Json

Converts to this type from the input type.
Source§

impl PartialEq for Json

Source§

fn eq(&self, other: &Self) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl StructuralPartialEq for Json

Auto Trait Implementations§

§

impl Freeze for Json

§

impl RefUnwindSafe for Json

§

impl Send for Json

§

impl Sync for Json

§

impl Unpin for Json

§

impl UnsafeUnpin for Json

§

impl UnwindSafe for Json

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.