gba 0.15.0

A crate for 'raw' style GBA development. If you want a 'managed' experience, try the `agb` crate instead.
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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
use core::ops::*;

/// `i16` with 8 bits of fixed-point fraction.
///
/// This is used by the affine matrix entries.
///
/// * This build of the docs does not use the `fixed` feature and uses the
///   crate's internal fixed point type.
#[allow(non_camel_case_types)]
#[cfg(not(feature = "fixed"))]
pub type i16fx8 = Fixed<i16, 8>;

/// `i16` with 14 bits of fixed-point fraction.
///
/// This is used by the [`ArcTan`](crate::bios::ArcTan) and
/// [`ArcTan2`](crate::bios::ArcTan2) BIOS functions.
///
/// * This build of the docs does not use the `fixed` feature and uses the
///   crate's internal fixed point type.
#[allow(non_camel_case_types)]
#[cfg(not(feature = "fixed"))]
pub type i16fx14 = Fixed<i16, 14>;

/// `i32` with 8 bits of fixed-point fraction.
///
/// This is used by the background reference point entries.
///
/// * This build of the docs does not use the `fixed` feature and uses the
///   crate's internal fixed point type.
#[allow(non_camel_case_types)]
#[cfg(not(feature = "fixed"))]
pub type i32fx8 = Fixed<i32, 8>;

/// `i16` with 8 bits of fixed-point fraction.
///
/// This is used by the affine matrix entries.
///
/// * This build of the docs uses the `fixed` feature and uses the fixed point
///   type from the `fixed` crate.
#[allow(non_camel_case_types)]
#[cfg(feature = "fixed")]
pub type i16fx8 = ::fixed::FixedI32<::fixed::types::extra::U8>;

/// `i16` with 14 bits of fixed-point fraction.
///
/// This is used by the [`ArcTan`](crate::bios::ArcTan) and
/// [`ArcTan2`](crate::bios::ArcTan2) BIOS functions.
///
/// * This build of the docs uses the `fixed` feature and uses the fixed point
///   type from the `fixed` crate.
#[allow(non_camel_case_types)]
#[cfg(feature = "fixed")]
pub type i16fx14 = ::fixed::FixedI16<::fixed::types::extra::U14>;

/// `i32` with 8 bits of fixed-point fraction.
///
/// This is used by the background reference point entries.
///
/// * This build of the docs uses the `fixed` feature and uses the fixed point
///   type from the `fixed` crate.
#[allow(non_camel_case_types)]
#[cfg(feature = "fixed")]
pub type i32fx8 = ::fixed::FixedI32<::fixed::types::extra::U8>;

/// A [fixed-point][wp-fp] number. This transparently wraps an integer with a
/// const generic for how many bits are fractional.
///
/// [wp-fp]: https://en.wikipedia.org/wiki/Fixed-point_arithmetic
///
/// * This type is generic, but the `I` type is intended to be a signed or
///   unsigned integer of a fixed bit size: `i8`, `i16`, `i32`, `u8`, `u16`, or
///   `u32`. This type is *not* semver supported to work with any other `I`
///   type. If it does work for other types of `I`, that's on accident.
/// * The `B` value is the number of bits that form the fractional part. It
///   should be *less than* the number of bits in the integer's type. Multiply
///   and divide ops need to shift the value by `B`, and so if `B` is greater
///   than or equal to the integer's size the op will panic.
#[derive(Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[repr(transparent)]
pub struct Fixed<I, const B: u32>(I);

macro_rules! impl_trait_op_unit {
  ($t:ty, $trait:ident, $op:ident) => {
    impl<const B: u32> $trait for Fixed<$t, B> {
      type Output = Self;
      #[inline]
      #[must_use]
      #[cfg_attr(feature = "track_caller", track_caller)]
      fn $op(self) -> Self::Output {
        Self::$op(self)
      }
    }
  };
}
macro_rules! impl_trait_op_self_rhs {
  ($t:ty, $trait:ident, $op:ident) => {
    impl<const B: u32> $trait for Fixed<$t, B> {
      type Output = Self;
      #[inline]
      #[must_use]
      #[cfg_attr(feature = "track_caller", track_caller)]
      fn $op(self, rhs: Self) -> Self::Output {
        Self::$op(self, rhs)
      }
    }
  };
}
macro_rules! impl_trait_op_assign_self_rhs {
  ($t:ty, $trait:ident, $op:ident, $op_assign:ident) => {
    impl<const B: u32> $trait for Fixed<$t, B> {
      #[inline]
      #[cfg_attr(feature = "track_caller", track_caller)]
      fn $op_assign(&mut self, rhs: Self) {
        *self = self.$op(rhs);
      }
    }
  };
}
macro_rules! impl_shift_self_u32 {
  ($t:ty, $trait:ident, $op:ident) => {
    impl<const B: u32> $trait<u32> for Fixed<$t, B> {
      type Output = Self;
      #[inline]
      #[must_use]
      #[cfg_attr(feature = "track_caller", track_caller)]
      fn $op(self, rhs: u32) -> Self::Output {
        Self::$op(self, rhs)
      }
    }
  };
}
macro_rules! impl_shift_assign_self_u32 {
  ($t:ty, $trait:ident, $op:ident, $op_assign:ident) => {
    impl<const B: u32> $trait<u32> for Fixed<$t, B> {
      #[inline]
      #[cfg_attr(feature = "track_caller", track_caller)]
      fn $op_assign(&mut self, rhs: u32) {
        *self = self.$op(rhs);
      }
    }
  };
}

