跳到正文

个人记录

更适合喜欢 Rust 的小朋友的读入模板(Rust)

ViynaNokphia约 24 分钟
原文
文章信息与版本

文章信息

发布
2024年5月17日
收录
2025年12月12日
更新
2026年11月13日
篇幅
约 24 分钟
获赞
4

版本

  1. v1当前

更适合喜欢 Rust 的小朋友的读入(雾)。写这个东西的初衷,是为了解决 Rust 在算法竞赛和大数据处理场景中的 I/O 性能瓶颈。标准的 std::io 库虽然安全易用,但在需要极速读入海量数据时,其性能表现往往不尽如人意。为了打破这一限制,我们使用了 Unsafe Rust,通过调用 libc 的相关函数,实现了性能上可以与 C++ 常见读入方式媲美且更加易用的读入模板。

请注意下面几个 extern "C" 在洛谷最新支持的 Rust 2024 中需要改为 unsafe extern "C"。由于测试环境 LibreOJ 仅支持到 Rust 2018,所以没有做更新的适配。


下面是几个读入模板的实现。由效率 快到慢 排序。

mmap 版本(最快,unsafe)

https://loj.ac/s/2384647

mmap 是最快的输入方式之一,它的核心是内存映射,内核会把目的文件映射在内存中,避免应用程序读取输入到内存中的开销。

Rust
// 是的显然 mmap 只能在类 unix 上用
// 还没有实现字符串和负数的读,不过我相信你都写 Rust 了自己实现一下应该不难吧(逃
#![cfg(unix)]

macro_rules! __fallback_to_default_type {
    () => {
        // 在这里改回退类型
        i32
    };
    ($x:ty) => {
        $x
    };
}

macro_rules! read {
    ($reader:ident, { $($name:ident $(: $vartype:ty)? $(,)?)+ }) => {
        $(let $name = {$reader.next::<__fallback_to_default_type!($($vartype)?)>()};)+
    };
}

mod _reader {
    use std::ffi::c_void;
    use std::os::unix::io::AsRawFd;

    mod c_ffi {
        use std::ffi::c_void;

        #[repr(C)]
        pub struct Stat {
            __unused_prefix: [u8; 48],
            pub st_size: i64, // offset = 0x30
            __unused_suffix: [u8; 86],
            // _tp: u32, // offset = 0x90
        }

        extern "C" {
            pub fn mmap(
                addr: *const c_void,
                len: usize,
                prot: i32,
                flags: i32,
                fd: i32,
                offset: i64,
            ) -> *mut c_void;

            pub fn munmap(addr: *const c_void, len: usize) -> i32;
            pub fn fstat(fd: i32, statbuf: *mut Stat) -> i32;
        }
    }

    pub struct Reader {
        data: *const u8,
        len: usize,
        pos: usize,
    }

    impl Reader {
        pub fn new() -> Self {
            let fd = std::io::stdin().as_raw_fd();

            let mut stat = unsafe { std::mem::zeroed::<c_ffi::Stat>() };
            unsafe {
                c_ffi::fstat(fd, &mut stat as *mut _);
            }

            let len = stat.st_size as usize;
            let data = unsafe {
                c_ffi::mmap(
                    std::ptr::null(),
                    len,
                    1, // PROT_READ
                    2, // MAP_PRIVATE
                    fd,
                    0,
                )
            };

            if data == std::ptr::null_mut() {
                panic!("mmap failed");
            }

            Self {
                data: data as *const u8,
                len,
                pos: 0,
            }
        }

        pub fn next<T>(&mut self) -> T
        where
            T: From<u8>
                + Default
                + std::ops::Mul<Output = T>
                + std::ops::Add<Output = T>
                + std::ops::Sub<Output = T>,
        {
            let mut res = T::default();
            let mut ch = self.getchar();
            while is_whitespace(ch) {
                ch = self.getchar();
            }
            while !is_whitespace(ch) {
                res = res * 10.into() + (ch - b'0').into();
                ch = self.getchar();
            }
            res
        }

        #[inline]
        fn getchar(&mut self) -> u8 {
            if self.pos >= self.len {
                return b' ';
            }
            unsafe {
                let ch = *self.data.add(self.pos);
                self.pos += 1;
                ch
            }
        }
    }

    impl Drop for Reader {
        fn drop(&mut self) {
            unsafe {
                c_ffi::munmap(self.data as *const c_void, self.len);
            }
        }
    }

    const fn is_whitespace(ch: u8) -> bool {
        ch == b' ' || ch == b'\n' || ch == b'\r' || ch == b'\t' || ch == 0
    }
}

