Skip to content

Commit 875ef75

Browse files
committed
transpile: Split off make_pointer_difference
1 parent 56d3fb2 commit 875ef75

2 files changed

Lines changed: 19 additions & 8 deletions

File tree

c2rust-transpile/src/translator/operators.rs

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -576,14 +576,8 @@ impl<'c> Translation<'c> {
576576
let rhs_type = &self.ast_context.resolve_type(rhs_type_id.ctype).kind;
577577

578578
if let &CTypeKind::Pointer(pointee) = rhs_type {
579-
let mut offset = mk().method_call_expr(lhs, "offset_from", vec![rhs]);
580-
581-
if let Some(sz) = self.compute_size_of_expr(pointee.ctype) {
582-
let div = cast_int(sz, "isize", false);
583-
offset = mk().binary_expr(BinOp::Div(Default::default()), offset, div);
584-
}
585-
586-
Ok(WithStmts::new_val(mk().cast_expr(offset, ty)).set_unsafe())
579+
let val = self.make_pointer_difference(lhs, rhs, pointee.ctype);
580+
Ok(val.map(|val| mk().cast_expr(val, ty)))
587581
} else if let &CTypeKind::Pointer(pointee) = lhs_type {
588582
Ok(self.convert_pointer_offset(lhs, rhs, pointee.ctype, true, false))
589583
} else if lhs_type.is_unsigned_integral_type() {

c2rust-transpile/src/translator/pointers.rs

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -385,6 +385,23 @@ impl<'c> Translation<'c> {
385385
WithStmts::new_val(res).set_unsafe()
386386
}
387387

388+
/// Creates a pointer difference expression. Returns an expression of type `isize`.
389+
pub fn make_pointer_difference(
390+
&self,
391+
lhs_rs: Box<Expr>,
392+
rhs_rs: Box<Expr>,
393+
pointee_type_id: CTypeId,
394+
) -> WithStmts<Box<Expr>> {
395+
let mut expr_rs = mk().method_call_expr(lhs_rs, "offset_from", vec![rhs_rs]);
396+
397+
if let Some(sz) = self.compute_size_of_expr(pointee_type_id) {
398+
let div_rs = cast_int(sz, "isize", false);
399+
expr_rs = mk().binary_expr(BinOp::Div(Default::default()), expr_rs, div_rs);
400+
}
401+
402+
WithStmts::new_val(expr_rs).set_unsafe()
403+
}
404+
388405
/// Construct an expression for a NULL at any type, including forward declarations,
389406
/// function pointers, and normal pointers.
390407
pub fn null_ptr(&self, type_id: CTypeId) -> TranslationResult<Box<Expr>> {

0 commit comments

Comments
 (0)