macro_rules! impl_common_fixed_ops {
  ($t:ty) => {
    impl<const B: u32> Fixed<$t, B> {
      /// Shifts the value left by `B`, wrapping it into the range of this Fixed
      /// type.
      #[inline]
      #[must_use]
      #[cfg_attr(feature = "track_caller", track_caller)]
      pub const fn wrapping_from(i: $t) -> Self {
        Self(i << B)
      }

      /// Makes a `Fixed` directly from a raw inner value (no shift).
      #[inline]
      #[must_use]
      #[cfg_attr(feature = "track_caller", track_caller)]
      pub const fn from_bits(i: $t) -> Self {
        Self(i)
      }

      /// Unwraps the inner value directly into the base type (no shift).
      #[inline]
      #[must_use]
      #[cfg_attr(feature = "track_caller", track_caller)]
      pub const fn to_bits(self) -> $t {
        self.0
      }

      /// Bitwise Not.
      #[inline]
      #[must_use]
      #[cfg_attr(feature = "track_caller", track_caller)]
      pub const fn not(self) -> Self {
        Self(!self.0)
      }

      /// Addition.
      #[inline]
      #[must_use]
      #[cfg_attr(feature = "track_caller", track_caller)]
      pub const fn add(self, rhs: Self) -> Self {
        Self(self.0 + rhs.0)
      }

      /// Subtraction.
      #[inline]
      #[must_use]
      #[cfg_attr(feature = "track_caller", track_caller)]
      pub const fn sub(self, rhs: Self) -> Self {
        Self(self.0 - rhs.0)
      }

      /// Remainder.
      #[inline]
      #[must_use]
      #[cfg_attr(feature = "track_caller", track_caller)]
      pub const fn rem(self, rhs: Self) -> Self {
        Self(self.0 % rhs.0)
      }

      /// Bitwise AND.
      #[inline]
      #[must_use]
      #[cfg_attr(feature = "track_caller", track_caller)]
      pub const fn bitand(self, rhs: Self) -> Self {
        Self(self.0 & rhs.0)
      }

      /// Bitwise OR.
      #[inline]
      #[must_use]
      #[cfg_attr(feature = "track_caller", track_caller)]
      pub const fn bitor(self, rhs: Self) -> Self {
        Self(self.0 | rhs.0)
      }

      /// Bitwise XOR.
      #[inline]
      #[must_use]
      #[cfg_attr(feature = "track_caller", track_caller)]
      pub const fn bitxor(self, rhs: Self) -> Self {
        Self(self.0 ^ rhs.0)
      }

      /// Bit-shift Left.
      #[inline]
      #[must_use]
      #[cfg_attr(feature = "track_caller", track_caller)]
      pub const fn shl(self, rhs: u32) -> Self {
        Self(self.0 << rhs)
      }

      /// Bit-shift Right.
      #[inline]
      #[must_use]
      #[cfg_attr(feature = "track_caller", track_caller)]
      pub const fn shr(self, rhs: u32) -> Self {
        Self(self.0 >> rhs)
      }
    }

    impl<const B: u32> core::fmt::Debug for Fixed<$t, B> {
      fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
        let raw: $t = self.to_bits();
        write!(
          f,
          concat!(
            "Fixed::<",
            stringify!($t),
            ",{}>::from_bits({:#x}_u32 as ",
            stringify!($t),
            ")"
          ),
          B, raw
        )
      }
    }

    impl_trait_op_unit!($t, Not, not);
    impl_trait_op_self_rhs!($t, Add, add);
    impl_trait_op_self_rhs!($t, Sub, sub);
    impl_trait_op_self_rhs!($t, Mul, mul);
    impl_trait_op_self_rhs!($t, Div, div);
    impl_trait_op_self_rhs!($t, Rem, rem);
    impl_trait_op_self_rhs!($t, BitAnd, bitand);
    impl_trait_op_self_rhs!($t, BitOr, bitor);
    impl_trait_op_self_rhs!($t, BitXor, bitxor);
    impl_shift_self_u32!($t, Shl, shl);
    impl_shift_self_u32!($t, Shr, shr);
    impl_trait_op_assign_self_rhs!($t, AddAssign, add, add_assign);
    impl_trait_op_assign_self_rhs!($t, SubAssign, sub, sub_assign);
    impl_trait_op_assign_self_rhs!($t, MulAssign, mul, mul_assign);
    impl_trait_op_assign_self_rhs!($t, DivAssign, div, div_assign);
    impl_trait_op_assign_self_rhs!($t, RemAssign, rem, rem_assign);
    impl_trait_op_assign_self_rhs!($t, BitAndAssign, bitand, bitand_assign);
    impl_trait_op_assign_self_rhs!($t, BitOrAssign, bitor, bitor_assign);
    impl_trait_op_assign_self_rhs!($t, BitXorAssign, bitxor, bitxor_assign);
    impl_shift_assign_self_u32!($t, ShlAssign, shl, shl_assign);
    impl_shift_assign_self_u32!($t, ShrAssign, shr, shr_assign);
  };
}
impl_common_fixed_ops!(i8);
impl_common_fixed_ops!(i16);
impl_common_fixed_ops!(i32);
impl_common_fixed_ops!(u8);
impl_common_fixed_ops!(u16);
impl_common_fixed_ops!(u32);

