Skip to main content

tpt_uir_serde/
lib.rs

1#![no_std]
2#![doc = include_str!("../README.md")]
3extern crate alloc;
4
5#[cfg(feature = "std")]
6extern crate std;
7
8use alloc::vec::Vec;
9
10use postcard::{from_bytes, to_allocvec};
11use tpt_uir_core::{Operation, Region};
12
13/// Serialize a single operation to a postcard byte vector.
14pub fn serialize_op(op: &Operation) -> Result<Vec<u8>, postcard::Error> {
15    to_allocvec(op)
16}
17
18/// Deserialize a single operation from postcard bytes.
19pub fn deserialize_op(bytes: &[u8]) -> Result<Operation, postcard::Error> {
20    from_bytes(bytes)
21}
22
23/// Serialize a region to a postcard byte vector.
24pub fn serialize_region(region: &Region) -> Result<Vec<u8>, postcard::Error> {
25    to_allocvec(region)
26}
27
28/// Deserialize a region from postcard bytes.
29pub fn deserialize_region(bytes: &[u8]) -> Result<Region, postcard::Error> {
30    from_bytes(bytes)
31}
32
33/// Write a region to a `.tptuir` file.
34#[cfg(feature = "std")]
35pub fn write_tptuir<P: AsRef<std::path::Path>>(path: P, region: &Region) -> std::io::Result<()> {
36    let bytes = serialize_region(region)
37        .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
38    std::fs::write(path, bytes)
39}
40
41/// Read a region from a `.tptuir` file.
42#[cfg(feature = "std")]
43pub fn read_tptuir<P: AsRef<std::path::Path>>(
44    path: P,
45) -> Result<Region, std::boxed::Box<dyn std::error::Error>> {
46    let bytes = std::fs::read(path)?;
47    let region = deserialize_region(&bytes)?;
48    Ok(region)
49}
50
51#[cfg(test)]
52mod tests {
53    extern crate std;
54    use super::*;
55    use alloc::vec;
56    use tpt_uir_core::attr::Attribute;
57    use tpt_uir_core::op_name::OpName;
58    use tpt_uir_core::types::Type;
59    use tpt_uir_core::{Block, Operation, Region};
60
61    fn sample_op() -> Operation {
62        Operation {
63            id: 1,
64            op_name: OpName::parse("core.add").unwrap(),
65            operands: vec![0, 1],
66            results: vec![2],
67            regions: vec![],
68            attributes: vec![Attribute::i64("axis", 0)],
69        }
70    }
71
72    fn sample_region() -> Region {
73        Region {
74            blocks: vec![Block {
75                arguments: vec![(0u32, Type::Index), (1u32, Type::Index)],
76                operations: vec![sample_op()],
77            }],
78        }
79    }
80
81    #[test]
82    fn roundtrip_op() {
83        let op = sample_op();
84        let bytes = serialize_op(&op).unwrap();
85        let back = deserialize_op(&bytes).unwrap();
86        assert_eq!(op, back);
87    }
88
89    #[test]
90    fn roundtrip_region() {
91        let region = sample_region();
92        let bytes = serialize_region(&region).unwrap();
93        let back = deserialize_region(&bytes).unwrap();
94        assert_eq!(region, back);
95    }
96
97    #[test]
98    fn roundtrip_region_with_nested_block() {
99        let inner = Operation {
100            id: 9,
101            op_name: OpName::parse("core.mul").unwrap(),
102            operands: vec![0],
103            results: vec![3],
104            regions: vec![],
105            attributes: vec![],
106        };
107        let outer = Operation {
108            id: 2,
109            op_name: OpName::parse("core.store").unwrap(),
110            operands: vec![2],
111            results: vec![],
112            regions: vec![Region {
113                blocks: vec![Block {
114                    arguments: vec![],
115                    operations: vec![inner],
116                }],
117            }],
118            attributes: vec![],
119        };
120        let region = Region {
121            blocks: vec![Block {
122                arguments: vec![(0u32, Type::Index), (1u32, Type::Index)],
123                operations: vec![sample_op(), outer],
124            }],
125        };
126        let bytes = serialize_region(&region).unwrap();
127        let back = deserialize_region(&bytes).unwrap();
128        assert_eq!(region, back);
129    }
130
131    #[cfg(feature = "std")]
132    #[test]
133    fn roundtrip_file() {
134        let region = sample_region();
135        let path = std::env::temp_dir().join("tpt_uir_test.tptuir");
136        write_tptuir(&path, &region).unwrap();
137        let back = read_tptuir(&path).unwrap();
138        assert_eq!(region, back);
139        let _ = std::fs::remove_file(&path);
140    }
141
142    // Wire-compatibility regression test.
143    //
144    // The `Quantization` variant was appended as the LAST `AttributeValue`
145    // variant. Postcard encodes enum variants by numeric index, so the indices
146    // of every pre-existing variant (I64=0 ... OpName=5) must stay fixed. This
147    // fixture encodes `AttributeValue::OpName("tpt_gpu.launch")` using only
148    // those pre-change indices (variant 5 = 0x05, then two length-prefixed
149    // postcard strings). It must still decode on the current code.
150    #[test]
151    fn wire_compat_attr_value_opname() {
152        // 0x05 = variant index 5 (OpName)
153        // 0x07 + "tpt_gpu", 0x06 + "launch"
154        let fixture: &[u8] = &[
155            0x05, 0x07, b't', b'p', b't', b'_', b'g', b'p', b'u', 0x06, b'l', b'a', b'u', b'n',
156            b'c', b'h',
157        ];
158        let decoded: tpt_uir_core::attr::AttributeValue = postcard::from_bytes(fixture).unwrap();
159        assert_eq!(
160            decoded,
161            tpt_uir_core::attr::AttributeValue::OpName(
162                tpt_uir_core::OpName::parse("tpt_gpu.launch").unwrap()
163            )
164        );
165
166        // Round-trips to identical bytes (proves the index is stable).
167        let reencoded = postcard::to_allocvec(&decoded).unwrap();
168        assert_eq!(reencoded, fixture);
169    }
170}