小编Öme*_*den的帖子

如何安全地从`&mut [u32]`获取不可变的字节片?

在我的项目的相当低级的部分中,函数接收可变的原始数据切片(&mut [u32]在这种情况下)。此数据应以小端序写入作者。

现在,仅此一项就不成问题,但是所有这些必须快速。我评估了我的应用程序,并将其确定为关键路径之一。特别是,如果不需要更改字节序(因为我们已经在一个小的字节序系统上),那么就不会有任何开销。

这是我的代码(Playground):

use std::{io, mem, slice};

fn write_data(mut w: impl io::Write, data: &mut [u32]) -> Result<(), io::Error> {
    adjust_endianness(data);

    // Is this safe?
    let bytes = unsafe {
        let len = data.len() * mem::size_of::<u32>();
        let ptr = data.as_ptr() as *const u8;
        slice::from_raw_parts(ptr, len)
    };

    w.write_all(bytes)
}

fn adjust_endianness(_: &mut [u32]) {
    // implementation omitted
}
Run Code Online (Sandbox Code Playgroud)

adjust_endianness更改位置的字节序(这很好,因为错误的字节序u32是垃圾,但仍然是有效的u32)。

该代码有效,但关键问题是:这样安全吗?特别是,在某个时刻,data并且bytes两者都存在,它们是同一数据的一个可变且一个不变的切片。听起来很不好,对吧?

另一方面,我可以这样做:

let bytes = &data[..];
Run Code Online (Sandbox Code Playgroud)

这样,我也有这两个方面。所不同的只是 …

unsafe rust

9
推荐指数
1
解决办法
165
查看次数

Future 生成器闭包时出错:捕获的变量无法转义“FnMut”闭包主体

我想创建一个简单的 websocket 服务器。我想处理传入的消息并发送响应,但收到错误:

error: captured variable cannot escape `FnMut` closure body
  --> src\main.rs:32:27
   |
32 |       incoming.for_each(|m| async {
   |  _________________________-_^
   | |                         |
   | |                         inferred to be a `FnMut` closure
33 | |         match m {
34 | |             // Error here...
35 | |             Ok(message) => do_something(message, db, &mut outgoing).await,
36 | |             Err(e) => panic!(e)
37 | |         }
38 | |     }).await;
   | |_____^ returns a reference to a captured variable which escapes the closure …
Run Code Online (Sandbox Code Playgroud)

rust async-await

9
推荐指数
1
解决办法
9840
查看次数

如何添加绑定到泛型关联类型的特征?

最近,Rust 博客上发表了“推动 GAT 稳定化”一文。我对这个LendingIterator特性很感兴趣,但在尝试使用它时遇到了问题。这是帖子中的定义:

trait LendingIterator {
    type Item<'a> where Self: 'a;
    fn next<'a>(&'a mut self) -> Option<Self::Item<'a>>;
}
Run Code Online (Sandbox Code Playgroud)

博客文章中宣传的所有内容都运行良好,我看到了 GAT 如何以多种方式提供帮助。但是:如何添加绑定到关联Item类型的特征?

使用标准Iterator特征,这很容易:

fn print_all<I>(mut i: I) 
where
    I: Iterator,
    I::Item: std::fmt::Debug,    // <-------
{
    while let Some(x) = i.next() {
        println!("{:?}", x);
    }
}
Run Code Online (Sandbox Code Playgroud)

但是有了新特性,这个边界就不会编译(Playground):

where
    I: LendingIterator,
    I::Item: std::fmt::Debug,
Run Code Online (Sandbox Code Playgroud)

编译器说:

trait LendingIterator {
    type Item<'a> where Self: 'a;
    fn next<'a>(&'a mut self) -> Option<Self::Item<'a>>;
}
Run Code Online (Sandbox Code Playgroud)

所以我们需要一个生命周期参数。除了仅使用'static …

rust generic-associated-types

9
推荐指数
1
解决办法
169
查看次数

调用clock_gettime()时,返回的tv_nsec字段实际上可能超过一秒?

当您调用clock_gettime()它时,返回timespec结构.

struct timespec {
    time_t tv_sec; /* seconds */
    long tv_nsec; /* nanoseconds */
};
Run Code Online (Sandbox Code Playgroud)

我没有在手册页中找到tv_nsec不会超过一秒的保证.实际存在保证吗?它可能依赖于linux的库(glibc?)实现吗?

关键的想法是:我是否需要"规范化"来自clock_gettime()函数的任何结果?

c linux glibc libc

8
推荐指数
1
解决办法
951
查看次数

异步REST客户端

如何编写异步休息客户端?我的控制器(不确定它是不是因为异步).

@RequestMapping(method = RequestMethod.GET, value = "/get/all")
@ResponseBody
public Callable < CustomersListDTO > getAllCustomers() {
    return new Callable < CustomersListDTO > () {

        @Override
        public CustomersListDTO call() throws Exception {
            Thread.sleep(2000);
            return customerService.getAllCustomers();
        }

    };
}
Run Code Online (Sandbox Code Playgroud)

