peakrdl-rust 0.2.1

Generate Rust register definitions from SystemRDL sources
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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
//! Types for numeric fixed-point field representations

use num_traits::{AsPrimitive, Float};

use crate::reg::RegInt;

/// A fixed-point number implementation using an underlying primitive integer type.
///
/// # Type Parameters
///
/// * `P` - The primitive integer type (signed or unsigned) used to store the fixed-point value
/// * `I` - The number of integer bits (can be negative for sub-integer representations)
/// * `F` - The number of fractional bits (can be negative for super-integer representations)
///
/// # Examples
///
/// Basic usage with different bit configurations:
///
/// ```
/// # use peakrdl_rust::fixedpoint::FixedPoint;
/// // 8-bit unsigned with 4 integer and 4 fractional bits
/// let fp = FixedPoint::<u8, 4, 4>::from_f64(2.25);
/// assert_eq!(fp.to_f64(), 2.25);
///
/// // 16-bit signed with 8 integer and 4 fractional bits
/// let fp = FixedPoint::<i16, 8, 4>::from_f64(-1.5);
/// assert_eq!(fp.to_bits(), -24);
/// ```
///
/// The total width is calculated as I + F:
///
/// ```
/// # use peakrdl_rust::fixedpoint::FixedPoint;
/// assert_eq!(FixedPoint::<u8, 8, 0>::width(), 8);
/// assert_eq!(FixedPoint::<i8, 7, -3>::width(), 4);
/// ```
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct FixedPoint<P, const I: isize, const F: isize> {
    val: P,
}

impl<P, const I: isize, const F: isize> core::fmt::Debug for FixedPoint<P, I, F>
where
    P: RegInt + AsPrimitive<f64>,
{
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        use core::fmt::Write as _;
        let mut name: heapless::String<32> = heapless::String::new();
        write!(&mut name, "FixedPoint<{I},{F}>")
            .expect("Fixedpoint type name should fit in small buffer");
        f.debug_struct(&name)
            .field("int", &self.val)
            .field("real", &self.to_f64())
            .finish()
    }
}