macro_rules! impl_signed_fixed_ops {
  ($t:ty, $unsigned:ty) => {
    impl<const B: u32> Fixed<$t, B> {
      /// Absolute value.
      #[inline]
      #[must_use]
      #[cfg_attr(feature = "track_caller", track_caller)]
      pub const fn abs(self) -> Self {
        Self(self.0.abs())
      }

      /// Negate.
      #[inline]
      #[must_use]
      #[cfg_attr(feature = "track_caller", track_caller)]
      pub const fn neg(self) -> Self {
        Self(-self.0)
      }

      /// If the number is negative or not.
      #[inline]
      #[must_use]
      #[cfg_attr(feature = "track_caller", track_caller)]
      pub const fn is_negative(self) -> bool {
        self.0 < 0
      }

      /// Multiply.
      #[inline]
      #[must_use]
      #[cfg_attr(feature = "track_caller", track_caller)]
      pub const fn mul(self, rhs: Self) -> Self {
        let raw = (self.0 as i32) * (rhs.0 as i32);
        Self((raw >> B) as $t)
      }

      /// Divide.
      #[inline]
      #[must_use]
      #[cfg_attr(feature = "track_caller", track_caller)]
      pub const fn div(self, rhs: Self) -> Self {
        let m = (self.0 as i32) * (1 << B);
        let d = m / (rhs.0 as i32);
        Self(d as $t)
      }

      /// Fractional part of the value.
      #[inline]
      #[must_use]
      #[cfg_attr(feature = "track_caller", track_caller)]
      pub const fn fract(self) -> Self {
        let frac_mask = (<$unsigned>::MAX >> (<$t>::BITS - B));
        Self((self.0.unsigned_abs() & frac_mask) as $t)
      }

      /// Whole part of the value.
      #[inline]
      #[must_use]
      #[cfg_attr(feature = "track_caller", track_caller)]
      pub const fn trunc(self) -> Self {
        Self(((self.0.unsigned_abs() >> B) << B) as $t)
      }
    }
    impl_trait_op_unit!($t, Neg, neg);

    impl<const B: u32> core::fmt::Display for Fixed<$t, B> {
      fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
        let neg = self.to_bits() < 0;
        fixed_fmt_abs::<B>(f, self.to_bits().abs() as u32, neg)
      }
    }
  };
}
impl_signed_fixed_ops!(i8, u8);
impl_signed_fixed_ops!(i16, u16);
impl_signed_fixed_ops!(i32, u32);

