File: remote_derive.rs

package info (click to toggle)
rustc 1.85.0%2Bdfsg3-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental, sid, trixie
  • size: 893,396 kB
  • sloc: xml: 158,127; python: 35,830; javascript: 19,497; cpp: 19,002; sh: 17,245; ansic: 13,127; asm: 4,376; makefile: 1,051; perl: 29; lisp: 29; ruby: 19; sql: 11
file content (42 lines) | stat: -rw-r--r-- 1,311 bytes parent folder | download | duplicates (4)
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
// Pretend that this is somebody else's crate, not a module.
mod other_crate {
    // Neither Schemars nor the other crate provides a JsonSchema impl
    // for this struct.
    pub struct Duration {
        pub secs: i64,
        pub nanos: i32,
    }
}

////////////////////////////////////////////////////////////////////////////////

use other_crate::Duration;
use schemars::{schema_for, JsonSchema};

// This is just a copy of the remote data structure that Schemars can use to
// create a suitable JsonSchema impl.
#[derive(JsonSchema)]
#[serde(remote = "Duration")]
pub struct DurationDef {
    pub secs: i64,
    pub nanos: i32,
}

// Now the remote type can be used almost like it had its own JsonSchema impl
// all along. The `with` attribute gives the path to the definition for the
// remote type. Note that the real type of the field is the remote type, not
// the definition type.
#[derive(JsonSchema)]
pub struct Process {
    pub command_line: String,
    #[serde(with = "DurationDef")]
    pub wall_time: Duration,
    // Generic types must be explicitly specified with turbofix `::<>` syntax.
    #[serde(with = "Vec::<DurationDef>")]
    pub durations: Vec<Duration>,
}

fn main() {
    let schema = schema_for!(Process);
    println!("{}", serde_json::to_string_pretty(&schema).unwrap());
}