simple_endian 0.4.10

A create for defining endianness within your data structures, to make handling portable data structures simpler.
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
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
//! Fixed-size UTF-32 code-unit storage and common conventions.

extern crate alloc;

use alloc::string::String;
use core::fmt;

use crate::{
    BigEndian, LittleEndian, SpecificEndian, SpecificEndianOwned, Utf32StrBE, Utf32StrLE,
    Utf32StringBE, Utf32StringLE,
};

/// Errors for fixed UTF-32 code-unit storage.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum FixedUtf32Error {
    /// Input had the wrong number of UTF-32 code units.
    WrongCodeUnitCount { expected: usize, found: usize },
    /// Input code units are not valid Unicode scalar values.
    InvalidUtf32,
}

impl fmt::Display for FixedUtf32Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            FixedUtf32Error::WrongCodeUnitCount { expected, found } => write!(
                f,
                "wrong number of UTF-32 code units (expected {expected}, found {found})"
            ),
            FixedUtf32Error::InvalidUtf32 => write!(f, "invalid UTF-32"),
        }
    }
}

#[cfg(any(feature = "io-std", feature = "io"))]
impl std::error::Error for FixedUtf32Error {}

/// Inline, fixed-size UTF-32 code units stored with explicit endianness.
///
/// This is the endian-parameterized core type. For the host-endian convenience
/// alias, see [`FixedUtf32CodeUnits`].
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
pub struct FixedUtf32CodeUnitsEndian<E, const N: usize> {
    pub(crate) units: [E; N],
}

/// A borrowed reference to exactly `N` UTF-32 code units stored with explicit endianness.
#[repr(transparent)]
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
pub struct FixedUtf32CodeUnitsRefEndian<'a, E, const N: usize>(pub &'a [E; N]);

/// Host-endian fixed UTF-32 code units.
#[cfg(target_endian = "little")]
pub type FixedUtf32CodeUnits<const N: usize> = FixedUtf32LeCodeUnits<N>;
/// Host-endian fixed UTF-32 code units.
#[cfg(target_endian = "big")]
pub type FixedUtf32CodeUnits<const N: usize> = FixedUtf32BeCodeUnits<N>;

/// A borrowed reference to exactly `N` host-endian UTF-32 code units.
#[cfg(target_endian = "little")]
pub type FixedUtf32CodeUnitsRef<'a, const N: usize> = FixedUtf32LeCodeUnitsRef<'a, N>;
/// A borrowed reference to exactly `N` host-endian UTF-32 code units.
#[cfg(target_endian = "big")]
pub type FixedUtf32CodeUnitsRef<'a, const N: usize> = FixedUtf32BeCodeUnitsRef<'a, N>;

pub type FixedUtf32LeCodeUnits<const N: usize> = FixedUtf32CodeUnitsEndian<LittleEndian<u32>, N>;
pub type FixedUtf32BeCodeUnits<const N: usize> = FixedUtf32CodeUnitsEndian<BigEndian<u32>, N>;

pub type FixedUtf32LeCodeUnitsRef<'a, const N: usize> =
    FixedUtf32CodeUnitsRefEndian<'a, LittleEndian<u32>, N>;
pub type FixedUtf32BeCodeUnitsRef<'a, const N: usize> =
    FixedUtf32CodeUnitsRefEndian<'a, BigEndian<u32>, N>;

impl<E, const N: usize> FixedUtf32CodeUnitsEndian<E, N> {
    pub const fn as_units(&self) -> &[E; N] {
        &self.units
    }
}

impl<'a, E, const N: usize> FixedUtf32CodeUnitsRefEndian<'a, E, N> {
    pub const fn as_units(&self) -> &'a [E; N] {
        self.0
    }
}

impl<E, const N: usize> From<[E; N]> for FixedUtf32CodeUnitsEndian<E, N> {
    fn from(units: [E; N]) -> Self {
        Self { units }
    }
}

impl<'a, E, const N: usize> From<&'a [E; N]> for FixedUtf32CodeUnitsRefEndian<'a, E, N> {
    fn from(v: &'a [E; N]) -> Self {
        Self(v)
    }
}

impl<const N: usize> TryFrom<&[u32]> for FixedUtf32LeCodeUnits<N> {
    type Error = FixedUtf32Error;