macro_rules! impl_unsigned_fixed_ops {
  ($t:ty) => {
    impl<const B: u32> Fixed<$t, B> {
      /// Multiply.
      #[inline]
      #[must_use]
      #[cfg_attr(feature = "track_caller", track_caller)]
      pub const fn mul(self, rhs: Self) -> Self {
        let raw = (self.0 as u32) * (rhs.0 as u32);
        Self((raw >> B) as $t)
      }

      /// Divide.
      #[inline]
      #[must_use]
      #[cfg_attr(feature = "track_caller", track_caller)]
      pub const fn div(self, rhs: Self) -> Self {
        let m = (self.0 as u32) * (1 << B);
        let d = m / (rhs.0 as u32);
        Self(d as $t)
      }

      /// Fractional part of the value.
      #[inline]
      #[must_use]
      #[cfg_attr(feature = "track_caller", track_caller)]
      pub const fn fract(self) -> Self {
        Self(self.0 & (<$t>::MAX >> (<$t>::BITS - B)))
      }

      /// Whole part of the value.
      #[inline]
      #[must_use]
      #[cfg_attr(feature = "track_caller", track_caller)]
      pub const fn trunc(self) -> Self {
        Self(self.0 & (<$t>::MAX << B))
      }
    }

    impl<const B: u32> core::fmt::Display for Fixed<$t, B> {
      fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
        fixed_fmt_abs::<B>(f, self.to_bits() as u32, false)
      }
    }
  };
}
impl_unsigned_fixed_ops!(u8);
impl_unsigned_fixed_ops!(u16);
impl_unsigned_fixed_ops!(u32);

fn fixed_fmt_abs<const B: u32>(
  f: &mut core::fmt::Formatter, abs: u32, neg: bool,
) -> core::fmt::Result {
  let precision = f.precision().unwrap_or(const { ((B as usize) + 1) / 3 });
  let width = f.width().unwrap_or(0).saturating_sub(precision + 1);
  let fract = abs & ((1 << B) - 1);
  let fract_dec = 10u32
    .checked_pow(precision as u32)
    .and_then(|digits| fract.checked_mul(digits))
    .map(|x| (x >> B) as u64)
    .unwrap_or_else(|| (fract as u64 * 10u64.pow(precision as u32) >> B));
  let mut ones = (abs >> B) as i32;
  if neg {
    if ones != 0 {
      ones = ones.neg()
    } else {
      let width = width.saturating_sub(2);
      return write!(f, "{:width$}-0.{fract_dec:0precision$}", "");
    }
  }
  write!(f, "{ones:width$}.{fract_dec:0precision$}")
}

#[cfg(test)]
mod test {
  use crate::fixed::{i16fx14, i32fx8};
  use core::{fmt::Write, str};

  struct WriteBuf<const N: usize>([u8; N], usize);
  impl<'a, const N: usize> Default for WriteBuf<N> {
    fn default() -> Self {
      Self([0u8; N], 0)
    }
  }
  impl<const N: usize> Write for WriteBuf<N> {
    fn write_str(&mut self, s: &str) -> core::fmt::Result {
      let src = s.as_bytes();
      let len = (self.0.len() - self.1).min(src.len());
      self.0[self.1..self.1 + len].copy_from_slice(&src[..len]);
      self.1 += len;
      if len < src.len() {
        Err(core::fmt::Error)
      } else {
        Ok(())
      }
    }
  }
  impl<const N: usize> WriteBuf<N> {
    fn take(&mut self) -> &str {
      let len = self.1;
      self.1 = 0;
      str::from_utf8(&self.0[..len]).unwrap()
    }
  }

  #[test_case]
  fn decimal_display() {
    let mut wbuf = WriteBuf::<16>::default();

    let x = i32fx8::from_bits(0x12345678);

    write!(&mut wbuf, "{x}").unwrap();
    assert_eq!(wbuf.take(), "1193046.468");

    write!(&mut wbuf, "{x:11.1}").unwrap();
    assert_eq!(wbuf.take(), "  1193046.4");

    write!(&mut wbuf, "{x:1.6}").unwrap();
    assert_eq!(wbuf.take(), "1193046.468750");

    let x = x.neg();
    write!(&mut wbuf, "{x}").unwrap();
    assert_eq!(wbuf.take(), "-1193046.468");

    let x = i16fx14::from_bits(0x6544 as i16);
    write!(&mut wbuf, "{x}").unwrap();
    assert_eq!(wbuf.take(), "1.58227");

    let x = x.neg();
    write!(&mut wbuf, "{x:.10}").unwrap();
    assert_eq!(wbuf.take(), "-1.5822753906");

    write!(&mut wbuf, "{x:9.1}").unwrap();
    assert_eq!(wbuf.take(), "     -1.5");

    let x = x.add(i16fx14::wrapping_from(1));
    write!(&mut wbuf, "{x:9.2}").unwrap();
    assert_eq!(wbuf.take(), "    -0.58");
  }
}