impl<P, const I: isize, const F: isize> FixedPoint<P, I, F>
where
    P: RegInt,
{
    /// Creates a fixed-point number from its raw bit representation.
    ///
    /// # Panics
    ///
    /// - (At compile time) If the primitive type P is not wide enough for the specified I + F bit width
    /// - (At compile time) If I + F is not positive
    /// - If the provided bits would overflow the fixed-point representation
    ///
    /// # Examples
    ///
    /// ```
    /// # use peakrdl_rust::fixedpoint::FixedPoint;
    /// let fp = FixedPoint::<u8, 4, 4>::from_bits(16); // represents 1.0
    /// assert_eq!(fp.to_f64(), 1.0);
    /// ```
    ///
    /// The following should not compile:
    ///
    /// ```compile_fail
    /// # use peakrdl_rust::fixedpoint::FixedPoint;
    /// FixedPoint::<u8, 5, 4>::from_bits(0); // u8 not large enough
    /// ```
    ///
    /// ```compile_fail
    /// # use peakrdl_rust::fixedpoint::FixedPoint;
    /// FixedPoint::<i8, -5, 4>::from_bits(0); // invalid negative width
    /// ```
    #[must_use]
    pub fn from_bits(bits: P) -> Self {
        const {
            assert!(
                I + F <= 8 * core::mem::size_of::<P>().cast_signed(),
                "The primitive integer type is not wide enough for this fixed-point representation"
            );
            assert!(I + F > 0, "The fixed-point bit width must be positive");
        }
        assert!(
            (bits <= Self::max_bits()) && (bits >= Self::min_bits()),
            "The provided bits overflow this fixed-point representation"
        );
        Self { val: bits }
    }

    /// Returns the raw bit representation of the fixed-point number.
    ///
    /// # Examples
    ///
    /// ```
    /// # use peakrdl_rust::fixedpoint::FixedPoint;
    /// let fp = FixedPoint::<u16, 8, 2>::from_f64(2.25);
    /// assert_eq!(fp.to_bits(), 9);
    /// ```
    #[must_use]
    pub const fn to_bits(self) -> P {
        self.val
    }

    /// Returns the number of integer bits.
    ///
    /// # Examples
    ///
    /// ```
    /// # use peakrdl_rust::fixedpoint::FixedPoint;
    /// assert_eq!(FixedPoint::<u8, 10, -4>::intwidth(), 10);
    /// ```
    #[must_use]
    pub const fn intwidth() -> isize {
        I
    }

    /// Returns the number of fractional bits.
    ///
    /// # Examples
    ///
    /// ```
    /// # use peakrdl_rust::fixedpoint::FixedPoint;
    /// assert_eq!(FixedPoint::<u8, 10, -4>::fracwidth(), -4);
    /// ```
    #[must_use]
    pub const fn fracwidth() -> isize {
        F
    }

    /// Returns the total bit width (I + F) of the fixed-point representation.
    ///
    /// # Examples
    ///
    /// ```
    /// # use peakrdl_rust::fixedpoint::FixedPoint;
    /// assert_eq!(FixedPoint::<u8, 8, 0>::width(), 8);
    /// assert_eq!(FixedPoint::<i8, 7, -3>::width(), 4);
    /// ```
    #[must_use]
    pub const fn width() -> usize {
        (I + F).cast_unsigned()
    }

    /// Returns true if the fixedpoint representation (underlying primitive type) is signed.
    ///
    /// # Examples
    ///
    /// ```
    /// # use peakrdl_rust::fixedpoint::FixedPoint;
    /// assert_eq!(FixedPoint::<u16, 8, 2>::is_signed(), false);
    /// assert_eq!(FixedPoint::<i16, 8, 2>::is_signed(), true);
    /// ```
    #[must_use]
    pub fn is_signed() -> bool {
        P::min_value() < P::zero()
    }

    /// Returns a fixed-point representation of zero.
    ///
    /// # Examples
    ///
    /// ```
    /// # use peakrdl_rust::fixedpoint::FixedPoint;
    /// let zero = FixedPoint::<u8, 4, 4>::zero();
    /// assert_eq!(zero.to_f64(), 0.0);
    /// ```
    #[must_use]
    pub fn zero() -> Self {
        Self::from_bits(P::zero())
    }

    #[must_use]
    fn max_bits() -> P {
        let unused_bits = core::mem::size_of::<P>() * 8 - Self::width();
        P::max_value().shr(unused_bits)
    }

    #[must_use]
    fn min_bits() -> P {
        let unused_bits = core::mem::size_of::<P>() * 8 - Self::width();
        P::min_value().shr(unused_bits)
    }

    /// Returns the maximum representable value for this fixed-point type.
    ///
    /// # Examples
    ///
    /// ```
    /// # use peakrdl_rust::fixedpoint::FixedPoint;
    /// assert_eq!(FixedPoint::<u8, 2, 6>::max_value().to_f32(), 3.984375);
    /// assert_eq!(FixedPoint::<i8, 3, 4>::max_value().to_f32(), 3.9375);
    /// ```
    #[must_use]
    pub fn max_value() -> Self {
        Self::from_bits(Self::max_bits())
    }

    /// Returns the minimum representable value for this fixed-point type.
    ///
    /// # Examples
    ///
    /// ```
    /// # use peakrdl_rust::fixedpoint::FixedPoint;
    /// assert_eq!(FixedPoint::<u8, 2, 6>::min_value().to_f32(), 0.0);
    /// assert_eq!(FixedPoint::<i8, 3, 4>::min_value().to_f32(), -4.0);
    /// ```
    #[must_use]
    pub fn min_value() -> Self {
        Self::from_bits(Self::min_bits())
    }

    /// Returns the smallest representable positive value (the resolution).
    ///
    /// # Examples
    ///
    /// ```
    /// # use peakrdl_rust::fixedpoint::FixedPoint;
    /// let res = FixedPoint::<u8, 4, 4>::resolution();
    /// assert_eq!(res.to_f64(), 0.0625); // 2^(-4)
    /// ```
    #[must_use]
    pub fn resolution() -> Self {
        Self::from_bits(P::one())
    }

    /// Quantizes a floating-point value to the resolution of this fixed-point type
    /// and returns it as a floating-point value.
    ///
    /// This is equivalent to converting to fixed-point and back to floating-point.
    ///
    /// # Examples
    ///
    /// ```
    /// # use peakrdl_rust::fixedpoint::FixedPoint;
    /// // 2.3 gets quantized to the nearest representable value
    /// let quantized = FixedPoint::<u8, 4, 4>::quantize(2.3);
    /// assert_eq!(quantized, 2.3125);
    /// ```
    pub fn quantize<T>(value: T) -> T
    where
        T: Float + 'static,
        P: AsPrimitive<T>,
    {
        Self::from_float(value).to_float()
    }

    /// Creates a fixed-point number from a 32-bit floating-point value.
    ///
    /// Values are rounded to the nearest representable fixed-point value.
    /// Ties are rounded away from 0.
    /// Out-of-range values are saturated to the min/max representable values.
    ///
    /// # Panics
    ///
    /// Panics if the input is NaN.
    ///
    /// # Examples
    ///
    /// ```
    /// # use peakrdl_rust::fixedpoint::FixedPoint;
    /// let fp = FixedPoint::<u8, 4, 4>::from_f32(1.5);
    /// assert_eq!(fp.to_bits(), 24);
    ///
    /// // saturation behavior
    /// let min_fp = FixedPoint::<i8, 4, 4>::from_f64(-100.0);
    /// assert_eq!(min_fp, FixedPoint::<i8, 4, 4>::min_value());
    /// ```
    #[must_use]
    pub fn from_f32(value: f32) -> Self
    where
        P: AsPrimitive<f32>,
    {
        Self::from_float(value)
    }

    /// Creates a fixed-point number from a 64-bit floating-point value.
    ///
    /// Values are rounded to the nearest representable fixed-point value.
    /// Ties are rounded away from 0.
    /// Out-of-range values are saturated to the min/max representable values.
    ///
    /// # Panics
    ///
    /// Panics if the input is NaN.
    ///
    /// # Examples
    ///
    /// ```
    /// # use peakrdl_rust::fixedpoint::FixedPoint;
    /// let fp = FixedPoint::<u16, 8, 2>::from_f64(2.25);
    /// assert_eq!(fp.to_bits(), 9);
    ///
    /// // Saturation behavior
    /// let max_fp = FixedPoint::<u8, 4, 4>::from_f64(100.0);
    /// assert_eq!(max_fp, FixedPoint::<u8, 4, 4>::max_value());
    /// ```
    #[must_use]
    pub fn from_f64(value: f64) -> Self
    where
        P: AsPrimitive<f64>,
    {
        Self::from_float(value)
    }

    #[must_use]
    fn from_float<T>(value: T) -> Self
    where
        T: Float + 'static,
        P: AsPrimitive<T>,
    {
        assert!(!value.is_nan(), "Can't convert NaN to FixedPoint");

        // scale
        #[allow(clippy::cast_possible_truncation)]
        let scale = T::from(2)
            .expect("two can be represented by any float type")
            .powi(F as i32);
        let scaled_value = value * scale;

        // saturate
        if scaled_value >= P::max_value().as_() {
            Self::from_bits(P::max_value())
        } else if scaled_value <= P::min_value().as_() {
            Self::from_bits(P::min_value())
        } else {
            // round
            Self::from_bits(
                P::from(scaled_value.round()).expect("shouldn't be NaN or out of range"),
            )
        }
    }

    /// Converts the fixed-point number to a 32-bit floating-point value.
    ///
    /// # Examples
    ///
    /// ```
    /// # use peakrdl_rust::fixedpoint::FixedPoint;
    /// assert_eq!(FixedPoint::<u16, 8, 2>::from_bits(8).to_f32(), 2.0);
    /// assert_eq!(FixedPoint::<u16, 8, 2>::from_bits(9).to_f32(), 2.25);
    /// assert_eq!(FixedPoint::<i16, 8, 4>::from_bits(-24).to_f32(), -1.5);
    /// assert_eq!(FixedPoint::<u8, 4, 4>::from_bits(1).to_f32(), 0.0625);
    /// assert_eq!(FixedPoint::<i8, 4, 4>::from_bits(-1).to_f32(), -0.0625);
    /// assert_eq!(FixedPoint::<u8, 4, 4>::from_bits(0).to_f32(), 0.0);
    /// ```
    #[must_use]
    pub fn to_f32(self) -> f32
    where
        P: AsPrimitive<f32>,
    {
        self.to_float()
    }

    /// Converts the fixed-point number to a 64-bit floating-point value.
    ///
    /// # Examples
    ///
    /// ```
    /// # use peakrdl_rust::fixedpoint::FixedPoint;
    /// assert_eq!(FixedPoint::<u16, 8, 2>::from_bits(8).to_f64(), 2.0);
    /// assert_eq!(FixedPoint::<u16, 8, 2>::from_bits(9).to_f64(), 2.25);
    /// assert_eq!(FixedPoint::<i16, 8, 4>::from_bits(-24).to_f64(), -1.5);
    /// assert_eq!(FixedPoint::<u8, 4, 4>::from_bits(1).to_f64(), 0.0625);
    /// assert_eq!(FixedPoint::<i8, 4, 4>::from_bits(-1).to_f64(), -0.0625);
    /// assert_eq!(FixedPoint::<u8, 4, 4>::from_bits(0).to_f64(), 0.0);
    /// ```
    #[must_use]
    pub fn to_f64(self) -> f64
    where
        P: AsPrimitive<f64>,
    {
        self.to_float()
    }

    #[must_use]
    fn to_float<T>(self) -> T
    where
        T: Float + 'static,
        P: AsPrimitive<T>,
    {
        #[allow(clippy::cast_possible_truncation)]
        let scale = T::from(2)
            .expect("two can be represented by any float type")
            .powi(-F as i32);
        self.val.as_() * scale
    }
}

