在开发程序的时候常常会需要处理文件路径或是 URL 网址的串接问题,如果字符串是从用户端输入的,由于不同用户的习惯不同,可能有人习惯在文件目录路径或是网址前面后面多加斜线,也可能有人习惯不加。如果程序是设计成要用某个用户输入的字符串当作前缀,去串接其它的字符串来组成文件路径或是网址的话,那么前缀是不是以斜线结尾的影响就很大了。例如用户输入了 path/to/folder/ 这样的文件目录路径,然后程序要串在其后的字符串为 /file,串起来之后的路径就变成 path/to/folder//file,这就可能会是一个不合法的路径。

因为用户习惯不同,所以我们必须要做其它的处理。例如以下程序,可以去除输入的字符串之最后面的斜线,但是如果它原本就只是一个斜线的话就不再去除:

let length = s.len();

if length > 1 && s.ends_with('/') {
    return &s[..length - 1];
} else {
    return s;
}

程序非常简单,但也是因为如此,如果每次都要在新的程序项目中,写这样类似或是一样的代码来处理斜线,那真的很无聊。

Slash Formatter

「Slash Formatter」是笔者开发的套件,提供多种函数来处理斜线和反斜线的字符串串接。

Crates.io

Cargo.toml

slash-formatter = "*"

使用方法

slash_formatter 这个 crate,提供了数十种的函数,主要有 add_start_slash、add_end_slash、delete_start_slash、delete_end_slash、concat_with_slash 这五大类,且每一类皆有 slash(斜线)、backslash(反斜线)、file_separator(根据编译目标的操作系统来决定用斜线或是反斜线)、file_separator_build(根据项目在哪个操作系统上编译来决定用斜线或是反斜线)的分别。其中每个函数都有不额外配置空间的「in-place」版本,例如 add_start_slash_in_place,所以每一类都有 8 个函数,五大类合起来共 40 个函数。

举例来说,如果要以斜线串接两个字符串,程序如下:

assert_eq!("path/to", slash_formatter::concat_with_slash("path", "to/"));

或

let mut s = String::from("path");

slash_formatter::concat_with_slash_in_place(&mut s, "to/");

assert_eq!("path/to", s);

如果要以反斜线串接两个字符串,程序如下:

assert_eq!(r"path\to", slash_formatter::concat_with_backslash("path", r"to\"));

或

let mut s = String::from("path");

slash_formatter::concat_with_backslash_in_place(&mut s, "to\\");

assert_eq!("path\\to", s);

如果要根据运行的操作系统环境来决定要使用斜线还是反斜线来串接两个字符串的话,程序如下:

assert_eq!(concat!("path", slash_formatter::file_separator!(), "to"), slash_formatter::concat_with_file_separator("path", concat!("to", slash_formatter::file_separator!())));

或

let mut s = String::from("path");

slash_formatter::concat_with_file_separator_in_place(&mut s, concat!("to", slash_formatter::file_separator!()));

assert_eq!(concat!("path", slash_formatter::file_separator!(), "to"), s);

其中的 file_separator!() 宏会产生编译目标的操作系统所使用的分隔符号(斜线或反斜线),所以以上的断言在任何操作系统上都会成立。

当然,如果您只是纯粹想串接出能用在目前程序运行的操作系统上的文件路径,可以直接使用 Rust 标准函数库提供的 std::path 模块来处理路径串接问题。

宏用法

concat_with_* 函数都有对应的宏,宏名称为函数名称再去除掉前缀 concat_with_,支持任意参数数量,换句话说可以将传入的任意数量的参数串接起来!

用法如下:

assert_eq!("path/to/file", slash_formatter::slash!("path", "to/", "/file/"));

let s = String::from("path");

let s = slash_formatter::slash!(s, "to/", "/file/");

assert_eq!("path/to/file", s);

或

let mut s = String::from("path");

slash_formatter::slash_in_place!(&mut s, "to/", "/file/");

assert_eq!("path/to/file", s);

另外还有以 concat_with_ 为名称前缀的宏(例如:concat_with_slash),可以将任意数量的定数在编译阶段时串接为 &'static str。是使用 concat_with 这个 crate 提供的 concat_impl 宏来实作的。

用法如下:

assert_eq!("test\\10\\b\\true", slash_formatter::concat_with_backslash!("test", 10, 'b', true));

concat_with_file_separator_build 宏还有一个变体,那就是 concat_with_file_separator_debug_release 宏。在 Debug 模式下编译,这个宏等同于 concat_with_file_separator;而在 Release 模式下编译,这个宏等同于 concat_with_file_separator_build 宏。