vhdl_syntax 0.2.0

VHDL parser for lossless concrete syntax trees
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
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
//! # Latin-1 String Types
//!
//! As opposed to the Rust default, in VHDL, text is [ISO-8859-1](https://de.wikipedia.org/wiki/ISO_8859-1)
//! ("Latin-1") encoded.
//! This module provides string types for working with Latin-1 encoded text
//! that behave closely to [`String`] and [`prim@str`].
//!
//! ## Differences to `String` and `str`
//!
//! In Rust's `String` and `str`, a character is a Unicode scalar value (represented as `char`),
//! which can be multiple bytes when encoded in UTF-8. In contrast, Latin-1 has a 1:1 mapping
//! between bytes and characters. Each byte (0-255) represents exactly one character.
//! This means [`Latin1String`] and [`Latin1Str`] work directly with bytes, where a single `u8`
//! is equivalent to a single character, simplifying indexing and iteration.
//!
//! ## Conversions
//!
//! ### UTF-8 to Latin-1
//!
//! Conversion from a standard Rust `&str` (UTF-8) to Latin-1 may fail and produce a [`Utf8ToLatin1Error`] when a UTF-8
//! character may not be represented in Latin-1.
//!
//! ```
//! # use vhdl_syntax::latin_1::Latin1String;
//! // Converting ASCII and extended Latin-1 characters
//! let latin1 = Latin1String::from_utf8("café").unwrap();
//! assert_eq!(latin1.as_bytes(), &[99, 97, 102, 233]); // 233 is é in Latin-1
//!
//! // Characters outside Latin-1 will produce an error
//! assert!(Latin1String::from_utf8("Hello €").is_err()); // Euro sign not in Latin-1
//! ```
//!
//! ### Latin-1 to UTF-8
//!
//! Converting a [`Latin1String`] or [`Latin1Str`] to UTF-8 always succeeds since every Latin-1 byte
//! can be represented as UTF-8 value.
//!
//! ```
//! # use vhdl_syntax::latin_1::Latin1String;
//! let latin1 = Latin1String::from_utf8("café").unwrap();
//! let utf8_string: String = latin1.to_string();
//! assert_eq!(utf8_string, "café");
//! ```
//!
//! Using [`Latin1Str::to_str`] optimizes the common case where the string is ASCII:
//!
//! ```
//! # use vhdl_syntax::latin_1::Latin1Str;
//! # use std::borrow::{Borrow, Cow};
//! let latin1 = Latin1Str::new(b"Hello, World!");
//! let utf8 = latin1.to_str();
//! assert!(matches!(utf8, Cow::Borrowed(_)));
//! ```
//!
//! ### From Raw Bytes
//!
//! Create a [`Latin1String`] directly from a byte vector or byte slice without validation:
//!
//! ```
//! # use vhdl_syntax::latin_1::Latin1String;
//! let bytes = vec![99, 97, 102, 233]; // "café" in Latin-1
//! let latin1 = Latin1String::from(bytes);
//! assert_eq!(latin1.to_string(), "café");
//! ```

// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at http://mozilla.org/MPL/2.0/.
//
// Copyright (c) 2025, Lukas Scheller lukasscheller@icloud.com

use std::borrow::{Borrow, Cow};
use std::hash::{Hash, Hasher};
use std::ops::{self, Range};
use std::str::{self, FromStr};
use std::{cmp, fmt, slice};

/// An owned Latin-1 string type.
pub struct Latin1String {
    bytes: Vec<u8>,
}

impl Latin1String {
    /// Creates a new empty `Latin1String`.
    #[must_use]
    pub fn new() -> Latin1String {
        Latin1String { bytes: Vec::new() }
    }

    /// Create a Latin1-string with allocated capacity.
    ///
    /// The `capacity` argument is passed to the backing `Vec`.
    #[must_use]
    pub fn with_capacity(capacity: usize) -> Latin1String {
        Latin1String {
            bytes: Vec::with_capacity(capacity),
        }
    }

    /// Extracts a string slice containing the entire String.
    ///
    /// # Examples
    ///
    /// ```
    /// # use vhdl_syntax::latin_1::{Latin1String, Latin1Str};
    /// let s = Latin1String::from(b"foo");
    ///
    /// assert_eq!(Latin1Str::new(b"foo"), s.as_latin1_str());
    /// ```
    #[must_use]
    pub fn as_latin1_str(&self) -> &Latin1Str {
        self
    }

