xref: /build/rust/tests/test_cxx_rust/src/main.rs (revision 5f9996aa)
1/*
2 * Copyright (c) 2023 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16//! test_cxx_rust
17#[cxx::bridge(namespace = "nsp_org::nsp_blobstore")]
18mod ffi {
19    // Shared structs with fields visible to both languages.
20    struct Metadata_Blob {
21        size: usize,
22        tags: Vec<String>,
23    }
24
25    // Rust types and signatures exposed to C++.
26    extern "Rust" {
27        type MultiBufs;
28
29        fn next_chunk(buf: &mut MultiBufs) -> &[u8];
30    }
31
32    // C++ types and signatures exposed to Rust.
33    unsafe extern "C++" {
34        include!("build/rust/tests/test_cxx_rust/include/client_blobstore.h");
35
36        type client_blobstore;
37
38        fn blobstore_client_new() -> UniquePtr<client_blobstore>;
39        fn put_buf(&self, parts: &mut MultiBufs) -> u64;
40        fn add_tag(&self, blobid: u64, add_tag: &str);
41        fn get_metadata(&self, blobid: u64) -> Metadata_Blob;
42    }
43}
44
45// An iterator over contiguous chunks of a discontiguous file object.
46//
47// Toy implementation uses a Vec<Vec<u8>> but in reality this might be iterating
48// over some more complex Rust data structure like a rope, or maybe loading
49// chunks lazily from somewhere.
50/// pub struct MultiBufs
51pub struct MultiBufs {
52    chunks: Vec<Vec<u8>>,
53    pos: usize,
54}
55/// pub fn next_chunk
56pub fn next_chunk(buf: &mut MultiBufs) -> &[u8] {
57    let next = buf.chunks.get(buf.pos);
58    buf.pos += 1;
59    next.map_or(&[], Vec::as_slice)
60}
61
62/// fn main()
63fn main() {
64    let client = ffi::blobstore_client_new();
65
66    // Upload a blob.
67    let chunks = vec![b"fearless".to_vec(), b"concurrency".to_vec()];
68    let mut buf = MultiBufs { chunks, pos: 0 };
69    let blobid = client.put_buf(&mut buf);
70    println!("This is a test for Rust call cpp:");
71    println!("blobid = {}", blobid);
72
73    // Add a add_tag.
74    client.add_tag(blobid, "rust");
75
76    // Read back the tags.
77    let get_metadata = client.get_metadata(blobid);
78    println!("tags = {:?}", get_metadata.tags);
79}
80