Debian Codegraph @

third_party/rust/encoding_rs/src/x_user_defined.rs

raw
1 // Copyright Mozilla Foundation. See the COPYRIGHT
2 // file at the top-level directory of this distribution.
3 //
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
9
10 use super::*;
11 use crate::handles::*;
12 use crate::variant::*;
13
14 cfg_if! {
15 if #[cfg(feature = "simd-accel")] {
16 use simd_funcs::*;
17 use core::simd::u16x8;
18 use core::simd::cmp::SimdPartialOrd;
19 #[rustversion::since(1.95)]
20 use core::simd::Select;
21
22 #[inline(always)]
23 fn shift_upper(unpacked: u16x8) -> u16x8 {
24 let highest_ascii = u16x8::splat(0x7F);
25 unpacked + unpacked.simd_gt(highest_ascii).select(u16x8::splat(0xF700), u16x8::splat(0)) }
26 } else {
27 }
28 }
29
30 pub struct UserDefinedDecoder;
31
32 impl UserDefinedDecoder {
33 pub fn new() -> VariantDecoder {
34 VariantDecoder::UserDefined(UserDefinedDecoder)
35 }
36
37 pub fn max_utf16_buffer_length(&self, byte_length: usize) -> Option<usize> {
38 Some(byte_length)
39 }
40
41 pub fn max_utf8_buffer_length_without_replacement(&self, byte_length: usize) -> Option<usize> {
42 byte_length.checked_mul(3)
43 }
44
45 pub fn max_utf8_buffer_length(&self, byte_length: usize) -> Option<usize> {
46 byte_length.checked_mul(3)
47 }
48
49 decoder_function!(
50 {},
51 {},
52 {},
53 {
54 if b < 0x80 {
55 // ASCII run not optimized, because binary data expected
56 destination_handle.write_ascii(b);
57 continue;
58 }
59 destination_handle.write_upper_bmp(u16::from(b) + 0xF700);
60 continue;
61 },
62 self,
63 src_consumed,
64 dest,
65 source,
66 b,
67 destination_handle,
68 _unread_handle,
69 check_space_bmp,
70 decode_to_utf8_raw,
71 u8,
72 Utf8Destination
73 );
74
75 #[cfg(not(feature = "simd-accel"))]
76 pub fn decode_to_utf16_raw(
77 &mut self,
78 src: &[u8],
79 dst: &mut [u16],
80 _last: bool,
81 ) -> (DecoderResult, usize, usize) {
82 let (pending, length) = if dst.len() < src.len() {
83 (DecoderResult::OutputFull, dst.len())
84 } else {
85 (DecoderResult::InputEmpty, src.len())
86 };
87 let src_trim = &src[..length];
88 let dst_trim = &mut dst[..length];
89 src_trim
90 .iter()
91 .zip(dst_trim.iter_mut())
92 .for_each(|(from, to)| {
93 *to = {
94 let unit = *from;
95 if unit < 0x80 {
96 u16::from(unit)
97 } else {
98 u16::from(unit) + 0xF700
99 }
100 }
101 });
102 (pending, length, length)
103 }
104
105 #[cfg(feature = "simd-accel")]
106 pub fn decode_to_utf16_raw(
107 &mut self,
108 src: &[u8],
109 dst: &mut [u16],
110 _last: bool,
111 ) -> (DecoderResult, usize, usize) {
112 let (pending, length) = if dst.len() < src.len() {
113 (DecoderResult::OutputFull, dst.len())
114 } else {
115 (DecoderResult::InputEmpty, src.len())
116 };
117 // Not bothering with alignment
118 let tail_start = length & !0xF;
119 let simd_iterations = length >> 4;
120 let src_ptr = src.as_ptr();
121 let dst_ptr = dst.as_mut_ptr();
122 // Safety: This is `for i in 0..length / 16`
123 for i in 0..simd_iterations {
124 // Safety: This is in bounds: length is the minumum valid length for both src/dst
125 // and i ranges to length/16, so multiplying by 16 will always be `< length` and can do
126 // a 16 byte read
127 let input = unsafe { load16_unaligned(src_ptr.add(i * 16)) };
128 let (first, second) = simd_unpack(input);
129 unsafe {
130 // Safety: same as above, but this is two consecutive 8-byte reads
131 store8_unaligned(dst_ptr.add(i * 16), shift_upper(first));
132 store8_unaligned(dst_ptr.add((i * 16) + 8), shift_upper(second));
133 }
134 }
135 let src_tail = &src[tail_start..length];
136 let dst_tail = &mut dst[tail_start..length];
137 src_tail
138 .iter()
139 .zip(dst_tail.iter_mut())
140 .for_each(|(from, to)| {
141 *to = {
142 let unit = *from;
143 if unit < 0x80 {
144 u16::from(unit)
145 } else {
146 u16::from(unit) + 0xF700
147 }
148 }
149 });
150 (pending, length, length)
151 }
152 }
153
154 pub struct UserDefinedEncoder;
155
156 impl UserDefinedEncoder {
157 pub fn new(encoding: &'static Encoding) -> Encoder {
158 Encoder::new(encoding, VariantEncoder::UserDefined(UserDefinedEncoder))
159 }
160
161 pub fn max_buffer_length_from_utf16_without_replacement(
162 &self,
163 u16_length: usize,
164 ) -> Option<usize> {
165 Some(u16_length)
166 }
167
168 pub fn max_buffer_length_from_utf8_without_replacement(
169 &self,
170 byte_length: usize,
171 ) -> Option<usize> {
172 Some(byte_length)
173 }
174
175 encoder_functions!(
176 {},
177 {
178 if c <= '\u{7F}' {
179 // TODO optimize ASCII run
180 destination_handle.write_one(c as u8);
181 continue;
182 }
183 if c < '\u{F780}' || c > '\u{F7FF}' {
184 return (
185 EncoderResult::Unmappable(c),
186 unread_handle.consumed(),
187 destination_handle.written(),
188 );
189 }
190 destination_handle.write_one((u32::from(c) - 0xF700) as u8);
191 continue;
192 },
193 self,
194 src_consumed,
195 source,
196 dest,
197 c,
198 destination_handle,
199 unread_handle,
200 check_space_one
201 );
202 }
203
204 // Any copyright to the test code below this comment is dedicated to the
205 // Public Domain. http://creativecommons.org/publicdomain/zero/1.0/
206
207 #[cfg(all(test, feature = "alloc"))]
208 mod tests {
209 use super::super::testing::*;
210 use super::super::*;
211
212 fn decode_x_user_defined(bytes: &[u8], expect: &str) {
213 decode(X_USER_DEFINED, bytes, expect);
214 }
215
216 fn encode_x_user_defined(string: &str, expect: &[u8]) {
217 encode(X_USER_DEFINED, string, expect);
218 }
219
220 #[test]
221 fn test_x_user_defined_decode() {
222 // Empty
223 decode_x_user_defined(b"", "");
224
225 // ASCII
226 decode_x_user_defined(b"\x61\x62", "\u{0061}\u{0062}");
227
228 decode_x_user_defined(b"\x80\xFF", "\u{F780}\u{F7FF}");
229 decode_x_user_defined(b"\x80\xFF\x61\x62\x80\xFF\x61\x62\x80\xFF\x61\x62\x80\xFF\x61\x62\x80\xFF\x61\x62", "\u{F780}\u{F7FF}\u{0061}\u{0062}\u{F780}\u{F7FF}\u{0061}\u{0062}\u{F780}\u{F7FF}\u{0061}\u{0062}\u{F780}\u{F7FF}\u{0061}\u{0062}\u{F780}\u{F7FF}\u{0061}\u{0062}");
230 }
231
232 #[test]
233 fn test_x_user_defined_encode() {
234 // Empty
235 encode_x_user_defined("", b"");
236
237 // ASCII
238 encode_x_user_defined("\u{0061}\u{0062}", b"\x61\x62");
239
240 encode_x_user_defined("\u{F780}\u{F7FF}", b"\x80\xFF");
241 encode_x_user_defined("\u{F77F}\u{F800}", b"&#63359;&#63488;");
242 }
243
244 #[test]
245 fn test_x_user_defined_from_two_low_surrogates() {
246 let expectation = b"&#65533;&#65533;";
247 let mut output = [0u8; 40];
248 let mut encoder = X_USER_DEFINED.new_encoder();
249 let (result, read, written, had_errors) =
250 encoder.encode_from_utf16(&[0xDC00u16, 0xDEDEu16], &mut output[..], true);
251 assert_eq!(result, CoderResult::InputEmpty);
252 assert_eq!(read, 2);
253 assert_eq!(written, expectation.len());
254 assert!(had_errors);
255 assert_eq!(&output[..written], expectation);
256 }
257 }