Skip to content

Commit 6a9a089

Browse files
authored
Turn collections of String into collections of Box<str> (#2594)
* Change `String` by `Box<str>` inside `RegexSet` * Turn `raw_lines` into a `Box<str>` * Turn keys and values of `module_lines` into `Box<str>`s * Turn `input_headers` into a `Vec<Box<str>>` * Turn `clang_args` into a `Vec<Box<str>>` * Turn keys and values of `input_header_contents` into `Box<str>`s * Add suggestions * Run rustfmt
1 parent bf5e79b commit 6a9a089

File tree

9 files changed

+94
-84
lines changed

9 files changed

+94
-84
lines changed

bindgen/clang.rs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1813,14 +1813,14 @@ impl TranslationUnit {
18131813
pub(crate) fn parse(
18141814
ix: &Index,
18151815
file: &str,
1816-
cmd_args: &[String],
1816+
cmd_args: &[Box<str>],
18171817
unsaved: &[UnsavedFile],
18181818
opts: CXTranslationUnit_Flags,
18191819
) -> Option<TranslationUnit> {
18201820
let fname = CString::new(file).unwrap();
18211821
let _c_args: Vec<CString> = cmd_args
18221822
.iter()
1823-
.map(|s| CString::new(s.clone()).unwrap())
1823+
.map(|s| CString::new(s.clone().into_boxed_bytes()).unwrap())
18241824
.collect();
18251825
let c_args: Vec<*const c_char> =
18261826
_c_args.iter().map(|s| s.as_ptr()).collect();
@@ -1923,9 +1923,9 @@ pub(crate) struct UnsavedFile {
19231923

19241924
impl UnsavedFile {
19251925
/// Construct a new unsaved file with the given `name` and `contents`.
1926-
pub(crate) fn new(name: String, contents: String) -> UnsavedFile {
1927-
let name = CString::new(name).unwrap();
1928-
let contents = CString::new(contents).unwrap();
1926+
pub(crate) fn new(name: &str, contents: &str) -> UnsavedFile {
1927+
let name = CString::new(name.as_bytes()).unwrap();
1928+
let contents = CString::new(contents.as_bytes()).unwrap();
19291929
let x = CXUnsavedFile {
19301930
Filename: name.as_ptr(),
19311931
Contents: contents.as_ptr(),

bindgen/codegen/mod.rs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -601,7 +601,10 @@ impl CodeGenerator for Module {
601601
let inner_items = result.inner(|result| {
602602
result.push(root_import(ctx, item));
603603

604-
let path = item.namespace_aware_canonical_path(ctx).join("::");
604+
let path = item
605+
.namespace_aware_canonical_path(ctx)
606+
.join("::")
607+
.into_boxed_str();
605608
if let Some(raw_lines) = ctx.options().module_lines.get(&path) {
606609
for raw_line in raw_lines {
607610
found_any = true;

bindgen/deps.rs

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -8,11 +8,11 @@ pub(crate) struct DepfileSpec {
88
}
99

1010
impl DepfileSpec {
11-
pub fn write(&self, deps: &BTreeSet<String>) -> std::io::Result<()> {
11+
pub fn write(&self, deps: &BTreeSet<Box<str>>) -> std::io::Result<()> {
1212
std::fs::write(&self.depfile_path, self.to_string(deps))
1313
}
1414

15-
fn to_string(&self, deps: &BTreeSet<String>) -> String {
15+
fn to_string(&self, deps: &BTreeSet<Box<str>>) -> String {
1616
// Transforms a string by escaping spaces and backslashes.
1717
let escape = |s: &str| s.replace('\\', "\\\\").replace(' ', "\\ ");
1818

@@ -35,14 +35,14 @@ mod tests {
3535
depfile_path: PathBuf::new(),
3636
};
3737

38-
let deps: BTreeSet<String> = vec![
39-
r"/absolute/path".to_owned(),
40-
r"C:\win\absolute\path".to_owned(),
41-
r"../relative/path".to_owned(),
42-
r"..\win\relative\path".to_owned(),
43-
r"../path/with spaces/in/it".to_owned(),
44-
r"..\win\path\with spaces\in\it".to_owned(),
45-
r"path\with/mixed\separators".to_owned(),
38+
let deps: BTreeSet<_> = vec![
39+
r"/absolute/path".into(),
40+
r"C:\win\absolute\path".into(),
41+
r"../relative/path".into(),
42+
r"..\win\relative\path".into(),
43+
r"../path/with spaces/in/it".into(),
44+
r"..\win\path\with spaces\in\it".into(),
45+
r"path\with/mixed\separators".into(),
4646
]
4747
.into_iter()
4848
.collect();

bindgen/ir/context.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -365,7 +365,7 @@ pub(crate) struct BindgenContext {
365365
includes: StdHashMap<String, (String, usize)>,
366366

367367
/// A set of all the included filenames.
368-
deps: BTreeSet<String>,
368+
deps: BTreeSet<Box<str>>,
369369

370370
/// The active replacements collected from replaces="xxx" annotations.
371371
replacements: HashMap<Vec<String>, ItemId>,
@@ -664,12 +664,12 @@ If you encounter an error missing from this list, please file an issue or a PR!"
664664
}
665665

666666
/// Add an included file.
667-
pub(crate) fn add_dep(&mut self, dep: String) {
667+
pub(crate) fn add_dep(&mut self, dep: Box<str>) {
668668
self.deps.insert(dep);
669669
}
670670

671671
/// Get any included files.
672-
pub(crate) fn deps(&self) -> &BTreeSet<String> {
672+
pub(crate) fn deps(&self) -> &BTreeSet<Box<str>> {
673673
&self.deps
674674
}
675675

bindgen/ir/item.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1465,7 +1465,7 @@ impl Item {
14651465
cb.include_file(&included_file);
14661466
}
14671467

1468-
ctx.add_dep(included_file);
1468+
ctx.add_dep(included_file.into_boxed_str());
14691469
}
14701470
}
14711471
}

bindgen/lib.rs

Lines changed: 45 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -94,15 +94,15 @@ fn file_is_cpp(name_file: &str) -> bool {
9494
name_file.ends_with(".h++")
9595
}
9696

97-
fn args_are_cpp(clang_args: &[String]) -> bool {
97+
fn args_are_cpp(clang_args: &[Box<str>]) -> bool {
9898
for w in clang_args.windows(2) {
99-
if w[0] == "-xc++" || w[1] == "-xc++" {
99+
if w[0].as_ref() == "-xc++" || w[1].as_ref() == "-xc++" {
100100
return true;
101101
}
102-
if w[0] == "-x" && w[1] == "c++" {
102+
if w[0].as_ref() == "-x" && w[1].as_ref() == "c++" {
103103
return true;
104104
}
105-
if w[0] == "-include" && file_is_cpp(&w[1]) {
105+
if w[0].as_ref() == "-include" && file_is_cpp(w[1].as_ref()) {
106106
return true;
107107
}
108108
}
@@ -319,22 +319,26 @@ impl Builder {
319319
/// Generate the Rust bindings using the options built up thus far.
320320
pub fn generate(mut self) -> Result<Bindings, BindgenError> {
321321
// Add any extra arguments from the environment to the clang command line.
322-
self.options
323-
.clang_args
324-
.extend(get_extra_clang_args(&self.options.parse_callbacks));
322+
self.options.clang_args.extend(
323+
get_extra_clang_args(&self.options.parse_callbacks)
324+
.into_iter()
325+
.map(String::into_boxed_str),
326+
);
325327

326328
// Transform input headers to arguments on the clang command line.
327329
self.options.clang_args.extend(
328330
self.options.input_headers
329331
[..self.options.input_headers.len().saturating_sub(1)]
330332
.iter()
331-
.flat_map(|header| ["-include".into(), header.to_string()]),
333+
.flat_map(|header| ["-include".into(), header.clone()]),
332334
);
333335

334336
let input_unsaved_files =
335337
std::mem::take(&mut self.options.input_header_contents)
336338
.into_iter()
337-
.map(|(name, contents)| clang::UnsavedFile::new(name, contents))
339+
.map(|(name, contents)| {
340+
clang::UnsavedFile::new(name.as_ref(), contents.as_ref())
341+
})
338342
.collect::<Vec<_>>();
339343

340344
Bindings::generate(self.options, input_unsaved_files)
@@ -401,7 +405,7 @@ impl Builder {
401405
.stdout(Stdio::piped());
402406

403407
for a in &self.options.clang_args {
404-
cmd.arg(a);
408+
cmd.arg(a.as_ref());
405409
}
406410

407411
for a in get_extra_clang_args(&self.options.parse_callbacks) {
@@ -668,16 +672,16 @@ pub(crate) const HOST_TARGET: &str =
668672

669673
// Some architecture triplets are different between rust and libclang, see #1211
670674
// and duplicates.
671-
fn rust_to_clang_target(rust_target: &str) -> String {
675+
fn rust_to_clang_target(rust_target: &str) -> Box<str> {
672676
if rust_target.starts_with("aarch64-apple-") {
673677
let mut clang_target = "arm64-apple-".to_owned();
674678
clang_target
675679
.push_str(rust_target.strip_prefix("aarch64-apple-").unwrap());
676-
return clang_target;
680+
return clang_target.into();
677681
} else if rust_target.starts_with("riscv64gc-") {
678682
let mut clang_target = "riscv64-".to_owned();
679683
clang_target.push_str(rust_target.strip_prefix("riscv64gc-").unwrap());
680-
return clang_target;
684+
return clang_target.into();
681685
} else if rust_target.ends_with("-espidf") {
682686
let mut clang_target =
683687
rust_target.strip_suffix("-espidf").unwrap().to_owned();
@@ -686,32 +690,32 @@ fn rust_to_clang_target(rust_target: &str) -> String {
686690
clang_target = "riscv32-".to_owned() +
687691
clang_target.strip_prefix("riscv32imc-").unwrap();
688692
}
689-
return clang_target;
693+
return clang_target.into();
690694
} else if rust_target.starts_with("riscv32imc-") {
691695
let mut clang_target = "riscv32-".to_owned();
692696
clang_target.push_str(rust_target.strip_prefix("riscv32imc-").unwrap());
693-
return clang_target;
697+
return clang_target.into();
694698
} else if rust_target.starts_with("riscv32imac-") {
695699
let mut clang_target = "riscv32-".to_owned();
696700
clang_target
697701
.push_str(rust_target.strip_prefix("riscv32imac-").unwrap());
698-
return clang_target;
702+
return clang_target.into();
699703
}
700-
rust_target.to_owned()
704+
rust_target.into()
701705
}
702706

703707
/// Returns the effective target, and whether it was explicitly specified on the
704708
/// clang flags.
705-
fn find_effective_target(clang_args: &[String]) -> (String, bool) {
709+
fn find_effective_target(clang_args: &[Box<str>]) -> (Box<str>, bool) {
706710
let mut args = clang_args.iter();
707711
while let Some(opt) = args.next() {
708712
if opt.starts_with("--target=") {
709713
let mut split = opt.split('=');
710714
split.next();
711-
return (split.next().unwrap().to_owned(), true);
715+
return (split.next().unwrap().into(), true);
712716
}
713717

714-
if opt == "-target" {
718+
if opt.as_ref() == "-target" {
715719
if let Some(target) = args.next() {
716720
return (target.clone(), true);
717721
}
@@ -756,9 +760,10 @@ impl Bindings {
756760
// opening libclang.so, it has to be the same architecture and thus the
757761
// check is fine.
758762
if !explicit_target && !is_host_build {
759-
options
760-
.clang_args
761-
.insert(0, format!("--target={}", effective_target));
763+
options.clang_args.insert(
764+
0,
765+
format!("--target={}", effective_target).into_boxed_str(),
766+
);
762767
};
763768

764769
fn detect_include_paths(options: &mut BindgenOptions) {
@@ -779,7 +784,7 @@ impl Bindings {
779784
return false;
780785
}
781786

782-
let arg = &**arg;
787+
let arg = arg.as_ref();
783788

784789
// https://clang.llvm.org/docs/ClangCommandLineReference.html
785790
// -isystem and -isystem-after are harmless.
@@ -796,7 +801,7 @@ impl Bindings {
796801

797802
true
798803
})
799-
.cloned()
804+
.map(|arg| arg.clone().into())
800805
.collect::<Vec<_>>()
801806
};
802807

@@ -828,8 +833,8 @@ impl Bindings {
828833
if let Some(search_paths) = search_paths {
829834
for path in search_paths.into_iter() {
830835
if let Ok(path) = path.into_os_string().into_string() {
831-
options.clang_args.push("-isystem".to_owned());
832-
options.clang_args.push(path);
836+
options.clang_args.push("-isystem".into());
837+
options.clang_args.push(path.into_boxed_str());
833838
}
834839
}
835840
}
@@ -849,7 +854,7 @@ impl Bindings {
849854
}
850855

851856
if let Some(h) = options.input_headers.last() {
852-
let path = Path::new(h);
857+
let path = Path::new(h.as_ref());
853858
if let Ok(md) = std::fs::metadata(path) {
854859
if md.is_dir() {
855860
return Err(BindgenError::FolderAsHeader(path.into()));
@@ -859,18 +864,17 @@ impl Bindings {
859864
path.into(),
860865
));
861866
}
862-
let h = h.clone();
863-
options.clang_args.push(h);
867+
options.clang_args.push(h.clone());
864868
} else {
865869
return Err(BindgenError::NotExist(path.into()));
866870
}
867871
}
868872

869873
for (idx, f) in input_unsaved_files.iter().enumerate() {
870874
if idx != 0 || !options.input_headers.is_empty() {
871-
options.clang_args.push("-include".to_owned());
875+
options.clang_args.push("-include".into());
872876
}
873-
options.clang_args.push(f.name.to_str().unwrap().to_owned())
877+
options.clang_args.push(f.name.to_str().unwrap().into())
874878
}
875879

876880
debug!("Fixed-up options: {:?}", options);
@@ -1285,33 +1289,36 @@ fn commandline_flag_unit_test_function() {
12851289

12861290
#[test]
12871291
fn test_rust_to_clang_target() {
1288-
assert_eq!(rust_to_clang_target("aarch64-apple-ios"), "arm64-apple-ios");
1292+
assert_eq!(
1293+
rust_to_clang_target("aarch64-apple-ios").as_ref(),
1294+
"arm64-apple-ios"
1295+
);
12891296
}
12901297

12911298
#[test]
12921299
fn test_rust_to_clang_target_riscv() {
12931300
assert_eq!(
1294-
rust_to_clang_target("riscv64gc-unknown-linux-gnu"),
1301+
rust_to_clang_target("riscv64gc-unknown-linux-gnu").as_ref(),
12951302
"riscv64-unknown-linux-gnu"
12961303
);
12971304
assert_eq!(
1298-
rust_to_clang_target("riscv32imc-unknown-none-elf"),
1305+
rust_to_clang_target("riscv32imc-unknown-none-elf").as_ref(),
12991306
"riscv32-unknown-none-elf"
13001307
);
13011308
assert_eq!(
1302-
rust_to_clang_target("riscv32imac-unknown-none-elf"),
1309+
rust_to_clang_target("riscv32imac-unknown-none-elf").as_ref(),
13031310
"riscv32-unknown-none-elf"
13041311
);
13051312
}
13061313

13071314
#[test]
13081315
fn test_rust_to_clang_target_espidf() {
13091316
assert_eq!(
1310-
rust_to_clang_target("riscv32imc-esp-espidf"),
1317+
rust_to_clang_target("riscv32imc-esp-espidf").as_ref(),
13111318
"riscv32-esp-elf"
13121319
);
13131320
assert_eq!(
1314-
rust_to_clang_target("xtensa-esp32-espidf"),
1321+
rust_to_clang_target("xtensa-esp32-espidf").as_ref(),
13151322
"xtensa-esp32-elf"
13161323
);
13171324
}

bindgen/options/as_args.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ impl AsArgs for bool {
2424
impl AsArgs for RegexSet {
2525
fn as_args(&self, args: &mut Vec<String>, flag: &str) {
2626
for item in self.get_items() {
27-
args.extend_from_slice(&[flag.to_owned(), item.clone()]);
27+
args.extend_from_slice(&[flag.to_owned(), item.clone().into()]);
2828
}
2929
}
3030
}

0 commit comments

Comments
 (0)