Skip to content

Commit

Permalink
Rollup merge of #99358 - compiler-errors:issue-99325, r=oli-obk
Browse files Browse the repository at this point in the history
Allow `ValTree::try_to_raw_bytes` on `u8` array

Fixes #99325

cc `@b-naber` I think who touched this last in 705d818
  • Loading branch information
GuillaumeGomez committed Jul 27, 2022
2 parents ef81fca + 91e91d8 commit 4ce1b0f
Show file tree
Hide file tree
Showing 4 changed files with 322 additions and 21 deletions.
34 changes: 14 additions & 20 deletions compiler/rustc_middle/src/ty/consts/valtree.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,31 +80,25 @@ impl<'tcx> ValTree<'tcx> {
}

/// Get the values inside the ValTree as a slice of bytes. This only works for
/// constants with types &str and &[u8].
/// constants with types &str, &[u8], or [u8; _].
pub fn try_to_raw_bytes(self, tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Option<&'tcx [u8]> {
match ty.kind() {
ty::Ref(_, inner_ty, _) => match inner_ty.kind() {
ty::Str => {
let leafs = self
.unwrap_branch()
.into_iter()
.map(|v| v.unwrap_leaf().try_to_u8().unwrap());

return Some(tcx.arena.alloc_from_iter(leafs));
}
ty::Slice(slice_ty) if *slice_ty == tcx.types.u8 => {
let leafs = self
.unwrap_branch()
.into_iter()
.map(|v| v.unwrap_leaf().try_to_u8().unwrap());

return Some(tcx.arena.alloc_from_iter(leafs));
}
_ => {}
// `&str` can be interpreted as raw bytes
ty::Str => {}
// `&[u8]` can be interpreted as raw bytes
ty::Slice(slice_ty) if *slice_ty == tcx.types.u8 => {}
// other `&_` can't be interpreted as raw bytes
_ => return None,
},
_ => {}
// `[u8; N]` can be interpreted as raw bytes
ty::Array(array_ty, _) if *array_ty == tcx.types.u8 => {}
// Otherwise, type cannot be interpreted as raw bytes
_ => return None,
}

None
Some(tcx.arena.alloc_from_iter(
self.unwrap_branch().into_iter().map(|v| v.unwrap_leaf().try_to_u8().unwrap()),
))
}
}
2 changes: 1 addition & 1 deletion compiler/rustc_middle/src/ty/print/pretty.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1452,7 +1452,7 @@ pub trait PrettyPrinter<'tcx>:
}
},
(ty::ValTree::Branch(_), ty::Array(t, _)) if *t == u8_type => {
let bytes = valtree.try_to_raw_bytes(self.tcx(), *t).unwrap_or_else(|| {
let bytes = valtree.try_to_raw_bytes(self.tcx(), ty).unwrap_or_else(|| {
bug!("expected to convert valtree to raw bytes for type {:?}", t)
});
p!("*");
Expand Down
12 changes: 12 additions & 0 deletions src/test/mir-opt/issue-99325.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
#![feature(adt_const_params)]
#![allow(incomplete_features)]

pub fn function_with_bytes<const BYTES: &'static [u8; 4]>() -> &'static [u8] {
BYTES
}

// EMIT_MIR issue_99325.main.mir_map.0.mir
pub fn main() {
assert_eq!(function_with_bytes::<b"AAAA">(), &[0x41, 0x41, 0x41, 0x41]);
assert_eq!(function_with_bytes::<{ &[0x41, 0x41, 0x41, 0x41] }>(), b"AAAA");
}
Loading

0 comments on commit 4ce1b0f

Please sign in to comment.