libc::read 版本(unsafe)

https://loj.ac/s/2179813

其实这个是 OI Wiki 上爆款快读的 Rust 改写版。

Rust
macro_rules! __reader_type {
    ($x:ident) => { __reader_type!($x, $x); };
    ($type:ty, $name:ident) => {
        #[inline] #[must_use] #[allow(dead_code)]
        pub fn $name(&self) -> $type { self.next() }
    };
}
#[macro_export] macro_rules! default_type { () => { i32 }; }
#[macro_export] macro_rules! __fallback_to_default_type {
    () => { default_type!() }; ($x:ty) => { $x };
}
#[macro_export] macro_rules! read {
    ($reader:ident, { $($name:ident $(: $vartype:ty)? $(,)?)* }) => {
        $(let $name = {$reader.next::<__fallback_to_default_type!($($vartype)?)>()};)*
    };
}
#[macro_export] macro_rules! init_reader {
    () => {{ $crate::reader::Reader::new() }};
}

mod reader {
    use std::ffi::c_void;
    use std::os::unix::io::AsRawFd;

    mod c_ffi {
        use std::ffi::c_void;

        extern "C" {
            pub fn read(fd: i32, buf: *const c_void, count: usize) -> isize;
        }
    }

    const MAXSIZE: usize = 1 << 20;
    static mut BUF: [u8; MAXSIZE] = [0; MAXSIZE];

    #[allow(non_upper_case_globals)]
    static mut stdin_fd: i32 = 0;
    static mut P1: *mut u8 = std::ptr::null_mut();
    static mut P2: *mut u8 = std::ptr::null_mut();

    use std::ops::{Add, Mul, Sub};

    pub struct Reader;

    impl Reader {
        #[inline]
        #[must_use]
        pub fn new() -> Reader {
            unsafe { stdin_fd = std::io::stdin().as_raw_fd(); }
            Reader
        }

        #[inline]
        pub fn next<T>(&self) -> T
        where
            T: From<u8>
            + Default
            + Mul<Output = T>
            + Add<Output = T>
            + Sub<Output = T>,
        {
            let mut res = T::default();
            let mut ch = getchar();
            while is_whitespace(ch) { ch = getchar(); }
            while !is_whitespace(ch) {
                res = res * 10.into() + (ch - b'0').into();
                ch = getchar();
            }
            res
        }

        __reader_type!(i32);
        __reader_type!(u32);
        __reader_type!(i64);
        __reader_type!(u64);
        __reader_type!(isize);
        __reader_type!(usize);
        __reader_type!(default_type!(), read);
    }

    const fn is_whitespace(ch: u8) -> bool {
        ch == b' ' || ch == b'\n' || ch == b'\r' || ch == b'\t' || ch == 0
    }

    #[inline]
    fn getchar() -> u8 {
        unsafe { 
            if P1 == P2 {
                let ptr = BUF[..].as_mut_ptr();
                P1 = ptr;
                P2 = ptr.wrapping_add(
                    c_ffi::read(stdin_fd, std::ptr::addr_of!(BUF) as *const c_void, MAXSIZE) as usize
                );
            }
            if P1 == P2 { return b' '; }
            let ch = *P1; P1 = P1.wrapping_add(1);

            ch
        }
    }
}

getchar(_unlocked)? 版本(unsafe)

目前尚不明确是否存在 unlocked 比没有 unlock 快,因为在 LOJ 上跑貌似不相上下。

这个是 C++ 中较为常见的快读的改写版。

Rust
mod reader {
    mod c_ffi {
        use std::os::raw::c_int;
        extern "C" {
            #[cfg(not(target_family = "unix"))]
            pub fn getchar() -> c_int;

            #[cfg(target_family = "unix")]
            pub fn getchar_unlocked() -> c_int;
        }
    }
    #[macro_export]
    macro_rules! default_type { () => { i32 }; }

    use std::ops::{Add, Mul, Sub};

    pub struct Reader;

    macro_rules! __reader_type {
        ($x:ident) => { __reader_type!($x, $x); };
        ($type:ty, $name:ident) => {
            #[inline]
            #[must_use]
            #[allow(dead_code)]
            pub fn $name(&self) -> $type {
                self.next()
            }
        };
    }
    macro_rules! __fallback_to_default_type {
        () => { default_type!() };
        ($x:ty) => { $x };
    }
    macro_rules! read {
        ($reader:ident, { $($name:ident $(: $vartype:ty)? $(,)?)* }) => {
            $(let $name = {
                $reader.next::<__fallback_to_default_type!($($vartype)?)>()
            };)*
        };
    }
    macro_rules! init_reader {
        () => {{ $crate::reader::Reader::new() }};
    }

