diff options
author | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-06-12 05:35:29 +0000 |
---|---|---|
committer | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-06-12 05:35:29 +0000 |
commit | 59203c63bb777a3bacec32fb8830fba33540e809 (patch) | |
tree | 58298e711c0ff0575818c30485b44a2f21bf28a0 /third_party/rust/encoding_rs/src | |
parent | Adding upstream version 126.0.1. (diff) | |
download | firefox-59203c63bb777a3bacec32fb8830fba33540e809.tar.xz firefox-59203c63bb777a3bacec32fb8830fba33540e809.zip |
Adding upstream version 127.0.upstream/127.0
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'third_party/rust/encoding_rs/src')
-rw-r--r-- | third_party/rust/encoding_rs/src/ascii.rs | 388 | ||||
-rw-r--r-- | third_party/rust/encoding_rs/src/handles.rs | 36 | ||||
-rw-r--r-- | third_party/rust/encoding_rs/src/lib.rs | 13 | ||||
-rw-r--r-- | third_party/rust/encoding_rs/src/mem.rs | 18 | ||||
-rw-r--r-- | third_party/rust/encoding_rs/src/simd_funcs.rs | 146 | ||||
-rw-r--r-- | third_party/rust/encoding_rs/src/single_byte.rs | 64 | ||||
-rw-r--r-- | third_party/rust/encoding_rs/src/x_user_defined.rs | 10 |
7 files changed, 590 insertions, 85 deletions
diff --git a/third_party/rust/encoding_rs/src/ascii.rs b/third_party/rust/encoding_rs/src/ascii.rs index 90644de7a4..80233f285e 100644 --- a/third_party/rust/encoding_rs/src/ascii.rs +++ b/third_party/rust/encoding_rs/src/ascii.rs @@ -51,6 +51,8 @@ cfg_if! { } } +// Safety invariants for masks: data & mask = 0 for valid ASCII or basic latin utf-16 + // `as` truncates, so works on 32-bit, too. #[allow(dead_code)] pub const ASCII_MASK: usize = 0x8080_8080_8080_8080u64 as usize; @@ -62,6 +64,9 @@ pub const BASIC_LATIN_MASK: usize = 0xFF80_FF80_FF80_FF80u64 as usize; #[allow(unused_macros)] macro_rules! ascii_naive { ($name:ident, $src_unit:ty, $dst_unit:ty) => { + /// Safety: src and dst must have len_unit elements and be aligned + /// Safety-usable invariant: will return Some() when it fails + /// to convert. The first value will be a u8 that is > 127. #[inline(always)] pub unsafe fn $name( src: *const $src_unit, @@ -71,10 +76,13 @@ macro_rules! ascii_naive { // Yes, manually omitting the bound check here matters // a lot for perf. for i in 0..len { + // Safety: len invariant used here let code_unit = *(src.add(i)); + // Safety: Upholds safety-usable invariant here if code_unit > 127 { return Some((code_unit, i)); } + // Safety: len invariant used here *(dst.add(i)) = code_unit as $dst_unit; } return None; @@ -85,9 +93,15 @@ macro_rules! ascii_naive { #[allow(unused_macros)] macro_rules! ascii_alu { ($name:ident, + // safety invariant: src/dst MUST be u8 $src_unit:ty, $dst_unit:ty, + // Safety invariant: stride_fn must consume and produce two usizes, and return the index of the first non-ascii when it fails $stride_fn:ident) => { + /// Safety: src and dst must have len elements, src is valid for read, dst is valid for + /// write + /// Safety-usable invariant: will return Some() when it fails + /// to convert. The first value will be a u8 that is > 127. #[cfg_attr(feature = "cargo-clippy", allow(never_loop, cast_ptr_alignment))] #[inline(always)] pub unsafe fn $name( @@ -98,6 +112,7 @@ macro_rules! ascii_alu { let mut offset = 0usize; // This loop is only broken out of as a `goto` forward loop { + // Safety: until_alignment becomes the number of bytes we need to munch until we are aligned to usize let mut until_alignment = { // Check if the other unit aligns if we move the narrower unit // to alignment. @@ -106,6 +121,7 @@ macro_rules! ascii_alu { let src_alignment = (src as usize) & ALU_ALIGNMENT_MASK; let dst_alignment = (dst as usize) & ALU_ALIGNMENT_MASK; if src_alignment != dst_alignment { + // Safety: bails early and ends up in the naïve branch where usize-alignment doesn't matter break; } (ALU_ALIGNMENT - src_alignment) & ALU_ALIGNMENT_MASK @@ -134,25 +150,40 @@ macro_rules! ascii_alu { // x86_64 should be using SSE2 in due course, keeping the move // to alignment here. It would be good to test on more ARM CPUs // and on real MIPS and POWER hardware. + // + // Safety: This is the naïve code once again, for `until_alignment` bytes while until_alignment != 0 { let code_unit = *(src.add(offset)); if code_unit > 127 { + // Safety: Upholds safety-usable invariant here return Some((code_unit, offset)); } *(dst.add(offset)) = code_unit as $dst_unit; + // Safety: offset is the number of bytes copied so far offset += 1; until_alignment -= 1; } let len_minus_stride = len - ALU_STRIDE_SIZE; loop { + // Safety: num_ascii is known to be a byte index of a non-ascii byte due to stride_fn's invariant if let Some(num_ascii) = $stride_fn( + // Safety: These are known to be valid and aligned since we have at + // least ALU_STRIDE_SIZE data in these buffers, and offset is the + // number of elements copied so far, which according to the + // until_alignment calculation above will cause both src and dst to be + // aligned to usize after this add src.add(offset) as *const usize, dst.add(offset) as *mut usize, ) { offset += num_ascii; + // Safety: Upholds safety-usable invariant here by indexing into non-ascii byte return Some((*(src.add(offset)), offset)); } + // Safety: offset continues to be the number of bytes copied so far, and + // maintains usize alignment for the next loop iteration offset += ALU_STRIDE_SIZE; + // Safety: This is `offset > len - stride. This loop will continue as long as + // `offset <= len - stride`, which means there are `stride` bytes to still be read. if offset > len_minus_stride { break; } @@ -160,11 +191,17 @@ macro_rules! ascii_alu { } break; } + + // Safety: This is the naïve code, same as ascii_naive, and has no requirements + // other than src/dst being valid for the the right lens while offset < len { + // Safety: len invariant used here let code_unit = *(src.add(offset)); if code_unit > 127 { + // Safety: Upholds safety-usable invariant here return Some((code_unit, offset)); } + // Safety: len invariant used here *(dst.add(offset)) = code_unit as $dst_unit; offset += 1; } @@ -176,9 +213,16 @@ macro_rules! ascii_alu { #[allow(unused_macros)] macro_rules! basic_latin_alu { ($name:ident, + // safety invariant: use u8 for src/dest for ascii, and u16 for basic_latin $src_unit:ty, $dst_unit:ty, + // safety invariant: stride function must munch ALU_STRIDE_SIZE*size(src_unit) bytes off of src and + // write ALU_STRIDE_SIZE*size(dst_unit) bytes to dst $stride_fn:ident) => { + /// Safety: src and dst must have len elements, src is valid for read, dst is valid for + /// write + /// Safety-usable invariant: will return Some() when it fails + /// to convert. The first value will be a u8 that is > 127. #[cfg_attr( feature = "cargo-clippy", allow(never_loop, cast_ptr_alignment, cast_lossless) @@ -192,6 +236,8 @@ macro_rules! basic_latin_alu { let mut offset = 0usize; // This loop is only broken out of as a `goto` forward loop { + // Safety: until_alignment becomes the number of bytes we need to munch from src/dest until we are aligned to usize + // We ensure basic-latin has the same alignment as ascii, starting with ascii since it is smaller. let mut until_alignment = { // Check if the other unit aligns if we move the narrower unit // to alignment. @@ -237,24 +283,37 @@ macro_rules! basic_latin_alu { // x86_64 should be using SSE2 in due course, keeping the move // to alignment here. It would be good to test on more ARM CPUs // and on real MIPS and POWER hardware. + // + // Safety: This is the naïve code once again, for `until_alignment` bytes while until_alignment != 0 { let code_unit = *(src.add(offset)); if code_unit > 127 { + // Safety: Upholds safety-usable invariant here return Some((code_unit, offset)); } *(dst.add(offset)) = code_unit as $dst_unit; + // Safety: offset is the number of bytes copied so far offset += 1; until_alignment -= 1; } let len_minus_stride = len - ALU_STRIDE_SIZE; loop { if !$stride_fn( + // Safety: These are known to be valid and aligned since we have at + // least ALU_STRIDE_SIZE data in these buffers, and offset is the + // number of elements copied so far, which according to the + // until_alignment calculation above will cause both src and dst to be + // aligned to usize after this add src.add(offset) as *const usize, dst.add(offset) as *mut usize, ) { break; } + // Safety: offset continues to be the number of bytes copied so far, and + // maintains usize alignment for the next loop iteration offset += ALU_STRIDE_SIZE; + // Safety: This is `offset > len - stride. This loop will continue as long as + // `offset <= len - stride`, which means there are `stride` bytes to still be read. if offset > len_minus_stride { break; } @@ -262,11 +321,15 @@ macro_rules! basic_latin_alu { } break; } + // Safety: This is the naïve code once again, for leftover bytes while offset < len { + // Safety: len invariant used here let code_unit = *(src.add(offset)); if code_unit > 127 { + // Safety: Upholds safety-usable invariant here return Some((code_unit, offset)); } + // Safety: len invariant used here *(dst.add(offset)) = code_unit as $dst_unit; offset += 1; } @@ -277,7 +340,11 @@ macro_rules! basic_latin_alu { #[allow(unused_macros)] macro_rules! latin1_alu { + // safety invariant: stride function must munch ALU_STRIDE_SIZE*size(src_unit) bytes off of src and + // write ALU_STRIDE_SIZE*size(dst_unit) bytes to dst ($name:ident, $src_unit:ty, $dst_unit:ty, $stride_fn:ident) => { + /// Safety: src and dst must have len elements, src is valid for read, dst is valid for + /// write #[cfg_attr( feature = "cargo-clippy", allow(never_loop, cast_ptr_alignment, cast_lossless) @@ -287,6 +354,8 @@ macro_rules! latin1_alu { let mut offset = 0usize; // This loop is only broken out of as a `goto` forward loop { + // Safety: until_alignment becomes the number of bytes we need to munch from src/dest until we are aligned to usize + // We ensure the UTF-16 side has the same alignment as the Latin-1 side, starting with Latin-1 since it is smaller. let mut until_alignment = { if ::core::mem::size_of::<$src_unit>() < ::core::mem::size_of::<$dst_unit>() { // unpack @@ -313,19 +382,30 @@ macro_rules! latin1_alu { } }; if until_alignment + ALU_STRIDE_SIZE <= len { + // Safety: This is the naïve code once again, for `until_alignment` bytes while until_alignment != 0 { let code_unit = *(src.add(offset)); *(dst.add(offset)) = code_unit as $dst_unit; + // Safety: offset is the number of bytes copied so far offset += 1; until_alignment -= 1; } let len_minus_stride = len - ALU_STRIDE_SIZE; loop { $stride_fn( + // Safety: These are known to be valid and aligned since we have at + // least ALU_STRIDE_SIZE data in these buffers, and offset is the + // number of elements copied so far, which according to the + // until_alignment calculation above will cause both src and dst to be + // aligned to usize after this add src.add(offset) as *const usize, dst.add(offset) as *mut usize, ); + // Safety: offset continues to be the number of bytes copied so far, and + // maintains usize alignment for the next loop iteration offset += ALU_STRIDE_SIZE; + // Safety: This is `offset > len - stride. This loop will continue as long as + // `offset <= len - stride`, which means there are `stride` bytes to still be read. if offset > len_minus_stride { break; } @@ -333,7 +413,9 @@ macro_rules! latin1_alu { } break; } + // Safety: This is the naïve code once again, for leftover bytes while offset < len { + // Safety: len invariant used here let code_unit = *(src.add(offset)); *(dst.add(offset)) = code_unit as $dst_unit; offset += 1; @@ -348,11 +430,19 @@ macro_rules! ascii_simd_check_align { $name:ident, $src_unit:ty, $dst_unit:ty, + // Safety: This function must require aligned src/dest that are valid for reading/writing SIMD_STRIDE_SIZE src_unit/dst_unit $stride_both_aligned:ident, + // Safety: This function must require aligned/unaligned src/dest that are valid for reading/writing SIMD_STRIDE_SIZE src_unit/dst_unit $stride_src_aligned:ident, + // Safety: This function must require unaligned/aligned src/dest that are valid for reading/writing SIMD_STRIDE_SIZE src_unit/dst_unit $stride_dst_aligned:ident, + // Safety: This function must require unaligned src/dest that are valid for reading/writing SIMD_STRIDE_SIZE src_unit/dst_unit $stride_neither_aligned:ident ) => { + /// Safety: src/dst must be valid for reads/writes of `len` elements of their units. + /// + /// Safety-usable invariant: will return Some() when it encounters non-ASCII, with the first element in the Some being + /// guaranteed to be non-ASCII (> 127), and the second being the offset where it is found #[inline(always)] pub unsafe fn $name( src: *const $src_unit, @@ -360,6 +450,7 @@ macro_rules! ascii_simd_check_align { len: usize, ) -> Option<($src_unit, usize)> { let mut offset = 0usize; + // Safety: if this check succeeds we're valid for reading/writing at least `SIMD_STRIDE_SIZE` elements. if SIMD_STRIDE_SIZE <= len { let len_minus_stride = len - SIMD_STRIDE_SIZE; // XXX Should we first process one stride unconditionally as unaligned to @@ -368,23 +459,29 @@ macro_rules! ascii_simd_check_align { // on Haswell, it would make sense to just use unaligned and not bother // checking. Need to benchmark older architectures before deciding. let dst_masked = (dst as usize) & SIMD_ALIGNMENT_MASK; + // Safety: checking whether src is aligned if ((src as usize) & SIMD_ALIGNMENT_MASK) == 0 { + // Safety: Checking whether dst is aligned if dst_masked == 0 { loop { + // Safety: We're valid to read/write SIMD_STRIDE_SIZE elements and have the appropriate alignments if !$stride_both_aligned(src.add(offset), dst.add(offset)) { break; } offset += SIMD_STRIDE_SIZE; + // Safety: This is `offset > len - SIMD_STRIDE_SIZE` which means we always have at least `SIMD_STRIDE_SIZE` elements to munch next time. if offset > len_minus_stride { break; } } } else { loop { + // Safety: We're valid to read/write SIMD_STRIDE_SIZE elements and have the appropriate alignments if !$stride_src_aligned(src.add(offset), dst.add(offset)) { break; } offset += SIMD_STRIDE_SIZE; + // Safety: This is `offset > len - SIMD_STRIDE_SIZE` which means we always have at least `SIMD_STRIDE_SIZE` elements to munch next time. if offset > len_minus_stride { break; } @@ -393,20 +490,24 @@ macro_rules! ascii_simd_check_align { } else { if dst_masked == 0 { loop { + // Safety: We're valid to read/write SIMD_STRIDE_SIZE elements and have the appropriate alignments if !$stride_dst_aligned(src.add(offset), dst.add(offset)) { break; } offset += SIMD_STRIDE_SIZE; + // Safety: This is `offset > len - SIMD_STRIDE_SIZE` which means we always have at least `SIMD_STRIDE_SIZE` elements to munch next time. if offset > len_minus_stride { break; } } } else { loop { + // Safety: We're valid to read/write SIMD_STRIDE_SIZE elements and have the appropriate alignments if !$stride_neither_aligned(src.add(offset), dst.add(offset)) { break; } offset += SIMD_STRIDE_SIZE; + // Safety: This is `offset > len - SIMD_STRIDE_SIZE` which means we always have at least `SIMD_STRIDE_SIZE` elements to munch next time. if offset > len_minus_stride { break; } @@ -415,8 +516,10 @@ macro_rules! ascii_simd_check_align { } } while offset < len { + // Safety: uses len invariant here and below let code_unit = *(src.add(offset)); if code_unit > 127 { + // Safety: upholds safety-usable invariant return Some((code_unit, offset)); } *(dst.add(offset)) = code_unit as $dst_unit; @@ -433,13 +536,21 @@ macro_rules! ascii_simd_check_align_unrolled { $name:ident, $src_unit:ty, $dst_unit:ty, + // Safety: This function must require aligned src/dest that are valid for reading/writing SIMD_STRIDE_SIZE src_unit/dst_unit $stride_both_aligned:ident, + // Safety: This function must require aligned/unaligned src/dest that are valid for reading/writing SIMD_STRIDE_SIZE src_unit/dst_unit $stride_src_aligned:ident, + // Safety: This function must require unaligned src/dest that are valid for reading/writing SIMD_STRIDE_SIZE src_unit/dst_unit $stride_neither_aligned:ident, + // Safety: This function must require aligned src/dest that are valid for reading/writing 2*SIMD_STRIDE_SIZE src_unit/dst_unit $double_stride_both_aligned:ident, + // Safety: This function must require aligned/unaligned src/dest that are valid for reading/writing 2*SIMD_STRIDE_SIZE src_unit/dst_unit $double_stride_src_aligned:ident ) => { - #[inline(always)] + /// Safety: src/dst must be valid for reads/writes of `len` elements of their units. + /// + /// Safety-usable invariant: will return Some() when it encounters non-ASCII, with the first element in the Some being + /// guaranteed to be non-ASCII (> 127), and the second being the offset where it is found #[inline(always)] pub unsafe fn $name( src: *const $src_unit, dst: *mut $dst_unit, @@ -450,8 +561,10 @@ macro_rules! ascii_simd_check_align_unrolled { // This loop is only broken out of as a goto forward without // actually looping 'outer: loop { + // Safety: if this check succeeds we're valid for reading/writing at least `SIMD_STRIDE_SIZE` elements. if SIMD_STRIDE_SIZE <= len { // First, process one unaligned + // Safety: this is safe to call since we're valid for this read/write if !$stride_neither_aligned(src, dst) { break 'outer; } @@ -461,37 +574,54 @@ macro_rules! ascii_simd_check_align_unrolled { // there will be enough more to justify more expense // in the case of non-ASCII. // Use aligned reads for the sake of old microachitectures. + // + // Safety: this correctly calculates the number of src_units that need to be read before the remaining list is aligned. + // This is less that SIMD_ALIGNMENT, which is also SIMD_STRIDE_SIZE (as documented) let until_alignment = ((SIMD_ALIGNMENT - ((src.add(offset) as usize) & SIMD_ALIGNMENT_MASK)) & SIMD_ALIGNMENT_MASK) / unit_size; - // This addition won't overflow, because even in the 32-bit PAE case the + // Safety: This addition won't overflow, because even in the 32-bit PAE case the // address space holds enough code that the slice length can't be that // close to address space size. // offset now equals SIMD_STRIDE_SIZE, hence times 3 below. + // + // Safety: if this check succeeds we're valid for reading/writing at least `2 * SIMD_STRIDE_SIZE` elements plus `until_alignment`. + // The extra SIMD_STRIDE_SIZE in the condition is because `offset` is already `SIMD_STRIDE_SIZE`. if until_alignment + (SIMD_STRIDE_SIZE * 3) <= len { if until_alignment != 0 { + // Safety: this is safe to call since we're valid for this read/write (and more), and don't care about alignment + // This will copy over bytes that get decoded twice since it's not incrementing `offset` by SIMD_STRIDE_SIZE. This is fine. if !$stride_neither_aligned(src.add(offset), dst.add(offset)) { break; } offset += until_alignment; } + // Safety: At this point we're valid for reading/writing 2*SIMD_STRIDE_SIZE elements + // Safety: Now `offset` is aligned for `src` let len_minus_stride_times_two = len - (SIMD_STRIDE_SIZE * 2); + // Safety: This is whether dst is aligned let dst_masked = (dst.add(offset) as usize) & SIMD_ALIGNMENT_MASK; if dst_masked == 0 { loop { + // Safety: both are aligned, we can call the aligned function. We're valid for reading/writing double stride from the initial condition + // and the loop break condition below if let Some(advance) = $double_stride_both_aligned(src.add(offset), dst.add(offset)) { offset += advance; let code_unit = *(src.add(offset)); + // Safety: uses safety-usable invariant on ascii_to_ascii_simd_double_stride to return + // guaranteed non-ascii return Some((code_unit, offset)); } offset += SIMD_STRIDE_SIZE * 2; + // Safety: This is `offset > len - 2 * SIMD_STRIDE_SIZE` which means we always have at least `2 * SIMD_STRIDE_SIZE` elements to munch next time. if offset > len_minus_stride_times_two { break; } } + // Safety: We're valid for reading/writing one more, and can still assume alignment if offset + SIMD_STRIDE_SIZE <= len { if !$stride_both_aligned(src.add(offset), dst.add(offset)) { break 'outer; @@ -500,18 +630,25 @@ macro_rules! ascii_simd_check_align_unrolled { } } else { loop { + // Safety: only src is aligned here. We're valid for reading/writing double stride from the initial condition + // and the loop break condition below if let Some(advance) = $double_stride_src_aligned(src.add(offset), dst.add(offset)) { offset += advance; let code_unit = *(src.add(offset)); + // Safety: uses safety-usable invariant on ascii_to_ascii_simd_double_stride to return + // guaranteed non-ascii return Some((code_unit, offset)); } offset += SIMD_STRIDE_SIZE * 2; + // Safety: This is `offset > len - 2 * SIMD_STRIDE_SIZE` which means we always have at least `2 * SIMD_STRIDE_SIZE` elements to munch next time. + if offset > len_minus_stride_times_two { break; } } + // Safety: We're valid for reading/writing one more, and can still assume alignment if offset + SIMD_STRIDE_SIZE <= len { if !$stride_src_aligned(src.add(offset), dst.add(offset)) { break 'outer; @@ -522,11 +659,13 @@ macro_rules! ascii_simd_check_align_unrolled { } else { // At most two iterations, so unroll if offset + SIMD_STRIDE_SIZE <= len { + // Safety: The check above ensures we're allowed to read/write this, and we don't use alignment if !$stride_neither_aligned(src.add(offset), dst.add(offset)) { break; } offset += SIMD_STRIDE_SIZE; if offset + SIMD_STRIDE_SIZE <= len { + // Safety: The check above ensures we're allowed to read/write this, and we don't use alignment if !$stride_neither_aligned(src.add(offset), dst.add(offset)) { break; } @@ -538,8 +677,10 @@ macro_rules! ascii_simd_check_align_unrolled { break 'outer; } while offset < len { + // Safety: relies straightforwardly on the `len` invariant let code_unit = *(src.add(offset)); if code_unit > 127 { + // Safety-usable invariant upheld here return Some((code_unit, offset)); } *(dst.add(offset)) = code_unit as $dst_unit; @@ -556,30 +697,45 @@ macro_rules! latin1_simd_check_align { $name:ident, $src_unit:ty, $dst_unit:ty, + // Safety: This function must require aligned src/dest that are valid for reading/writing SIMD_STRIDE_SIZE src_unit/dst_unit $stride_both_aligned:ident, + // Safety: This function must require aligned/unaligned src/dest that are valid for reading/writing SIMD_STRIDE_SIZE src_unit/dst_unit $stride_src_aligned:ident, + // Safety: This function must require unaligned/aligned src/dest that are valid for reading/writing SIMD_STRIDE_SIZE src_unit/dst_unit $stride_dst_aligned:ident, + // Safety: This function must require unaligned src/dest that are valid for reading/writing SIMD_STRIDE_SIZE src_unit/dst_unit $stride_neither_aligned:ident + ) => { + /// Safety: src/dst must be valid for reads/writes of `len` elements of their units. #[inline(always)] pub unsafe fn $name(src: *const $src_unit, dst: *mut $dst_unit, len: usize) { let mut offset = 0usize; + // Safety: if this check succeeds we're valid for reading/writing at least `SIMD_STRIDE_SIZE` elements. if SIMD_STRIDE_SIZE <= len { let len_minus_stride = len - SIMD_STRIDE_SIZE; + // Whether dst is aligned let dst_masked = (dst as usize) & SIMD_ALIGNMENT_MASK; + // Whether src is aligned if ((src as usize) & SIMD_ALIGNMENT_MASK) == 0 { if dst_masked == 0 { loop { + // Safety: Both were aligned, we can use the aligned function $stride_both_aligned(src.add(offset), dst.add(offset)); offset += SIMD_STRIDE_SIZE; + // Safety: This is `offset > len - SIMD_STRIDE_SIZE`, which means in the next iteration we're valid for + // reading/writing at least SIMD_STRIDE_SIZE elements. if offset > len_minus_stride { break; } } } else { loop { + // Safety: src was aligned, dst was not $stride_src_aligned(src.add(offset), dst.add(offset)); offset += SIMD_STRIDE_SIZE; + // Safety: This is `offset > len - SIMD_STRIDE_SIZE`, which means in the next iteration we're valid for + // reading/writing at least SIMD_STRIDE_SIZE elements. if offset > len_minus_stride { break; } @@ -588,16 +744,22 @@ macro_rules! latin1_simd_check_align { } else { if dst_masked == 0 { loop { + // Safety: src was aligned, dst was not $stride_dst_aligned(src.add(offset), dst.add(offset)); offset += SIMD_STRIDE_SIZE; + // Safety: This is `offset > len - SIMD_STRIDE_SIZE`, which means in the next iteration we're valid for + // reading/writing at least SIMD_STRIDE_SIZE elements. if offset > len_minus_stride { break; } } } else { loop { + // Safety: Neither were aligned $stride_neither_aligned(src.add(offset), dst.add(offset)); offset += SIMD_STRIDE_SIZE; + // Safety: This is `offset > len - SIMD_STRIDE_SIZE`, which means in the next iteration we're valid for + // reading/writing at least SIMD_STRIDE_SIZE elements. if offset > len_minus_stride { break; } @@ -606,6 +768,7 @@ macro_rules! latin1_simd_check_align { } } while offset < len { + // Safety: relies straightforwardly on the `len` invariant let code_unit = *(src.add(offset)); *(dst.add(offset)) = code_unit as $dst_unit; offset += 1; @@ -620,56 +783,74 @@ macro_rules! latin1_simd_check_align_unrolled { $name:ident, $src_unit:ty, $dst_unit:ty, + // Safety: This function must require aligned src/dest that are valid for reading/writing SIMD_STRIDE_SIZE src_unit/dst_unit $stride_both_aligned:ident, + // Safety: This function must require aligned/unaligned src/dest that are valid for reading/writing SIMD_STRIDE_SIZE src_unit/dst_unit $stride_src_aligned:ident, + // Safety: This function must require unaligned/aligned src/dest that are valid for reading/writing SIMD_STRIDE_SIZE src_unit/dst_unit $stride_dst_aligned:ident, + // Safety: This function must require unaligned src/dest that are valid for reading/writing SIMD_STRIDE_SIZE src_unit/dst_unit $stride_neither_aligned:ident ) => { + /// Safety: src/dst must be valid for reads/writes of `len` elements of their units. #[inline(always)] pub unsafe fn $name(src: *const $src_unit, dst: *mut $dst_unit, len: usize) { let unit_size = ::core::mem::size_of::<$src_unit>(); let mut offset = 0usize; + // Safety: if this check succeeds we're valid for reading/writing at least `SIMD_STRIDE_SIZE` elements. if SIMD_STRIDE_SIZE <= len { + // Safety: this correctly calculates the number of src_units that need to be read before the remaining list is aligned. + // This is by definition less than SIMD_STRIDE_SIZE. let mut until_alignment = ((SIMD_STRIDE_SIZE - ((src as usize) & SIMD_ALIGNMENT_MASK)) & SIMD_ALIGNMENT_MASK) / unit_size; while until_alignment != 0 { + // Safety: This is a straightforward copy, since until_alignment is < SIMD_STRIDE_SIZE < len, this is in-bounds *(dst.add(offset)) = *(src.add(offset)) as $dst_unit; offset += 1; until_alignment -= 1; } + // Safety: here offset will be `until_alignment`, i.e. enough to align `src`. let len_minus_stride = len - SIMD_STRIDE_SIZE; + // Safety: if this check succeeds we're valid for reading/writing at least `2 * SIMD_STRIDE_SIZE` elements. if offset + SIMD_STRIDE_SIZE * 2 <= len { let len_minus_stride_times_two = len_minus_stride - SIMD_STRIDE_SIZE; + // Safety: at this point src is known to be aligned at offset, dst is not. if (dst.add(offset) as usize) & SIMD_ALIGNMENT_MASK == 0 { loop { + // Safety: We checked alignment of dst above, we can use the alignment functions. We're allowed to read/write 2*SIMD_STRIDE_SIZE elements, which we do. $stride_both_aligned(src.add(offset), dst.add(offset)); offset += SIMD_STRIDE_SIZE; $stride_both_aligned(src.add(offset), dst.add(offset)); offset += SIMD_STRIDE_SIZE; + // Safety: This is `offset > len - 2 * SIMD_STRIDE_SIZE` which means we always have at least `2 * SIMD_STRIDE_SIZE` elements to munch next time. if offset > len_minus_stride_times_two { break; } } } else { loop { + // Safety: we ensured alignment of src already. $stride_src_aligned(src.add(offset), dst.add(offset)); offset += SIMD_STRIDE_SIZE; $stride_src_aligned(src.add(offset), dst.add(offset)); offset += SIMD_STRIDE_SIZE; + // Safety: This is `offset > len - 2 * SIMD_STRIDE_SIZE` which means we always have at least `2 * SIMD_STRIDE_SIZE` elements to munch next time. if offset > len_minus_stride_times_two { break; } } } } + // Safety: This is `offset > len - SIMD_STRIDE_SIZE` which means we are valid to munch SIMD_STRIDE_SIZE more elements, which we do if offset < len_minus_stride { $stride_src_aligned(src.add(offset), dst.add(offset)); offset += SIMD_STRIDE_SIZE; } } while offset < len { + // Safety: uses len invariant here and below let code_unit = *(src.add(offset)); // On x86_64, this loop autovectorizes but in the pack // case there are instructions whose purpose is to make sure @@ -693,7 +874,12 @@ macro_rules! latin1_simd_check_align_unrolled { #[allow(unused_macros)] macro_rules! ascii_simd_unalign { + // Safety: stride_neither_aligned must be a function that requires src/dest be valid for unaligned reads/writes for SIMD_STRIDE_SIZE elements of type src_unit/dest_unit ($name:ident, $src_unit:ty, $dst_unit:ty, $stride_neither_aligned:ident) => { + /// Safety: src and dst must be valid for reads/writes of len elements of type src_unit/dst_unit + /// + /// Safety-usable invariant: will return Some() when it encounters non-ASCII, with the first element in the Some being + /// guaranteed to be non-ASCII (> 127), and the second being the offset where it is found #[inline(always)] pub unsafe fn $name( src: *const $src_unit, @@ -701,21 +887,26 @@ macro_rules! ascii_simd_unalign { len: usize, ) -> Option<($src_unit, usize)> { let mut offset = 0usize; + // Safety: if this check succeeds we're valid for reading/writing at least `stride` elements. if SIMD_STRIDE_SIZE <= len { let len_minus_stride = len - SIMD_STRIDE_SIZE; loop { + // Safety: We know we're valid for `stride` reads/writes, so we can call this function. We don't need alignment. if !$stride_neither_aligned(src.add(offset), dst.add(offset)) { break; } offset += SIMD_STRIDE_SIZE; + // This is `offset > len - stride` which means we always have at least `stride` elements to munch next time. if offset > len_minus_stride { break; } } } while offset < len { + // Safety: Uses len invariant here and below let code_unit = *(src.add(offset)); if code_unit > 127 { + // Safety-usable invariant upheld here return Some((code_unit, offset)); } *(dst.add(offset)) = code_unit as $dst_unit; @@ -728,21 +919,27 @@ macro_rules! ascii_simd_unalign { #[allow(unused_macros)] macro_rules! latin1_simd_unalign { + // Safety: stride_neither_aligned must be a function that requires src/dest be valid for unaligned reads/writes for SIMD_STRIDE_SIZE elements of type src_unit/dest_unit ($name:ident, $src_unit:ty, $dst_unit:ty, $stride_neither_aligned:ident) => { + /// Safety: src and dst must be valid for unaligned reads/writes of len elements of type src_unit/dst_unit #[inline(always)] pub unsafe fn $name(src: *const $src_unit, dst: *mut $dst_unit, len: usize) { let mut offset = 0usize; + // Safety: if this check succeeds we're valid for reading/writing at least `stride` elements. if SIMD_STRIDE_SIZE <= len { let len_minus_stride = len - SIMD_STRIDE_SIZE; loop { + // Safety: We know we're valid for `stride` reads/writes, so we can call this function. We don't need alignment. $stride_neither_aligned(src.add(offset), dst.add(offset)); offset += SIMD_STRIDE_SIZE; + // This is `offset > len - stride` which means we always have at least `stride` elements to munch next time. if offset > len_minus_stride { break; } } } while offset < len { + // Safety: Uses len invariant here let code_unit = *(src.add(offset)); *(dst.add(offset)) = code_unit as $dst_unit; offset += 1; @@ -753,7 +950,11 @@ macro_rules! latin1_simd_unalign { #[allow(unused_macros)] macro_rules! ascii_to_ascii_simd_stride { + // Safety: load/store must be valid for 16 bytes of read/write, which may be unaligned. (candidates: `(load|store)(16|8)_(unaligned|aligned)` functions) ($name:ident, $load:ident, $store:ident) => { + /// Safety: src and dst must be valid for 16 bytes of read/write according to + /// the $load/$store fn, which may allow for unaligned reads/writes or require + /// alignment to either 16x8 or u8x16. #[inline(always)] pub unsafe fn $name(src: *const u8, dst: *mut u8) -> bool { let simd = $load(src); @@ -768,19 +969,32 @@ macro_rules! ascii_to_ascii_simd_stride { #[allow(unused_macros)] macro_rules! ascii_to_ascii_simd_double_stride { + // Safety: store must be valid for 32 bytes of write, which may be unaligned (candidates: `store(8|16)_(aligned|unaligned)`) ($name:ident, $store:ident) => { + /// Safety: src must be valid for 32 bytes of aligned u8x16 read + /// dst must be valid for 32 bytes of unaligned write according to + /// the $store fn, which may allow for unaligned writes or require + /// alignment to either 16x8 or u8x16. + /// + /// Safety-usable invariant: Returns Some(index) if the element at `index` is invalid ASCII #[inline(always)] pub unsafe fn $name(src: *const u8, dst: *mut u8) -> Option<usize> { let first = load16_aligned(src); let second = load16_aligned(src.add(SIMD_STRIDE_SIZE)); $store(dst, first); if unlikely(!simd_is_ascii(first | second)) { + // Safety: mask_ascii produces a mask of all the high bits. let mask_first = mask_ascii(first); if mask_first != 0 { + // Safety: on little endian systems this will be the number of ascii bytes + // before the first non-ascii, i.e. valid for indexing src + // TODO SAFETY: What about big-endian systems? return Some(mask_first.trailing_zeros() as usize); } $store(dst.add(SIMD_STRIDE_SIZE), second); let mask_second = mask_ascii(second); + // Safety: on little endian systems this will be the number of ascii bytes + // before the first non-ascii, i.e. valid for indexing src return Some(SIMD_STRIDE_SIZE + mask_second.trailing_zeros() as usize); } $store(dst.add(SIMD_STRIDE_SIZE), second); @@ -791,7 +1005,11 @@ macro_rules! ascii_to_ascii_simd_double_stride { #[allow(unused_macros)] macro_rules! ascii_to_basic_latin_simd_stride { + // Safety: load/store must be valid for 16 bytes of read/write, which may be unaligned. (candidates: `(load|store)(16|8)_(unaligned|aligned)` functions) ($name:ident, $load:ident, $store:ident) => { + /// Safety: src and dst must be valid for 16/32 bytes of read/write according to + /// the $load/$store fn, which may allow for unaligned reads/writes or require + /// alignment to either 16x8 or u8x16. #[inline(always)] pub unsafe fn $name(src: *const u8, dst: *mut u16) -> bool { let simd = $load(src); @@ -808,13 +1026,18 @@ macro_rules! ascii_to_basic_latin_simd_stride { #[allow(unused_macros)] macro_rules! ascii_to_basic_latin_simd_double_stride { + // Safety: store must be valid for 16 bytes of write, which may be unaligned ($name:ident, $store:ident) => { + /// Safety: src must be valid for 2*SIMD_STRIDE_SIZE bytes of aligned reads, + /// aligned to either 16x8 or u8x16. + /// dst must be valid for 2*SIMD_STRIDE_SIZE bytes of aligned or unaligned reads #[inline(always)] pub unsafe fn $name(src: *const u8, dst: *mut u16) -> Option<usize> { let first = load16_aligned(src); let second = load16_aligned(src.add(SIMD_STRIDE_SIZE)); let (a, b) = simd_unpack(first); $store(dst, a); + // Safety: divide by 2 since it's a u16 pointer $store(dst.add(SIMD_STRIDE_SIZE / 2), b); if unlikely(!simd_is_ascii(first | second)) { let mask_first = mask_ascii(first); @@ -837,7 +1060,11 @@ macro_rules! ascii_to_basic_latin_simd_double_stride { #[allow(unused_macros)] macro_rules! unpack_simd_stride { + // Safety: load/store must be valid for 16 bytes of read/write, which may be unaligned. (candidates: `(load|store)(16|8)_(unaligned|aligned)` functions) ($name:ident, $load:ident, $store:ident) => { + /// Safety: src and dst must be valid for 16 bytes of read/write according to + /// the $load/$store fn, which may allow for unaligned reads/writes or require + /// alignment to either 16x8 or u8x16. #[inline(always)] pub unsafe fn $name(src: *const u8, dst: *mut u16) { let simd = $load(src); @@ -850,7 +1077,11 @@ macro_rules! unpack_simd_stride { #[allow(unused_macros)] macro_rules! basic_latin_to_ascii_simd_stride { + // Safety: load/store must be valid for 16 bytes of read/write, which may be unaligned. (candidates: `(load|store)(16|8)_(unaligned|aligned)` functions) ($name:ident, $load:ident, $store:ident) => { + /// Safety: src and dst must be valid for 32/16 bytes of read/write according to + /// the $load/$store fn, which may allow for unaligned reads/writes or require + /// alignment to either 16x8 or u8x16. #[inline(always)] pub unsafe fn $name(src: *const u16, dst: *mut u8) -> bool { let first = $load(src); @@ -867,7 +1098,11 @@ macro_rules! basic_latin_to_ascii_simd_stride { #[allow(unused_macros)] macro_rules! pack_simd_stride { + // Safety: load/store must be valid for 16 bytes of read/write, which may be unaligned. (candidates: `(load|store)(16|8)_(unaligned|aligned)` functions) ($name:ident, $load:ident, $store:ident) => { + /// Safety: src and dst must be valid for 32/16 bytes of read/write according to + /// the $load/$store fn, which may allow for unaligned reads/writes or require + /// alignment to either 16x8 or u8x16. #[inline(always)] pub unsafe fn $name(src: *const u16, dst: *mut u8) { let first = $load(src); @@ -893,6 +1128,8 @@ cfg_if! { pub const ALU_ALIGNMENT_MASK: usize = 7; + // Safety for stride macros: We stick to the load8_aligned/etc family of functions. We consistently produce + // neither_unaligned variants using only unaligned inputs. ascii_to_ascii_simd_stride!(ascii_to_ascii_stride_neither_aligned, load16_unaligned, store16_unaligned); ascii_to_basic_latin_simd_stride!(ascii_to_basic_latin_stride_neither_aligned, load16_unaligned, store8_unaligned); @@ -901,6 +1138,8 @@ cfg_if! { basic_latin_to_ascii_simd_stride!(basic_latin_to_ascii_stride_neither_aligned, load8_unaligned, store16_unaligned); pack_simd_stride!(pack_stride_neither_aligned, load8_unaligned, store16_unaligned); + // Safety for conversion macros: We use the unalign macro with unalign functions above. All stride functions were produced + // by stride macros that universally munch a single SIMD_STRIDE_SIZE worth of elements. ascii_simd_unalign!(ascii_to_ascii, u8, u8, ascii_to_ascii_stride_neither_aligned); ascii_simd_unalign!(ascii_to_basic_latin, u8, u16, ascii_to_basic_latin_stride_neither_aligned); ascii_simd_unalign!(basic_latin_to_ascii, u16, u8, basic_latin_to_ascii_stride_neither_aligned); @@ -919,6 +1158,9 @@ cfg_if! { pub const SIMD_ALIGNMENT_MASK: usize = 15; + // Safety for stride macros: We stick to the load8_aligned/etc family of functions. We consistently name + // aligned/unaligned functions according to src/dst being aligned/unaligned + ascii_to_ascii_simd_stride!(ascii_to_ascii_stride_both_aligned, load16_aligned, store16_aligned); ascii_to_ascii_simd_stride!(ascii_to_ascii_stride_src_aligned, load16_aligned, store16_unaligned); ascii_to_ascii_simd_stride!(ascii_to_ascii_stride_dst_aligned, load16_unaligned, store16_aligned); @@ -944,6 +1186,9 @@ cfg_if! { pack_simd_stride!(pack_stride_dst_aligned, load8_unaligned, store16_aligned); pack_simd_stride!(pack_stride_neither_aligned, load8_unaligned, store16_unaligned); + // Safety for conversion macros: We use the correct pattern of both/src/dst/neither here. All stride functions were produced + // by stride macros that universally munch a single SIMD_STRIDE_SIZE worth of elements. + ascii_simd_check_align!(ascii_to_ascii, u8, u8, ascii_to_ascii_stride_both_aligned, ascii_to_ascii_stride_src_aligned, ascii_to_ascii_stride_dst_aligned, ascii_to_ascii_stride_neither_aligned); ascii_simd_check_align!(ascii_to_basic_latin, u8, u16, ascii_to_basic_latin_stride_both_aligned, ascii_to_basic_latin_stride_src_aligned, ascii_to_basic_latin_stride_dst_aligned, ascii_to_basic_latin_stride_neither_aligned); ascii_simd_check_align!(basic_latin_to_ascii, u16, u8, basic_latin_to_ascii_stride_both_aligned, basic_latin_to_ascii_stride_src_aligned, basic_latin_to_ascii_stride_dst_aligned, basic_latin_to_ascii_stride_neither_aligned); @@ -958,12 +1203,16 @@ cfg_if! { pub const SIMD_STRIDE_SIZE: usize = 16; + /// Safety-usable invariant: This should be identical to SIMD_STRIDE_SIZE (used by ascii_simd_check_align_unrolled) pub const SIMD_ALIGNMENT: usize = 16; pub const MAX_STRIDE_SIZE: usize = 16; pub const SIMD_ALIGNMENT_MASK: usize = 15; + // Safety for stride macros: We stick to the load8_aligned/etc family of functions. We consistently name + // aligned/unaligned functions according to src/dst being aligned/unaligned + ascii_to_ascii_simd_double_stride!(ascii_to_ascii_simd_double_stride_both_aligned, store16_aligned); ascii_to_ascii_simd_double_stride!(ascii_to_ascii_simd_double_stride_src_aligned, store16_unaligned); @@ -989,6 +1238,9 @@ cfg_if! { pack_simd_stride!(pack_stride_both_aligned, load8_aligned, store16_aligned); pack_simd_stride!(pack_stride_src_aligned, load8_aligned, store16_unaligned); + // Safety for conversion macros: We use the correct pattern of both/src/dst/neither/double_both/double_src here. All stride functions were produced + // by stride macros that universally munch a single SIMD_STRIDE_SIZE worth of elements. + ascii_simd_check_align_unrolled!(ascii_to_ascii, u8, u8, ascii_to_ascii_stride_both_aligned, ascii_to_ascii_stride_src_aligned, ascii_to_ascii_stride_neither_aligned, ascii_to_ascii_simd_double_stride_both_aligned, ascii_to_ascii_simd_double_stride_src_aligned); ascii_simd_check_align_unrolled!(ascii_to_basic_latin, u8, u16, ascii_to_basic_latin_stride_both_aligned, ascii_to_basic_latin_stride_src_aligned, ascii_to_basic_latin_stride_neither_aligned, ascii_to_basic_latin_simd_double_stride_both_aligned, ascii_to_basic_latin_simd_double_stride_src_aligned); @@ -998,14 +1250,21 @@ cfg_if! { } else if #[cfg(all(target_endian = "little", target_pointer_width = "64"))] { // Aligned ALU word, little-endian, 64-bit + /// Safety invariant: this is the amount of bytes consumed by + /// unpack_alu. This will be twice the pointer width, as it consumes two usizes. + /// This is also the number of bytes produced by pack_alu. + /// This is also the number of u16 code units produced/consumed by unpack_alu/pack_alu respectively. pub const ALU_STRIDE_SIZE: usize = 16; pub const MAX_STRIDE_SIZE: usize = 16; + // Safety invariant: this is the pointer width in bytes pub const ALU_ALIGNMENT: usize = 8; + // Safety invariant: this is a mask for getting the bits of a pointer not aligned to ALU_ALIGNMENT pub const ALU_ALIGNMENT_MASK: usize = 7; + /// Safety: dst must point to valid space for writing four `usize`s #[inline(always)] unsafe fn unpack_alu(word: usize, second_word: usize, dst: *mut usize) { let first = ((0x0000_0000_FF00_0000usize & word) << 24) | @@ -1024,12 +1283,14 @@ cfg_if! { ((0x00FF_0000_0000_0000usize & second_word) >> 16) | ((0x0000_FF00_0000_0000usize & second_word) >> 24) | ((0x0000_00FF_0000_0000usize & second_word) >> 32); + // Safety: fn invariant used here *dst = first; *(dst.add(1)) = second; *(dst.add(2)) = third; *(dst.add(3)) = fourth; } + /// Safety: dst must point to valid space for writing two `usize`s #[inline(always)] unsafe fn pack_alu(first: usize, second: usize, third: usize, fourth: usize, dst: *mut usize) { let word = ((0x00FF_0000_0000_0000usize & second) << 8) | @@ -1048,20 +1309,28 @@ cfg_if! { ((0x0000_00FF_0000_0000usize & third) >> 16) | ((0x0000_0000_00FF_0000usize & third) >> 8) | (0x0000_0000_0000_00FFusize & third); + // Safety: fn invariant used here *dst = word; *(dst.add(1)) = second_word; } } else if #[cfg(all(target_endian = "little", target_pointer_width = "32"))] { // Aligned ALU word, little-endian, 32-bit + /// Safety invariant: this is the amount of bytes consumed by + /// unpack_alu. This will be twice the pointer width, as it consumes two usizes. + /// This is also the number of bytes produced by pack_alu. + /// This is also the number of u16 code units produced/consumed by unpack_alu/pack_alu respectively. pub const ALU_STRIDE_SIZE: usize = 8; pub const MAX_STRIDE_SIZE: usize = 8; + // Safety invariant: this is the pointer width in bytes pub const ALU_ALIGNMENT: usize = 4; + // Safety invariant: this is a mask for getting the bits of a pointer not aligned to ALU_ALIGNMENT pub const ALU_ALIGNMENT_MASK: usize = 3; + /// Safety: dst must point to valid space for writing four `usize`s #[inline(always)] unsafe fn unpack_alu(word: usize, second_word: usize, dst: *mut usize) { let first = ((0x0000_FF00usize & word) << 8) | @@ -1072,12 +1341,14 @@ cfg_if! { (0x0000_00FFusize & second_word); let fourth = ((0xFF00_0000usize & second_word) >> 8) | ((0x00FF_0000usize & second_word) >> 16); + // Safety: fn invariant used here *dst = first; *(dst.add(1)) = second; *(dst.add(2)) = third; *(dst.add(3)) = fourth; } + /// Safety: dst must point to valid space for writing two `usize`s #[inline(always)] unsafe fn pack_alu(first: usize, second: usize, third: usize, fourth: usize, dst: *mut usize) { let word = ((0x00FF_0000usize & second) << 8) | @@ -1088,20 +1359,28 @@ cfg_if! { ((0x0000_00FFusize & fourth) << 16) | ((0x00FF_0000usize & third) >> 8) | (0x0000_00FFusize & third); + // Safety: fn invariant used here *dst = word; *(dst.add(1)) = second_word; } } else if #[cfg(all(target_endian = "big", target_pointer_width = "64"))] { // Aligned ALU word, big-endian, 64-bit + /// Safety invariant: this is the amount of bytes consumed by + /// unpack_alu. This will be twice the pointer width, as it consumes two usizes. + /// This is also the number of bytes produced by pack_alu. + /// This is also the number of u16 code units produced/consumed by unpack_alu/pack_alu respectively. pub const ALU_STRIDE_SIZE: usize = 16; pub const MAX_STRIDE_SIZE: usize = 16; + // Safety invariant: this is the pointer width in bytes pub const ALU_ALIGNMENT: usize = 8; + // Safety invariant: this is a mask for getting the bits of a pointer not aligned to ALU_ALIGNMENT pub const ALU_ALIGNMENT_MASK: usize = 7; + /// Safety: dst must point to valid space for writing four `usize`s #[inline(always)] unsafe fn unpack_alu(word: usize, second_word: usize, dst: *mut usize) { let first = ((0xFF00_0000_0000_0000usize & word) >> 8) | @@ -1120,12 +1399,14 @@ cfg_if! { ((0x0000_0000_00FF_0000usize & second_word) << 16) | ((0x0000_0000_0000_FF00usize & second_word) << 8) | (0x0000_0000_0000_00FFusize & second_word); + // Safety: fn invariant used here *dst = first; *(dst.add(1)) = second; *(dst.add(2)) = third; *(dst.add(3)) = fourth; } + /// Safety: dst must point to valid space for writing two `usize`s #[inline(always)] unsafe fn pack_alu(first: usize, second: usize, third: usize, fourth: usize, dst: *mut usize) { let word = ((0x00FF0000_00000000usize & first) << 8) | @@ -1144,20 +1425,28 @@ cfg_if! { ((0x000000FF_00000000usize & fourth) >> 16) | ((0x00000000_00FF0000usize & fourth) >> 8) | (0x00000000_000000FFusize & fourth); + // Safety: fn invariant used here *dst = word; *(dst.add(1)) = second_word; } } else if #[cfg(all(target_endian = "big", target_pointer_width = "32"))] { // Aligned ALU word, big-endian, 32-bit + /// Safety invariant: this is the amount of bytes consumed by + /// unpack_alu. This will be twice the pointer width, as it consumes two usizes. + /// This is also the number of bytes produced by pack_alu. + /// This is also the number of u16 code units produced/consumed by unpack_alu/pack_alu respectively. pub const ALU_STRIDE_SIZE: usize = 8; pub const MAX_STRIDE_SIZE: usize = 8; + // Safety invariant: this is the pointer width in bytes pub const ALU_ALIGNMENT: usize = 4; + // Safety invariant: this is a mask for getting the bits of a pointer not aligned to ALU_ALIGNMENT pub const ALU_ALIGNMENT_MASK: usize = 3; + /// Safety: dst must point to valid space for writing four `usize`s #[inline(always)] unsafe fn unpack_alu(word: usize, second_word: usize, dst: *mut usize) { let first = ((0xFF00_0000usize & word) >> 8) | @@ -1168,12 +1457,14 @@ cfg_if! { ((0x00FF_0000usize & second_word) >> 16); let fourth = ((0x0000_FF00usize & second_word) << 8) | (0x0000_00FFusize & second_word); + // Safety: fn invariant used here *dst = first; *(dst.add(1)) = second; *(dst.add(2)) = third; *(dst.add(3)) = fourth; } + /// Safety: dst must point to valid space for writing two `usize`s #[inline(always)] unsafe fn pack_alu(first: usize, second: usize, third: usize, fourth: usize, dst: *mut usize) { let word = ((0x00FF_0000usize & first) << 8) | @@ -1184,6 +1475,7 @@ cfg_if! { ((0x0000_00FFusize & third) << 16) | ((0x00FF_0000usize & fourth) >> 8) | (0x0000_00FFusize & fourth); + // Safety: fn invariant used here *dst = word; *(dst.add(1)) = second_word; } @@ -1195,6 +1487,8 @@ cfg_if! { } cfg_if! { + // Safety-usable invariant: this counts the zeroes from the "first byte" of utf-8 data packed into a usize + // with the target endianness if #[cfg(target_endian = "little")] { #[allow(dead_code)] #[inline(always)] @@ -1212,19 +1506,24 @@ cfg_if! { cfg_if! { if #[cfg(all(feature = "simd-accel", target_endian = "little", target_arch = "disabled"))] { + /// Safety-usable invariant: Will return the value and position of the first non-ASCII byte in the slice in a Some if found. + /// In other words, the first element of the Some is always `> 127` #[inline(always)] pub fn validate_ascii(slice: &[u8]) -> Option<(u8, usize)> { let src = slice.as_ptr(); let len = slice.len(); let mut offset = 0usize; + // Safety: if this check succeeds we're valid for reading/writing at least `stride` elements. if SIMD_STRIDE_SIZE <= len { let len_minus_stride = len - SIMD_STRIDE_SIZE; loop { + // Safety: src at offset is valid for a `SIMD_STRIDE_SIZE` read let simd = unsafe { load16_unaligned(src.add(offset)) }; if !simd_is_ascii(simd) { break; } offset += SIMD_STRIDE_SIZE; + // This is `offset > len - SIMD_STRIDE_SIZE` which means we always have at least `SIMD_STRIDE_SIZE` elements to munch next time. if offset > len_minus_stride { break; } @@ -1233,6 +1532,7 @@ cfg_if! { while offset < len { let code_unit = slice[offset]; if code_unit > 127 { + // Safety: Safety-usable invariant upheld here return Some((code_unit, offset)); } offset += 1; @@ -1240,13 +1540,17 @@ cfg_if! { None } } else if #[cfg(all(feature = "simd-accel", target_feature = "sse2"))] { + /// Safety-usable invariant: will return Some() when it encounters non-ASCII, with the first element in the Some being + /// guaranteed to be non-ASCII (> 127), and the second being the offset where it is found #[inline(always)] pub fn validate_ascii(slice: &[u8]) -> Option<(u8, usize)> { let src = slice.as_ptr(); let len = slice.len(); let mut offset = 0usize; + // Safety: if this check succeeds we're valid for reading at least `stride` elements. if SIMD_STRIDE_SIZE <= len { // First, process one unaligned vector + // Safety: src is valid for a `SIMD_STRIDE_SIZE` read let simd = unsafe { load16_unaligned(src) }; let mask = mask_ascii(simd); if mask != 0 { @@ -1255,18 +1559,26 @@ cfg_if! { return Some((non_ascii, offset)); } offset = SIMD_STRIDE_SIZE; + // Safety: Now that offset has changed we don't yet know how much it is valid for // We have now seen 16 ASCII bytes. Let's guess that // there will be enough more to justify more expense // in the case of non-ASCII. // Use aligned reads for the sake of old microachitectures. + // Safety: this correctly calculates the number of src_units that need to be read before the remaining list is aligned. + // This is by definition less than SIMD_ALIGNMENT, which is defined to be equal to SIMD_STRIDE_SIZE. let until_alignment = unsafe { (SIMD_ALIGNMENT - ((src.add(offset) as usize) & SIMD_ALIGNMENT_MASK)) & SIMD_ALIGNMENT_MASK }; // This addition won't overflow, because even in the 32-bit PAE case the // address space holds enough code that the slice length can't be that // close to address space size. // offset now equals SIMD_STRIDE_SIZE, hence times 3 below. + // + // Safety: if this check succeeds we're valid for reading at least `2 * SIMD_STRIDE_SIZE` elements plus `until_alignment`. + // The extra SIMD_STRIDE_SIZE in the condition is because `offset` is already `SIMD_STRIDE_SIZE`. if until_alignment + (SIMD_STRIDE_SIZE * 3) <= len { if until_alignment != 0 { + // Safety: this is safe to call since we're valid for this read (and more), and don't care about alignment + // This will copy over bytes that get decoded twice since it's not incrementing `offset` by SIMD_STRIDE_SIZE. This is fine. let simd = unsafe { load16_unaligned(src.add(offset)) }; let mask = mask_ascii(simd); if mask != 0 { @@ -1276,53 +1588,78 @@ cfg_if! { } offset += until_alignment; } + // Safety: At this point we're valid for reading 2*SIMD_STRIDE_SIZE elements + // Safety: Now `offset` is aligned for `src` let len_minus_stride_times_two = len - (SIMD_STRIDE_SIZE * 2); loop { + // Safety: We were valid for this read, and were aligned. let first = unsafe { load16_aligned(src.add(offset)) }; let second = unsafe { load16_aligned(src.add(offset + SIMD_STRIDE_SIZE)) }; if !simd_is_ascii(first | second) { + // Safety: mask_ascii produces a mask of all the high bits. let mask_first = mask_ascii(first); if mask_first != 0 { + // Safety: on little endian systems this will be the number of ascii bytes + // before the first non-ascii, i.e. valid for indexing src + // TODO SAFETY: What about big-endian systems? offset += mask_first.trailing_zeros() as usize; } else { let mask_second = mask_ascii(second); + // Safety: on little endian systems this will be the number of ascii bytes + // before the first non-ascii, i.e. valid for indexing src offset += SIMD_STRIDE_SIZE + mask_second.trailing_zeros() as usize; } + // Safety: We know this is non-ASCII, and can uphold the safety-usable invariant here let non_ascii = unsafe { *src.add(offset) }; + return Some((non_ascii, offset)); } offset += SIMD_STRIDE_SIZE * 2; + // Safety: This is `offset > len - 2 * SIMD_STRIDE_SIZE` which means we always have at least `2 * SIMD_STRIDE_SIZE` elements to munch next time. if offset > len_minus_stride_times_two { break; } } + // Safety: if this check succeeds we're valid for reading at least `SIMD_STRIDE_SIZE` if offset + SIMD_STRIDE_SIZE <= len { - let simd = unsafe { load16_aligned(src.add(offset)) }; - let mask = mask_ascii(simd); + // Safety: We were valid for this read, and were aligned. + let simd = unsafe { load16_aligned(src.add(offset)) }; + // Safety: mask_ascii produces a mask of all the high bits. + let mask = mask_ascii(simd); if mask != 0 { + // Safety: on little endian systems this will be the number of ascii bytes + // before the first non-ascii, i.e. valid for indexing src offset += mask.trailing_zeros() as usize; let non_ascii = unsafe { *src.add(offset) }; + // Safety: We know this is non-ASCII, and can uphold the safety-usable invariant here return Some((non_ascii, offset)); } offset += SIMD_STRIDE_SIZE; } } else { + // Safety: this is the unaligned branch // At most two iterations, so unroll + // Safety: if this check succeeds we're valid for reading at least `SIMD_STRIDE_SIZE` if offset + SIMD_STRIDE_SIZE <= len { + // Safety: We're valid for this read but must use an unaligned read let simd = unsafe { load16_unaligned(src.add(offset)) }; let mask = mask_ascii(simd); if mask != 0 { offset += mask.trailing_zeros() as usize; let non_ascii = unsafe { *src.add(offset) }; + // Safety-usable invariant upheld here (same as above) return Some((non_ascii, offset)); } offset += SIMD_STRIDE_SIZE; + // Safety: if this check succeeds we're valid for reading at least `SIMD_STRIDE_SIZE` if offset + SIMD_STRIDE_SIZE <= len { + // Safety: We're valid for this read but must use an unaligned read let simd = unsafe { load16_unaligned(src.add(offset)) }; let mask = mask_ascii(simd); if mask != 0 { offset += mask.trailing_zeros() as usize; let non_ascii = unsafe { *src.add(offset) }; + // Safety-usable invariant upheld here (same as above) return Some((non_ascii, offset)); } offset += SIMD_STRIDE_SIZE; @@ -1331,8 +1668,10 @@ cfg_if! { } } while offset < len { + // Safety: relies straightforwardly on the `len` invariant let code_unit = unsafe { *(src.add(offset)) }; if code_unit > 127 { + // Safety-usable invariant upheld here return Some((code_unit, offset)); } offset += 1; @@ -1340,31 +1679,40 @@ cfg_if! { None } } else { + // Safety-usable invariant: returns byte index of first non-ascii byte #[inline(always)] fn find_non_ascii(word: usize, second_word: usize) -> Option<usize> { let word_masked = word & ASCII_MASK; let second_masked = second_word & ASCII_MASK; if (word_masked | second_masked) == 0 { + // Both are ascii, invariant upheld return None; } if word_masked != 0 { let zeros = count_zeros(word_masked); - // `zeros` now contains 7 (for the seven bits of non-ASCII) + // `zeros` now contains 0 to 7 (for the seven bits of masked ASCII in little endian, + // or up to 7 bits of non-ASCII in big endian if the first byte is non-ASCII) // plus 8 times the number of ASCII in text order before the // non-ASCII byte in the little-endian case or 8 times the number of ASCII in // text order before the non-ASCII byte in the big-endian case. let num_ascii = (zeros >> 3) as usize; + // Safety-usable invariant upheld here return Some(num_ascii); } let zeros = count_zeros(second_masked); - // `zeros` now contains 7 (for the seven bits of non-ASCII) + // `zeros` now contains 0 to 7 (for the seven bits of masked ASCII in little endian, + // or up to 7 bits of non-ASCII in big endian if the first byte is non-ASCII) // plus 8 times the number of ASCII in text order before the // non-ASCII byte in the little-endian case or 8 times the number of ASCII in // text order before the non-ASCII byte in the big-endian case. let num_ascii = (zeros >> 3) as usize; + // Safety-usable invariant upheld here Some(ALU_ALIGNMENT + num_ascii) } + /// Safety: `src` must be valid for the reads of two `usize`s + /// + /// Safety-usable invariant: will return byte index of first non-ascii byte #[inline(always)] unsafe fn validate_ascii_stride(src: *const usize) -> Option<usize> { let word = *src; @@ -1372,6 +1720,8 @@ cfg_if! { find_non_ascii(word, second_word) } + /// Safety-usable invariant: will return Some() when it encounters non-ASCII, with the first element in the Some being + /// guaranteed to be non-ASCII (> 127), and the second being the offset where it is found #[cfg_attr(feature = "cargo-clippy", allow(cast_ptr_alignment))] #[inline(always)] pub fn validate_ascii(slice: &[u8]) -> Option<(u8, usize)> { @@ -1379,23 +1729,30 @@ cfg_if! { let len = slice.len(); let mut offset = 0usize; let mut until_alignment = (ALU_ALIGNMENT - ((src as usize) & ALU_ALIGNMENT_MASK)) & ALU_ALIGNMENT_MASK; + // Safety: If this check fails we're valid to read `until_alignment + ALU_STRIDE_SIZE` elements if until_alignment + ALU_STRIDE_SIZE <= len { while until_alignment != 0 { let code_unit = slice[offset]; if code_unit > 127 { + // Safety-usable invairant upheld here return Some((code_unit, offset)); } offset += 1; until_alignment -= 1; } + // Safety: At this point we have read until_alignment elements and + // are valid for `ALU_STRIDE_SIZE` more. let len_minus_stride = len - ALU_STRIDE_SIZE; loop { + // Safety: we were valid for this read let ptr = unsafe { src.add(offset) as *const usize }; if let Some(num_ascii) = unsafe { validate_ascii_stride(ptr) } { offset += num_ascii; + // Safety-usable invairant upheld here using the invariant from validate_ascii_stride() return Some((unsafe { *(src.add(offset)) }, offset)); } offset += ALU_STRIDE_SIZE; + // Safety: This is `offset > ALU_STRIDE_SIZE` which means we always have at least `2 * ALU_STRIDE_SIZE` elements to munch next time. if offset > len_minus_stride { break; } @@ -1404,6 +1761,7 @@ cfg_if! { while offset < len { let code_unit = slice[offset]; if code_unit > 127 { + // Safety-usable invairant upheld here return Some((code_unit, offset)); } offset += 1; @@ -1428,36 +1786,47 @@ cfg_if! { pub const ALU_ALIGNMENT_MASK: usize = 3; } else { + // Safety: src points to two valid `usize`s, dst points to four valid `usize`s #[inline(always)] unsafe fn unpack_latin1_stride_alu(src: *const usize, dst: *mut usize) { + // Safety: src safety invariant used here let word = *src; let second_word = *(src.add(1)); + // Safety: dst safety invariant passed down unpack_alu(word, second_word, dst); } + // Safety: src points to four valid `usize`s, dst points to two valid `usize`s #[inline(always)] unsafe fn pack_latin1_stride_alu(src: *const usize, dst: *mut usize) { + // Safety: src safety invariant used here let first = *src; let second = *(src.add(1)); let third = *(src.add(2)); let fourth = *(src.add(3)); + // Safety: dst safety invariant passed down pack_alu(first, second, third, fourth, dst); } + // Safety: src points to two valid `usize`s, dst points to four valid `usize`s #[inline(always)] unsafe fn ascii_to_basic_latin_stride_alu(src: *const usize, dst: *mut usize) -> bool { + // Safety: src safety invariant used here let word = *src; let second_word = *(src.add(1)); // Check if the words contains non-ASCII if (word & ASCII_MASK) | (second_word & ASCII_MASK) != 0 { return false; } + // Safety: dst safety invariant passed down unpack_alu(word, second_word, dst); true } + // Safety: src points four valid `usize`s, dst points to two valid `usize`s #[inline(always)] unsafe fn basic_latin_to_ascii_stride_alu(src: *const usize, dst: *mut usize) -> bool { + // Safety: src safety invariant used here let first = *src; let second = *(src.add(1)); let third = *(src.add(2)); @@ -1465,16 +1834,22 @@ cfg_if! { if (first & BASIC_LATIN_MASK) | (second & BASIC_LATIN_MASK) | (third & BASIC_LATIN_MASK) | (fourth & BASIC_LATIN_MASK) != 0 { return false; } + // Safety: dst safety invariant passed down pack_alu(first, second, third, fourth, dst); true } + // Safety: src, dst both point to two valid `usize`s each + // Safety-usable invariant: Will return byte index of first non-ascii byte. #[inline(always)] unsafe fn ascii_to_ascii_stride(src: *const usize, dst: *mut usize) -> Option<usize> { + // Safety: src safety invariant used here let word = *src; let second_word = *(src.add(1)); + // Safety: src safety invariant used here *dst = word; *(dst.add(1)) = second_word; + // Relies on safety-usable invariant here find_non_ascii(word, second_word) } @@ -1482,6 +1857,7 @@ cfg_if! { basic_latin_alu!(basic_latin_to_ascii, u16, u8, basic_latin_to_ascii_stride_alu); latin1_alu!(unpack_latin1, u8, u16, unpack_latin1_stride_alu); latin1_alu!(pack_latin1, u16, u8, pack_latin1_stride_alu); + // Safety invariant upheld: ascii_to_ascii_stride will return byte index of first non-ascii if found ascii_alu!(ascii_to_ascii, u8, u8, ascii_to_ascii_stride); } } diff --git a/third_party/rust/encoding_rs/src/handles.rs b/third_party/rust/encoding_rs/src/handles.rs index b5404c01d9..f44a834672 100644 --- a/third_party/rust/encoding_rs/src/handles.rs +++ b/third_party/rust/encoding_rs/src/handles.rs @@ -34,7 +34,7 @@ use crate::simd_funcs::*; all(target_endian = "little", target_feature = "neon") ) ))] -use packed_simd::u16x8; +use core::simd::u16x8; use super::DecoderResult; use super::EncoderResult; @@ -90,19 +90,23 @@ impl Endian for LittleEndian { #[derive(Debug, Copy, Clone)] struct UnalignedU16Slice { + // Safety invariant: ptr must be valid for reading 2*len bytes ptr: *const u8, len: usize, } impl UnalignedU16Slice { + /// Safety: ptr must be valid for reading 2*len bytes #[inline(always)] pub unsafe fn new(ptr: *const u8, len: usize) -> UnalignedU16Slice { + // Safety: field invariant passed up to caller here UnalignedU16Slice { ptr, len } } #[inline(always)] pub fn trim_last(&mut self) { assert!(self.len > 0); + // Safety: invariant upheld here: a slice is still valid with a shorter len self.len -= 1; } @@ -113,7 +117,9 @@ impl UnalignedU16Slice { assert!(i < self.len); unsafe { let mut u: MaybeUninit<u16> = MaybeUninit::uninit(); + // Safety: i is at most len - 1, which works here ::core::ptr::copy_nonoverlapping(self.ptr.add(i * 2), u.as_mut_ptr() as *mut u8, 2); + // Safety: valid read above lets us do this u.assume_init() } } @@ -121,8 +127,13 @@ impl UnalignedU16Slice { #[cfg(feature = "simd-accel")] #[inline(always)] pub fn simd_at(&self, i: usize) -> u16x8 { + // Safety: i/len are on the scale of u16s, each one corresponds to 2 u8s assert!(i + SIMD_STRIDE_SIZE / 2 <= self.len); let byte_index = i * 2; + // Safety: load16_unaligned needs SIMD_STRIDE_SIZE=16 u8 elements to read, + // or 16/2 = 8 u16 elements to read. + // We have checked that we have at least that many above. + unsafe { to_u16_lanes(load16_unaligned(self.ptr.add(byte_index))) } } @@ -136,6 +147,7 @@ impl UnalignedU16Slice { // XXX the return value should be restricted not to // outlive self. assert!(from <= self.len); + // Safety: This upholds the same invariant: `from` is in bounds and we're returning a shorter slice unsafe { UnalignedU16Slice::new(self.ptr.add(from * 2), self.len - from) } } @@ -144,6 +156,8 @@ impl UnalignedU16Slice { pub fn copy_bmp_to<E: Endian>(&self, other: &mut [u16]) -> Option<(u16, usize)> { assert!(self.len <= other.len()); let mut offset = 0; + // Safety: SIMD_STRIDE_SIZE is measured in bytes, whereas len is in u16s. We check we can + // munch SIMD_STRIDE_SIZE / 2 u16s which means we can write SIMD_STRIDE_SIZE u8s if SIMD_STRIDE_SIZE / 2 <= self.len { let len_minus_stride = self.len - SIMD_STRIDE_SIZE / 2; loop { @@ -151,6 +165,7 @@ impl UnalignedU16Slice { if E::OPPOSITE_ENDIAN { simd = simd_byte_swap(simd); } + // Safety: we have enough space on the other side to write this unsafe { store8_unaligned(other.as_mut_ptr().add(offset), simd); } @@ -158,6 +173,7 @@ impl UnalignedU16Slice { break; } offset += SIMD_STRIDE_SIZE / 2; + // Safety: This ensures we still have space for writing SIMD_STRIDE_SIZE u8s if offset > len_minus_stride { break; } @@ -236,6 +252,7 @@ fn copy_unaligned_basic_latin_to_ascii<E: Endian>( ) -> CopyAsciiResult<usize, (u16, usize)> { let len = ::core::cmp::min(src.len(), dst.len()); let mut offset = 0; + // Safety: This check ensures we are able to read/write at least SIMD_STRIDE_SIZE elements if SIMD_STRIDE_SIZE <= len { let len_minus_stride = len - SIMD_STRIDE_SIZE; loop { @@ -249,10 +266,13 @@ fn copy_unaligned_basic_latin_to_ascii<E: Endian>( break; } let packed = simd_pack(first, second); + // Safety: We are able to write SIMD_STRIDE_SIZE elements in this iteration unsafe { store16_unaligned(dst.as_mut_ptr().add(offset), packed); } offset += SIMD_STRIDE_SIZE; + // Safety: This is `offset > len - SIMD_STRIDE_SIZE`, which ensures that we can write at least SIMD_STRIDE_SIZE elements + // in the next iteration if offset > len_minus_stride { break; } @@ -637,7 +657,7 @@ impl<'a> Utf16Destination<'a> { self.write_code_unit((0xDC00 + (astral & 0x3FF)) as u16); } #[inline(always)] - pub fn write_surrogate_pair(&mut self, high: u16, low: u16) { + fn write_surrogate_pair(&mut self, high: u16, low: u16) { self.write_code_unit(high); self.write_code_unit(low); } @@ -646,6 +666,7 @@ impl<'a> Utf16Destination<'a> { self.write_bmp_excl_ascii(combined); self.write_bmp_excl_ascii(combining); } + // Safety-usable invariant: CopyAsciiResult::GoOn will only contain bytes >=0x80 #[inline(always)] pub fn copy_ascii_from_check_space_bmp<'b>( &'b mut self, @@ -659,6 +680,8 @@ impl<'a> Utf16Destination<'a> { } else { (DecoderResult::InputEmpty, src_remaining.len()) }; + // Safety: This function is documented as needing valid pointers for src/dest and len, which + // is true since we've passed the minumum length of the two match unsafe { ascii_to_basic_latin(src_remaining.as_ptr(), dst_remaining.as_mut_ptr(), length) } { @@ -667,16 +690,20 @@ impl<'a> Utf16Destination<'a> { self.pos += length; return CopyAsciiResult::Stop((pending, source.pos, self.pos)); } + // Safety: the function is documented as returning bytes >=0x80 in the Some Some((non_ascii, consumed)) => { source.pos += consumed; self.pos += consumed; source.pos += 1; // +1 for non_ascii + // Safety: non-ascii bubbled out here non_ascii } } }; + // Safety: non-ascii returned here CopyAsciiResult::GoOn((non_ascii_ret, Utf16BmpHandle::new(self))) } + // Safety-usable invariant: CopyAsciiResult::GoOn will only contain bytes >=0x80 #[inline(always)] pub fn copy_ascii_from_check_space_astral<'b>( &'b mut self, @@ -691,6 +718,8 @@ impl<'a> Utf16Destination<'a> { } else { (DecoderResult::InputEmpty, src_remaining.len()) }; + // Safety: This function is documented as needing valid pointers for src/dest and len, which + // is true since we've passed the minumum length of the two match unsafe { ascii_to_basic_latin(src_remaining.as_ptr(), dst_remaining.as_mut_ptr(), length) } { @@ -699,11 +728,13 @@ impl<'a> Utf16Destination<'a> { self.pos += length; return CopyAsciiResult::Stop((pending, source.pos, self.pos)); } + // Safety: the function is documented as returning bytes >=0x80 in the Some Some((non_ascii, consumed)) => { source.pos += consumed; self.pos += consumed; if self.pos + 1 < dst_len { source.pos += 1; // +1 for non_ascii + // Safety: non-ascii bubbled out here non_ascii } else { return CopyAsciiResult::Stop(( @@ -715,6 +746,7 @@ impl<'a> Utf16Destination<'a> { } } }; + // Safety: non-ascii returned here CopyAsciiResult::GoOn((non_ascii_ret, Utf16AstralHandle::new(self))) } #[inline(always)] diff --git a/third_party/rust/encoding_rs/src/lib.rs b/third_party/rust/encoding_rs/src/lib.rs index 6cc920ef88..1faf02e6bd 100644 --- a/third_party/rust/encoding_rs/src/lib.rs +++ b/third_party/rust/encoding_rs/src/lib.rs @@ -689,7 +689,7 @@ //! for discussion about the UTF-16 family. #![no_std] -#![cfg_attr(feature = "simd-accel", feature(core_intrinsics))] +#![cfg_attr(feature = "simd-accel", feature(core_intrinsics, portable_simd))] #[cfg(feature = "alloc")] #[cfg_attr(test, macro_use)] @@ -699,17 +699,6 @@ extern crate core; #[macro_use] extern crate cfg_if; -#[cfg(all( - feature = "simd-accel", - any( - target_feature = "sse2", - all(target_endian = "little", target_arch = "aarch64"), - all(target_endian = "little", target_feature = "neon") - ) -))] -#[macro_use(shuffle)] -extern crate packed_simd; - #[cfg(feature = "serde")] extern crate serde; diff --git a/third_party/rust/encoding_rs/src/mem.rs b/third_party/rust/encoding_rs/src/mem.rs index ba8d9e3f4c..0f9f3c1977 100644 --- a/third_party/rust/encoding_rs/src/mem.rs +++ b/third_party/rust/encoding_rs/src/mem.rs @@ -116,6 +116,11 @@ macro_rules! by_unit_check_alu { } let len_minus_stride = len - ALU_ALIGNMENT / unit_size; if offset + (4 * (ALU_ALIGNMENT / unit_size)) <= len { + // Safety: the above check lets us perform 4 consecutive reads of + // length ALU_ALIGNMENT / unit_size. ALU_ALIGNMENT is the size of usize, and unit_size + // is the size of the `src` pointer, so this is equal to performing four usize reads. + // + // This invariant is upheld on all loop iterations let len_minus_unroll = len - (4 * (ALU_ALIGNMENT / unit_size)); loop { let unroll_accu = unsafe { *(src.add(offset) as *const usize) } @@ -134,12 +139,14 @@ macro_rules! by_unit_check_alu { return false; } offset += 4 * (ALU_ALIGNMENT / unit_size); + // Safety: this check lets us continue to perform the 4 reads earlier if offset > len_minus_unroll { break; } } } while offset <= len_minus_stride { + // Safety: the above check lets us perform one usize read. accu |= unsafe { *(src.add(offset) as *const usize) }; offset += ALU_ALIGNMENT / unit_size; } @@ -189,6 +196,11 @@ macro_rules! by_unit_check_simd { } let len_minus_stride = len - SIMD_STRIDE_SIZE / unit_size; if offset + (4 * (SIMD_STRIDE_SIZE / unit_size)) <= len { + // Safety: the above check lets us perform 4 consecutive reads of + // length SIMD_STRIDE_SIZE / unit_size. SIMD_STRIDE_SIZE is the size of $simd_ty, and unit_size + // is the size of the `src` pointer, so this is equal to performing four $simd_ty reads. + // + // This invariant is upheld on all loop iterations let len_minus_unroll = len - (4 * (SIMD_STRIDE_SIZE / unit_size)); loop { let unroll_accu = unsafe { *(src.add(offset) as *const $simd_ty) } @@ -208,6 +220,7 @@ macro_rules! by_unit_check_simd { return false; } offset += 4 * (SIMD_STRIDE_SIZE / unit_size); + // Safety: this check lets us continue to perform the 4 reads earlier if offset > len_minus_unroll { break; } @@ -215,6 +228,7 @@ macro_rules! by_unit_check_simd { } let mut simd_accu = $splat; while offset <= len_minus_stride { + // Safety: the above check lets us perform one $simd_ty read. simd_accu = simd_accu | unsafe { *(src.add(offset) as *const $simd_ty) }; offset += SIMD_STRIDE_SIZE / unit_size; } @@ -234,8 +248,8 @@ macro_rules! by_unit_check_simd { cfg_if! { if #[cfg(all(feature = "simd-accel", any(target_feature = "sse2", all(target_endian = "little", target_arch = "aarch64"), all(target_endian = "little", target_feature = "neon"))))] { use crate::simd_funcs::*; - use packed_simd::u8x16; - use packed_simd::u16x8; + use core::simd::u8x16; + use core::simd::u16x8; const SIMD_ALIGNMENT: usize = 16; diff --git a/third_party/rust/encoding_rs/src/simd_funcs.rs b/third_party/rust/encoding_rs/src/simd_funcs.rs index 96feeab5a6..5ae00e62e0 100644 --- a/third_party/rust/encoding_rs/src/simd_funcs.rs +++ b/third_party/rust/encoding_rs/src/simd_funcs.rs @@ -7,55 +7,74 @@ // option. This file may not be copied, modified, or distributed // except according to those terms. -use packed_simd::u16x8; -use packed_simd::u8x16; -use packed_simd::IntoBits; +use any_all_workaround::all_mask16x8; +use any_all_workaround::all_mask8x16; +use any_all_workaround::any_mask16x8; +use any_all_workaround::any_mask8x16; +use core::simd::cmp::SimdPartialEq; +use core::simd::cmp::SimdPartialOrd; +use core::simd::mask16x8; +use core::simd::mask8x16; +use core::simd::simd_swizzle; +use core::simd::u16x8; +use core::simd::u8x16; +use core::simd::ToBytes; // TODO: Migrate unaligned access to stdlib code if/when the RFC // https://github.com/rust-lang/rfcs/pull/1725 is implemented. +/// Safety invariant: ptr must be valid for an unaligned read of 16 bytes #[inline(always)] pub unsafe fn load16_unaligned(ptr: *const u8) -> u8x16 { - let mut simd = ::core::mem::uninitialized(); - ::core::ptr::copy_nonoverlapping(ptr, &mut simd as *mut u8x16 as *mut u8, 16); - simd + let mut simd = ::core::mem::MaybeUninit::<u8x16>::uninit(); + ::core::ptr::copy_nonoverlapping(ptr, simd.as_mut_ptr() as *mut u8, 16); + // Safety: copied 16 bytes of initialized memory into this, it is now initialized + simd.assume_init() } +/// Safety invariant: ptr must be valid for an aligned-for-u8x16 read of 16 bytes #[allow(dead_code)] #[inline(always)] pub unsafe fn load16_aligned(ptr: *const u8) -> u8x16 { *(ptr as *const u8x16) } +/// Safety invariant: ptr must be valid for an unaligned store of 16 bytes #[inline(always)] pub unsafe fn store16_unaligned(ptr: *mut u8, s: u8x16) { ::core::ptr::copy_nonoverlapping(&s as *const u8x16 as *const u8, ptr, 16); } +/// Safety invariant: ptr must be valid for an aligned-for-u8x16 store of 16 bytes #[allow(dead_code)] #[inline(always)] pub unsafe fn store16_aligned(ptr: *mut u8, s: u8x16) { *(ptr as *mut u8x16) = s; } +/// Safety invariant: ptr must be valid for an unaligned read of 16 bytes #[inline(always)] pub unsafe fn load8_unaligned(ptr: *const u16) -> u16x8 { - let mut simd = ::core::mem::uninitialized(); - ::core::ptr::copy_nonoverlapping(ptr as *const u8, &mut simd as *mut u16x8 as *mut u8, 16); - simd + let mut simd = ::core::mem::MaybeUninit::<u16x8>::uninit(); + ::core::ptr::copy_nonoverlapping(ptr as *const u8, simd.as_mut_ptr() as *mut u8, 16); + // Safety: copied 16 bytes of initialized memory into this, it is now initialized + simd.assume_init() } +/// Safety invariant: ptr must be valid for an aligned-for-u16x8 read of 16 bytes #[allow(dead_code)] #[inline(always)] pub unsafe fn load8_aligned(ptr: *const u16) -> u16x8 { *(ptr as *const u16x8) } +/// Safety invariant: ptr must be valid for an unaligned store of 16 bytes #[inline(always)] pub unsafe fn store8_unaligned(ptr: *mut u16, s: u16x8) { ::core::ptr::copy_nonoverlapping(&s as *const u16x8 as *const u8, ptr as *mut u8, 16); } +/// Safety invariant: ptr must be valid for an aligned-for-u16x8 store of 16 bytes #[allow(dead_code)] #[inline(always)] pub unsafe fn store8_aligned(ptr: *mut u16, s: u16x8) { @@ -100,7 +119,7 @@ pub fn simd_byte_swap(s: u16x8) -> u16x8 { #[inline(always)] pub fn to_u16_lanes(s: u8x16) -> u16x8 { - s.into_bits() + u16x8::from_ne_bytes(s) } cfg_if! { @@ -108,10 +127,11 @@ cfg_if! { // Expose low-level mask instead of higher-level conclusion, // because the non-ASCII case would perform less well otherwise. + // Safety-usable invariant: This returned value is whether each high bit is set #[inline(always)] pub fn mask_ascii(s: u8x16) -> i32 { unsafe { - _mm_movemask_epi8(s.into_bits()) + _mm_movemask_epi8(s.into()) } } @@ -125,14 +145,16 @@ cfg_if! { #[inline(always)] pub fn simd_is_ascii(s: u8x16) -> bool { unsafe { - _mm_movemask_epi8(s.into_bits()) == 0 + // Safety: We have cfg()d the correct platform + _mm_movemask_epi8(s.into()) == 0 } } } else if #[cfg(target_arch = "aarch64")]{ #[inline(always)] pub fn simd_is_ascii(s: u8x16) -> bool { unsafe { - vmaxvq_u8(s.into_bits()) < 0x80 + // Safety: We have cfg()d the correct platform + vmaxvq_u8(s.into()) < 0x80 } } } else { @@ -141,7 +163,7 @@ cfg_if! { // This optimizes better on ARM than // the lt formulation. let highest_ascii = u8x16::splat(0x7F); - !s.gt(highest_ascii).any() + !any_mask8x16(s.simd_gt(highest_ascii)) } } } @@ -154,20 +176,21 @@ cfg_if! { return true; } let above_str_latin1 = u8x16::splat(0xC4); - s.lt(above_str_latin1).all() + s.simd_lt(above_str_latin1).all() } } else if #[cfg(target_arch = "aarch64")]{ #[inline(always)] pub fn simd_is_str_latin1(s: u8x16) -> bool { unsafe { - vmaxvq_u8(s.into_bits()) < 0xC4 + // Safety: We have cfg()d the correct platform + vmaxvq_u8(s.into()) < 0xC4 } } } else { #[inline(always)] pub fn simd_is_str_latin1(s: u8x16) -> bool { let above_str_latin1 = u8x16::splat(0xC4); - s.lt(above_str_latin1).all() + all_mask8x16(s.simd_lt(above_str_latin1)) } } } @@ -177,21 +200,23 @@ cfg_if! { #[inline(always)] pub fn simd_is_basic_latin(s: u16x8) -> bool { unsafe { - vmaxvq_u16(s.into_bits()) < 0x80 + // Safety: We have cfg()d the correct platform + vmaxvq_u16(s.into()) < 0x80 } } #[inline(always)] pub fn simd_is_latin1(s: u16x8) -> bool { unsafe { - vmaxvq_u16(s.into_bits()) < 0x100 + // Safety: We have cfg()d the correct platform + vmaxvq_u16(s.into()) < 0x100 } } } else { #[inline(always)] pub fn simd_is_basic_latin(s: u16x8) -> bool { let above_ascii = u16x8::splat(0x80); - s.lt(above_ascii).all() + all_mask16x8(s.simd_lt(above_ascii)) } #[inline(always)] @@ -200,7 +225,7 @@ cfg_if! { // seems faster in this case while the above // function is better the other way round... let highest_latin1 = u16x8::splat(0xFF); - !s.gt(highest_latin1).any() + !any_mask16x8(s.simd_gt(highest_latin1)) } } } @@ -209,7 +234,7 @@ cfg_if! { pub fn contains_surrogates(s: u16x8) -> bool { let mask = u16x8::splat(0xF800); let surrogate_bits = u16x8::splat(0xD800); - (s & mask).eq(surrogate_bits).any() + any_mask16x8((s & mask).simd_eq(surrogate_bits)) } cfg_if! { @@ -217,7 +242,8 @@ cfg_if! { macro_rules! aarch64_return_false_if_below_hebrew { ($s:ident) => ({ unsafe { - if vmaxvq_u16($s.into_bits()) < 0x0590 { + // Safety: We have cfg()d the correct platform + if vmaxvq_u16($s.into()) < 0x0590 { return false; } } @@ -234,7 +260,7 @@ cfg_if! { macro_rules! non_aarch64_return_false_if_all { ($s:ident) => ({ - if $s.all() { + if all_mask16x8($s) { return false; } }) @@ -245,7 +271,7 @@ cfg_if! { macro_rules! in_range16x8 { ($s:ident, $start:expr, $end:expr) => {{ // SIMD sub is wrapping - ($s - u16x8::splat($start)).lt(u16x8::splat($end - $start)) + ($s - u16x8::splat($start)).simd_lt(u16x8::splat($end - $start)) }}; } @@ -259,43 +285,44 @@ pub fn is_u16x8_bidi(s: u16x8) -> bool { aarch64_return_false_if_below_hebrew!(s); - let below_hebrew = s.lt(u16x8::splat(0x0590)); + let below_hebrew = s.simd_lt(u16x8::splat(0x0590)); non_aarch64_return_false_if_all!(below_hebrew); - if (below_hebrew | in_range16x8!(s, 0x0900, 0x200F) | in_range16x8!(s, 0x2068, 0xD802)).all() { + if all_mask16x8( + below_hebrew | in_range16x8!(s, 0x0900, 0x200F) | in_range16x8!(s, 0x2068, 0xD802), + ) { return false; } // Quick refutation failed. Let's do the full check. - (in_range16x8!(s, 0x0590, 0x0900) - | in_range16x8!(s, 0xFB1D, 0xFE00) - | in_range16x8!(s, 0xFE70, 0xFEFF) - | in_range16x8!(s, 0xD802, 0xD804) - | in_range16x8!(s, 0xD83A, 0xD83C) - | s.eq(u16x8::splat(0x200F)) - | s.eq(u16x8::splat(0x202B)) - | s.eq(u16x8::splat(0x202E)) - | s.eq(u16x8::splat(0x2067))) - .any() + any_mask16x8( + (in_range16x8!(s, 0x0590, 0x0900) + | in_range16x8!(s, 0xFB1D, 0xFE00) + | in_range16x8!(s, 0xFE70, 0xFEFF) + | in_range16x8!(s, 0xD802, 0xD804) + | in_range16x8!(s, 0xD83A, 0xD83C) + | s.simd_eq(u16x8::splat(0x200F)) + | s.simd_eq(u16x8::splat(0x202B)) + | s.simd_eq(u16x8::splat(0x202E)) + | s.simd_eq(u16x8::splat(0x2067))), + ) } #[inline(always)] pub fn simd_unpack(s: u8x16) -> (u16x8, u16x8) { - unsafe { - let first: u8x16 = shuffle!( - s, - u8x16::splat(0), - [0, 16, 1, 17, 2, 18, 3, 19, 4, 20, 5, 21, 6, 22, 7, 23] - ); - let second: u8x16 = shuffle!( - s, - u8x16::splat(0), - [8, 24, 9, 25, 10, 26, 11, 27, 12, 28, 13, 29, 14, 30, 15, 31] - ); - (first.into_bits(), second.into_bits()) - } + let first: u8x16 = simd_swizzle!( + s, + u8x16::splat(0), + [0, 16, 1, 17, 2, 18, 3, 19, 4, 20, 5, 21, 6, 22, 7, 23] + ); + let second: u8x16 = simd_swizzle!( + s, + u8x16::splat(0), + [8, 24, 9, 25, 10, 26, 11, 27, 12, 28, 13, 29, 14, 30, 15, 31] + ); + (u16x8::from_ne_bytes(first), u16x8::from_ne_bytes(second)) } cfg_if! { @@ -303,21 +330,20 @@ cfg_if! { #[inline(always)] pub fn simd_pack(a: u16x8, b: u16x8) -> u8x16 { unsafe { - _mm_packus_epi16(a.into_bits(), b.into_bits()).into_bits() + // Safety: We have cfg()d the correct platform + _mm_packus_epi16(a.into(), b.into()).into() } } } else { #[inline(always)] pub fn simd_pack(a: u16x8, b: u16x8) -> u8x16 { - unsafe { - let first: u8x16 = a.into_bits(); - let second: u8x16 = b.into_bits(); - shuffle!( - first, - second, - [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30] - ) - } + let first: u8x16 = a.to_ne_bytes(); + let second: u8x16 = b.to_ne_bytes(); + simd_swizzle!( + first, + second, + [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30] + ) } } } diff --git a/third_party/rust/encoding_rs/src/single_byte.rs b/third_party/rust/encoding_rs/src/single_byte.rs index b3b6089d31..b7a4bf23da 100644 --- a/third_party/rust/encoding_rs/src/single_byte.rs +++ b/third_party/rust/encoding_rs/src/single_byte.rs @@ -53,6 +53,9 @@ impl SingleByteDecoder { // statically omit the bound check when accessing // `[u16; 128]` with an index // `non_ascii as usize - 0x80usize`. + // + // Safety: `non_ascii` is a u8 byte >=0x80, from the invariants + // on Utf8Destination::copy_ascii_from_check_space_bmp() let mapped = unsafe { *(self.table.get_unchecked(non_ascii as usize - 0x80usize)) }; // let mapped = self.table[non_ascii as usize - 0x80usize]; @@ -151,9 +154,12 @@ impl SingleByteDecoder { } else { (DecoderResult::InputEmpty, src.len()) }; + // Safety invariant: converted <= length. Quite often we have `converted < length` + // which will be separately marked. let mut converted = 0usize; 'outermost: loop { match unsafe { + // Safety: length is the minimum length, `src/dst + x` will always be valid for reads/writes of `len - x` ascii_to_basic_latin( src.as_ptr().add(converted), dst.as_mut_ptr().add(converted), @@ -164,6 +170,12 @@ impl SingleByteDecoder { return (pending, length, length); } Some((mut non_ascii, consumed)) => { + // Safety invariant: `converted <= length` upheld, since this can only consume + // up to `length - converted` bytes. + // + // Furthermore, in this context, + // we can assume `converted < length` since this branch is only ever hit when + // ascii_to_basic_latin fails to consume the entire slice converted += consumed; 'middle: loop { // `converted` doesn't count the reading of `non_ascii` yet. @@ -172,6 +184,9 @@ impl SingleByteDecoder { // statically omit the bound check when accessing // `[u16; 128]` with an index // `non_ascii as usize - 0x80usize`. + // + // Safety: We can rely on `non_ascii` being between `0x80` and `0xFF` due to + // the invariants of `ascii_to_basic_latin()`, and our table has enough space for that. let mapped = unsafe { *(self.table.get_unchecked(non_ascii as usize - 0x80usize)) }; // let mapped = self.table[non_ascii as usize - 0x80usize]; @@ -183,9 +198,10 @@ impl SingleByteDecoder { ); } unsafe { - // The bound check has already been performed + // Safety: As mentioned above, `converted < length` *(dst.get_unchecked_mut(converted)) = mapped; } + // Safety: `converted <= length` upheld, since `converted < length` before this converted += 1; // Next, handle ASCII punctuation and non-ASCII without // going back to ASCII acceleration. Non-ASCII scripts @@ -198,7 +214,10 @@ impl SingleByteDecoder { if converted == length { return (pending, length, length); } + // Safety: We are back to `converted < length` because of the == above + // and can perform this check. let mut b = unsafe { *(src.get_unchecked(converted)) }; + // Safety: `converted < length` is upheld for this loop 'innermost: loop { if b > 127 { non_ascii = b; @@ -208,15 +227,20 @@ impl SingleByteDecoder { // byte unconditionally instead of trying to unread it // to make it part of the next SIMD stride. unsafe { + // Safety: `converted < length` is true for this loop *(dst.get_unchecked_mut(converted)) = u16::from(b); } + // Safety: We are now at `converted <= length`. We should *not* `continue` + // the loop without reverifying converted += 1; if b < 60 { // We've got punctuation if converted == length { return (pending, length, length); } + // Safety: we're back to `converted <= length` because of the == above b = unsafe { *(src.get_unchecked(converted)) }; + // Safety: The loop continues as `converted < length` continue 'innermost; } // We've got markup or ASCII text @@ -234,6 +258,8 @@ impl SingleByteDecoder { loop { if let Some((non_ascii, offset)) = validate_ascii(bytes) { total += offset; + // Safety: We can rely on `non_ascii` being between `0x80` and `0xFF` due to + // the invariants of `ascii_to_basic_latin()`, and our table has enough space for that. let mapped = unsafe { *(self.table.get_unchecked(non_ascii as usize - 0x80usize)) }; if mapped != u16::from(non_ascii) { return total; @@ -384,9 +410,12 @@ impl SingleByteEncoder { } else { (EncoderResult::InputEmpty, src.len()) }; + // Safety invariant: converted <= length. Quite often we have `converted < length` + // which will be separately marked. let mut converted = 0usize; 'outermost: loop { match unsafe { + // Safety: length is the minimum length, `src/dst + x` will always be valid for reads/writes of `len - x` basic_latin_to_ascii( src.as_ptr().add(converted), dst.as_mut_ptr().add(converted), @@ -397,15 +426,23 @@ impl SingleByteEncoder { return (pending, length, length); } Some((mut non_ascii, consumed)) => { + // Safety invariant: `converted <= length` upheld, since this can only consume + // up to `length - converted` bytes. + // + // Furthermore, in this context, + // we can assume `converted < length` since this branch is only ever hit when + // ascii_to_basic_latin fails to consume the entire slice converted += consumed; 'middle: loop { // `converted` doesn't count the reading of `non_ascii` yet. match self.encode_u16(non_ascii) { Some(byte) => { unsafe { + // Safety: we're allowed this access since `converted < length` *(dst.get_unchecked_mut(converted)) = byte; } converted += 1; + // `converted <= length` now } None => { // At this point, we need to know if we @@ -421,6 +458,8 @@ impl SingleByteEncoder { converted, ); } + // Safety: convered < length from outside the match, and `converted + 1 != length`, + // So `converted + 1 < length` as well. We're in bounds let second = u32::from(unsafe { *src.get_unchecked(converted + 1) }); if second & 0xFC00u32 != 0xDC00u32 { @@ -432,6 +471,18 @@ impl SingleByteEncoder { } // The next code unit is a low surrogate. let astral: char = unsafe { + // Safety: We can rely on non_ascii being 0xD800-0xDBFF since the high bits are 0xD800 + // Then, (non_ascii << 10 - 0xD800 << 10) becomes between (0 to 0x3FF) << 10, which is between + // 0x400 to 0xffc00. Adding the 0x10000 gives a range of 0x10400 to 0x10fc00. Subtracting the 0xDC00 + // gives 0x2800 to 0x102000 + // The second term is between 0xDC00 and 0xDFFF from the check above. This gives a maximum + // possible range of (0x10400 + 0xDC00) to (0x102000 + 0xDFFF) which is 0x1E000 to 0x10ffff. + // This is in range. + // + // From a Unicode principles perspective this can also be verified as we have checked that `non_ascii` is a high surrogate + // (0xD800..=0xDBFF), and that `second` is a low surrogate (`0xDC00..=0xDFFF`), and we are applying reverse of the UTC16 transformation + // algorithm <https://en.wikipedia.org/wiki/UTF-16#Code_points_from_U+010000_to_U+10FFFF>, by applying the high surrogate - 0xD800 to the + // high ten bits, and the low surrogate - 0xDc00 to the low ten bits, and then adding 0x10000 ::core::char::from_u32_unchecked( (u32::from(non_ascii) << 10) + second - (((0xD800u32 << 10) - 0x1_0000u32) + 0xDC00u32), @@ -456,6 +507,7 @@ impl SingleByteEncoder { converted + 1, // +1 `for non_ascii` converted, ); + // Safety: This branch diverges, so no need to uphold invariants on `converted` } } // Next, handle ASCII punctuation and non-ASCII without @@ -469,8 +521,12 @@ impl SingleByteEncoder { if converted == length { return (pending, length, length); } + // Safety: we're back to `converted < length` due to the == above and can perform + // the unchecked read let mut unit = unsafe { *(src.get_unchecked(converted)) }; 'innermost: loop { + // Safety: This loop always begins with `converted < length`, see + // the invariant outside and the comment on the continue below if unit > 127 { non_ascii = unit; continue 'middle; @@ -479,19 +535,25 @@ impl SingleByteEncoder { // byte unconditionally instead of trying to unread it // to make it part of the next SIMD stride. unsafe { + // Safety: Can rely on converted < length *(dst.get_unchecked_mut(converted)) = unit as u8; } converted += 1; + // `converted <= length` here if unit < 60 { // We've got punctuation if converted == length { return (pending, length, length); } + // Safety: `converted < length` due to the == above. The read is safe. unit = unsafe { *(src.get_unchecked(converted)) }; + // Safety: This only happens if `converted < length`, maintaining it continue 'innermost; } // We've got markup or ASCII text continue 'outermost; + // Safety: All other routes to here diverge so the continue is the only + // way to run the innermost loop. } } } diff --git a/third_party/rust/encoding_rs/src/x_user_defined.rs b/third_party/rust/encoding_rs/src/x_user_defined.rs index 103c9afba9..7af7d5e3d6 100644 --- a/third_party/rust/encoding_rs/src/x_user_defined.rs +++ b/third_party/rust/encoding_rs/src/x_user_defined.rs @@ -14,12 +14,13 @@ use crate::variant::*; cfg_if! { if #[cfg(feature = "simd-accel")] { use simd_funcs::*; - use packed_simd::u16x8; + use core::simd::u16x8; + use core::simd::cmp::SimdPartialOrd; #[inline(always)] fn shift_upper(unpacked: u16x8) -> u16x8 { let highest_ascii = u16x8::splat(0x7F); - unpacked + unpacked.gt(highest_ascii).select(u16x8::splat(0xF700), u16x8::splat(0)) } + unpacked + unpacked.simd_gt(highest_ascii).select(u16x8::splat(0xF700), u16x8::splat(0)) } } else { } } @@ -116,10 +117,15 @@ impl UserDefinedDecoder { let simd_iterations = length >> 4; let src_ptr = src.as_ptr(); let dst_ptr = dst.as_mut_ptr(); + // Safety: This is `for i in 0..length / 16` for i in 0..simd_iterations { + // Safety: This is in bounds: length is the minumum valid length for both src/dst + // and i ranges to length/16, so multiplying by 16 will always be `< length` and can do + // a 16 byte read let input = unsafe { load16_unaligned(src_ptr.add(i * 16)) }; let (first, second) = simd_unpack(input); unsafe { + // Safety: same as above, but this is two consecutive 8-byte reads store8_unaligned(dst_ptr.add(i * 16), shift_upper(first)); store8_unaligned(dst_ptr.add((i * 16) + 8), shift_upper(second)); } |