如何将输出格式化为带有 no_std 且没有分配器的字节数组? [英] How to format output to a byte array with no_std and no allocator?

查看:62
本文介绍了如何将输出格式化为带有 no_std 且没有分配器的字节数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做类似的事情:

let x = 123;
let mut buf = [0 as u8; 20];
format_to!(x --> buf);
assert_eq!(&buf[..3], &b"123"[..]);

使用 #![no_std] 并且没有任何内存分配器.

With #![no_std] and without any memory allocator.

据我所知,u64 有一个 core::fmt::Display 的实现,如果可能的话,我想使用它.

As I understand, there is an implementation of core::fmt::Display for u64, and I want to use it if possible.

换句话说,我想做一些类似 format!(...) 的事情,但没有内存分配器.我该怎么做?

In other words, I want to do something like format!(...), but without a memory allocator. How can I do this?

推荐答案

先从标准版说起:

use std::io::Write;

fn main() {
    let x = 123;
    let mut buf = [0 as u8; 20];
    write!(&mut buf[..], "{}", x).expect("Can't write");
    assert_eq!(&buf[0..3], b"123");
}

如果我们删除标准库:

#![feature(lang_items)]
#![no_std]

use core::panic::PanicInfo;

#[lang = "eh_personality"]
extern "C" fn eh_personality() {}

#[panic_handler]
fn panic(info: &PanicInfo) -> ! {
    loop {}
}

fn main() {
    let x = 123;
    let mut buf = [0 as u8; 20];
    write!(&mut buf[..], "{}", x).expect("Can't write");
    assert_eq!(&buf[0..3], b"123");
}

我们得到错误

error[E0599]: no method named `write_fmt` found for type `&mut [u8]` in the current scope
  --> src/main.rs:17:5
   |
17 |     write!(&mut buf[..], "{}", x).expect("Can't write");
   |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   |
   = note: this error originates in a macro outside of the current crate (in Nightly builds, run with -Z external-macro-backtrace for more info)

write_fmtcore::fmt::Write.如果我们自己实现它,我们就可以传递那个错误:

write_fmt is implemented in the core library by core::fmt::Write. If we implement it ourselves, we are able to pass that error:

#![feature(lang_items)]
#![feature(start)]
#![no_std]

use core::panic::PanicInfo;

#[lang = "eh_personality"]
extern "C" fn eh_personality() {}

#[panic_handler]
fn panic(info: &PanicInfo) -> ! {
    loop {}
}

use core::fmt::{self, Write};

struct Wrapper<'a> {
    buf: &'a mut [u8],
    offset: usize,
}

impl<'a> Wrapper<'a> {
    fn new(buf: &'a mut [u8]) -> Self {
        Wrapper {
            buf: buf,
            offset: 0,
        }
    }
}

impl<'a> fmt::Write for Wrapper<'a> {
    fn write_str(&mut self, s: &str) -> fmt::Result {
        let bytes = s.as_bytes();

        // Skip over already-copied data
        let remainder = &mut self.buf[self.offset..];
        // Check if there is space remaining (return error instead of panicking)
        if remainder.len() < bytes.len() { return Err(core::fmt::Error); }
        // Make the two slices the same length
        let remainder = &mut remainder[..bytes.len()];
        // Copy
        remainder.copy_from_slice(bytes);

        // Update offset to avoid overwriting
        self.offset += bytes.len();

        Ok(())
    }
}

#[start]
fn start(_argc: isize, _argv: *const *const u8) -> isize {
    let x = 123;
    let mut buf = [0 as u8; 20];
    write!(Wrapper::new(&mut buf), "{}", x).expect("Can't write");
    assert_eq!(&buf[0..3], b"123");
    0
}

请注意,我们正在复制 io:: 的行为光标 进入这个包装器.通常,对 &mut [u8] 的多次写入会相互覆盖.这有利于重用分配,但在连续写入相同数据时没有用.

Note that we are duplicating the behavior of io::Cursor into this wrapper. Normally, multiple writes to a &mut [u8] will overwrite each other. This is good for reusing allocation, but not useful when you have consecutive writes of the same data.

那么只要你愿意,只要写一个宏就行了.

Then it's just a matter of writing a macro if you want to.

您还应该能够使用像 arrayvec 这样的 crate,它为您编写了此代码.这是未经测试的:

You should also be able to use a crate like arrayvec, which has written this code for you. This is untested:

#![feature(lang_items)]
#![feature(start)]
#![no_std]

use core::panic::PanicInfo;

#[lang = "eh_personality"]
extern "C" fn eh_personality() {}

#[panic_handler]
fn panic(_info: &PanicInfo) -> ! {
    loop {}
}

use arrayvec::ArrayString; // 0.4.10
use core::fmt::Write;

#[start]
fn start(_argc: isize, _argv: *const *const u8) -> isize {
    let x = 123;
    let mut buf = ArrayString::<[u8; 20]>::new();
    write!(&mut buf, "{}", x).expect("Can't write");
    assert_eq!(&buf, "123");
    0
}

这篇关于如何将输出格式化为带有 no_std 且没有分配器的字节数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