    fn try_from(v: &[u32]) -> Result<Self, Self::Error> {
        if v.len() != N {
            return Err(FixedUtf32Error::WrongCodeUnitCount {
                expected: N,
                found: v.len(),
            });
        }
        let mut units = [LittleEndian::from_bits(0u32); N];
        for (dst, src) in units.iter_mut().zip(v.iter().copied()) {
            *dst = LittleEndian::from_bits(src);
        }
        Ok(Self { units })
    }
}

impl<const N: usize> TryFrom<&[u32]> for FixedUtf32BeCodeUnits<N> {
    type Error = FixedUtf32Error;

    fn try_from(v: &[u32]) -> Result<Self, Self::Error> {
        if v.len() != N {
            return Err(FixedUtf32Error::WrongCodeUnitCount {
                expected: N,
                found: v.len(),
            });
        }
        let mut units = [BigEndian::from_bits(0u32); N];
        for (dst, src) in units.iter_mut().zip(v.iter().copied()) {
            *dst = BigEndian::from_bits(src);
        }
        Ok(Self { units })
    }
}

impl<const N: usize> TryFrom<&[LittleEndian<u32>]> for FixedUtf32LeCodeUnits<N> {
    type Error = FixedUtf32Error;

    fn try_from(v: &[LittleEndian<u32>]) -> Result<Self, Self::Error> {
        if v.len() != N {
            return Err(FixedUtf32Error::WrongCodeUnitCount {
                expected: N,
                found: v.len(),
            });
        }
        let mut units = [LittleEndian::from_bits(0u32); N];
        units.copy_from_slice(v);
        Ok(Self { units })
    }
}

impl<const N: usize> TryFrom<&[BigEndian<u32>]> for FixedUtf32BeCodeUnits<N> {
    type Error = FixedUtf32Error;

    fn try_from(v: &[BigEndian<u32>]) -> Result<Self, Self::Error> {
        if v.len() != N {
            return Err(FixedUtf32Error::WrongCodeUnitCount {
                expected: N,
                found: v.len(),
            });
        }
        let mut units = [BigEndian::from_bits(0u32); N];
        units.copy_from_slice(v);
        Ok(Self { units })
    }
}

impl<const N: usize> TryFrom<&str> for FixedUtf32LeCodeUnits<N> {
    type Error = FixedUtf32Error;

    fn try_from(s: &str) -> Result<Self, Self::Error> {
        let mut it = s.chars();
        let mut units = [LittleEndian::from_bits(0u32); N];

        for (idx, dst) in units.iter_mut().enumerate() {
            match it.next() {
                Some(ch) => *dst = LittleEndian::from_bits(ch as u32),
                None => {
                    return Err(FixedUtf32Error::WrongCodeUnitCount {
                        expected: N,
                        found: idx,
                    });
                }
            }
        }

        if let Some(_) = it.next() {
            return Err(FixedUtf32Error::WrongCodeUnitCount {
                expected: N,
                found: N + 1,
            });
        }

        Ok(Self { units })
    }
}

impl<const N: usize> TryFrom<&str> for FixedUtf32BeCodeUnits<N> {
    type Error = FixedUtf32Error;

    fn try_from(s: &str) -> Result<Self, Self::Error> {
        let mut it = s.chars();
        let mut units = [BigEndian::from_bits(0u32); N];

        for (idx, dst) in units.iter_mut().enumerate() {
            match it.next() {
                Some(ch) => *dst = BigEndian::from_bits(ch as u32),
                None => {
                    return Err(FixedUtf32Error::WrongCodeUnitCount {
                        expected: N,
                        found: idx,
                    });
                }
            }
        }

        if let Some(_) = it.next() {
            return Err(FixedUtf32Error::WrongCodeUnitCount {
                expected: N,
                found: N + 1,
            });
        }

        Ok(Self { units })
    }
}

impl<const N: usize> TryFrom<String> for FixedUtf32LeCodeUnits<N> {
    type Error = FixedUtf32Error;

    fn try_from(s: String) -> Result<Self, Self::Error> {
        Self::try_from(s.as_str())
    }
}

impl<const N: usize> TryFrom<String> for FixedUtf32BeCodeUnits<N> {
    type Error = FixedUtf32Error;

    fn try_from(s: String) -> Result<Self, Self::Error> {
        Self::try_from(s.as_str())
    }
}

impl<const N: usize> TryFrom<Utf32StringLE> for FixedUtf32LeCodeUnits<N> {
    type Error = FixedUtf32Error;

