Skip to main content

onnx_std/
codec.rs

1//! Uniform string-codec API for ONNX model interchange.
2
3use crate::{Model, Result, json, text, textproto};
4
5/// A textual serialization format for [`Model`].
6///
7/// Binary protobuf file I/O remains separate because it also manages paths,
8/// external weights, and file-format detection.
9pub trait TextCodec {
10    /// Format-specific serialization options.
11    type Options: Default;
12
13    /// Serialize `model` with explicit format options.
14    fn serialize(model: &Model, options: &Self::Options) -> Result<String>;
15
16    /// Deserialize a model from this format.
17    fn deserialize(source: &str) -> Result<Model>;
18}
19
20/// The human-readable ONNX text DSL (ONNX_RS §5).
21#[derive(Clone, Copy, Debug, Default)]
22pub struct Text;
23
24impl TextCodec for Text {
25    type Options = text::PrintOptions;
26
27    fn serialize(model: &Model, options: &Self::Options) -> Result<String> {
28        Ok(text::to_text_with(model, options))
29    }
30
31    fn deserialize(source: &str) -> Result<Model> {
32        text::from_text(source)
33    }
34}
35
36/// Canonical protobuf JSON mapping (ONNX_RS §6).
37#[derive(Clone, Copy, Debug, Default)]
38pub struct Json;
39
40impl TextCodec for Json {
41    type Options = ();
42
43    fn serialize(model: &Model, _options: &Self::Options) -> Result<String> {
44        json::to_json(model)
45    }
46
47    fn deserialize(source: &str) -> Result<Model> {
48        json::from_json(source)
49    }
50}
51
52/// Protobuf TextFormat (`.onnxtxt` / `.pbtxt`) (ONNX_RS §6).
53#[derive(Clone, Copy, Debug, Default)]
54pub struct TextProto;
55
56impl TextCodec for TextProto {
57    type Options = ();
58
59    fn serialize(model: &Model, _options: &Self::Options) -> Result<String> {
60        textproto::to_textproto(model)
61    }
62
63    fn deserialize(source: &str) -> Result<Model> {
64        textproto::from_textproto(source)
65    }
66}