    /// Extracts a mutable string slice containing the entire String.
    ///
    /// # Examples
    ///
    /// ```
    /// # use vhdl_syntax::latin_1::{Latin1String, Latin1Str};
    /// let mut s = Latin1String::from(b"foo");
    ///
    /// let slice = s.as_latin1_str_mut();
    /// slice[0] = b'o';
    ///
    /// assert_eq!(Latin1Str::new(b"ooo"), slice);
    /// ```
    #[must_use]
    pub fn as_latin1_str_mut(&mut self) -> &mut Latin1Str {
        self
    }

    #[must_use = "`self` will be dropped if the result is not used"]
    pub fn into_bytes(self) -> Vec<u8> {
        self.bytes
    }

    pub fn clear(&mut self) {
        self.bytes.clear()
    }

    pub fn from_utf8(string: &str) -> Result<Latin1String, Utf8ToLatin1Error> {
        let bytes = string.as_bytes();
        let mut latin1_bytes = Vec::with_capacity(string.len());
        let mut i = 0;

        let mut pos = 0;

        while i < bytes.len() {
            let byte = bytes[i];

            let mut error = false;
            if byte < 128 {
                latin1_bytes.push(byte);
                i += 1;
            } else if byte == 0xc2 {
                let next_byte = bytes[i + 1];
                if (128..192).contains(&next_byte) {
                    latin1_bytes.push(next_byte);
                    i += 2;
                } else {
                    error = true;
                }
            } else if byte == 0xc3 {
                let next_byte = bytes[i + 1];
                if (128..192).contains(&next_byte) {
                    latin1_bytes.push(next_byte + 64);
                    i += 2;
                } else {
                    error = true;
                }
            } else {
                error = true;
            }

            if error {
                let value = string[i..].chars().next().unwrap();
                return Err(Utf8ToLatin1Error { pos, value });
            }

            pos += 1;
        }
        Ok(Latin1String::from(latin1_bytes))
    }

    #[cfg(test)]
    pub fn from_utf8_unchecked(string: &str) -> Latin1String {
        Self::from_utf8(string).unwrap()
    }

    pub fn push(&mut self, byte: u8) {
        self.bytes.push(byte)
    }

    pub fn append(&mut self, other: &mut Latin1String) {
        self.bytes.append(&mut other.bytes);
    }

    /// Converts this `Latin1String` into a [boxed](Box) [`Latin1Str`].
    #[must_use = "`self` will be dropped if the result is not used"]
    pub fn into_boxed_latin1_str(self) -> Box<Latin1Str> {
        let rw = Box::into_raw(self.bytes.into_boxed_slice()) as *mut Latin1Str;
        unsafe { Box::from_raw(rw) }
    }
}

impl Clone for Latin1String {
    fn clone(&self) -> Self {
        Self {
            bytes: self.bytes.clone(),
        }
    }

    fn clone_from(&mut self, source: &Self) {
        self.bytes.clone_from(&source.bytes)
    }
}

impl From<&Latin1Str> for Box<Latin1Str> {
    fn from(value: &Latin1Str) -> Self {
        value.to_boxed()
    }
}

impl From<&mut Latin1Str> for Box<Latin1Str> {
    /// Creates a boxed [`Latin1Str`] from a reference.
    ///
    /// This will allocate and clone `value` to it.
    fn from(value: &mut Latin1Str) -> Self {
        Self::from(&*value)
    }
}

impl AsRef<Latin1Str> for Latin1String {
    fn as_ref(&self) -> &Latin1Str {
        self.as_latin1_str()
    }
}

impl From<Box<Latin1Str>> for Latin1String {
    /// Converts a `[Box]&lt;[Latin1Str]&gt;</code> into a [`Latin1String`].
    ///
    /// This conversion does not allocate or copy memory.
    fn from(value: Box<Latin1Str>) -> Self {
        value.into_latin1_string()
    }
}

impl From<Latin1String> for Box<Latin1Str> {
    /// Converts a [`Latin1String`] into a <code>[Box]&lt;[Latin1Str]&gt;</code>.
    ///
    /// This conversion does not allocate memory.
    fn from(value: Latin1String) -> Self {
        value.into_boxed_latin1_str()
    }
}

impl From<&[u8]> for Box<Latin1Str> {
    fn from(value: &[u8]) -> Self {
        Latin1String::from(value).into_boxed_latin1_str()
    }
}