    fn try_from(v: Utf32StringLE) -> Result<Self, Self::Error> {
        Self::try_from(v.0.as_slice())
    }
}

impl<const N: usize> TryFrom<Utf32StringBE> for FixedUtf32BeCodeUnits<N> {
    type Error = FixedUtf32Error;

    fn try_from(v: Utf32StringBE) -> Result<Self, Self::Error> {
        Self::try_from(v.0.as_slice())
    }
}

impl<const N: usize> TryFrom<&FixedUtf32LeCodeUnits<N>> for String {
    type Error = FixedUtf32Error;

    fn try_from(v: &FixedUtf32LeCodeUnits<N>) -> Result<Self, Self::Error> {
        let mut out = String::new();
        for cu in v.units.iter().map(|x| x.to_native()) {
            match char::from_u32(cu) {
                Some(c) => out.push(c),
                None => return Err(FixedUtf32Error::InvalidUtf32),
            }
        }
        Ok(out)
    }
}

impl<const N: usize> TryFrom<&FixedUtf32BeCodeUnits<N>> for String {
    type Error = FixedUtf32Error;

    fn try_from(v: &FixedUtf32BeCodeUnits<N>) -> Result<Self, Self::Error> {
        let mut out = String::new();
        for cu in v.units.iter().map(|x| x.to_native()) {
            match char::from_u32(cu) {
                Some(c) => out.push(c),
                None => return Err(FixedUtf32Error::InvalidUtf32),
            }
        }
        Ok(out)
    }
}

impl<const N: usize> fmt::Display for FixedUtf32LeCodeUnits<N> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match String::try_from(self) {
            Ok(s) => write!(f, "{s}"),
            Err(_) => write!(f, "<invalid UTF-32>"),
        }
    }
}

impl<const N: usize> fmt::Display for FixedUtf32BeCodeUnits<N> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match String::try_from(self) {
            Ok(s) => write!(f, "{s}"),
            Err(_) => write!(f, "<invalid UTF-32>"),
        }
    }
}

/// Fixed UTF-32LE code units interpreted as a *packed* string.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
pub struct FixedUtf32LePacked<const N: usize>(pub FixedUtf32LeCodeUnits<N>);

/// Fixed UTF-32BE code units interpreted as a *packed* string.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
pub struct FixedUtf32BePacked<const N: usize>(pub FixedUtf32BeCodeUnits<N>);

/// Fixed UTF-32LE code units interpreted as a *NUL-padded* string.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
pub struct FixedUtf32LeNullPadded<const N: usize>(pub FixedUtf32LeCodeUnits<N>);

/// Fixed UTF-32BE code units interpreted as a *NUL-padded* string.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
pub struct FixedUtf32BeNullPadded<const N: usize>(pub FixedUtf32BeCodeUnits<N>);

/// Fixed UTF-32LE code units interpreted as a *space-padded* string.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
pub struct FixedUtf32LeSpacePadded<const N: usize>(pub FixedUtf32LeCodeUnits<N>);

/// Fixed UTF-32BE code units interpreted as a *space-padded* string.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
pub struct FixedUtf32BeSpacePadded<const N: usize>(pub FixedUtf32BeCodeUnits<N>);

impl<const N: usize> From<FixedUtf32LeCodeUnits<N>> for FixedUtf32LePacked<N> {
    fn from(v: FixedUtf32LeCodeUnits<N>) -> Self {
        Self(v)
    }
}

impl<const N: usize> From<FixedUtf32BeCodeUnits<N>> for FixedUtf32BePacked<N> {
    fn from(v: FixedUtf32BeCodeUnits<N>) -> Self {
        Self(v)
    }
}

impl<const N: usize> From<FixedUtf32LeCodeUnits<N>> for FixedUtf32LeNullPadded<N> {
    fn from(v: FixedUtf32LeCodeUnits<N>) -> Self {
        Self(v)
    }
}

impl<const N: usize> From<FixedUtf32BeCodeUnits<N>> for FixedUtf32BeNullPadded<N> {
    fn from(v: FixedUtf32BeCodeUnits<N>) -> Self {
        Self(v)
    }
}

impl<const N: usize> From<FixedUtf32LeCodeUnits<N>> for FixedUtf32LeSpacePadded<N> {
    fn from(v: FixedUtf32LeCodeUnits<N>) -> Self {
        Self(v)
    }
}

