hugr-core 0.27.1

Quantinuum's Hierarchical Unified Graph Representation
Documentation
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
//! Definitions for the header of an envelope.

use std::io::{Read, Write};
use std::num::NonZeroU8;

use itertools::Itertools;
use thiserror::Error;

/// Magic number identifying the start of an envelope.
///
/// In ascii, this is "`HUGRiHJv`". The second half is a randomly generated string
/// to avoid accidental collisions with other file formats.
pub const MAGIC_NUMBERS: &[u8] = "HUGRiHJv".as_bytes();

/// The all-unset header flags configuration.
/// Bit 7 is always set to ensure we have a printable ASCII character.
const DEFAULT_FLAGS: u8 = 0b0100_0000u8;
/// The ZSTD flag bit in the header's flags.
const ZSTD_FLAG: u8 = 0b0000_0001;

/// Header at the start of a binary envelope file.
///
/// See the [`crate::envelope`] module documentation for the binary format.
#[derive(Clone, Copy, Eq, PartialEq, Debug, Default, derive_more::Display)]
#[display("EnvelopeHeader({format}{})",
    if *zstd { ", zstd compressed" } else { "" },
)]
pub struct EnvelopeHeader {
    /// The format used for the payload.
    pub format: EnvelopeFormat,
    /// Whether the payload is compressed with zstd.
    pub zstd: bool,
}

mod silenced {
    #![expect(deprecated, reason = "https://github.com/Peternator7/strum/issues/404")]
    /// Encoded format of an envelope payload.
    #[derive(
        Clone, Copy, Eq, PartialEq, Debug, Default, Hash, derive_more::Display, strum::FromRepr,
    )]
    #[non_exhaustive]
    pub enum EnvelopeFormat {
        /// `hugr-model` v0 binary capnproto message.
        Model = 1,
        /// `hugr-model` v0 binary capnproto message followed by a json-encoded
        /// [`crate::extension::ExtensionRegistry`].
        ///
        /// This is a temporary format required until the model adds support for
        /// extensions.
        #[default]
        ModelWithExtensions = 2,
        /// Human-readable S-expression encoding using [`hugr_model::v0`].
        ///
        /// Uses a printable ascii value as the discriminant so the envelope can be
        /// read as text.
        ///
        /// :caution: This format does not yet support extension encoding, so it should
        /// be avoided.
        //
        // TODO: Update comment once extension encoding is supported.
        SExpression = 40, // '(' in ascii
        /// Human-readable S-expression encoding using [`hugr_model::v0`].
        ///
        /// Uses a printable ascii value as the discriminant so the envelope can be
        /// read as text.
        ///
        /// This is a temporary format required until the model adds support for
        /// extensions.
        SExpressionWithExtensions = 41, // ')' in ascii
        /// Json-encoded [`crate::package::Package`]
        ///
        /// Uses a printable ascii value as the discriminant so the envelope can be
        /// read as text. DEPRECATED.
        #[deprecated(since = "0.27.0")]
        PackageJson = 63, // '?' in ascii
    }
}

pub use silenced::EnvelopeFormat;

// We use a u8 to represent EnvelopeFormat in the binary format, so we should not
// add any non-unit variants or ones with discriminants > 255.
static_assertions::assert_eq_size!(EnvelopeFormat, u8);

impl EnvelopeFormat {
    /// If the format is a model format, returns its version number.
    #[must_use]
    pub fn model_version(self) -> Option<u32> {
        match self {
            Self::Model
            | Self::ModelWithExtensions
            | Self::SExpression
            | Self::SExpressionWithExtensions => Some(0),
            _ => None,
        }
    }

    /// Returns whether the encoding format is ASCII-printable.
    ///
    /// If true, the encoded envelope can be read as text.
    #[must_use]
    #[expect(deprecated)]
    pub fn ascii_printable(self) -> bool {
        matches!(
            self,
            Self::PackageJson | Self::SExpression | Self::SExpressionWithExtensions
        )
    }
}

/// Configuration for encoding an envelope.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
#[non_exhaustive]
pub struct EnvelopeConfig {
    /// The format to use for the payload.
    pub format: EnvelopeFormat,
    /// Whether to compress the payload with zstd, and the compression level to
    /// use.
    pub zstd: Option<ZstdConfig>,
}

impl EnvelopeConfig {
    /// Create a new envelope configuration with the specified format.
    /// `zstd` compression is disabled by default.
    pub fn new(format: EnvelopeFormat) -> Self {
        Self {
            format,
            ..Default::default()
        }
    }