    impl Reader {
        #[inline]
        #[must_use]
        pub fn new() -> Reader { Reader }

        #[inline]
        pub fn next<T>(&self) -> T
        where
            T: From<u8>
            + Default
            + Mul<Output = T>
            + Add<Output = T>
            + Sub<Output = T>,
        {
            let mut res = T::default();
            let mut ch = getchar();
            while is_whitespace(ch) { ch = getchar(); }
            while !is_whitespace(ch) {
                res = res * 10.into() + (ch - b'0').into();
                ch = getchar();
            }
            res
        }

        __reader_type!(i32);
        __reader_type!(u32);
        __reader_type!(i64);
        __reader_type!(u64);
        __reader_type!(isize);
        __reader_type!(usize);
        __reader_type!(default_type!(), read);
    }

    const fn is_whitespace(ch: u8) -> bool {
        ch == b' ' || ch == b'\n' || ch == b'\r' || ch == b'\t' || ch == 0
    }

    #[inline]
    #[cfg(target_family = "unix")]
    fn getchar() -> u8 {
        (unsafe { c_ffi::getchar_unlocked() }) as u8
    }
    
    #[inline]
    #[cfg(not(target_family = "unix"))]
    fn getchar() -> u8 {
        (unsafe { c_ffi::getchar() }) as u8
    }
}

字符串切分版本(非常安全)

这是非常安全的 Rust 写法。不过一般来说算法竞赛不需要特别内存安全,所以上面几个比较快的读入方法在不读超出 stdin 的内容时还是比较安全了。

但是算法竞赛(一般)不需要内存安全那你为什么要选择 Rust?(小声:因为 Rust 的宏太好用了)

Rust
mod reader {
    use std::{collections::LinkedList, fmt::Debug};

    pub struct Reader(LinkedList<String>);

    #[macro_export]
    macro_rules! default_type {
        () => { /* 这东西有需要的可以改 */ i32 };
    }

    macro_rules! __reader_type {
        ($x:ident) => { __reader_type!($x, $x); };

        ($type:ty, $name:ident) => {
            #[inline]
            #[must_use]
            #[allow(dead_code)]
            pub fn $name(&mut self) -> $type {
                self.next::<$type>()
            }
        };
    }

    #[macro_export]
    macro_rules! __fallback_to_default {
        () => { default_type!() };
        ($x:ty) => { $x };
    }

    #[macro_export]
    macro_rules! read {
        ($reader:ident, { $($name:ident $(: $vartype:ty)? $(,)?)* }) => {
            $(
                let $name = $reader.next::<__fallback_to_default!($($vartype)?)>();
            )*
        };
    }
  
  	#[macro_export]
    macro_rules! read_mut {
        ($reader:ident, { $($name:ident $(: $vartype:ty)? $(,)?)* }) => {
            $(
                let mut $name = {
                    $reader.next::<__fallback_to_default_type!($($vartype)?)>()
                };
            )*
        };
    }

    #[macro_export]
    macro_rules! init_reader {
        () => {{
            &mut $crate::reader::Reader::new(&mut std::io::stdin())
        }};
    }

    impl Reader {
        #[inline]
        pub fn new<R: std::io::Read>(inner: &mut R) -> Reader {
            let mut buf = String::new();
            inner.read_to_string(&mut buf).unwrap();
            Reader(buf.trim().split_whitespace().map(str::to_string).collect())
        }

        #[inline]
        pub fn next<T>(&mut self) -> T
        where
            T: std::str::FromStr,
            <T as std::str::FromStr>::Err: Debug
        {
            self.0
                .pop_front()
                .expect("overflow")
                .as_str()
                .parse::<T>()
                .expect(format!("expected {}", stringify!(T)).as_str())
        }

        __reader_type!(i32);
        __reader_type!(u32);
        __reader_type!(i64);
        __reader_type!(u64);
        __reader_type!(isize);
        __reader_type!(usize);
        __reader_type!(String, string);

        __reader_type!(i32, read);
    }
}

使用方法:

Rust
fn main() {
    let reader = init_reader!();
    read!(reader, {
        n: i32,
        m: String,
        q /*: default_type!() */,
    });
    // 那么这个地方已经有 n: i32, m: String, q: default_type!() 三个变量的定义了

    for _ in 0..n {
        read!(reader, { u, v });
        let w = reader.i32();
        let it_is_more_complex = reader.next::<i32>();
        /* Do something */
    }
}

综上所述,在保留安全性的同时会牺牲(相当一部分的)性能。

原文
存档评论1 条抓取于