impl<const N: usize> From<FixedUtf32BeCodeUnits<N>> for FixedUtf32BeSpacePadded<N> {
    fn from(v: FixedUtf32BeCodeUnits<N>) -> Self {
        Self(v)
    }
}

impl<const N: usize> From<FixedUtf32LePacked<N>> for FixedUtf32LeCodeUnits<N> {
    fn from(v: FixedUtf32LePacked<N>) -> Self {
        v.0
    }
}

impl<const N: usize> From<FixedUtf32BePacked<N>> for FixedUtf32BeCodeUnits<N> {
    fn from(v: FixedUtf32BePacked<N>) -> Self {
        v.0
    }
}

impl<const N: usize> From<FixedUtf32LeNullPadded<N>> for FixedUtf32LeCodeUnits<N> {
    fn from(v: FixedUtf32LeNullPadded<N>) -> Self {
        v.0
    }
}

impl<const N: usize> From<FixedUtf32BeNullPadded<N>> for FixedUtf32BeCodeUnits<N> {
    fn from(v: FixedUtf32BeNullPadded<N>) -> Self {
        v.0
    }
}

impl<const N: usize> From<FixedUtf32LeSpacePadded<N>> for FixedUtf32LeCodeUnits<N> {
    fn from(v: FixedUtf32LeSpacePadded<N>) -> Self {
        v.0
    }
}

impl<const N: usize> From<FixedUtf32BeSpacePadded<N>> for FixedUtf32BeCodeUnits<N> {
    fn from(v: FixedUtf32BeSpacePadded<N>) -> Self {
        v.0
    }
}

impl<const N: usize> TryFrom<&str> for FixedUtf32LePacked<N> {
    type Error = FixedUtf32Error;

    fn try_from(s: &str) -> Result<Self, Self::Error> {
        FixedUtf32LeCodeUnits::try_from(s).map(Self)
    }
}

impl<const N: usize> TryFrom<&str> for FixedUtf32BePacked<N> {
    type Error = FixedUtf32Error;

    fn try_from(s: &str) -> Result<Self, Self::Error> {
        FixedUtf32BeCodeUnits::try_from(s).map(Self)
    }
}

impl<const N: usize> TryFrom<&str> for FixedUtf32LeNullPadded<N> {
    type Error = FixedUtf32Error;

    fn try_from(s: &str) -> Result<Self, Self::Error> {
        let mut it = s.chars();
        let mut units = [LittleEndian::from_bits(0u32); N];
        let mut i = 0usize;

        while i < N {
            match it.next() {
                Some(ch) => {
                    units[i] = LittleEndian::from_bits(ch as u32);
                    i += 1;
                }
                None => break,
            }
        }

        if let Some(_) = it.next() {
            return Err(FixedUtf32Error::WrongCodeUnitCount {
                expected: N,
                found: N + 1,
            });
        }

        Ok(Self(FixedUtf32CodeUnitsEndian { units }))
    }
}

impl<const N: usize> TryFrom<&str> for FixedUtf32BeNullPadded<N> {
    type Error = FixedUtf32Error;

    fn try_from(s: &str) -> Result<Self, Self::Error> {
        let mut it = s.chars();
        let mut units = [BigEndian::from_bits(0u32); N];
        let mut i = 0usize;

        while i < N {
            match it.next() {
                Some(ch) => {
                    units[i] = BigEndian::from_bits(ch as u32);
                    i += 1;
                }
                None => break,
            }
        }

        if let Some(_) = it.next() {
            return Err(FixedUtf32Error::WrongCodeUnitCount {
                expected: N,
                found: N + 1,
            });
        }

        Ok(Self(FixedUtf32CodeUnitsEndian { units }))
    }
}

impl<const N: usize> TryFrom<&str> for FixedUtf32LeSpacePadded<N> {
    type Error = FixedUtf32Error;