    /// Set the zstd compression configuration for the envelope.
    pub fn with_zstd(self, zstd: ZstdConfig) -> Self {
        Self {
            zstd: Some(zstd),
            ..self
        }
    }

    /// Disable zstd compression in the envelope configuration.
    pub fn disable_compression(self) -> Self {
        Self { zstd: None, ..self }
    }

    /// Create a new envelope header with the specified configuration.
    pub(super) fn make_header(&self) -> EnvelopeHeader {
        EnvelopeHeader {
            format: self.format,
            zstd: self.zstd.is_some(),
        }
    }

    /// Default configuration for a plain-text envelope.
    #[must_use]
    pub const fn text() -> Self {
        Self {
            format: EnvelopeFormat::SExpressionWithExtensions,
            zstd: None,
        }
    }

    /// Default configuration for a binary envelope.
    ///
    /// If the `zstd` feature is enabled, this will use zstd compression.
    #[must_use]
    pub const fn binary() -> Self {
        Self {
            format: EnvelopeFormat::ModelWithExtensions,
            zstd: Some(ZstdConfig::default_level()),
        }
    }
}

/// Configuration for zstd compression.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
#[non_exhaustive]
pub struct ZstdConfig {
    /// The compression level to use.
    ///
    /// The current range is 1-22, where 1 is fastest and 22 is best
    /// compression. Values above 20 should be used with caution, as they
    /// require additional memory.
    ///
    /// If `None`, zstd's default level is used.
    pub level: Option<NonZeroU8>,
}

impl ZstdConfig {
    /// Create a new zstd configuration with the specified compression level.
    pub fn new(level: u8) -> Self {
        Self {
            level: NonZeroU8::new(level),
        }
    }
    /// Create a new zstd configuration with default compression level.
    #[must_use]
    pub const fn default_level() -> Self {
        Self { level: None }
    }

    /// Returns the zstd compression level to pass to the zstd library.
    ///
    /// Uses [`zstd::DEFAULT_COMPRESSION_LEVEL`] if the level is not set.
    #[must_use]
    pub fn level(&self) -> i32 {
        #[allow(unused_assignments, unused_mut)]
        let mut default = 0;
        #[cfg(feature = "zstd")]
        {
            default = zstd::DEFAULT_COMPRESSION_LEVEL;
        }
        self.level.map_or(default, |l| i32::from(l.get()))
    }
}

#[derive(Debug, Error, derive_more::Display)]
#[display("Error reading the envelope header. {_0}")]
pub struct HeaderError(HeaderErrorInner);

#[derive(Debug, Error)]
#[non_exhaustive]
pub(super) enum HeaderErrorInner {
    /// Bad magic number.
    #[error(
        "Bad magic number. expected 0x{:X} found 0x{:X}",
        u64::from_be_bytes(*expected),
        u64::from_be_bytes(*found)
    )]
    MagicNumber {
        /// The expected magic number.
        ///
        /// See [`MAGIC_NUMBERS`].
        expected: [u8; 8],
        /// The magic number in the envelope.
        found: [u8; 8],
    },
    /// The specified payload format is invalid.
    #[error("Format descriptor {descriptor} is invalid.")]
    InvalidFormatDescriptor {
        /// The unsupported format.
        descriptor: usize,
    },
    /// IO read/write error.
    #[error(transparent)]
    IO {
        /// The source error.
        #[from]
        source: std::io::Error,
    },
    /// The specified payload format is not supported.
    #[error(
        "The envelope configuration has unknown {}. Please update your HUGR version.",
        if flag_ids.len() == 1 {format!("flag #{}", flag_ids[0])} else {format!("flags {}", flag_ids.iter().join(", "))}
    )]
    FlagUnsupported {
        /// The unrecognized flag bits.
        flag_ids: Vec<usize>,
    },
    #[cfg(not(feature = "zstd"))]
    /// Envelope encoding required zstd compression, but the feature is not enabled.
    #[error("Zstd compression is not supported. This requires the 'zstd' feature for `hugr`.")]
    ZstdUnsupported,
}

impl<T: Into<HeaderErrorInner>> From<T> for HeaderError {
    fn from(value: T) -> Self {
        Self(value.into())
    }
}
impl EnvelopeHeader {
    /// Returns the envelope configuration corresponding to this header.
    ///
    /// Note that zstd compression level is not stored in the header.
    pub fn config(&self) -> EnvelopeConfig {
        EnvelopeConfig {
            format: self.format,
            zstd: if self.zstd {
                Some(ZstdConfig { level: None })
            } else {
                None
            },
        }
    }

