5
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Rust】UTF-8 BOMについて

Posted at

はじめに

RustでのUTF-8 BOMについて調べました。

ファイル読込

以下の様なUTF-8 BOM形式のテキストファイルを開くとします。

test.txt
Hello

このファイルを開くと先頭に奇妙な文字が付いています。

// test.txtを読み込む
let content: String = fs::read_to_string("test.txt")?;
// charのベクタに変換
let chars: Vec<char> = content.chars().collect();
println!("{:?}", chars);
実行結果
['\u{feff}', 'H', 'e', 'l', 'l', 'o']

\u{feff}

\u{feff}はUTF-8 BOM(ファイルの先頭にある0xEF 0xBB 0xBFの3バイト)をchar形式に変換した文字になります。
この文字を整数型に変換すると65279(16進数で0xFEFF)になり
バイト配列に変換すると、上記の3バイトになります。

let c = '\u{feff}';
c as u32; // 65279
c.to_string().as_bytes(); // [0xEF, 0xBB, 0xBF]

UTF-8 BOMを除く関数

「文字列の先頭1文字がBOMならそれを除く」という処理はPeekableを使えば簡単に実装できます。
Peekableとはイテレータの一種ですが、先に進めずに現在の値を確認することができます。
UTF-8 BOMを除く関数は以下の様になります。

fn remove_utf8_bom(s: String) -> String {
    let mut chars = s.chars().peekable();
    if let Some('\u{feff}') = chars.peek() {
        chars.next();
    }
    chars.collect()
}

参考文献

5
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?