Skip to content

Commit 46a24ed

Browse files
committed
Auto merge of #118405 - matthiaskrgr:rollup-3a2eevc, r=matthiaskrgr
Rollup of 7 pull requests Successful merges: - #115331 (optimize str::iter::Chars::advance_by) - #118236 (Update mod comment) - #118299 (Update `OnceLock` documentation to give a concrete 'lazy static' example, and expand on the existing example.) - #118314 (Rename `{collections=>alloc}{tests,benches}`) - #118341 (Simplify indenting in THIR printing) - #118366 (Detect and reject malformed `repr(Rust)` hints) - #118397 (Fix comments for unsigned non-zero `checked_add`, `saturating_add`) r? `@ghost` `@rustbot` modify labels: rollup
2 parents e06c94d + 4f3ee30 commit 46a24ed

File tree

13 files changed

+174
-29
lines changed

13 files changed

+174
-29
lines changed

compiler/rustc_attr/src/builtin.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -985,7 +985,7 @@ pub fn parse_repr_attr(sess: &Session, attr: &Attribute) -> Vec<ReprAttr> {
985985
Ok(literal) => acc.push(ReprPacked(literal)),
986986
Err(message) => literal_error = Some(message),
987987
};
988-
} else if matches!(name, sym::C | sym::simd | sym::transparent)
988+
} else if matches!(name, sym::Rust | sym::C | sym::simd | sym::transparent)
989989
|| int_type_of_word(name).is_some()
990990
{
991991
recognised = true;
@@ -1018,7 +1018,7 @@ pub fn parse_repr_attr(sess: &Session, attr: &Attribute) -> Vec<ReprAttr> {
10181018
});
10191019
} else if matches!(
10201020
meta_item.name_or_empty(),
1021-
sym::C | sym::simd | sym::transparent
1021+
sym::Rust | sym::C | sym::simd | sym::transparent
10221022
) || int_type_of_word(meta_item.name_or_empty()).is_some()
10231023
{
10241024
recognised = true;
@@ -1043,7 +1043,7 @@ pub fn parse_repr_attr(sess: &Session, attr: &Attribute) -> Vec<ReprAttr> {
10431043
);
10441044
} else if matches!(
10451045
meta_item.name_or_empty(),
1046-
sym::C | sym::simd | sym::transparent
1046+
sym::Rust | sym::C | sym::simd | sym::transparent
10471047
) || int_type_of_word(meta_item.name_or_empty()).is_some()
10481048
{
10491049
recognised = true;

compiler/rustc_mir_build/src/thir/print.rs

+8-2
Original file line numberDiff line numberDiff line change
@@ -31,8 +31,8 @@ const INDENT: &str = " ";
3131

3232
macro_rules! print_indented {
3333
($writer:ident, $s:expr, $indent_lvl:expr) => {
34-
let indent = (0..$indent_lvl).map(|_| INDENT).collect::<Vec<_>>().concat();
35-
writeln!($writer, "{}{}", indent, $s).expect("unable to write to ThirPrinter");
34+
$writer.indent($indent_lvl);
35+
writeln!($writer, "{}", $s).expect("unable to write to ThirPrinter");
3636
};
3737
}
3838

@@ -48,6 +48,12 @@ impl<'a, 'tcx> ThirPrinter<'a, 'tcx> {
4848
Self { thir, fmt: String::new() }
4949
}
5050

51+
fn indent(&mut self, level: usize) {
52+
for _ in 0..level {
53+
self.fmt.push_str(INDENT);
54+
}
55+
}
56+
5157
fn print(&mut self) {
5258
print_indented!(self, "params: [", 0);
5359
for param in self.thir.params.iter() {

library/alloc/Cargo.toml

+2-2
Original file line numberDiff line numberDiff line change
@@ -17,11 +17,11 @@ rand = { version = "0.8.5", default-features = false, features = ["alloc"] }
1717
rand_xorshift = "0.3.0"
1818

1919
[[test]]
20-
name = "collectionstests"
20+
name = "alloctests"
2121
path = "tests/lib.rs"
2222

2323
[[bench]]
24-
name = "collectionsbenches"
24+
name = "allocbenches"
2525
path = "benches/lib.rs"
2626
test = true
2727

library/alloc/tests/str.rs

+11
Original file line numberDiff line numberDiff line change
@@ -1170,6 +1170,17 @@ fn test_iterator() {
11701170
assert_eq!(s.chars().count(), v.len());
11711171
}
11721172

1173+
#[test]
1174+
fn test_iterator_advance() {
1175+
let s = "「赤錆」と呼ばれる鉄錆は、水の存在下での鉄の自然酸化によって生じる、オキシ水酸化鉄(III) 等の(含水)酸化物粒子の疎な凝集膜であるとみなせる。";
1176+
let chars: Vec<char> = s.chars().collect();
1177+
let mut it = s.chars();
1178+
it.advance_by(1).unwrap();
1179+
assert_eq!(it.next(), Some(chars[1]));
1180+
it.advance_by(33).unwrap();
1181+
assert_eq!(it.next(), Some(chars[35]));
1182+
}
1183+
11731184
#[test]
11741185
fn test_rev_iterator() {
11751186
let s = "ศไทย中华Việt Nam";

library/core/benches/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
#![feature(trusted_random_access)]
66
#![feature(iter_array_chunks)]
77
#![feature(iter_next_chunk)]
8+
#![feature(iter_advance_by)]
89

910
extern crate test;
1011

library/core/benches/str.rs

+1
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ use test::{black_box, Bencher};
33

44
mod char_count;
55
mod corpora;
6+
mod iter;
67

78
#[bench]
89
fn str_validate_emoji(b: &mut Bencher) {

library/core/benches/str/iter.rs

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
use super::corpora;
2+
use test::{black_box, Bencher};
3+
4+
#[bench]
5+
fn chars_advance_by_1000(b: &mut Bencher) {
6+
b.iter(|| black_box(corpora::ru::LARGE).chars().advance_by(1000));
7+
}
8+
9+
#[bench]
10+
fn chars_advance_by_0010(b: &mut Bencher) {
11+
b.iter(|| black_box(corpora::ru::LARGE).chars().advance_by(10));
12+
}
13+
14+
#[bench]
15+
fn chars_advance_by_0001(b: &mut Bencher) {
16+
b.iter(|| black_box(corpora::ru::LARGE).chars().advance_by(1));
17+
}

library/core/src/num/mod.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -474,7 +474,7 @@ impl isize {
474474
}
475475
}
476476

477-
/// If 6th bit is set ascii is lower case.
477+
/// If the 6th bit is set ascii is lower case.
478478
const ASCII_CASE_MASK: u8 = 0b0010_0000;
479479

480480
impl u8 {
@@ -549,7 +549,7 @@ impl u8 {
549549
#[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.52.0")]
550550
#[inline]
551551
pub const fn to_ascii_uppercase(&self) -> u8 {
552-
// Toggle the fifth bit if this is a lowercase letter
552+
// Toggle the 6th bit if this is a lowercase letter
553553
*self ^ ((self.is_ascii_lowercase() as u8) * ASCII_CASE_MASK)
554554
}
555555

@@ -574,7 +574,7 @@ impl u8 {
574574
#[rustc_const_stable(feature = "const_ascii_methods_on_intrinsics", since = "1.52.0")]
575575
#[inline]
576576
pub const fn to_ascii_lowercase(&self) -> u8 {
577-
// Set the fifth bit if this is an uppercase letter
577+
// Set the 6th bit if this is an uppercase letter
578578
*self | (self.is_ascii_uppercase() as u8 * ASCII_CASE_MASK)
579579
}
580580

library/core/src/num/nonzero.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -355,7 +355,7 @@ macro_rules! nonzero_unsigned_operations {
355355
if let Some(result) = self.get().checked_add(other) {
356356
// SAFETY:
357357
// - `checked_add` returns `None` on overflow
358-
// - `self` and `other` are non-zero
358+
// - `self` is non-zero
359359
// - the only way to get zero from an addition without overflow is for both
360360
// sides to be zero
361361
//
@@ -393,7 +393,7 @@ macro_rules! nonzero_unsigned_operations {
393393
pub const fn saturating_add(self, other: $Int) -> $Ty {
394394
// SAFETY:
395395
// - `saturating_add` returns `u*::MAX` on overflow, which is non-zero
396-
// - `self` and `other` are non-zero
396+
// - `self` is non-zero
397397
// - the only way to get zero from an addition without overflow is for both
398398
// sides to be zero
399399
//

library/core/src/str/iter.rs

+50
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ use crate::iter::{TrustedRandomAccess, TrustedRandomAccessNoCoerce};
88
use crate::ops::Try;
99
use crate::option;
1010
use crate::slice::{self, Split as SliceSplit};
11+
use core::num::NonZeroUsize;
1112

1213
use super::from_utf8_unchecked;
1314
use super::pattern::Pattern;
@@ -49,6 +50,55 @@ impl<'a> Iterator for Chars<'a> {
4950
super::count::count_chars(self.as_str())
5051
}
5152

53+
#[inline]
54+
fn advance_by(&mut self, mut remainder: usize) -> Result<(), NonZeroUsize> {
55+
const CHUNK_SIZE: usize = 32;
56+
57+
if remainder >= CHUNK_SIZE {
58+
let mut chunks = self.iter.as_slice().array_chunks::<CHUNK_SIZE>();
59+
let mut bytes_skipped: usize = 0;
60+
61+
while remainder > CHUNK_SIZE
62+
&& let Some(chunk) = chunks.next()
63+
{
64+
bytes_skipped += CHUNK_SIZE;
65+
66+
let mut start_bytes = [false; CHUNK_SIZE];
67+
68+
for i in 0..CHUNK_SIZE {
69+
start_bytes[i] = !super::validations::utf8_is_cont_byte(chunk[i]);
70+
}
71+
72+
remainder -= start_bytes.into_iter().map(|i| i as u8).sum::<u8>() as usize;
73+
}
74+
75+
// SAFETY: The amount of bytes exists since we just iterated over them,
76+
// so advance_by will succeed.
77+
unsafe { self.iter.advance_by(bytes_skipped).unwrap_unchecked() };
78+
79+
// skip trailing continuation bytes
80+
while self.iter.len() > 0 {
81+
let b = self.iter.as_slice()[0];
82+
if !super::validations::utf8_is_cont_byte(b) {
83+
break;
84+
}
85+
// SAFETY: We just peeked at the byte, therefore it exists
86+
unsafe { self.iter.advance_by(1).unwrap_unchecked() };
87+
}
88+
}
89+
90+
while (remainder > 0) && (self.iter.len() > 0) {
91+
remainder -= 1;
92+
let b = self.iter.as_slice()[0];
93+
let slurp = super::validations::utf8_char_width(b);
94+
// SAFETY: utf8 validity requires that the string must contain
95+
// the continuation bytes (if any)
96+
unsafe { self.iter.advance_by(slurp).unwrap_unchecked() };
97+
}
98+
99+
NonZeroUsize::new(remainder).map_or(Ok(()), Err)
100+
}
101+
52102
#[inline]
53103
fn size_hint(&self) -> (usize, Option<usize>) {
54104
let len = self.iter.len();

library/std/src/sync/once_lock.rs

+41-9
Original file line numberDiff line numberDiff line change
@@ -13,22 +13,54 @@ use crate::sync::Once;
1313
///
1414
/// # Examples
1515
///
16+
/// Using `OnceCell` to store a function’s previously computed value (a.k.a.
17+
/// ‘lazy static’ or ‘memoizing’):
18+
///
19+
/// ```
20+
/// use std::collections::HashMap;
21+
/// use std::sync::OnceLock;
22+
///
23+
/// fn hash_map() -> &'static HashMap<u32, char> {
24+
/// static HASHMAP: OnceLock<HashMap<u32, char>> = OnceLock::new();
25+
/// HASHMAP.get_or_init(|| {
26+
/// let mut m = HashMap::new();
27+
/// m.insert(0, 'a');
28+
/// m.insert(1, 'b');
29+
/// m.insert(2, 'c');
30+
/// m
31+
/// })
32+
/// }
33+
///
34+
/// // The `HashMap` is built, stored in the `OnceLock`, and returned.
35+
/// let _ = hash_map();
36+
///
37+
/// // The `HashMap` is retrieved from the `OnceLock` and returned.
38+
/// let _ = hash_map();
39+
/// ```
40+
///
41+
/// Writing to a `OnceLock` from a separate thread:
42+
///
1643
/// ```
1744
/// use std::sync::OnceLock;
1845
///
19-
/// static CELL: OnceLock<String> = OnceLock::new();
46+
/// static CELL: OnceLock<usize> = OnceLock::new();
47+
///
48+
/// // `OnceLock` has not been written to yet.
2049
/// assert!(CELL.get().is_none());
2150
///
51+
/// // Spawn a thread and write to `OnceLock`.
2252
/// std::thread::spawn(|| {
23-
/// let value: &String = CELL.get_or_init(|| {
24-
/// "Hello, World!".to_string()
25-
/// });
26-
/// assert_eq!(value, "Hello, World!");
27-
/// }).join().unwrap();
53+
/// let value = CELL.get_or_init(|| 12345);
54+
/// assert_eq!(value, &12345);
55+
/// })
56+
/// .join()
57+
/// .unwrap();
2858
///
29-
/// let value: Option<&String> = CELL.get();
30-
/// assert!(value.is_some());
31-
/// assert_eq!(value.unwrap().as_str(), "Hello, World!");
59+
/// // `OnceLock` now contains the value.
60+
/// assert_eq!(
61+
/// CELL.get(),
62+
/// Some(&12345),
63+
/// );
3264
/// ```
3365
#[stable(feature = "once_cell", since = "1.70.0")]
3466
pub struct OnceLock<T> {

tests/ui/repr/issue-83921-ice.rs tests/ui/repr/malformed-repr-hints.rs

+9
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,15 @@ struct S3;
1919
//~^ ERROR: incorrect `repr(align)` attribute format
2020
struct S4;
2121

22+
// Regression test for issue #118334:
23+
#[repr(Rust(u8))]
24+
//~^ ERROR: invalid representation hint
25+
#[repr(Rust(0))]
26+
//~^ ERROR: invalid representation hint
27+
#[repr(Rust = 0)]
28+
//~^ ERROR: invalid representation hint
29+
struct S5;
30+
2231
#[repr(i8())]
2332
//~^ ERROR: invalid representation hint
2433
enum E1 { A, B }
Original file line numberDiff line numberDiff line change
@@ -1,46 +1,64 @@
11
error[E0552]: incorrect `repr(packed)` attribute format: `packed` takes exactly one parenthesized argument, or no parentheses at all
2-
--> $DIR/issue-83921-ice.rs:6:8
2+
--> $DIR/malformed-repr-hints.rs:6:8
33
|
44
LL | #[repr(packed())]
55
| ^^^^^^^^
66

77
error[E0589]: invalid `repr(align)` attribute: `align` needs an argument
8-
--> $DIR/issue-83921-ice.rs:10:8
8+
--> $DIR/malformed-repr-hints.rs:10:8
99
|
1010
LL | #[repr(align)]
1111
| ^^^^^ help: supply an argument here: `align(...)`
1212

1313
error[E0693]: incorrect `repr(align)` attribute format: `align` takes exactly one argument in parentheses
14-
--> $DIR/issue-83921-ice.rs:14:8
14+
--> $DIR/malformed-repr-hints.rs:14:8
1515
|
1616
LL | #[repr(align(2, 4))]
1717
| ^^^^^^^^^^^
1818

1919
error[E0693]: incorrect `repr(align)` attribute format: `align` takes exactly one argument in parentheses
20-
--> $DIR/issue-83921-ice.rs:18:8
20+
--> $DIR/malformed-repr-hints.rs:18:8
2121
|
2222
LL | #[repr(align())]
2323
| ^^^^^^^
2424

25+
error[E0552]: invalid representation hint: `Rust` does not take a parenthesized argument list
26+
--> $DIR/malformed-repr-hints.rs:23:8
27+
|
28+
LL | #[repr(Rust(u8))]
29+
| ^^^^^^^^
30+
31+
error[E0552]: invalid representation hint: `Rust` does not take a parenthesized argument list
32+
--> $DIR/malformed-repr-hints.rs:25:8
33+
|
34+
LL | #[repr(Rust(0))]
35+
| ^^^^^^^
36+
37+
error[E0552]: invalid representation hint: `Rust` does not take a value
38+
--> $DIR/malformed-repr-hints.rs:27:8
39+
|
40+
LL | #[repr(Rust = 0)]
41+
| ^^^^^^^^
42+
2543
error[E0552]: invalid representation hint: `i8` does not take a parenthesized argument list
26-
--> $DIR/issue-83921-ice.rs:22:8
44+
--> $DIR/malformed-repr-hints.rs:31:8
2745
|
2846
LL | #[repr(i8())]
2947
| ^^^^
3048

3149
error[E0552]: invalid representation hint: `u32` does not take a parenthesized argument list
32-
--> $DIR/issue-83921-ice.rs:26:8
50+
--> $DIR/malformed-repr-hints.rs:35:8
3351
|
3452
LL | #[repr(u32(42))]
3553
| ^^^^^^^
3654

3755
error[E0552]: invalid representation hint: `i64` does not take a value
38-
--> $DIR/issue-83921-ice.rs:30:8
56+
--> $DIR/malformed-repr-hints.rs:39:8
3957
|
4058
LL | #[repr(i64 = 2)]
4159
| ^^^^^^^
4260

43-
error: aborting due to 7 previous errors
61+
error: aborting due to 10 previous errors
4462

4563
Some errors have detailed explanations: E0552, E0589, E0693.
4664
For more information about an error, try `rustc --explain E0552`.

0 commit comments

Comments
 (0)