cadmpeg 0.6.3

Convert and inspect native CAD files.
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
414
415
416
417
418
419
420
// SPDX-License-Identifier: Apache-2.0
//! Offset argument parsing and fixed-width scalar reads.

use clap::ValueEnum;

/// Parses a byte count or file offset written in hexadecimal or decimal.
///
/// `0x`/`0X` selects hexadecimal, anything else is decimal. Underscores
/// separate digit groups and are ignored. The value is unsigned; a leading
/// sign is rejected so that a mistyped offset never silently wraps.
pub(super) fn parse_offset(text: &str) -> Result<u64, String> {
    let trimmed = text.trim();
    if trimmed.is_empty() {
        return Err("expected a byte offset, found an empty value".to_string());
    }
    let (digits, radix) = match trimmed
        .strip_prefix("0x")
        .or_else(|| trimmed.strip_prefix("0X"))
    {
        Some(rest) => (rest, 16),
        None => (trimmed, 10),
    };
    let cleaned: String = digits.chars().filter(|c| *c != '_').collect();
    if cleaned.is_empty() {
        return Err(format!("{trimmed}: no digits after the radix prefix"));
    }
    if !cleaned.chars().all(|c| c.is_digit(radix)) {
        let kind = if radix == 16 {
            "hexadecimal"
        } else {
            "decimal"
        };
        return Err(format!("{trimmed}: not a {kind} byte offset"));
    }
    u64::from_str_radix(&cleaned, radix).map_err(|_| format!("{trimmed}: does not fit in 64 bits"))
}

/// Byte order applied to a multi-byte scalar read.
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
pub(super) enum Endian {
    /// Least significant byte first.
    Le,
    /// Most significant byte first.
    Be,
}

impl Endian {
    /// Returns the two-letter suffix used in output and in layout specs.
    const fn suffix(self) -> &'static str {
        match self {
            Self::Le => "le",
            Self::Be => "be",
        }
    }
}

/// Parses `--type`, teaching the right tool for non-scalar guesses.
///
/// Delegates to the `ScalarType` value enum — including its possible-values
/// help list — but catches the recurring text and hex-dump guesses with an
/// error that names the tool that does that job.
#[derive(Clone)]
pub(super) struct ScalarTypeParser;

impl clap::builder::TypedValueParser for ScalarTypeParser {
    type Value = ScalarType;

    fn parse_ref(
        &self,
        cmd: &clap::Command,
        arg: Option<&clap::Arg>,
        value: &std::ffi::OsStr,
    ) -> Result<ScalarType, clap::Error> {
        let redirect = match value.to_str().map(str::to_ascii_lowercase).as_deref() {
            Some("ascii" | "string" | "str" | "text" | "utf8") => Some(
                "--type takes a fixed-width scalar; for text use `cadmpeg inspect strings`, \
                 or `cadmpeg inspect find FILE --encoding ascii TEXT` to locate it",
            ),
            Some("hex" | "bytes") => {
                Some("--type takes a fixed-width scalar; for a hex dump use `cadmpeg inspect hex`")
            }
            _ => None,
        };
        if let Some(message) = redirect {
            return Err(clap::Error::raw(
                clap::error::ErrorKind::InvalidValue,
                format!("{message}\n"),
            )
            .with_cmd(cmd));
        }
        clap::builder::EnumValueParser::<ScalarType>::new().parse_ref(cmd, arg, value)
    }

    fn possible_values(
        &self,
    ) -> Option<Box<dyn Iterator<Item = clap::builder::PossibleValue> + '_>> {
        Some(Box::new(
            clap::ValueEnum::value_variants()
                .iter()
                .filter_map(|variant: &ScalarType| clap::ValueEnum::to_possible_value(variant)),
        ))
    }
}

