Skip to content

Commit 0d09c11

Browse files
committed
Code simplifications
1 parent f7908fc commit 0d09c11

41 files changed

Lines changed: 161 additions & 206 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎cpp2rust/converter/converter.cpp‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2619,6 +2619,10 @@ bool Converter::VisitExplicitCastExpr(clang::ExplicitCastExpr *expr) {
26192619
auto type = expr->getTypeAsWritten();
26202620
auto *sub_expr = expr->getSubExpr();
26212621
if (type->isVoidType()) {
2622+
if (!sub_expr->HasSideEffects(ctx_)) {
2623+
EmitFresh("()");
2624+
return false;
2625+
}
26222626
StrCat(token::kRef);
26232627
PushParen paren(*this);
26242628
PushExprKind push(*this, ExprKind::Void);

‎cpp2rust/converter/models/converter_refcount.cpp‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2729,7 +2729,7 @@ void ConverterRefCount::ConvertArraySubscript(clang::Expr *base,
27292729
}
27302730

27312731
if (is_inner_boxed) {
2732-
StrCat(".as_pointer()");
2732+
StrCat(".decay()");
27332733
}
27342734
}
27352735

@@ -2818,7 +2818,7 @@ void ConverterRefCount::ConvertPointerSubscript(
28182818
} else {
28192819
ConvertPointerOffset(base, idx);
28202820
if (expr->getType()->isArrayType()) {
2821-
StrCat(".as_pointer()");
2821+
StrCat(".decay()");
28222822
}
28232823
}
28242824
}
@@ -2890,7 +2890,7 @@ void ConverterRefCount::ConvertDeref(clang::Expr *expr) {
28902890
}
28912891

28922892
if (isAddrOf() && pointee_type->isArrayType()) {
2893-
str = std::format("({}).as_pointer()", std::move(str));
2893+
str = std::format("({}).decay()", std::move(str));
28942894
}
28952895
StrCat(std::move(str));
28962896
}

‎libcc2rs/src/cstr.rs‎