impl<const N: usize> From<&[u8; N]> for Box<Latin1Str> {
    fn from(value: &[u8; N]) -> Self {
        Latin1String::from(value).into_boxed_latin1_str()
    }
}

impl Clone for Box<Latin1Str> {
    fn clone(&self) -> Self {
        self.to_latin1_string().into_boxed_latin1_str()
    }
}

impl<T: ?Sized + AsRef<[u8]>> From<&T> for Latin1String {
    fn from(s: &T) -> Latin1String {
        Latin1String::from(s.as_ref().to_vec())
    }
}

impl From<Vec<u8>> for Latin1String {
    fn from(value: Vec<u8>) -> Self {
        Latin1String { bytes: value }
    }
}

impl From<u8> for Latin1String {
    fn from(value: u8) -> Self {
        Latin1String { bytes: vec![value] }
    }
}

impl From<Latin1String> for Vec<u8> {
    fn from(value: Latin1String) -> Self {
        value.bytes
    }
}

impl From<&Latin1Str> for Latin1String {
    fn from(value: &Latin1Str) -> Self {
        value.to_owned()
    }
}

impl FromStr for Latin1String {
    type Err = Utf8ToLatin1Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Latin1String::from_utf8(s)
    }
}

impl FromIterator<u8> for Latin1String {
    fn from_iter<T: IntoIterator<Item = u8>>(iter: T) -> Self {
        Latin1String::from(iter.into_iter().collect::<Vec<_>>())
    }
}

impl Extend<u8> for Latin1String {
    fn extend<T: IntoIterator<Item = u8>>(&mut self, iter: T) {
        self.bytes.extend(iter);
    }
}

impl<'a> Extend<&'a u8> for Latin1String {
    fn extend<T: IntoIterator<Item = &'a u8>>(&mut self, iter: T) {
        self.bytes.extend(iter);
    }
}

impl fmt::Debug for Latin1String {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(&**self, f)
    }
}

impl ops::Deref for Latin1String {
    type Target = Latin1Str;

    fn deref(&self) -> &Self::Target {
        Latin1Str::new(self.bytes.as_ref())
    }
}

impl ops::DerefMut for Latin1String {
    fn deref_mut(&mut self) -> &mut Self::Target {
        Latin1Str::new_mut(&mut self.bytes)
    }
}

impl Borrow<Latin1Str> for Latin1String {
    fn borrow(&self) -> &Latin1Str {
        self
    }
}

impl Default for Latin1String {
    fn default() -> Self {
        Latin1String::new()
    }
}

impl ToOwned for Latin1Str {
    type Owned = Latin1String;

    fn to_owned(&self) -> Self::Owned {
        self.to_latin1_string()
    }

    fn clone_into(&self, target: &mut Latin1String) {
        self.inner.clone_into(&mut target.bytes);
    }
}

impl cmp::PartialEq for Latin1String {
    fn eq(&self, other: &Self) -> bool {
        self.as_latin1_str() == other.as_latin1_str()
    }
}

impl Hash for Latin1String {
    fn hash<H: Hasher>(&self, h: &mut H) {
        self.as_latin1_str().hash(h)
    }
}

impl Eq for Latin1String {}

impl cmp::PartialEq<str> for Latin1String {
    fn eq(&self, other: &str) -> bool {
        cmp_latin1_to_str(self.as_latin1_str(), other)
    }
}

impl cmp::PartialEq<String> for Latin1String {
    fn eq(&self, other: &String) -> bool {
        cmp_latin1_to_str(self.as_latin1_str(), other.as_str())
    }
}

impl cmp::PartialEq<Latin1String> for str {
    fn eq(&self, other: &Latin1String) -> bool {
        cmp_latin1_to_str(other.as_latin1_str(), self)
    }
}

impl cmp::PartialEq<Latin1String> for String {
    fn eq(&self, other: &Latin1String) -> bool {
        cmp_latin1_to_str(other.as_latin1_str(), self.as_str())
    }
}

impl PartialOrd for Latin1String {
    fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for Latin1String {
    fn cmp(&self, other: &Self) -> cmp::Ordering {
        self.as_latin1_str().cmp(other.as_latin1_str())
    }
}

impl AsRef<[u8]> for Latin1String {
    fn as_ref(&self) -> &[u8] {
        &self.bytes[..]
    }
}

impl AsRef<Latin1Str> for [u8] {
    fn as_ref(&self) -> &Latin1Str {
        Latin1Str::new(self)
    }
}

impl<const N: usize> AsRef<Latin1Str> for [u8; N] {
    fn as_ref(&self) -> &Latin1Str {
        Latin1Str::new(self)
    }
}

impl fmt::Display for Latin1String {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(&**self, f)
    }
}