/// A fixed-width scalar that a decoder reads out of a record.
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
pub(super) enum ScalarType {
    /// Unsigned 8-bit.
    U8,
    /// Signed 8-bit.
    I8,
    /// Unsigned 16-bit.
    U16,
    /// Signed 16-bit.
    I16,
    /// Unsigned 32-bit.
    U32,
    /// Signed 32-bit.
    I32,
    /// Unsigned 64-bit.
    U64,
    /// Signed 64-bit.
    I64,
    /// IEEE-754 binary32.
    F32,
    /// IEEE-754 binary64.
    F64,
}

impl ScalarType {
    /// The widest encoding any variant uses.
    pub(super) const MAX_WIDTH: usize = 8;

    /// Returns the encoded width in bytes.
    pub(super) const fn width(self) -> usize {
        match self {
            Self::U8 | Self::I8 => 1,
            Self::U16 | Self::I16 => 2,
            Self::U32 | Self::I32 | Self::F32 => 4,
            Self::U64 | Self::I64 | Self::F64 => 8,
        }
    }

    /// Returns true when the encoding is one byte wide and byte order is moot.
    pub(super) const fn is_single_byte(self) -> bool {
        self.width() == 1
    }

    /// Returns the spec name without a byte-order suffix.
    const fn base_name(self) -> &'static str {
        match self {
            Self::U8 => "u8",
            Self::I8 => "i8",
            Self::U16 => "u16",
            Self::I16 => "i16",
            Self::U32 => "u32",
            Self::I32 => "i32",
            Self::U64 => "u64",
            Self::I64 => "i64",
            Self::F32 => "f32",
            Self::F64 => "f64",
        }
    }

    /// Returns the display name, with a byte-order suffix for wide types.
    pub(super) fn display_name(self, endian: Endian) -> String {
        if self.is_single_byte() {
            self.base_name().to_string()
        } else {
            format!("{}{}", self.base_name(), endian.suffix())
        }
    }

    /// Parses a base type name with no byte-order suffix.
    pub(super) fn from_base_name(name: &str) -> Option<Self> {
        [
            Self::U8,
            Self::I8,
            Self::U16,
            Self::I16,
            Self::U32,
            Self::I32,
            Self::U64,
            Self::I64,
            Self::F32,
            Self::F64,
        ]
        .into_iter()
        .find(|candidate| candidate.base_name() == name)
    }

    /// Returns a window over the leading [`ScalarType::width`] bytes of a maximum-width buffer.
    pub(super) fn window_of(self, buffer: &[u8; ScalarType::MAX_WIDTH]) -> ScalarWindow<'_> {
        ScalarWindow {
            ty: self,
            bytes: &buffer[..self.width()],
        }
    }
}

/// A byte window of exactly the width of the scalar type that minted it.
#[derive(Debug, Clone, Copy)]
pub(in crate::inspect) struct ScalarWindow<'a> {
    ty: ScalarType,
    bytes: &'a [u8],
}

impl ScalarWindow<'_> {
    /// Decodes the window in the stated byte order.
    pub(super) fn read(self, endian: Endian) -> ScalarValue {
        let bytes = self.bytes;
        let mut raw = [0u8; ScalarType::MAX_WIDTH];
        raw[..bytes.len()].copy_from_slice(bytes);
        if endian == Endian::Be {
            raw[..bytes.len()].reverse();
        }
        match self.ty {
            ScalarType::U8 => ScalarValue::U8(raw[0]),
            // endian-exception: reconstructed-scalar
            ScalarType::I8 => ScalarValue::I8(i8::from_le_bytes([raw[0]])),
            // endian-exception: reconstructed-scalar
            ScalarType::U16 => ScalarValue::U16(u16::from_le_bytes([raw[0], raw[1]])),
            // endian-exception: reconstructed-scalar
            ScalarType::I16 => ScalarValue::I16(i16::from_le_bytes([raw[0], raw[1]])),
            ScalarType::U32 => {
                // endian-exception: reconstructed-scalar
                ScalarValue::U32(u32::from_le_bytes([raw[0], raw[1], raw[2], raw[3]]))
            }
            ScalarType::I32 => {
                // endian-exception: reconstructed-scalar
                ScalarValue::I32(i32::from_le_bytes([raw[0], raw[1], raw[2], raw[3]]))
            }
            // endian-exception: reconstructed-scalar
            ScalarType::U64 => ScalarValue::U64(u64::from_le_bytes(raw)),
            // endian-exception: reconstructed-scalar
            ScalarType::I64 => ScalarValue::I64(i64::from_le_bytes(raw)),
            ScalarType::F32 => {
                // endian-exception: reconstructed-scalar
                ScalarValue::F32(f32::from_le_bytes([raw[0], raw[1], raw[2], raw[3]]))
            }
            // endian-exception: reconstructed-scalar
            ScalarType::F64 => ScalarValue::F64(f64::from_le_bytes(raw)),
        }
    }
}

