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
//! A Unicode code point: from U+0000 to U+10FFFF.

use core::fmt;
use core::iter::{FusedIterator, Peekable};

#[cfg(test)]
mod tests;

/// A Unicode code point: from U+0000 to U+10FFFF.
///
/// Compares with the `char` type,
/// which represents a Unicode scalar value:
/// a code point that is not a surrogate (U+D800 to U+DFFF).
#[derive(Eq, PartialEq, Ord, PartialOrd, Clone, Copy)]
pub struct CodePoint {
    value: u32,
}

/// Format the code point as `U+` followed by four to six hexadecimal digits.
/// Example: `U+1F4A9`
impl fmt::Debug for CodePoint {
    #[inline]
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "U+{:04X}", self.value)
    }
}

impl CodePoint {
    /// Unsafely creates a new `CodePoint` without checking the value.
    ///
    /// # Safety
    ///
    /// Only safe if `value` is less than or equal to 0x10FFFF.
    #[inline]
    pub unsafe fn from_u32_unchecked(value: u32) -> CodePoint {
        CodePoint { value }
    }

    /// Creates a new `CodePoint` if the value is a valid code point.
    ///
    /// Returns `None` if `value` is above 0x10FFFF.
    #[inline]
    pub fn from_u32(value: u32) -> Option<CodePoint> {
        match value {
            0..=0x10FFFF => Some(CodePoint { value }),
            _ => None,
        }
    }

    /// Creates a new `CodePoint` from a `char`.
    ///
    /// Since all Unicode scalar values are code points, this always succeeds.
    #[inline]
    pub fn from_char(value: char) -> CodePoint {
        CodePoint {
            value: value as u32,
        }
    }

    /// Returns the numeric value of the code point.
    #[inline]
    pub fn to_u32(&self) -> u32 {
        self.value
    }

    /// Optionally returns a Unicode scalar value for the code point.
    ///
    /// Returns `None` if the code point is a surrogate (from U+D800 to U+DFFF).
    #[inline]
    pub fn to_char(&self) -> Option<char> {
        match self.value {
            0xD800..=0xDFFF => None,
            // Safety: value is known to be in char range, because it is not
            // a surrogate, and is less than (#impl-Index<T>) as this is guaranteed
            // by the type.
            _ => Some(unsafe { char::from_u32_unchecked(self.value) }),
        }
    }

    /// Returns a Unicode scalar value for the code point.
    ///
    /// Returns `'\u{FFFD}'` (the replacement character “�”)
    /// if the code point is a surrogate (from U+D800 to U+DFFF).
    #[inline]
    pub fn to_char_lossy(&self) -> char {
        self.to_char().unwrap_or('\u{FFFD}')
    }

    /// Decode potentially ill-formed UTF-16.
    #[inline]
    pub fn decode_utf16<I>(input: I) -> DecodeUtf16<I>
    where
        I: Iterator<Item = u16>,
    {
        DecodeUtf16 {
            input: input.peekable(),
        }
    }

    /// Encode potentially ill-formed UTF-16.
    #[inline]
    pub fn encode_utf16<I>(input: I) -> EncodeUtf16<I>
    where
        I: Iterator<Item = CodePoint>,
    {
        EncodeUtf16 { input, buf: None }
    }
}

impl From<char> for CodePoint {
    #[inline]
    fn from(c: char) -> Self {
        Self::from_char(c)
    }
}

/// An iterator for decoding potentially ill-formed UTF-16.
pub struct DecodeUtf16<I>
where
    I: Iterator<Item = u16>,
{
    input: Peekable<I>,
}
impl<I> Iterator for DecodeUtf16<I>
where
    I: Iterator<Item = u16>,
{
    type Item = CodePoint;

    #[inline]
    fn next(&mut self) -> Option<CodePoint> {
        let mut val = self.input.next()? as u32;

        if let 0xD800..=0xDBFF = val {
            if let Some(y @ 0xDC00..=0xDFFF) = self.input.peek().copied() {
                val = 0x1_0000 | ((val - 0xD800) << 10) | (y as u32 - 0xDC00);
                self.input.next();
            }
        }

        // Safety: this can not be greater than 0x10FFFF by construction.
        Some(unsafe { CodePoint::from_u32_unchecked(val) })
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        let (l, h) = self.input.size_hint();
        (l / 2, h)
    }
}
impl<I> FusedIterator for DecodeUtf16<I> where I: FusedIterator<Item = u16> {}

/// An iterator for encoding potentially ill-formed UTF-16.
pub struct EncodeUtf16<I>
where
    I: Iterator<Item = CodePoint>,
{
    input: I,
    buf: Option<u16>,
}
impl<I> Iterator for EncodeUtf16<I>
where
    I: Iterator<Item = CodePoint>,
{
    type Item = u16;

    #[inline]
    fn next(&mut self) -> Option<u16> {
        if let Some(x) = self.buf.take() {
            return Some(x);
        }

        let p = self.input.next()?.to_u32();
        if p >= 0x1_0000 {
            self.buf = Some(((p - 0x1_0000) & 0x3FF) as u16 | 0xDC00);
            Some(((p - 0x1_0000) >> 10) as u16 | 0xD800)
        } else {
            Some(p as u16)
        }
    }

    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        let (l, h) = self.input.size_hint();
        (
            l.saturating_add(self.buf.is_some() as usize),
            h.and_then(|x| x.checked_mul(2))
                .and_then(|x| x.checked_add(self.buf.is_some() as usize)),
        )
    }
}
impl<I> FusedIterator for EncodeUtf16<I> where I: FusedIterator<Item = CodePoint> {}