我的同步休息客户端方法:

public Response get_all_customers() {
    ResponseEntity < CustomersListDTO > response;
    try {
        response = restTemplate.getForEntity(
            getMethodURI(ServiceExplanation.GET_ALL_CUSTOMERS),
            CustomersListDTO.class
        );
        message = "Customers obtained successfully!";
    } catch (HttpServerErrorException ex) {
        message = "ERROR: " + ex.getMessage() + " - " + ex.getResponseBodyAsString();
    } catch (HttpClientErrorException ex) …
Run Code Online (Sandbox Code Playgroud)

java rest spring asynchronous resttemplate

7
推荐指数
2
解决办法
2万
查看次数

如何在Rust中运行特定的单元测试?

我在一个名为的软件包中有单元测试,school-info并且有一个名为的测试函数repeat_students_should_not_get_full_marks

我可以通过运行模块中的所有测试cargo test --package school_info

cargo test test-name将匹配并运行测试,其中包含test_name尽管没有帮助。

如何仅repeat_students_should_not_get_full_marks运行测试而不运行所有测试?我在文档中找不到执行此操作的命令。

unit-testing rust rust-cargo

7
推荐指数
1
解决办法
1620
查看次数

如何在 Rust 中调用泛型特征方法

拥有这些相当人为的类型定义

trait Generic<T> {
    fn some(&self) -> T;
}

impl<T> Generic<T> for i32
where
    T: Default,
{
    fn some(&self) -> T {
        T::default()
    }
}
Run Code Online (Sandbox Code Playgroud)

我想调用some显式指定类型 T 的方法。下面的代码显然不起作用,因为该方法本身不是通用的。

fn main() {
    let int: i32 = 45;
    println!( "some: {}", int.some<bool>() );
}
Run Code Online (Sandbox Code Playgroud)

正确的通话方式是什么some

rust

7
推荐指数
1
解决办法
4826
查看次数

使用iText将图像添加到PDF

我正在尝试使用iText将图像添加到PDF文件.文件从.TXT转换为PDF,并且应该添加图像:

//Convert Reports to PDF
File conv = new File("Report Forms/");
String[] filesconv = conv.list(only);
for (int c = 0; c < filesconv.length; c++) {
    PdfWriter writer = null;
    try {
        Document output = new Document(PageSize.B4);
        Rectangle page = output.getPageSize();
        page.setBackgroundColor(new java.awt.Color(255, 255, 255));
        FileInputStream fs = new FileInputStream("Report Forms/" + filesconv[c]);
        FileOutputStream file = new FileOutputStream(new File("Report Forms/" + name + " " + exa + " FORM " + level + " " + year + ".pdf"));
        DataInputStream …
Run Code Online (Sandbox Code Playgroud)

java pdf io image itext

6
推荐指数
1
解决办法
5万
查看次数

具有关联类型的工厂方法

我正在尝试实现一个返回Service具有关联类型的工厂方法。我让它在没有关联类型的情况下工作,但是一旦我添加了它,无论我如何按摩它,我都无法编译它..

这是Service

trait QType {}

trait Service {
    type Query: QType;

    fn sanitize(&self, query: &str) -> Result<Self::Query, String>;

    fn run(&self, query: &Self::Query) -> Result<(), String>;
}
Run Code Online (Sandbox Code Playgroud)

所以想法是sanitize函数返回 的一个实例Query,然后可以将其传递给run函数。

工厂看起来像这样(不编译):

fn factory<Q: QType>(name: &str) -> Box<dyn Service<Query = Q>> {
    match name {
        "amazon" => Box::new(amzn::Amazon {}),
        other => panic!("Invalid service {}", other),
    }
}
Run Code Online (Sandbox Code Playgroud)

现在我这里只有一个服务,我可以在签名中的类型参数中进行特定——这将使它编译——但我​​想要一个通用的工厂方法并添加更多服务。

下面是Amazon服务的实现:

mod amzn {
    use super::*;

    pub struct Amazon {}

    pub struct Product …
Run Code Online (Sandbox Code Playgroud)

rust

6
推荐指数
1
解决办法
236
查看次数

从 CMake 调用 Cargo 的最佳方式?

我发现了这个:https : //github.com/AndrewGaspar/cmake-cargo但无法让它工作

无论如何,如果我要使用 Makefile 而不是 CMake,我只需创建一个规则来监视 .rs 文件的更改和重新编译。

我找不到从 Cmake 调用 Cargo的解决方案(而不是相反),所以我在这里打开一个。

如何CMakeLists.txt通过调用监视 .rs 文件更改并重新编译cargo build

cmake rust rust-cargo

6
推荐指数
2
解决办法
1272
查看次数