/// A decoded scalar whose variant retains its exact encoded type.
#[derive(Debug, Clone, Copy, PartialEq)]
pub(super) enum ScalarValue {
    U8(u8),
    I8(i8),
    U16(u16),
    I16(i16),
    U32(u32),
    I32(i32),
    U64(u64),
    I64(i64),
    F32(f32),
    F64(f64),
}

impl ScalarValue {
    /// Returns the encoded type the value was decoded from.
    pub(super) const fn ty(self) -> ScalarType {
        match self {
            Self::U8(_) => ScalarType::U8,
            Self::I8(_) => ScalarType::I8,
            Self::U16(_) => ScalarType::U16,
            Self::I16(_) => ScalarType::I16,
            Self::U32(_) => ScalarType::U32,
            Self::I32(_) => ScalarType::I32,
            Self::U64(_) => ScalarType::U64,
            Self::I64(_) => ScalarType::I64,
            Self::F32(_) => ScalarType::F32,
            Self::F64(_) => ScalarType::F64,
        }
    }

    /// Renders the value the way a human reads it.
    pub(super) fn decimal(self) -> String {
        match self {
            Self::U8(value) => value.to_string(),
            Self::I8(value) => value.to_string(),
            Self::U16(value) => value.to_string(),
            Self::I16(value) => value.to_string(),
            Self::U32(value) => value.to_string(),
            Self::I32(value) => value.to_string(),
            Self::U64(value) => value.to_string(),
            Self::I64(value) => value.to_string(),
            Self::F32(value) => format!("{:?}", f64::from(value)),
            Self::F64(value) => format!("{value:?}"),
        }
    }

    /// Renders the encoded bit pattern, zero-padded to the type width.
    ///
    /// Signed values print their two's-complement pattern and floats print
    /// their IEEE-754 bits, so the text always matches what is in the file.
    pub(super) fn hex(self) -> String {
        let bits = match self {
            Self::U8(value) => u64::from(value),
            Self::I8(value) => u64::from(value.cast_unsigned()),
            Self::U16(value) => u64::from(value),
            Self::I16(value) => u64::from(value.cast_unsigned()),
            Self::U32(value) => u64::from(value),
            Self::I32(value) => u64::from(value.cast_unsigned()),
            Self::U64(value) => value,
            Self::I64(value) => value.cast_unsigned(),
            Self::F32(value) => u64::from(value.to_bits()),
            Self::F64(value) => value.to_bits(),
        };
        let digits = match self {
            Self::U8(_) | Self::I8(_) => 2,
            Self::U16(_) | Self::I16(_) => 4,
            Self::U32(_) | Self::I32(_) | Self::F32(_) => 8,
            Self::U64(_) | Self::I64(_) | Self::F64(_) => 16,
        };
        format!("0x{bits:0digits$x}")
    }
}

#[cfg(test)]
mod tests {
    use super::{parse_offset, Endian, ScalarType, ScalarValue};