/// A borrowed, Latin-1 string slice type.
#[derive(PartialEq, Eq, Hash, PartialOrd, Ord)]
#[repr(transparent)]
pub struct Latin1Str {
    inner: [u8],
}

pub fn latin1_char_lowercased(chr: u8) -> u8 {
    match chr {
        b'A'..=b'Z' | 0xC0..=0xD6 | 0xD8..=0xDE => chr + 32,
        _ => chr,
    }
}

pub fn latin1_char_uppercased(chr: u8) -> u8 {
    match chr {
        b'a'..=b'z' | 0xE0..=0xF6 | 0xF8..=0xFE => chr - 32,
        _ => chr,
    }
}

/// An iterator over the chars of a Latin-1 encoded string
pub struct Chars<'a> {
    iter: slice::Iter<'a, u8>,
}

impl<'a> Chars<'a> {
    pub fn new(value: &'a Latin1Str) -> Chars<'a> {
        Chars {
            iter: value.inner.iter(),
        }
    }
}

impl<'a> Iterator for Chars<'a> {
    type Item = char;

    fn next(&mut self) -> Option<Self::Item> {
        self.iter.next().map(|byte| *byte as char)
    }

    fn count(self) -> usize
    where
        Self: Sized,
    {
        self.iter.count()
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        self.iter.size_hint()
    }

    fn last(self) -> Option<Self::Item>
    where
        Self: Sized,
    {
        self.iter.last().map(|byte| *byte as char)
    }
}

impl<'a> ExactSizeIterator for Chars<'a> {}

impl<'a> DoubleEndedIterator for Chars<'a> {
    fn next_back(&mut self) -> Option<Self::Item> {
        self.iter.next_back().map(|byte| *byte as char)
    }
}

impl Latin1Str {
    pub fn new(bytes: &[u8]) -> &Latin1Str {
        // SAFETY: Latin1Str is a transparent newtype wrapper around [u8],
        // so this transmute is sound.
        unsafe { &*(bytes as *const [u8] as *const Latin1Str) }
    }

    pub fn new_mut(bytes: &mut [u8]) -> &mut Latin1Str {
        // SAFETY: Latin1Str is a transparent newtype wrapper around [u8],
        // so this transmute is sound.
        unsafe { &mut *(bytes as *mut [u8] as *mut Latin1Str) }
    }

    pub fn as_bytes(&self) -> &[u8] {
        &self.inner
    }

    pub fn as_mut_bytes(&mut self) -> &mut [u8] {
        &mut self.inner
    }

    pub fn to_latin1_string(&self) -> Latin1String {
        Latin1String::from(&self.inner)
    }

    pub fn chars(&self) -> Chars<'_> {
        Chars::new(self)
    }

    pub fn len(&self) -> usize {
        self.inner.len()
    }

    pub fn is_empty(&self) -> bool {
        self.inner.is_empty()
    }

    pub fn make_lowercase(&mut self) {
        for i in 0..self.inner.len() {
            self.inner[i] = latin1_char_lowercased(self.inner[i]);
        }
    }

    pub fn make_uppercase(&mut self) {
        for i in 0..self.inner.len() {
            self.inner[i] = latin1_char_uppercased(self.inner[i]);
        }
    }

    pub fn to_lowercase(&self) -> Latin1String {
        let mut latin1 = self.to_owned();
        latin1.make_lowercase();
        latin1
    }

    pub fn to_uppercase(&self) -> Latin1String {
        let mut latin1 = self.to_owned();
        latin1.make_uppercase();
        latin1
    }

    pub fn starts_with(&self, other: &Latin1String) -> bool {
        if other.len() <= self.len() {
            self.inner[0..other.len()] == other.bytes
        } else {
            false
        }
    }

    /// Converts a [`Box<Latin1Str>`](Box) into a [`Latin1String`] without copying or
    /// allocating.
    #[must_use = "`self` will be dropped if the result is not used"]
    pub fn into_latin1_string(self: Box<Self>) -> Latin1String {
        let rw = Box::into_raw(self) as *mut [u8];
        let inner = unsafe { Box::from_raw(rw) };
        Latin1String {
            bytes: Vec::from(inner),
        }
    }