Lines changed: 6 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -100,12 +100,8 @@ impl<T: CChar> fmt::Display for Ptr<T> {
100100
match &self.kind {
101101
PtrKind::Null => write!(f, "NULL"),
102102
_ => {
103-
for value in self {
104-
let ch = value.read().to_byte();
105-
if ch == 0 {
106-
break;
107-
}
108-
write!(f, "{}", char::from(ch))?;
103+
for ch in self.to_c_string_iterator() {
104+
write!(f, "{}", char::from(ch.to_byte()))?;
109105
}
110106
Ok(())
111107
}
@@ -192,16 +188,12 @@ impl<T: CChar> Ptr<T> {
192188
return;
193189
}
194190
let mut dst = self.clone();
195-
let mut i: usize = 0;
196-
for value in src {
197-
if i >= len {
198-
break;
199-
}
200-
dst.write(value.read());
191+
let mut s = src.clone();
192+
for _ in 0..len {
193+
dst.write(s.read());
201194
dst += 1;
202-
i += 1;
195+
s += 1;
203196
}
204-
assert_eq!(i, len, "ub: memcpy");
205197
}
206198

207199
#[allow(clippy::explicit_counter_loop)]

‎libcc2rs/src/field.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1554,7 +1554,7 @@ mod tests {
15541554
let nums: Ptr<i32> = field_ptr!(s, nums).decay();
15551555
nums.sort(3);
15561556
assert_eq!(s.borrow().nums, vec![1, 2, 3]);
1557-
assert_eq!(nums.collect::<Vec<_>>().len(), 3);
1557+
assert_eq!(nums.len(), 3);
15581558
}
15591559

15601560
#[test]

‎libcc2rs/src/fn_ptr.rs‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -507,6 +507,9 @@ impl<T: FnSig> ErasedPtr for FnPtr<T> {
507507
fn as_bytes(&self) -> Ptr<u8> {
508508
panic!("byte view not supported on fn pointer");
509509
}
510+
fn byte_address(&self) -> usize {
511+
panic!("byte view not supported on fn pointer");
512+
}
510513
fn as_any(&self) -> &dyn Any {
511514
self
512515
}

‎libcc2rs/src/rc.rs‎

Lines changed: 15 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -521,6 +521,21 @@ impl<T> Ptr<T> {
521521
self.kind.address().wrapping_add(self.byte_offset())
522522
}
523523

524+
// The address of the object that the pointer points to in the C++ layout
525+
// of its allocation, which reinterpreted views of the allocation share,
526+
// e.g., to compare pointers of different types as void*.
527+
pub(crate) fn byte_address(&self) -> usize
528+
where
529+
T: ByteRepr,
530+
{
531+
let offset = match &self.kind {
532+
PtrKind::Null => return 0,
533+
PtrKind::Reinterpreted(_) | PtrKind::Field(_, _, FieldShape::Single) => self.offset,
534+
_ => self.offset.wrapping_mul(T::byte_size()),
535+
};
536+
self.kind.address().wrapping_add(offset)
537+
}
538+
524539
// Normalize offset to bytes for cross-variant comparison.
525540
#[inline]
526541
fn byte_offset(&self) -> usize {
@@ -1240,38 +1255,6 @@ impl<T: std::cmp::Ord + 'static> Ptr<T> {
12401255
}
12411256
}
12421257

1243-
impl<T> IntoIterator for &Ptr<T>
1244-
where
1245-
T: Clone,
1246-
{
1247-
type Item = Ptr<T>;
1248-
type IntoIter = Ptr<T>;
1249-
1250-
fn into_iter(self) -> Self::IntoIter {
1251-
self.clone()
1252-
}
1253-
}
1254-
1255-
impl<T> Iterator for Ptr<T> {
1256-
type Item = Ptr<T>;
1257-
fn next(&mut self) -> Option<Self::Item> {
1258-
if self.get_offset() < self.len() {
1259-
let value = self.clone();
1260-
self.offset += self.elem_step();
1261-
Some(value)
1262-
} else {
1263-
None
1264-
}
1265-
}
1266-
1267-
// Lets collections built from the iterator (e.g. `std::string`'s
1268-
// constructors) allocate their storage once instead of growing it.
1269-
fn size_hint(&self) -> (usize, Option<usize>) {
1270-
let remaining = self.len().saturating_sub(self.get_offset());
1271-
(remaining, Some(remaining))
1272-
}
1273-
}
1274-
12751258
impl<T> Sub for Ptr<T> {
12761259
type Output = isize;
12771260
fn sub(self, other: Self) -> Self::Output {
@@ -1428,13 +1411,6 @@ impl<T> AsPointer<T> for Option<Rc<RefCell<Box<[T]>>>> {
14281411
}
14291412
}
14301413

1431-
impl<T> AsPointer<Vec<T>> for Ptr<Vec<T>> {
1432-
#[inline]
1433-
fn as_pointer(&self) -> Ptr<Vec<T>> {
1434-
self.clone()
1435-
}
1436-
}
1437-
14381414
impl<T: 'static> Ptr<Vec<T>> {
14391415
#[inline]
14401416
pub fn decay(&self) -> Ptr<T> {
@@ -1467,20 +1443,6 @@ impl<T: 'static> Ptr<Vec<T>> {
14671443
}
14681444
}
14691445

1470-
impl<T> AsPointer<Box<[T]>> for Ptr<Box<[T]>> {
1471-
#[inline]
1472-
fn as_pointer(&self) -> Ptr<Box<[T]>> {
1473-
self.clone()
1474-
}
1475-
}
1476-
1477-
impl<T: 'static> AsPointer<T> for Ptr<Box<[T]>> {
1478-
#[inline]
1479-
fn as_pointer(&self) -> Ptr<T> {
1480-
self.decay()
1481-
}
1482-
}
1483-
14841446
impl<T: 'static> Ptr<Box<[T]>> {
14851447
#[inline]
14861448
pub fn decay(&self) -> Ptr<T> {

‎libcc2rs/src/void.rs‎

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,9 @@ use crate::reinterpret::ByteRepr;
88

99
pub trait ErasedPtr: std::any::Any {
1010
fn as_bytes(&self) -> Ptr<u8>;
11+
// The address of the byte that the pointer points to, which is the same
12+
// for pointers of any type to the same object.
13+
fn byte_address(&self) -> usize;
1114
fn as_any(&self) -> &dyn std::any::Any;
1215
fn equals(&self, other: &dyn ErasedPtr) -> bool;
1316
fn is_null(&self) -> bool;
@@ -33,12 +36,16 @@ where
3336
self.reinterpret_cast::<u8>()
3437
}
3538

39+
fn byte_address(&self) -> usize {
40+
Ptr::byte_address(self)
41+
}
42+
3643
fn as_any(&self) -> &dyn std::any::Any {
3744
self
3845
}
3946

4047
fn equals(&self, other: &dyn ErasedPtr) -> bool {
41-
other.as_bytes() == self.as_bytes()
48+
other.byte_address() == self.byte_address()
4249
}
4350

4451
fn is_null(&self) -> bool {
@@ -180,6 +187,18 @@ mod tests {
180187
assert!(p3.is_null());
181188
}
182189

190+
#[test]
191+
fn anyptr_eq_across_types() {
192+
let p: Ptr<i32> = Ptr::alloc_array(vec![1, 2, 3].into_boxed_slice());
193+
let bytes = p.reinterpret_cast::<u8>();
194+
assert!(p.offset(1).to_any() == bytes.offset(4).to_any());
195+
assert!(p.offset(1).to_any() != bytes.offset(3).to_any());
196+
assert!(bytes.offset(8).reinterpret_cast::<u16>().to_any() == p.offset(2).to_any());
197+
assert!(Ptr::<i32>::null().to_any() == Ptr::<u8>::null().to_any());
198+
assert!(p.to_any() != Ptr::<i32>::null().to_any());
199+
p.delete();
200+
}
201+
183202
#[test]
184203
fn to_any_without_clone() {
185204
let p: Ptr<std::fs::File> = Ptr::null(); // std::fs::File is not Clone

‎tests/multi-file/opaque_forward_decl/out/refcount/opaque_forward_decl.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ fn main_0() -> i32 {
3030
return 0;
3131
}
3232
pub fn touch_0(mut c: Ptr<container>) {
33-
&(c.with(|__s| __s.p.clone()));
33+
();
3434
}
3535
#[derive(Clone, Copy, Default, ByteRepr, VaArg, FnPtrArg)]
3636
#[byte_size(1)]

‎tests/multi-file/opaque_forward_decl/out/unsafe/opaque_forward_decl.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ unsafe fn main_0() -> i32 {
2929
return 0;
3030
}
3131
pub unsafe fn touch_0(mut c: *mut container) {
32-
&((*c).p);
32+
();
3333
}
3434
#[derive(Clone, Copy, Default, VaArg, FnPtrArg)]
3535
pub struct opaque;

‎tests/ub/out/refcount/reinterpret_cast_oob_read.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ fn main_0() -> i32 {
1414
let val: Value<u32> = Rc::new(RefCell::new(67305985_u32));
1515
let mut bytes: Ptr<u8> = (val.as_pointer()).reinterpret_cast::<u8>();
1616
let mut x: u8 = (elem!(bytes, 4).read());
17-
&(x);
17+
();
1818
return 0;
1919
}
2020
pub fn __cpp2rust_init_globals() {}

0 commit comments

Comments
 (0)