# std::ascii

只看 ASCII 範圍（0–127）的字元判斷、大小寫轉換與跳脫工具，適合處理協定、檔頭、指令等純英文資料。

## 這個模組做什麼

ASCII 是最早的英文字元集，只有 128 個字元：英文字母、數字、標點與控制字元。很多資料格式（HTTP 標頭、檔案副檔名、十六進位字串、指令關鍵字）只用到 ASCII，這時不需要完整的 Unicode 規則。

ASCII 專用方法的特點：

- 只認 ASCII，非 ASCII 字元（例如中文）一律原樣保留、判斷結果為 `false`
- 不會配置或改變字串長度，速度快，結果可預期
- 同一組方法分別出現在 `u8`、`char`、`str`、`[u8]` 上

| 需求 | Unicode 版本 | ASCII 版本 |
| --- | --- | --- |
| 轉大寫 | `to_uppercase()`（見 [std::char](/pkg-char)） | `to_ascii_uppercase()` |
| 判斷數字 | `is_numeric()` | `is_ascii_digit()` |
| 忽略大小寫比較 | 無直接方法 | `eq_ignore_ascii_case()` |

`std::ascii` 模組本身只放了 `escape_default` 函式與它回傳的 `EscapeDefault` 型別；其他方法直接寫在各型別上。

## 匯入

`u8`、`char`、`str` 上的 ASCII 方法不需要 `use`。只有模組函式需要：

```rust
use std::ascii;
use std::ascii::escape_default;
```

## 常用 API

### is_ascii：是不是純 ASCII

`is_ascii()` 檢查值是否全部落在 ASCII 範圍。用在 `str` 或 `[u8]` 上會檢查每個位元組，常用來決定能不能走較簡單的處理路徑。

簽名：
```rust
pub const fn is_ascii(&self) -> bool
```

範例：
```rust
fn main() {
    println!("{}", "hello.txt".is_ascii());
    println!("{}", "報告.txt".is_ascii());
    println!("{}", 'Z'.is_ascii());
    println!("{}", 200u8.is_ascii());
    let raw: &[u8] = b"GET /index.html";
    println!("{}", raw.is_ascii());
}
```

輸出：
```text
true
false
true
false
true
```

### is_ascii_digit 與其他分類判斷

這組方法判斷 ASCII 中的特定類別：`is_ascii_digit`（0–9）、`is_ascii_alphabetic`、`is_ascii_alphanumeric`、`is_ascii_hexdigit`、`is_ascii_whitespace`、`is_ascii_punctuation`、`is_ascii_uppercase` 等。全形數字或中文字都會得到 `false`。

簽名：
```rust
pub const fn is_ascii_digit(&self) -> bool
pub const fn is_ascii_alphabetic(&self) -> bool
pub const fn is_ascii_hexdigit(&self) -> bool
pub const fn is_ascii_punctuation(&self) -> bool
```

範例：
```rust
fn is_valid_hex(s: &str) -> bool {
    !s.is_empty() && s.chars().all(|c| c.is_ascii_hexdigit())
}

fn main() {
    for c in ['7', '３', 'a', '中', '#'] {
        println!(
            "{}: digit={} alpha={} punct={}",
            c,
            c.is_ascii_digit(),
            c.is_ascii_alphabetic(),
            c.is_ascii_punctuation()
        );
    }
    println!("ff00aa -> {}", is_valid_hex("ff00aa"));
    println!("ffzz -> {}", is_valid_hex("ffzz"));
}
```

輸出：
```text
7: digit=true alpha=false punct=false
３: digit=false alpha=false punct=false
a: digit=false alpha=true punct=false
中: digit=false alpha=false punct=false
#: digit=false alpha=false punct=true
ff00aa -> true
ffzz -> false
```

### eq_ignore_ascii_case：忽略大小寫比較

比較兩個值時忽略 ASCII 字母大小寫，不需要先轉成新字串，因此不會配置記憶體。適合比對 HTTP 標頭名稱、副檔名、指令。

簽名：
```rust
pub fn eq_ignore_ascii_case(&self, other: &str) -> bool
pub const fn eq_ignore_ascii_case(&self, other: &u8) -> bool
```