    /// Reinterprets the underlying bytes as a UTF-8 `&str` without
    /// allocation and validation. For the safe, allocating equivalent
    /// that handles non-ASCII bytes correctly, use [`Latin1Str::to_str`].
    ///
    /// # Safety
    ///
    /// The caller must guarantee that every byte in `self` is < 0x80
    /// (i.e. pure ASCII).
    ///
    /// In safe code, guard the call with [`Latin1Str::is_utf8`].
    pub unsafe fn to_str_unchecked(&self) -> &str {
        debug_assert!(
            self.is_utf8(),
            "called to_str_unchecked with non-ascii bytes"
        );
        str::from_utf8_unchecked(&self.inner)
    }

    /// Checks if all chars in this string are UTF-8 compatible
    pub fn is_utf8(&self) -> bool {
        // All ASCII symbols are UTF-8 compatible.
        // Non-ascii symbols have different encodings.
        self.inner.is_ascii()
    }

    pub fn to_str(&self) -> Cow<'_, str> {
        if self.is_utf8() {
            // SAFETY: all characters are UTF-8, the Latin1-String can safely be transmuted to a str
            Cow::Borrowed(unsafe { self.to_str_unchecked() })
        } else {
            Cow::Owned(iso_8859_1_to_utf8(&self.inner))
        }
    }

    /// Creates a boxed [`Latin1Str`] from this reference
    pub fn to_boxed(&self) -> Box<Latin1Str> {
        let boxed: Box<[u8]> = self.inner.into();
        let raw = Box::into_raw(boxed) as *mut Latin1Str;
        unsafe { Box::from_raw(raw) }
    }

    pub fn eq_ignore_case(&self, other: impl AsRef<Latin1Str>) -> bool {
        // TODO: optimize this. No need to allocate for comparison only
        self.to_lowercase() == other.as_ref().to_lowercase()
    }

    pub fn neq_ignore_case(&self, other: impl AsRef<Latin1Str>) -> bool {
        // TODO: optimize this. No need to allocate for comparison only
        self.to_lowercase() != other.as_ref().to_lowercase()
    }
}

fn iso_8859_1_to_utf8(bytes: &[u8]) -> String {
    let mut utf8_bytes = Vec::with_capacity(bytes.len());
    for byte in bytes.iter().copied() {
        if byte < 128 {
            utf8_bytes.push(byte);
        } else if byte < 192 {
            utf8_bytes.push(0xc2);
            utf8_bytes.push(byte);
        } else {
            utf8_bytes.push(0xc3);
            utf8_bytes.push(byte - 64);
        }
    }

    // SAFETY: We only push valid UTF-8 sequences into utf8_bytes:
    // - ASCII bytes (< 128) are valid UTF-8 single bytes
    // - 0xc2 followed by 128..192 creates valid 2-byte UTF-8 sequences
    // - 0xc3 followed by 128..192 creates valid 2-byte UTF-8 sequences
    unsafe { String::from_utf8_unchecked(utf8_bytes) }
}

impl fmt::Debug for Latin1Str {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(&iso_8859_1_to_utf8(&self.inner), f)
    }
}

impl fmt::Display for Latin1Str {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(&iso_8859_1_to_utf8(&self.inner), f)
    }
}

impl AsRef<Latin1Str> for Latin1Str {
    fn as_ref(&self) -> &Latin1Str {
        self
    }
}

impl<const N: usize> From<[u8; N]> for Latin1String {
    fn from(value: [u8; N]) -> Self {
        Self {
            bytes: value.into(),
        }
    }
}

impl std::ops::Index<Range<usize>> for Latin1String {
    type Output = Latin1Str;

    fn index(&self, index: Range<usize>) -> &Self::Output {
        Latin1Str::new(self.bytes.index(index))
    }
}

impl std::ops::Index<usize> for Latin1Str {
    type Output = u8;

    fn index(&self, index: usize) -> &Self::Output {
        &self.inner[index]
    }
}

impl std::ops::IndexMut<usize> for Latin1Str {
    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
        &mut self.inner[index]
    }
}

// We cannot use `latin1 == str` since this is the code used to implement
// this comparison, effectively creating an infinite recursion.
// OPTIMIZATION: This is for simplicity only.
// There is no need to allocate a string just for comparison.
#[allow(clippy::cmp_owned)]
fn cmp_latin1_to_str(latin1: &Latin1Str, str: &str) -> bool {
    latin1.to_string() == str
}

