Java 编程语言的 java.util.Scanner 是一个非常方便的类别,可以用来读取任意的字符串或是串流中的文字数据,它也是刚开始学习 Java 的人通常会第一个使用到的 java.util 套件中的类别。而 Rust 的标准函数库中并没有提供像是 Java 的 Scanner 这样方便好用的模块,大多就是用已经有实作好 Read 特性的结构实体所提供的 read、read_to_end、read_to_string 等低级方法,而要稍微高级一点的话就是用 BufRead 特性所提供的 read_line 方法。Java 的 Scanner 之所以如此方便的原因主要就是它提供了略过来源数据中空白字符的功能,并且可以直接以调用 next 或是 nextXXX 方法的方式来得到我们预期会取得的数据,我们也不必自行再另外去做字符串数据的解析。
为了在 Rust 编程语言中也能享有 Java 编程语言的 Scanner 的益处,笔者决定用 Rust 编程语言实作出 Scanner 的主要功能。不考虑把 Scanner 大部份功能实作出来的原因是,Rust 编程语言是比较注重性能和内存使用量的相对低级的语言,而 Java 编程语言的 Scanner 功能实在太多了,有一大半笔者从来没用到过,像是不同进制的数值转换、或是读取自订的正则表达式样本的数据等,就连在数值转换上,Java 的 Scanner 也还支持「123,456」这种格式(有用逗号分隔位数)的字符串,这类特殊格式笔者觉得还是要由程序员自行在使用 Scanner 读取字符串后再另外处理会比较好一点,不然不需使用到的话会消耗额外的运算资源。
Scanner
「Scanner」是笔者用 Rust 编程语言撰写的类似 Java 的 Scanner 的同名套件(不过因为 scanner 这个名称已经被功能完全不同的 crate 占用,只好将 crate 命名为 scanner-rust),可以用来读取字符串或是串流中的 ASCII 或是 UTF-8 数据。实作了 next、next_line、next_u8、next_u16、next_u32、next_u64、next_u128、next_usize、next_i8、next_i16、next_i32、next_i64、next_i128、next_isize、next_f32、next_f64,遵守 Java 的 Scanner 略过空白字符的策略,且另外还提供 Java 的 Scanner 所没有的 next_char、skip_whitespaces、drop_next 和 drop_next_line 方法。
Crates.io
Cargo.toml
使用方法
使用方法很简单,参考以下范例即可:
use std::io::{self, Write};
use scanner_rust::ScannerAscii;
print!("Please input two integers, a and b: ");
io::stdout().flush().unwrap();
let mut sc = ScannerAscii::new(io::stdin());
let a = {
loop {
match sc.next_isize() {
Ok(i) => break i.unwrap_or(0),
Err(_) => {
print!("Re-input a and b: ");
io::stdout().flush().unwrap();
}
}
}
};
let b = {
loop {
match sc.next_isize() {
Ok(i) => break i.unwrap_or(0),
Err(_) => {
print!("Re-input b: ");
io::stdout().flush().unwrap();
}
}
}
};
println!("{} + {} = {}", a, b, a + b);
以上范例使用的是 ScannerAscii 结构体,适合在确定输入的串流数据是 ASCII 编码时使用,性能会比较好。如果输入的数据有可能含有 ASCII 以外的 UTF-8 字符,就要改用 Scanner 结构体。
预设的缓冲空间大小为 256 个字节。若您想要改变缓冲空间大小,可以使用 new2 或是 scan_path2 关联函数并且明确地定义要使用的长度(透过泛型),来产生出上面介绍的结构体的实体。
例如,要将缓冲空间大小改为 64 个字节的话,程序可以这样写:
use scanner_rust::generic_array::typenum::U64;
use scanner_rust::Scanner;
let mut sc: Scanner<_, U64> = Scanner::scan_path2("Cargo.toml").unwrap();
此外,如果要解析的数据已存在于内存中,可以使用 ScannerStr、ScannerU8Slice 或是 ScannerU8SliceAscii 结构体,避免在内存中拷贝数据。
use std::io::{self, Write};
use scanner_rust::ScannerU8Slice;
let mut sc = ScannerU8Slice::new(" 123 456.7 \t\r\n\n c中文字\n\tHello world!".as_bytes());
assert_eq!(Some(123), sc.next_u8().unwrap());
assert_eq!(Some(456.7), sc.next_f64().unwrap());
assert_eq!(Some(' '), sc.next_char().unwrap());
assert_eq!(Some(' '), sc.next_char().unwrap());
assert_eq!(true, sc.skip_whitespaces().unwrap());
assert_eq!(Some('c'), sc.next_char().unwrap());
assert_eq!(Some("中文字".as_bytes()), sc.next_line().unwrap());
assert_eq!(Some("\tHello world!".as_bytes()), sc.next_line().unwrap());
assert_eq!(None, sc.next_line().unwrap());
