rust - 如何将 C 可变长度数组代码转换为 Rust?

标签 rust variable-length-array borrow-checker

我知道 Rust 不支持可变长度数组,但这让我想知道用什么来替换它们,因为:

  • 我不想在循环中分配和释放一个小的 Vec
  • 借用检查器不允许我将代码移出循环
  • 固定大小的数组有很多限制,所以我不知道如何使用它们

我正在转换的 C 代码通过在每一行调用回调并传递一个小指针数组来处理图像:

float *tmp[img->channels]; // Small, up to 4 elements
for(int y = 0; y < height; y++) {
    for(int ch = 0; ch < img->channels; ch++) {
        tmp[ch] = &img->channel[ch]->pixels[width * y];
    }
    callback(tmp, img->channels);
}

我的 Rust 尝试(example in playpen):

for y in 0..height {
    let tmp = &img.channel.iter().map(|channel| {
        &mut channel.pixels.as_ref().unwrap()[width * y .. width * (y+1)]
    }).collect();
    callback(tmp);
}

但是被拒绝了:

a collection of type [&mut [f32]] cannot be built from an iterator over elements of type &mut [f32]

遗憾的是,这听起来和我想做的一模一样!

我试过使用固定大小的数组,但 Rust 不支持它们的泛型,所以我不能从迭代器填充它,我也不能在类似 C 的循环中填充它们,因为循环中的引用不会比它长。

the trait core::iter::FromIterator<&mut [f32]> is not implemented for the type [&mut [f32]; 4]


另一种从固定大小数组中获取内存片段的方法也失败了:

let mut row_tmp: [&mut [f32]; 4] = unsafe{mem::zeroed()};
for y in 0..height {
    row_tmp[0..channels].iter_mut().zip(img.chan.iter_mut()).map(|(t, chan)| {
        *t = &mut chan.img.as_ref().unwrap()[(width * y) as usize .. (width * (y+1)) as usize]
    });
    cb(&row_tmp[0..channels], y, width, image_data);
}

error: cannot borrow img.chan as mutable more than once at a time

最佳答案

arrayvec是一个可以满足您需求的库。 (此外,您可能需要 iter_mutas_mut 而不是 iteras_ref。)

for y in 0..height {
    let tmp: ArrayVec<[_; 4]> = img.channel.iter_mut().map(|channel| {
        &mut channel.pixels.as_mut().unwrap()[width * y .. width * (y+1)]
    }).collect();
    callback(&tmp);
}

它在堆栈上分配固定数量的存储空间(此处为 4 个项目),其行为类似于 Vec,其大小是有界的(最大为编译时指定的容量)但可变。

arrayvec 中的大部分复杂性是处理可变数量项的运行析构函数。但是由于 &mut _ 没有析构函数,您也可以只使用固定大小的数组。但是你必须使用不安全代码并且注意不要读取未初始化的项目。 (固定大小的数组不实现 FromIterator,这是 Iterator::collect 使用的。)

( Playpen )

let n_channels = img.channel.len();
for y in 0..height {
    let tmp: [_; 4] = unsafe { mem::uninitialized() }
    for (i, channel) in img.channel.iter_mut().enumerate() {
        tmp[i] = &mut channel.pixels.as_mut().unwrap()[width * y .. width * (y+1)];
    }
    // Careful to only touch initialized items...
    callback(&tmp[..n_channels]);
}

编辑:不安全代码可以替换为:

let mut tmp: [&mut [_]; 4] = [&mut [], &mut [], &mut [], &mut []];

较短的 [&mut []; 4] 初始化器语法不适用于此处,因为 &mut [_] 不可隐式复制。类型注解是必要的,这样你就不会得到 [&mut [_; 0]; 4]

关于rust - 如何将 C 可变长度数组代码转换为 Rust?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30423786/

相关文章:

rust生命周期问题,为什么第一次调用没有编译错误?

hash - 如何使用氧化钠 crate 对字符串进行哈希处理?

arrays - 将数组分配到运行时已知大小的堆上

rust - 具有结构 "cannot move out of borrowed content"的向量的多次迭代

rust - 为什么不能在同一结构中存储值和对该值的引用?

macros - 我找不到 `mock!` 的定义

c - 数组类型和使用 malloc 分配的数组之间的区别

c - [c]中变长数组(VLA)的初始值从哪里来?

c - 编译器如何解析变长数组后声明的变量地址?

rust - 请求消息值必须在静态生命周期内有效