impl cmp::PartialEq<str> for Latin1Str {
    fn eq(&self, other: &str) -> bool {
        cmp_latin1_to_str(self, other)
    }
}

impl cmp::PartialEq<String> for Latin1Str {
    fn eq(&self, other: &String) -> bool {
        cmp_latin1_to_str(self, other.as_str())
    }
}

impl cmp::PartialEq<Latin1Str> for str {
    fn eq(&self, other: &Latin1Str) -> bool {
        cmp_latin1_to_str(other, self)
    }
}

impl cmp::PartialEq<Latin1Str> for String {
    fn eq(&self, other: &Latin1Str) -> bool {
        cmp_latin1_to_str(other, self.as_str())
    }
}

impl<'a> IntoIterator for &'a Latin1Str {
    type Item = &'a u8;

    type IntoIter = slice::Iter<'a, u8>;

    fn into_iter(self) -> Self::IntoIter {
        self.inner.iter()
    }
}

#[derive(PartialEq, Eq, Debug)]
pub struct Utf8ToLatin1Error {
    pub pos: usize,
    pub value: char,
}

impl fmt::Display for Utf8ToLatin1Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "Invalid latin-1 character '{}' at position {}",
            self.value, self.pos
        )
    }
}

impl std::error::Error for Utf8ToLatin1Error {}

pub fn char_to_latin1(chr: char) -> Result<u8, NonLatin1CharError> {
    let mut bytes = [0; 4];
    chr.encode_utf8(&mut bytes);
    let byte = bytes[0];
    if byte < 128 {
        Ok(byte)
    } else if byte == 0xc2 {
        let next_byte = bytes[1];
        if (128..192).contains(&next_byte) {
            Ok(next_byte)
        } else {
            Err(NonLatin1CharError { ch: chr })
        }
    } else if byte == 0xc3 {
        let next_byte = bytes[1];
        if (128..192).contains(&next_byte) {
            Ok(next_byte + 64)
        } else {
            Err(NonLatin1CharError { ch: chr })
        }
    } else {
        Err(NonLatin1CharError { ch: chr })
    }
}

/// Error returned when a Rust `char` cannot be represented in Latin-1.
#[derive(Debug, PartialEq, Eq)]
pub struct NonLatin1CharError {
    pub ch: char,
}

impl fmt::Display for NonLatin1CharError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "character '{}' (U+{:04X}) cannot be represented in Latin-1",
            self.ch, self.ch as u32
        )
    }
}

impl std::error::Error for NonLatin1CharError {}

pub trait ToLatin1 {
    fn to_latin1(&self) -> Latin1String;
}

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

    #[test]
    fn latin1_to_utf8() {
        for byte in 0..=255 {
            let latin1 = Latin1String::from(&[byte]);
            assert_eq!(
                Latin1String::from_utf8(&latin1.to_string()).unwrap(),
                latin1
            )
        }
    }

    #[test]
    fn latin1_lowercase() {
        for byte in 0..=255u8 {
            let latin1 = Latin1String::from(&[byte]);
            let utf8 = latin1.to_string();
            assert_eq!(latin1.to_lowercase().to_string(), utf8.to_lowercase());
        }
    }

    #[test]
    fn utf8_to_latin1() {
        let utf8 = "åäö";
        assert_matches!(Latin1String::from_utf8(utf8), Ok(latin1) => {
            assert_eq!(latin1.bytes, [229, 228, 246]);
            assert_eq!(latin1.to_string(), utf8);
        })
    }

    #[test]
    fn utf8_to_latin1_error() {
        let utf8 = "abö€";
        assert_matches!(Latin1String::from_utf8(utf8), Err(err) => {
            assert_eq!(err.pos, 3);
            assert_eq!(err.value, '€');
        });

        let utf8 = "a\nbö\n€";
        assert_matches!(Latin1String::from_utf8(utf8), Err(err) => {
            assert_eq!(err.pos, 5);
            assert_eq!(err.value, '€');
            assert_eq!(format!("{}", err), "Invalid latin-1 character '€' at position 5");
        });
    }

    #[test]
    fn compare_latin1_to_utf8() {
        let utf8 = "café";
        let latin1 = Latin1String::from_utf8("café").unwrap();
        // bytes are not equal due to the different encoding
        assert!(utf8.as_bytes() != latin1.as_bytes());
        // The string-value is still the same though
        assert!(latin1.as_latin1_str() == utf8);
    }
}