Skip to main content

fiber_json_types/
schema_helpers.rs

1//! Schema helper functions for generating JSON Schema descriptions of custom hex types.
2
3use schemars::json_schema;
4use schemars::{JsonSchema, Schema, SchemaGenerator};
5
6pub fn schema_as_string(generator: &mut SchemaGenerator) -> Schema {
7    let mut schema = String::json_schema(generator);
8    schema.insert("format".into(), "string".into());
9    schema
10}
11
12pub fn schema_as_hex_no_prefix(generator: &mut SchemaGenerator) -> Schema {
13    let mut schema = String::json_schema(generator);
14    schema.insert("pattern".into(), "^([0-9a-fA-F]{2})*$".into());
15    schema
16}
17
18pub fn schema_as_string_array(generator: &mut SchemaGenerator) -> Schema {
19    let item_schema = schema_as_string(generator);
20    json_schema!({
21        "type": "array",
22        "items": item_schema
23    })
24}
25
26pub fn schema_as_string_optional(generator: &mut SchemaGenerator) -> Schema {
27    let string_schema = schema_as_string(generator);
28    json_schema!({
29        "anyOf": [
30            string_schema,
31            { "type": "null" }
32        ]
33    })
34}
35
36pub fn schema_as_integer(_generator: &mut SchemaGenerator) -> Schema {
37    json_schema!({
38        "type": "integer"
39    })
40}
41
42pub fn schema_as_hex_bytes(generator: &mut SchemaGenerator) -> Schema {
43    let mut schema = String::json_schema(generator);
44    schema.insert("pattern".into(), "^0x([0-9a-fA-F]{2})*$".into());
45    schema
46}
47
48pub fn schema_as_hex_bytes_optional(generator: &mut SchemaGenerator) -> Schema {
49    let hex_schema = schema_as_hex_bytes(generator);
50    json_schema!({
51        "anyOf": [
52            hex_schema,
53            { "type": "null" }
54        ]
55    })
56}
57
58pub fn schema_as_uint_hex(generator: &mut SchemaGenerator) -> Schema {
59    let mut schema = String::json_schema(generator);
60    schema.insert("pattern".into(), "^0x(0|[1-9a-fA-F][0-9a-fA-F]*)$".into());
61    schema
62}
63
64pub fn schema_as_uint_hex_optional(generator: &mut SchemaGenerator) -> Schema {
65    let hex_schema = schema_as_uint_hex(generator);
66    json_schema!({
67        "anyOf": [
68            hex_schema,
69            { "type": "null" }
70        ]
71    })
72}