    /// Write an envelope header to a writer.
    ///
    /// See the [`crate::envelope`] module documentation for the binary format.
    pub fn write(&self, writer: &mut impl Write) -> Result<(), HeaderError> {
        // The first 8 bytes are the magic number in little-endian.
        writer.write_all(MAGIC_NUMBERS)?;
        // Next is the format descriptor.
        let format_bytes = [self.format as u8];
        writer.write_all(&format_bytes)?;
        // Next is the flags byte.
        let mut flags = DEFAULT_FLAGS;
        if self.zstd {
            flags |= ZSTD_FLAG;
        }
        writer.write_all(&[flags])?;

        Ok(())
    }

    /// Reads an envelope header from a reader.
    ///
    /// Consumes exactly 10 bytes from the reader.
    /// See the [`crate::envelope`] module documentation for the binary format.
    pub fn read(reader: &mut impl Read) -> Result<EnvelopeHeader, HeaderError> {
        // The first 8 bytes are the magic number in little-endian.
        let mut magic = [0; 8];
        reader.read_exact(&mut magic)?;
        if magic != MAGIC_NUMBERS {
            return Err(HeaderErrorInner::MagicNumber {
                expected: MAGIC_NUMBERS.try_into().unwrap(),
                found: magic,
            }
            .into());
        }

        // Next is the format descriptor.
        let mut format_bytes = [0; 1];
        reader.read_exact(&mut format_bytes)?;
        let format_discriminant = format_bytes[0] as usize;
        let Some(format) = EnvelopeFormat::from_repr(format_discriminant) else {
            return Err(HeaderErrorInner::InvalidFormatDescriptor {
                descriptor: format_discriminant,
            }
            .into());
        };

        // Next is the flags byte.
        let mut flags_bytes = [0; 1];
        reader.read_exact(&mut flags_bytes)?;
        let flags: u8 = flags_bytes[0];

        let zstd = flags & ZSTD_FLAG != 0;

        // Check if there's any unrecognized flags.
        let other_flags = (flags ^ DEFAULT_FLAGS) & !ZSTD_FLAG;
        if other_flags != 0 {
            let flag_ids = (0..8).filter(|i| other_flags & (1 << i) != 0).collect_vec();
            return Err(HeaderErrorInner::FlagUnsupported { flag_ids }.into());
        }

        Ok(Self { format, zstd })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use cool_asserts::assert_matches;
    use rstest::rstest;

    #[rstest]
    #[case(EnvelopeFormat::Model)]
    #[case(EnvelopeFormat::ModelWithExtensions)]
    #[case(EnvelopeFormat::SExpression)]
    #[case(EnvelopeFormat::SExpressionWithExtensions)]
    #[case(EnvelopeFormat::PackageJson)]
    #[allow(deprecated)]
    fn header_round_trip(#[case] format: EnvelopeFormat) {
        // With zstd compression
        let header = EnvelopeHeader { format, zstd: true };

        let mut buffer = Vec::new();
        header.write(&mut buffer).unwrap();
        let read_header = EnvelopeHeader::read(&mut buffer.as_slice()).unwrap();
        assert_eq!(header, read_header);

        // Without zstd compression
        let header = EnvelopeHeader {
            format,
            zstd: false,
        };

        let mut buffer = Vec::new();
        header.write(&mut buffer).unwrap();
        let read_header = EnvelopeHeader::read(&mut buffer.as_slice()).unwrap();
        assert_eq!(header, read_header);
    }

    #[rstest]
    fn header_errors() {
        let header = EnvelopeHeader {
            format: EnvelopeFormat::Model,
            zstd: false,
        };
        let mut buffer = Vec::new();
        header.write(&mut buffer).unwrap();

        assert_eq!(buffer.len(), 10);
        let flags = buffer[9];
        assert_eq!(flags, DEFAULT_FLAGS);

        // Invalid magic
        let mut invalid_magic = buffer.clone();
        invalid_magic[7] = 0xFF;
        assert_matches!(
            EnvelopeHeader::read(&mut invalid_magic.as_slice()),
            Err(HeaderError(HeaderErrorInner::MagicNumber { .. }))
        );

        // Unrecognised flags
        let mut unrecognised_flags = buffer.clone();
        unrecognised_flags[9] |= 0b0001_0010;
        assert_matches!(
            EnvelopeHeader::read(&mut unrecognised_flags.as_slice()),
            Err(HeaderError(HeaderErrorInner::FlagUnsupported { flag_ids }))
            => assert_eq!(flag_ids, vec![1, 4])
        );
    }
}