範例：
```rust
fn is_image(name: &str) -> bool {
    match name.rsplit_once('.') {
        Some((_, ext)) => ["png", "jpg", "gif"].iter().any(|e| ext.eq_ignore_ascii_case(e)),
        None => false,
    }
}

fn main() {
    println!("{}", "Content-Type".eq_ignore_ascii_case("content-type"));
    println!("{}", is_image("Photo.JPG"));
    println!("{}", is_image("note.txt"));
    println!("{}", b'a'.eq_ignore_ascii_case(&b'A'));
    println!("{}", "Ä".eq_ignore_ascii_case("ä"));
}
```

輸出：
```text
true
true
false
true
false
```

注意：最後一行是 `false`，因為 `Ä` 不是 ASCII，不在忽略範圍內。

### to_ascii_uppercase 與 to_ascii_lowercase：轉換大小寫

回傳轉換後的新值：在 `str` 上回傳新的 `String`，在 `char`、`u8` 上回傳單一值。只改 ASCII 字母，其他字元原樣保留，所以字串長度不變。

簽名：
```rust
pub fn to_ascii_uppercase(&self) -> String
pub fn to_ascii_lowercase(&self) -> String
pub const fn to_ascii_uppercase(&self) -> char
```

範例：
```rust
fn main() {
    let cmd = "select * from 使用者";
    let upper = cmd.to_ascii_uppercase();
    println!("{}", upper);
    println!("長度相同：{}", cmd.len() == upper.len());
    println!("{}", "HeLLo".to_ascii_lowercase());
    println!("{}", 'q'.to_ascii_uppercase());
    println!("{}", b'x'.to_ascii_uppercase() as char);
}
```

輸出：
```text
SELECT * FROM 使用者
長度相同：true
hello
Q
X
```

### make_ascii_uppercase：原地轉換

`make_ascii_uppercase`／`make_ascii_lowercase` 直接修改原本的資料，不產生新字串。需要 `&mut`，適合處理大量資料時省下配置。

簽名：
```rust
pub fn make_ascii_uppercase(&mut self)
pub fn make_ascii_lowercase(&mut self)
```

範例：
```rust
fn main() {
    let mut s = String::from("Hello, 世界");
    s.make_ascii_uppercase();
    println!("{}", s);

    let mut bytes = *b"ABC-def";
    bytes.make_ascii_lowercase();
    println!("{}", String::from_utf8_lossy(&bytes));

    let mut c = 'k';
    c.make_ascii_uppercase();
    println!("{}", c);
}
```

輸出：
```text
HELLO, 世界
abc-def
K
```

### escape_default：把位元組跳脫成可讀文字

`std::ascii::escape_default(b)` 把一個位元組轉成可列印的 ASCII 表示：一般字元保持原樣，換行、Tab、引號、反斜線用反斜線跳脫，其他位元組用 `\xNN` 表示。適合在除錯時印出二進位資料。`u8` 與 `[u8]` 上的 `escape_ascii()` 是同樣規則的方法版。

簽名：
```rust
pub fn escape_default(c: u8) -> EscapeDefault
pub fn escape_ascii(self) -> EscapeDefault
```

範例：
```rust
use std::ascii;

fn main() {
    let data = b"OK\t\"done\"\n\x00\xff";
    let escaped: String = data.iter().flat_map(|&b| ascii::escape_default(b)).map(char::from).collect();
    println!("{}", escaped);
    println!("{}", data.escape_ascii());
    println!("{}", "中".as_bytes().escape_ascii());
}
```

輸出：
```text
OK\t\"done\"\n\x00\xff
OK\t\"done\"\n\x00\xff
\xe4\xb8\xad
```

## 重點整理

- ASCII 方法只處理 0–127 範圍，其他字元原樣保留或判斷為 `false`
- 同一組方法出現在 `u8`、`char`、`str`、`[u8]` 上，不需要 `use`
- 比對副檔名、標頭等英文關鍵字用 `eq_ignore_ascii_case`，不必先轉大小寫
- `to_ascii_*` 產生新值，`make_ascii_*` 原地修改
- 除錯印二進位資料用 `escape_ascii()` 或 `ascii::escape_default`
