【CXX】6.3 &[T], &mut [T] — rust::Slice<T>

rust::Slice, rust::Slice

复制代码
Rust 中的 &[T] 在 C++ 中写作 rust::Slice<const T>
Rust 中的 &mut [T] 在 C++ 中写作 rust::Slice<T>
公共 API:
cpp 复制代码
// rust/cxx.h

template <typename T>
class Slice final {
public:
using value_type = T;

Slice() noexcept;
Slice(const Slice<T> &) noexcept;
Slice(T *, size_t count) noexcept;

template <typename C>
explicit Slice(C &c) : Slice(c.data(), c.size());

Slice &operator=(Slice<T> &&) & noexcept;
Slice &operator=(const Slice<T> &) & noexcept
requires std::is_const_v<T>;

T *data() const noexcept;
size_t size() const noexcept;
size_t length() const noexcept;
bool empty() const noexcept;

T &operator[](size_t n) const noexcept;
T &at(size_t n) const;
T &front() const noexcept;
T &back() const noexcept;

class iterator;
iterator begin() const noexcept;
iterator end() const noexcept;

void swap(Slice &) noexcept;
};
限制:

T 不能是不透明的 Rust 类型或不透明的 C++ 类型。对不透明 Rust 类型的切片支持即将推出。

允许作为函数参数或返回值。不支持在共享结构体中使用。

只有 rust::Slice 是可复制赋值的,rust::Slice 则不行。(两者都是可移动赋值的。)你需要偶尔写 std::move 来提醒自己,意外地将重叠的 &mut T 暴露给 Rust 是未定义行为。

示例

这个示例是一个 C++ 程序,它构造了一个包含 JSON 数据的切片(通过从 stdin 读取,但也可以来自任何地方),然后调用 Rust 来通过 serde_json 和 serde_transcode 库将该 JSON 数据漂亮地打印到一个 std::string 中。

rust 复制代码
// src/main.rs

#![no_main] // main 定义在 C++ 的 main.cc 中

use cxx::CxxString;
use std::io::{self, Write};
use std::pin::Pin;

#[cxx::bridge]
mod ffi {
extern "Rust" {
fn prettify_json(input: &[u8], output: Pin<&mut CxxString>) -> Result<()>;
}
}

struct WriteToCxxString<'a>(Pin<&'a mut CxxString>);

impl<'a> Write for WriteToCxxString<'a> {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.0.as_mut().push_bytes(buf);
Ok(buf.len())
}
fn flush(&mut self) -> io::Result<()> {
Ok(())
}
}

fn prettify_json(input: &[u8], output: Pin<&mut CxxString>) -> serde_json::Result<()> {
let writer = WriteToCxxString(output);
let mut deserializer = serde_json::Deserializer::from_slice(input);
let mut serializer = serde_json::Serializer::pretty(writer);
serde_transcode::transcode(&mut deserializer, &mut serializer)
}
cpp 复制代码
// src/main.cc

#include "example/src/main.rs.h"
#include <iostream>
#include <iterator>
#include <string>
#include <vector>

int main() {
// 从 stdin 读取 json。
std::istreambuf_iterator<char> begin{std::cin}, end;
std::vector<unsigned char> input{begin, end};
rust::Slice<const uint8_t> slice{input.data(), input.size()};

// 使用 serde_json 和 serde_transcode 进行漂亮打印。
std::string output;
prettify_json(slice, output);

// 写入 stdout。
std::cout << output << std::endl;
}
测试示例:
复制代码
$ echo '{"fearless":"concurrency"}' | cargo run
Finished dev [unoptimized + debuginfo] target(s) in 0.02s
Running target/debug/example
{
"fearless": "concurrency"
}
相关推荐
lpfasd1237 小时前
node-sass 停止维护!老项目迁移 Dart Sass 完整教程
前端·rust·sass
Flynt8 小时前
我把真实的 ES 查询怼到 7059 星的 Rust 搜索引擎上:1366/1369 的兼容承诺,裂了 3 个缝
elasticsearch·搜索引擎·rust
小杍随笔10 小时前
egui 0.37 升级实录:卡顿修复与5倍性能回退
windows·rust·egui
geovindu17 小时前
rust: Iterator Pattern
开发语言·后端·设计模式·rust·行为模式·迭代器模
gopher95111 天前
RUST:错误处理 thiserror 详解
开发语言·后端·rust
geovindu1 天前
rust:Memento Pattern(续)
开发语言·后端·设计模式·rust·行为模式·备忘录模
Kapaseker2 天前
同样 4 行代码,C++ 编译通过,Rust 为什么直接拒绝?
rust
DongQiShanRen2 天前
六根硬件映射(中):双站校验、生克闭环与驱动接口
数据库·人工智能·算法·rust·哈希算法·集成学习
Amos_Web2 天前
Rspack 源码解析(二十五):CssParserAndGenerator 如何把 CSS 变成可 Tree Shaking 的模块
前端·rust·前端框架
Kainy2 天前
Rust重写Photoshop开源项目PhotoCraft:无头命令行修图与AI Agent自动化实战
人工智能·rust·photoshop