1 // Copyright 2022 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 use std::alloc::{alloc, dealloc, Layout};
6
7 #[cxx::bridge]
8 mod ffi {
9 pub struct SomeStruct {
10 a: i32,
11 }
12 extern "Rust" {
say_hello()13 fn say_hello();
alloc_aligned()14 fn alloc_aligned();
add_two_ints_via_rust(x: i32, y: i32) -> i3215 fn add_two_ints_via_rust(x: i32, y: i32) -> i32;
allocate_via_rust() -> Box<SomeStruct>16 fn allocate_via_rust() -> Box<SomeStruct>;
allocate_huge_via_rust(size: usize, align: usize) -> bool17 fn allocate_huge_via_rust(size: usize, align: usize) -> bool;
18 }
19 }
20
say_hello()21 pub fn say_hello() {
22 println!(
23 "Hello, world - from a Rust library. Calculations suggest that 3+4={}",
24 add_two_ints_via_rust(3, 4)
25 );
26 }
27
alloc_aligned()28 pub fn alloc_aligned() {
29 let layout = unsafe { Layout::from_size_align_unchecked(1024, 512) };
30 let ptr = unsafe { alloc(layout) };
31 println!("Alloc aligned ptr: {:p}", ptr);
32 unsafe { dealloc(ptr, layout) };
33 }
34
35 #[test]
test_hello()36 fn test_hello() {
37 assert_eq!(7, add_two_ints_via_rust(3, 4));
38 }
39
add_two_ints_via_rust(x: i32, y: i32) -> i3240 pub fn add_two_ints_via_rust(x: i32, y: i32) -> i32 {
41 x + y
42 }
43
44 // Used from the RustComponentUsesPartitionAlloc unit tests.
allocate_via_rust() -> Box<ffi::SomeStruct>45 pub fn allocate_via_rust() -> Box<ffi::SomeStruct> {
46 Box::new(ffi::SomeStruct { a: 43 })
47 }
48
49 // Used from the RustLargeAllocationFailure unit tests.
allocate_huge_via_rust(size: usize, align: usize) -> bool50 pub fn allocate_huge_via_rust(size: usize, align: usize) -> bool {
51 let layout = std::alloc::Layout::from_size_align(size, align).unwrap();
52 let p = unsafe { std::alloc::alloc(layout) };
53 // Rust can optimize out allocations. By printing the pointer value we ensure
54 // the allocation actually happens (and can thus fail).
55 dbg!(p);
56 if !p.is_null() {
57 unsafe { std::alloc::dealloc(p, layout) };
58 }
59 !p.is_null()
60 }
61