const_json/lib.rs
1// Copyright Proa Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4#![no_std]
5
6//! Const-only JSON serialization and parsing runtime helpers.
7//!
8//! This crate pairs with the `ConstJson` derive macro to generate
9//! fully `const fn` JSON serialization with zero heap allocation.
10//!
11//! It also provides compile-time JSON parsing via `const fn`.
12
13/// Serialize literal JSON at compile time, returning a compact `&'static str`.
14///
15/// Supports objects, arrays, strings, JSON numbers, booleans, and null. Object
16/// keys must be string literals. Runtime expressions and duplicate keys are
17/// rejected; use `ConstJson` or a runtime serializer for typed values instead.
18/// Rust raw strings, comments, and trailing commas are accepted in the input.
19/// Object key order depends on the serializer configuration.
20/// Integers must fit `i64`/`u64`; floating-point literals must fit finite `f64`.
21///
22/// ```
23/// use const_json::const_json;
24/// const SCHEMA: &str = const_json!({"required": ["name"]});
25/// assert_eq!(SCHEMA, r#"{"required":["name"]}"#);
26/// ```
27///
28/// ```compile_fail
29/// let name = "runtime";
30/// let json = const_json::const_json!({"name": name});
31/// ```
32pub use const_json_macros::const_json;
33pub use const_json_macros::ConstJson;
34
35mod buffer;
36pub mod parse;
37pub mod ser;
38
39pub use buffer::JsonBuffer;
40pub use parse::{JsonObject, JsonValue, ParseError};
41
42#[cfg(test)]
43extern crate std;
44
45#[cfg(test)]
46mod tests {
47 use super::*;
48 use crate as const_json;
49
50 #[derive(ConstJson)]
51 #[const_json(capacity = 64)]
52 struct Example<'a> {
53 title: &'a str,
54 count: u32,
55 enabled: bool,
56 }
57
58 const fn build_example() -> JsonBuffer<64> {
59 Example {
60 title: "example",
61 count: 42,
62 enabled: true,
63 }
64 .to_json()
65 }
66
67 #[test]
68 fn generates_expected_json() {
69 const BUF: JsonBuffer<64> = build_example();
70 assert_eq!(
71 BUF.as_str(),
72 r#"{"title":"example","count":42,"enabled":true}"#
73 );
74 }
75}