    #[track_caller]
    fn read(ty: ScalarType, bytes: &[u8], endian: Endian) -> ScalarValue {
        let mut raw = [0u8; ScalarType::MAX_WIDTH];
        raw[..bytes.len()].copy_from_slice(bytes);
        ty.window_of(&raw).read(endian)
    }

    #[test]
    fn parse_offset_reads_both_radixes() {
        assert_eq!(parse_offset("0"), Ok(0));
        assert_eq!(parse_offset("4096"), Ok(4096));
        assert_eq!(parse_offset("0x1000"), Ok(4096));
        assert_eq!(parse_offset("0X1000"), Ok(4096));
        assert_eq!(parse_offset("  0x1_0000 "), Ok(65536));
        assert_eq!(parse_offset("1_000"), Ok(1000));
    }

    #[test]
    fn parse_offset_rejects_garbage() {
        for bad in ["", "   ", "0x", "-1", "+1", "12g", "0xzz", "1.5", "0b101"] {
            assert!(parse_offset(bad).is_err(), "{bad} should not parse");
        }
    }

    #[test]
    fn parse_offset_rejects_overflow() {
        assert_eq!(parse_offset("0xffffffffffffffff"), Ok(u64::MAX));
        assert!(parse_offset("0x1_0000_0000_0000_0000").is_err());
    }

    #[test]
    fn unsigned_reads_follow_byte_order() {
        // 0x0102 big-endian is 258; the same bytes little-endian are 0x0201.
        let bytes = [0x01, 0x02];
        assert_eq!(
            read(ScalarType::U16, &bytes, Endian::Be),
            ScalarValue::U16(258)
        );
        assert_eq!(
            read(ScalarType::U16, &bytes, Endian::Le),
            ScalarValue::U16(513)
        );
    }

    #[test]
    fn signed_reads_sign_extend_at_each_width() {
        assert_eq!(
            read(ScalarType::I8, &[0xff], Endian::Le),
            ScalarValue::I8(-1)
        );
        assert_eq!(
            read(ScalarType::I16, &[0x00, 0x80], Endian::Le),
            ScalarValue::I16(-32768)
        );
        assert_eq!(
            read(ScalarType::I32, &[0xff, 0xff, 0xff, 0xff], Endian::Be),
            ScalarValue::I32(-1)
        );
        assert_eq!(
            read(ScalarType::I64, &[0, 0, 0, 0, 0, 0, 0, 0x80], Endian::Le),
            ScalarValue::I64(i64::MIN)
        );
    }

    #[test]
    fn float_reads_match_hand_built_bit_patterns() {
        // 1.5f64 is sign 0, exponent 0x3ff, mantissa 0x8000000000000.
        let one_point_five = 0x3ff8_0000_0000_0000u64.to_le_bytes();
        assert_eq!(
            read(ScalarType::F64, &one_point_five, Endian::Le),
            ScalarValue::F64(1.5)
        );
        // -2.0f32 is sign 1, exponent 0x80, mantissa 0.
        let minus_two = 0xc000_0000u32.to_be_bytes();
        assert_eq!(
            read(ScalarType::F32, &minus_two, Endian::Be),
            ScalarValue::F32(-2.0)
        );
    }

    #[test]
    fn hex_rendering_pads_to_the_type_width() {
        assert_eq!(ScalarValue::U32(1).hex(), "0x00000001");
        assert_eq!(ScalarValue::I16(-1).hex(), "0xffff");
        assert_eq!(ScalarValue::I64(-1).hex(), "0xffffffffffffffff");
        assert_eq!(ScalarValue::F64(1.5).hex(), "0x3ff8000000000000");
        assert_eq!(ScalarValue::F32(-2.0).hex(), "0xc0000000");
    }

    #[test]
    fn display_names_carry_a_suffix_only_for_wide_types() {
        assert_eq!(ScalarType::U8.display_name(Endian::Be), "u8");
        assert_eq!(ScalarType::F64.display_name(Endian::Be), "f64be");
    }
}