    fn try_from(s: &str) -> Result<Self, Self::Error> {
        let mut it = s.chars();
        // SpecificEndian wrappers store the raw bits in the specified endianness.
        // We want the *native scalar value* to survive a `.to_native()` call.
        // That means we must pre-swap on big-endian hosts for LE storage.
        let space_bits = if cfg!(target_endian = "big") {
            0x0020u32.swap_bytes()
        } else {
            0x0020u32
        };
        let mut units = [LittleEndian::from_bits(space_bits); N];
        let mut i = 0usize;

        while i < N {
            match it.next() {
                Some(ch) => {
                    let bits = if cfg!(target_endian = "big") {
                        (ch as u32).swap_bytes()
                    } else {
                        ch as u32
                    };
                    units[i] = LittleEndian::from_bits(bits);
                    i += 1;
                }
                None => break,
            }
        }

        if let Some(_) = it.next() {
            return Err(FixedUtf32Error::WrongCodeUnitCount {
                expected: N,
                found: N + 1,
            });
        }

        Ok(Self(FixedUtf32CodeUnitsEndian { units }))
    }
}

impl<const N: usize> TryFrom<&str> for FixedUtf32BeSpacePadded<N> {
    type Error = FixedUtf32Error;

    fn try_from(s: &str) -> Result<Self, Self::Error> {
        let mut it = s.chars();
        // Pre-swap on little-endian hosts for BE storage.
        let space_bits = if cfg!(target_endian = "little") {
            0x0020u32.swap_bytes()
        } else {
            0x0020u32
        };
        let mut units = [BigEndian::from_bits(space_bits); N];
        let mut i = 0usize;

        while i < N {
            match it.next() {
                Some(ch) => {
                    let bits = if cfg!(target_endian = "little") {
                        (ch as u32).swap_bytes()
                    } else {
                        ch as u32
                    };
                    units[i] = BigEndian::from_bits(bits);
                    i += 1;
                }
                None => break,
            }
        }

        if let Some(_) = it.next() {
            return Err(FixedUtf32Error::WrongCodeUnitCount {
                expected: N,
                found: N + 1,
            });
        }

        Ok(Self(FixedUtf32CodeUnitsEndian { units }))
    }
}

impl<const N: usize> TryFrom<&FixedUtf32LePacked<N>> for String {
    type Error = FixedUtf32Error;

    fn try_from(v: &FixedUtf32LePacked<N>) -> Result<Self, Self::Error> {
        String::try_from(&v.0)
    }
}

impl<const N: usize> TryFrom<&FixedUtf32BePacked<N>> for String {
    type Error = FixedUtf32Error;

    fn try_from(v: &FixedUtf32BePacked<N>) -> Result<Self, Self::Error> {
        String::try_from(&v.0)
    }
}

impl<const N: usize> TryFrom<&FixedUtf32LeNullPadded<N>> for String {
    type Error = FixedUtf32Error;

    fn try_from(v: &FixedUtf32LeNullPadded<N>) -> Result<Self, Self::Error> {
        let mut end = N;
        for (i, cu) in v.0.as_units().iter().enumerate() {
            if cu.to_native() == 0 {
                end = i;
                break;
            }
        }
        String::try_from(Utf32StrLE::from(&v.0.as_units()[..end]))
            .map_err(|_| FixedUtf32Error::InvalidUtf32)
    }
}

impl<const N: usize> TryFrom<&FixedUtf32BeNullPadded<N>> for String {
    type Error = FixedUtf32Error;

    fn try_from(v: &FixedUtf32BeNullPadded<N>) -> Result<Self, Self::Error> {
        let mut end = N;
        for (i, cu) in v.0.as_units().iter().enumerate() {
            if cu.to_native() == 0 {
                end = i;
                break;
            }
        }
        String::try_from(Utf32StrBE::from(&v.0.as_units()[..end]))
            .map_err(|_| FixedUtf32Error::InvalidUtf32)
    }
}

impl<const N: usize> TryFrom<&FixedUtf32LeSpacePadded<N>> for String {
    type Error = FixedUtf32Error;

    fn try_from(v: &FixedUtf32LeSpacePadded<N>) -> Result<Self, Self::Error> {
        let mut end = N;
        while end > 0 {
            let cu = v.0.as_units()[end - 1].to_native();
            if cu == 0x0020 {
                end -= 1;
            } else {
                break;
            }
        }
        String::try_from(Utf32StrLE::from(&v.0.as_units()[..end]))
            .map_err(|_| FixedUtf32Error::InvalidUtf32)
    }
}

impl<const N: usize> TryFrom<&FixedUtf32BeSpacePadded<N>> for String {
    type Error = FixedUtf32Error;

