blob: dca596aea10e57090723bd4fc681fc6cf0fbf796 [file] [log] [blame]
David Tolnay4ca366f2020-11-10 20:55:31 -08001#[cxx::bridge(namespace = "org::blobstore")]
David Tolnay7db73692019-10-20 14:51:12 -04002mod ffi {
David Tolnay4ca366f2020-11-10 20:55:31 -08003 // Shared structs with fields visible to both languages.
4 struct BlobMetadata {
5 size: usize,
6 tags: Vec<String>,
David Tolnay7db73692019-10-20 14:51:12 -04007 }
8
David Tolnay4ca366f2020-11-10 20:55:31 -08009 // Rust types and signatures exposed to C++.
David Tolnay7db73692019-10-20 14:51:12 -040010 extern "Rust" {
David Tolnay4ca366f2020-11-10 20:55:31 -080011 type MultiBuf;
12
13 fn next_chunk(buf: &mut MultiBuf) -> &[u8];
14 }
15
16 // C++ types and signatures exposed to Rust.
David Tolnay7be5b1f2020-11-11 10:48:32 -080017 unsafe extern "C++" {
David Tolnay4ca366f2020-11-10 20:55:31 -080018 include!("demo/include/blobstore.h");
19
20 type BlobstoreClient;
21
22 fn new_blobstore_client() -> UniquePtr<BlobstoreClient>;
23 fn put(&self, parts: &mut MultiBuf) -> u64;
24 fn tag(&self, blobid: u64, tag: &str);
25 fn metadata(&self, blobid: u64) -> BlobMetadata;
David Tolnay7db73692019-10-20 14:51:12 -040026 }
27}
28
David Tolnay4ca366f2020-11-10 20:55:31 -080029// An iterator over contiguous chunks of a discontiguous file object.
30//
31// Toy implementation uses a Vec<Vec<u8>> but in reality this might be iterating
32// over some more complex Rust data structure like a rope, or maybe loading
33// chunks lazily from somewhere.
34pub struct MultiBuf {
35 chunks: Vec<Vec<u8>>,
36 pos: usize,
37}
38pub fn next_chunk(buf: &mut MultiBuf) -> &[u8] {
39 let next = buf.chunks.get(buf.pos);
40 buf.pos += 1;
41 next.map(Vec::as_slice).unwrap_or(&[])
David Tolnay7db73692019-10-20 14:51:12 -040042}
43
44fn main() {
David Tolnay4ca366f2020-11-10 20:55:31 -080045 let client = ffi::new_blobstore_client();
David Tolnay7db73692019-10-20 14:51:12 -040046
David Tolnay4ca366f2020-11-10 20:55:31 -080047 // Upload a blob.
48 let chunks = vec![b"fearless".to_vec(), b"concurrency".to_vec()];
49 let mut buf = MultiBuf { chunks, pos: 0 };
50 let blobid = client.put(&mut buf);
51 println!("blobid = {}", blobid);
52
53 // Add a tag.
54 client.tag(blobid, "rust");
55
56 // Read back the tags.
57 let metadata = client.metadata(blobid);
58 println!("tags = {:?}", metadata.tags);
David Tolnay7db73692019-10-20 14:51:12 -040059}