1 // Copyright 2021 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();
allocate_via_rust() -> Box<SomeStruct>15 fn allocate_via_rust() -> Box<SomeStruct>;
add_two_ints_via_rust(x: i32, y: i32) -> i3216 fn add_two_ints_via_rust(x: i32, y: i32) -> i32;
17 }
18 }
19
say_hello()20 pub fn say_hello() {
21 println!(
22 "Hello, world - from a Rust library. Calculations suggest that 3+4={}",
23 add_two_ints_via_rust(3, 4)
24 );
25 }
26
alloc_aligned()27 pub fn alloc_aligned() {
28 let layout = unsafe { Layout::from_size_align_unchecked(1024, 512) };
29 let ptr = unsafe { alloc(layout) };
30 println!("Alloc aligned ptr: {:p}", ptr);
31 unsafe { dealloc(ptr, layout) };
32 }
33
34 #[test]
test_hello()35 fn test_hello() {
36 assert_eq!(7, add_two_ints_via_rust(3, 4));
37 }
38
add_two_ints_via_rust(x: i32, y: i32) -> i3239 pub fn add_two_ints_via_rust(x: i32, y: i32) -> i32 {
40 x + y
41 }
42
43 // The next function is used from the
44 // AllocatorTest.RustComponentUsesPartitionAlloc unit test.
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 mod tests {
50 #[test]
test_in_mod()51 fn test_in_mod() {
52 // Always passes; just to see if tests in modules are handled correctly.
53 }
54 }
55