    fn try_from(v: &FixedUtf32BeSpacePadded<N>) -> Result<Self, Self::Error> {
        let mut end = N;
        while end > 0 {
            let cu = v.0.as_units()[end - 1].to_native();
            if cu == 0x0020 {
                end -= 1;
            } else {
                break;
            }
        }
        String::try_from(Utf32StrBE::from(&v.0.as_units()[..end]))
            .map_err(|_| FixedUtf32Error::InvalidUtf32)
    }
}

impl<const N: usize> SpecificEndianOwned for FixedUtf32LeCodeUnits<N> {
    type Big = FixedUtf32BeCodeUnits<N>;
    type Little = FixedUtf32LeCodeUnits<N>;

    fn to_big_endian(&self) -> Self::Big {
        let mut units = [BigEndian::from_bits(0u32); N];
        for (dst, src) in units.iter_mut().zip(self.units.iter()) {
            *dst = BigEndian::from_bits(src.to_native());
        }
        FixedUtf32CodeUnitsEndian { units }
    }

    fn to_little_endian(&self) -> Self::Little {
        *self
    }

    fn from_big_endian(&self) -> Self::Big {
        SpecificEndianOwned::to_big_endian(self)
    }

    fn from_little_endian(&self) -> Self::Little {
        *self
    }
}

impl<const N: usize> SpecificEndianOwned for FixedUtf32BeCodeUnits<N> {
    type Big = FixedUtf32BeCodeUnits<N>;
    type Little = FixedUtf32LeCodeUnits<N>;

    fn to_big_endian(&self) -> Self::Big {
        *self
    }

    fn to_little_endian(&self) -> Self::Little {
        let mut units = [LittleEndian::from_bits(0u32); N];
        for (dst, src) in units.iter_mut().zip(self.units.iter()) {
            *dst = LittleEndian::from_bits(src.to_native());
        }
        FixedUtf32CodeUnitsEndian { units }
    }

    fn from_big_endian(&self) -> Self::Big {
        *self
    }

    fn from_little_endian(&self) -> Self::Little {
        SpecificEndianOwned::to_little_endian(self)
    }
}

// Implement `SpecificEndian<T>` so the fixed buffers can be wrapped in `BigEndian<T>` / `LittleEndian<T>`.
impl<const N: usize> SpecificEndian<FixedUtf32LeCodeUnits<N>> for FixedUtf32LeCodeUnits<N> {
    fn to_big_endian(&self) -> FixedUtf32LeCodeUnits<N> {
        let mut units = [LittleEndian::from_bits(0u32); N];
        for (dst, src) in units.iter_mut().zip(self.units.iter()) {
            let v = src.to_native();
            *dst = LittleEndian::from_bits(v.to_be());
        }
        FixedUtf32CodeUnitsEndian { units }
    }

    fn to_little_endian(&self) -> FixedUtf32LeCodeUnits<N> {
        *self
    }

    fn from_big_endian(&self) -> FixedUtf32LeCodeUnits<N> {
        let mut units = [LittleEndian::from_bits(0u32); N];
        for (dst, src) in units.iter_mut().zip(self.units.iter()) {
            let v = src.to_native();
            *dst = LittleEndian::from_bits(u32::from_be(v));
        }
        FixedUtf32CodeUnitsEndian { units }
    }

    fn from_little_endian(&self) -> FixedUtf32LeCodeUnits<N> {
        *self
    }
}

impl<const N: usize> SpecificEndian<FixedUtf32BeCodeUnits<N>> for FixedUtf32BeCodeUnits<N> {
    fn to_big_endian(&self) -> FixedUtf32BeCodeUnits<N> {
        *self
    }

    fn to_little_endian(&self) -> FixedUtf32BeCodeUnits<N> {
        let mut units = [BigEndian::from_bits(0u32); N];
        for (dst, src) in units.iter_mut().zip(self.units.iter()) {
            let v = src.to_native();
            *dst = BigEndian::from_bits(v.to_le());
        }
        FixedUtf32CodeUnitsEndian { units }
    }

    fn from_big_endian(&self) -> FixedUtf32BeCodeUnits<N> {
        *self
    }

    fn from_little_endian(&self) -> FixedUtf32BeCodeUnits<N> {
        let mut units = [BigEndian::from_bits(0u32); N];
        for (dst, src) in units.iter_mut().zip(self.units.iter()) {
            let v = src.to_native();
            *dst = BigEndian::from_bits(u32::from_le(v));
        }
        FixedUtf32CodeUnitsEndian { units }
    }
}