/// Automatic conversion from floating-point types to fixed-point.
///
/// This provides convenient syntax for creating fixed-point numbers from floats.
/// Note that this is a lossy conversion that will never fail (unless NaN). Saturation
/// and rounding are applied.
///
/// # Panics
///
/// Panics if the value is NaN.
///
/// # Examples
///
/// ```
/// # use peakrdl_rust::fixedpoint::FixedPoint;
/// let fp: FixedPoint<u8, 4, 4> = 2.5.into();
/// assert_eq!(fp.to_f64(), 2.5);
/// ```
impl<T, P, const I: isize, const F: isize> From<T> for FixedPoint<P, I, F>
where
    T: Float + 'static,
    P: RegInt + AsPrimitive<T>,
{
    fn from(value: T) -> Self {
        Self::from_float(value)
    }
}

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

    #[test]
    fn test_from_float() {
        assert_eq!(FixedPoint::<u16, 8, 2>::from_float(2.25).to_bits(), 9);
        assert_eq!(FixedPoint::<i16, 8, 4>::from_float(-1.5).to_bits(), -24);
        assert_eq!(FixedPoint::<u8, 4, 4>::from_float(0.0625).to_bits(), 1);

        // Test rounding
        assert_eq!(FixedPoint::<u8, 4, 4>::from_float(0.03124).to_bits(), 0); // rounds down
        assert_eq!(FixedPoint::<u8, 4, 4>::from_float(0.03125).to_bits(), 1); // rounds ties away from 0
        assert_eq!(FixedPoint::<u8, 4, 4>::from_float(0.03126).to_bits(), 1); // rounds up
        assert_eq!(FixedPoint::<i8, 4, 4>::from_float(-0.03124).to_bits(), 0); // rounds up
        assert_eq!(FixedPoint::<i8, 4, 4>::from_float(-0.03125).to_bits(), -1); // rounds ties away from 0
        assert_eq!(FixedPoint::<i8, 4, 4>::from_float(-0.03126).to_bits(), -1); // rounds down

        // Test saturation - positive overflow
        assert_eq!(
            FixedPoint::<u8, 4, 4>::from_float(100.0),
            FixedPoint::<u8, 4, 4>::max_value()
        );
        assert_eq!(
            FixedPoint::<i8, 4, 4>::from_float(100.0),
            FixedPoint::<i8, 4, 4>::max_value()
        );

        // Test saturation - negative overflow
        assert_eq!(
            FixedPoint::<u8, 4, 4>::from_float(-100.0),
            FixedPoint::<u8, 4, 4>::min_value()
        );
        assert_eq!(
            FixedPoint::<i8, 4, 4>::from_float(-100.0),
            FixedPoint::<i8, 4, 4>::min_value()
        );
    }

    #[test]
    #[should_panic(expected = "Can't convert NaN to FixedPoint")]
    fn test_from_float_nan_panic() {
        let _ = FixedPoint::<u8, 4, 4>::from_float(f64::NAN);
    }

    #[test]
    #[should_panic(expected = "The provided bits overflow this fixed-point representation")]
    fn test_positive_overflow1() {
        let _ = FixedPoint::<u8, 2, 4>::from_bits(64);
    }

    #[test]
    #[should_panic(expected = "The provided bits overflow this fixed-point representation")]
    fn test_negative_overflow() {
        let _ = FixedPoint::<i8, 2, 4>::from_bits(-33);
    }
}