Sitemap

【知其然,更知其所以然】toyDB:Encoding 源碼解析

29 min readOct 22, 2025

--

模塊結構概覽

src/encoding/mod.rs 定義了整個編碼模塊的結構,兩個子模塊各司其職:

- keycode:保序的鍵編碼

- bincode:高效的值編碼

Value trait:值的統一接口

/// Adds automatic Bincode encode/decode methods to value types. These are used
/// for values in key/value storage engines, and also for e.g. network protocol
/// messages and other values.
pub trait Value: Serialize + DeserializeOwned {
/// Decodes a value from a byte slice using Bincode.
fn decode(bytes: &[u8]) -> Result<Self> {
bincode::deserialize(bytes)
}

/// Decodes a value from a reader using Bincode.
fn decode_from<R: Read>(reader: R) -> Result<Self> {
bincode::deserialize_from(reader)
}

/// Decodes a value from a reader using Bincode, or returns None if the
/// reader is closed.
fn maybe_decode_from<R: Read>(reader: R) -> Result<Option<Self>> {
bincode::maybe_deserialize_from(reader)
}

/// Encodes a value to a byte vector using Bincode.
fn encode(&self) -> Vec<u8> {
bincode::serialize(self)
}

/// Encodes a value into a writer using Bincode.
fn encode_into<W: Write>(&self, writer: W) -> Result<()> {
bincode::serialize_into(writer, self)
}
}

設計要點:

1.統一接口:所有值類型只需實現 Serialize + DeserializeOwned,自動獲得編解碼方法

2.內部調用 bincode:保證所有值使用高效編碼

3.DeserializeOwned 而非 Deserialize<'de>:

  • 原因:Value 用於網絡協議和流式讀取,數據來自臨時緩衝區
  • decode_from(reader: R) 擁有 reader,讀取後 reader 被銷毀,無法返回借用其內部數據的結果
  • 所以解碼結果必須擁有所有數據,不能依賴任何借用

4.流式操作:提供 decode_from 和 encode_into,支持從 Read/Write 流式處理

  • 流式處理:逐步讀取/寫入數據,不需要一次性加載整個數據到內存
  • 適合網絡通信(從 TCP socket 直接讀取)和大文件處理
  • 例如:Value::decode_from(tcp_stream) 直接從網絡讀取,而非先緩衝再解碼

5.容錯解碼:maybe_decode_from 處理連接關閉的情況,返回 Option<T>

泛型實現:自動擴展支持

/// Blanket implementations for various types wrapping a value type.
impl<V: Value> Value for Option<V> {}
impl<V: Value> Value for Result<V> {}
impl<V: Value> Value for Vec<V> {}
impl<V1: Value, V2: Value> Value for (V1, V2) {}
impl<V: Value + Eq + Hash> Value for HashSet<V> {}
impl<V: Value + Eq + Ord + Hash> Value for BTreeSet<V> {}

泛型魔法:

只要 T 實現了 Value,這些包裝類型自動實現 Value。

具體例子:

假設你有一個結構體:

#[derive(Serialize, Deserialize)]
struct User {
id: u64,
name: String,
}

impl Value for User {}

現在,因為有了上面的泛型實現,下面這些類型自動實現了 Value,不需要再寫代碼:

// 1. Option<User> 自動實現 Value
let user: Option<User> = Some(User { id: 1, name: "Alice".into() });
let bytes = user.encode(); // ✓ 可以直接調用
let decoded: Option<User> = Value::decode(&bytes)?; // ✓ 可以直接解碼

// 2. Vec<User> 自動實現 Value
let users: Vec<User> = vec![
User { id: 1, name: "Alice".into() },
User { id: 2, name: "Bob".into() },
];
let bytes = users.encode(); // ✓ 可以直接調用
let decoded: Vec<User> = Value::decode(&bytes)?; // ✓ 可以直接解碼

// 3. (User, String) 自動實現 Value
let pair: (User, String) = (User { id: 1, name: "Alice".into() }, "metadata".into());
let bytes = pair.encode(); // ✓ 可以直接調用
let decoded: (User, String) = Value::decode(&bytes)?; // ✓ 可以直接解碼

// 4. 甚至嵌套也可以
let complex: Option<Vec<User>> = Some(vec![User { id: 1, name: "Alice".into() }]);
let bytes = complex.encode(); // ✓ 可以直接調用
let decoded: Option<Vec<User>> = Value::decode(&bytes)?; // ✓ 可以直接解碼

如果沒有這些泛型實現,你需要手動為每個組合寫代碼:

// 如果沒有泛型實現,需要手動寫這些(非常繁瑣):
impl Value for Option<User> {}
impl Value for Vec<User> {}
impl Value for (User, String) {}
impl Value for Option<Vec<User>> {}
// ... 無窮無盡的組合

這就是 blanket implementation 的威力:一次性為所有符合條件的類型實現 trait,極大減少樣板代碼。

Bincode:高效值編碼

src/encoding/bincode.rs 是對 bincode crate 的薄封裝。

配置與設計理念

/// Use the standard Bincode configuration.
const CONFIG: bincode::config::Configuration = bincode::config::standard();

standard() 配置:

  • 小端序(little-endian):符合大多數現代 CPU 架構
  • 固定大小整數:不使用 varint 壓縮
  • varint (variable-length integer):變長整數編碼,小數字用少字節,大數字用多字節
  • Bincode 選擇固定大小:u64 永遠 8 字節,無論值大小
  • 優點:編碼/解碼更快;缺點:小數字佔用較多空間

核心函數實現

serialize 函數:序列化到向量

/// Serializes a value using Bincode.
pub fn serialize<T: Serialize>(value: &T) -> Vec<u8> {
// Panic on failure, as this is a problem with the data structure.
bincode::serde::encode_to_vec(value, CONFIG).expect("value must be serializable")
}

設計決策:

  • Panic 而非 Result:序列化失敗被視為程序錯誤(數據結構定義問題)
  • expect 訊息:明確說明失敗原因

deserialize 函數:從字節切片反序列化

/// Deserializes a value using Bincode.
pub fn deserialize<'de, T: Deserialize<'de>>(bytes: &'de [u8]) -> Result<T> {
Ok(bincode::serde::borrow_decode_from_slice(bytes, CONFIG)?.0)
}

實現細節:

  • borrow_decode_from_slice:零拷貝反序列化,返回 (T, usize)
  • .0:只取值,忽略已讀字節數
  • 返回 Result:反序列化可能因數據損壞而失敗

serialize_into / deserialize_from 函數:流式操作

/// Serializes a value to a writer using Bincode.
pub fn serialize_into<W: Write, T: Serialize>(mut writer: W, value: &T) -> Result<()> {
bincode::serde::encode_into_std_write(value, &mut writer, CONFIG)?;
Ok(())
}
/// Deserializes a value from a reader using Bincode.
pub fn deserialize_from<R: Read, T: DeserializeOwned>(mut reader: R) -> Result<T> {
Ok(bincode::serde::decode_from_std_read(&mut reader, CONFIG)?)
}

流式操作的優勢:

  • 不需要一次性加載整個數據到內存
  • 適合網絡協議(從 TCP socket 直接讀取)
  • 適合大文件處理

maybe_deserialize_from 函數:容錯反序列化

/// Deserializes a value from a reader using Bincode, or returns None if the
/// reader is closed.
pub fn maybe_deserialize_from<R: Read, T: DeserializeOwned>(mut reader: R) -> Result<Option<T>> {
match bincode::serde::decode_from_std_read(&mut reader, CONFIG) {
Ok(t) => Ok(Some(t)),
Err(bincode::error::DecodeError::Io { inner, .. })
if inner.kind() == std::io::ErrorKind::UnexpectedEof
|| inner.kind() == std::io::ErrorKind::ConnectionReset =>
{
Ok(None)
}
Err(err) => Err(Error::from(err)),
}
}

錯誤處理邏輯:

  1. 成功:返回 Ok(Some(value))
  2. 連接關閉:UnexpectedEof 或 ConnectionReset → 返回 Ok(None)
  3. 其他錯誤:返回 Err

這個函數專門用於網絡通信:當客戶端斷開連接時,不視為錯誤,而是正常返回 None。

Bincode 為何不適合鍵編碼

讓我們通過實驗理解為什麼不能用 Bincode 編碼鍵。這些問題正是我們需要引入 Keycode 的原因。

實驗 1:小端序破壞順序

use toydb::encoding::bincode;

let val1: u64 = 1;
let val2: u64 = 256;
let bytes1 = bincode::serialize(&val1);
let bytes2 = bincode::serialize(&val2);
println!("{:?}", bytes1); // [01, 00, 00, 00, 00, 00, 00, 00]
println!("{:?}", bytes2); // [00, 01, 00, 00, 00, 00, 00, 00]
// 字節序比較:bytes1 > bytes2
// 但實際:1 < 256 X 順序錯誤!

原因:小端序將低位字節放在前面,bytes1[0] = 0x01 > bytes2[0] = 0x00。

實驗 2:變長編碼破壞順序

let s1 = "a";
let s2 = "aa";
let s3 = "b";

let b1 = bincode::serialize(&s1); // [1, 0, 0, 0, 0, 0, 0, 0, 'a'] 長度 + 內容
let b2 = bincode::serialize(&s2); // [2, 0, 0, 0, 0, 0, 0, 0, 'a', 'a']
let b3 = bincode::serialize(&s3); // [1, 0, 0, 0, 0, 0, 0, 0, 'b']
// 字典序:'a' < 'aa' < 'b'
// 字節比較:b1 < b2 ✓,但 b2 > b3 X (應該 'aa' < 'b')
// 問題:長度前綴 [2...] > [1...]

實驗 3:符號位破壞負數順序

let n1: i64 = -1;
let n2: i64 = 0;
let n3: i64 = 1;

let b1 = bincode::serialize(&n1); // [ff, ff, ff, ff, ff, ff, ff, ff]
let b2 = bincode::serialize(&n2); // [00, 00, 00, 00, 00, 00, 00, 00]
let b3 = bincode::serialize(&n3); // [01, 00, 00, 00, 00, 00, 00, 00]
// 字節比較:b1 > b3 > b2
// 結果:-1 > 1 > 0 X 完全錯誤!

結論:Bincode 的設計目標是高效序列化,完全不考慮字典序。對於 key/value 存儲引擎來說,我們需要能夠根據鍵的順序進行範圍查詢和前綴掃描,這就需要一種能夠保持字典序的編碼方式。這正是 Keycode 存在的理由。

Key trait:鍵的統一接口

/// Adds automatic Keycode encode/decode methods to key enums. These are used
/// as keys in the key/value store.
pub trait Key<'de>: Serialize + Deserialize<'de> {
/// Decodes a key from a byte slice using Keycode.
fn decode(bytes: &'de [u8]) -> Result<Self> {
keycode::deserialize(bytes)
}

/// Encodes a key to a byte vector using Keycode.
///
/// In the common case, the encoded key is borrowed for a storage engine
/// call and then thrown away. We could avoid a bunch of allocations by
/// taking a reusable byte vector to encode into and return a reference to
/// it, but we keep it simple.
fn encode(&self) -> Vec<u8> {
keycode::serialize(self)
}
}

設計要點:

  1. 統一接口:所有鍵類型只需實現 Serialize + Deserialize,自動獲得 encode/decode 方法
  2. 內部調用 keycode:保證所有鍵都使用保序編碼
  3. 與 Value trait 的差異:
  • Key trait 有生命週期參數 'de,允許零拷貝反序列化
  • 使用 Deserialize<'de> 而非 DeserializeOwned
  • 原因:鍵通常從存儲引擎的內存映射文件或持久化緩衝區讀取,這些數據生命週期足夠長

註釋解讀:

/// In the common case, the encoded key is borrowed for a storage engine
/// call and then thrown away. We could avoid a bunch of allocations by
/// taking a reusable byte vector to encode into and return a reference to
/// it, but we keep it simple.

這段註釋說明了性能優化的可能性:可以傳入可重用的 Vec<u8> 來避免分配,但為了簡潔性選擇每次分配新的向量。這是 toyDB 的設計哲學:簡潔性優先於性能。

Keycode:保序鍵編碼

src/encoding/keycode.rs 是 toyDB 自己實現的保序編碼系統。

設計目標與實現策略

//! Keycode is a lexicographical order-preserving binary encoding for use with
//! keys in key/value stores. It is designed for simplicity, not efficiency
//! (i.e. it does not use varints or other compression methods).

核心設計原則:

  1. 字典序保持:a < b ⇔ encode(a) < encode(b)(字節序比較)
  2. 簡潔性優先:不使用 varint 壓縮,固定長度編碼
  3. 支持範圍掃描:前綴掃描、範圍查詢的基礎

核心函數實現

serialize 函數:序列化鍵

/// Serializes a key to a binary Keycode representation.
pub fn serialize<T: Serialize>(key: &T) -> Vec<u8> {
let mut serializer = Serializer { output: Vec::new() };
// Panic on failure, as this is a problem with the data structure.
key.serialize(&mut serializer).expect("key must be serializable");
serializer.output
}

實現模式:

  1. 創建 Serializer 結構(包含輸出緩衝區)
  2. 調用 key.serialize(&mut serializer)(Serde 機制)
  3. 返回序列化結果

deserialize 函數:反序列化鍵

/// Deserializes a key from a binary Keycode representation.
pub fn deserialize<'a, T: Deserialize<'a>>(input: &'a [u8]) -> Result<T> {
let mut deserializer = Deserializer::from_bytes(input);
let t = T::deserialize(&mut deserializer)?;
if !deserializer.input.is_empty() {
return errdata!(
"unexpected trailing bytes {:x?} at end of key {input:x?}",
deserializer.input,
);
}
Ok(t)
}

代碼詳解

Get Stan Hsu’s stories in your inbox

Join Medium for free to get updates from this writer.

函數簽名

pub fn deserialize<'a, T: Deserialize<'a>>(input: &'a [u8]) -> Result<T>
  • 'a:生命週期參數,允許返回的 T 借用 input 中的數據(零拷貝)
  • T: Deserialize<'a>:目標類型必須實現 Deserialize trait
  • input: &'a [u8]:待解碼的字節切片
  • Result<T>:成功返回解碼的值,失敗返回錯誤

步驟 1:創建 Deserializer

let mut deserializer = Deserializer::from_bytes(input);

創建一個 Deserializer 對象來包裝輸入:

// Deserializer 結構體(簡化)
struct Deserializer<'de> {
input: &'de [u8], // 指向剩餘未解析的字節
}

impl<'de> Deserializer<'de> {
fn from_bytes(input: &'de [u8]) -> Self {
Self { input }
}
}
  • input 初始指向整個字節切片
  • 隨著解析進行,input 會逐步向後移動(消耗字節)

步驟 2:調用類型的 deserialize 方法

let t = T::deserialize(&mut deserializer)?;

這是關鍵的一步!

語法解析:

  • T::deserialize:關聯函數調用(不是實例方法)
  • 等價於:<T as Deserialize>::deserialize(&mut deserializer)
  • 由 Serde 透過 #[derive(Deserialize)] 自動生成

實際發生什麼:

假設 T = Key enum,Serde 生成的代碼類似:

impl<'de> Deserialize<'de> for Key<'de> {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
// Serde 根據類型調用對應的 deserialize_* 方法
deserializer.deserialize_enum(
"Key",
&["NextVersion", "TxnActive", ...],
KeyVisitor,
)
}
}

Serde 的調用鏈:

T::deserialize(&mut deserializer)
↓
deserializer.deserialize_enum(...) // 根據 T 的類型選擇方法
↓
KeyVisitor::visit_enum(...) // Visitor 模式構造最終值
↓
返回 Key::TxnActive(5)

步驟 3:檢查剩餘字節

if !deserializer.input.is_empty() {
return errdata!(
"unexpected trailing bytes {:x?} at end of key {input:x?}",
deserializer.input,
);
}

為什麼需要這個檢查:

  • 確保所有字節都被消耗完畢
  • 如果還有剩餘,說明輸入數據格式錯誤或類型不匹配

錯誤範例:

// Key::NextVersion 的編碼只需要 [0x00, 0x00]
// 但輸入包含額外的垃圾字節
let bad_input = [0x00, 0x00, 0xFF, 0xFF];
^^^^^^^^ 多餘的字節

let result: Result<Key> = deserialize(&bad_input);
// 錯誤:unexpected trailing bytes [ff, ff] at end of key [00, 00, ff, ff]

步驟 4:返回結果

Ok(t)

所有檢查通過後,返回解碼的值。

Serializer/Deserializer 實現

Keycode 完全按照 Serde 框架規範實現 serde::Serializer 和 serde::Deserializer trait。 Serde 定義了統一的序列化介面,讓不同格式(JSON、Bincode、Keycode)能用相同方式處理任意 Rust 類型。

工作原理:

// 序列化流程
keycode::serialize(value)
→ Serde 根據類型調用對應的 serialize_* 方法
→ Keycode 按保序規則編碼輸出

// 反序列化流程
keycode::deserialize(bytes)
→ Serde 根據目標類型調用對應的 deserialize_* 方法
→ Keycode 按規則解析字節恢復原值

字節切片編碼/解碼:最複雜案例

字節切片(&[u8]、String)是 Keycode 中最複雜的類型,原因:

  1. 長度可變:無法預先知道佔用多少字節
  2. 需要終止符:標記字符串結束位置
  3. 終止符衝突:數據本身可能包含終止符字節,需要轉義
  4. 保持字典序:編碼後字節序必須與原始字典序一致

編碼實現

// Strings are encoded like bytes.
fn serialize_str(self, v: &str) -> Result<()> {
self.serialize_bytes(v.as_bytes())
}

// Byte slices are terminated by 0x0000, escaping 0x00 as 0x00ff. This
// ensures that we can detect the end, and that for two overlapping slices,
// the shorter one orders before the longer one.
//
// We can't use e.g. length prefix encoding, since it doesn't sort correctly.
fn serialize_bytes(self, v: &[u8]) -> Result<()> {
let bytes = v
.iter()
.flat_map(|&byte| match byte {
0x00 => Either::Left([0x00, 0xff].into_iter()),
byte => Either::Right([byte].into_iter()),
})
.chain([0x00, 0x00]);
self.output.extend(bytes);
Ok(())
}

代碼詳解:

  1. v.iter(): 遍歷輸入字節切片的每個字節
  2. flat_map(|&byte| ...): 將每個字節映射為一個或多個字節的迭代器
  • &byte: 解引用 &u8 → u8
  • flat_map 將所有迭代器拉平成單一序列
  1. match byte: 根據字節值決定輸出
  • 0x00 → Either::Left([0x00, 0xff].into_iter()):轉義為兩字節
  • 其他 → Either::Right([byte].into_iter()):保持不變
  1. Either<L, R>: 統一不同長度迭代器的類型,讓 flat_map 可處理
  2. .chain([0x00, 0x00]): 追加終止符
  3. self.output.extend(bytes): 將所有字節寫入輸出

完整執行示例:

// 輸入: "a\x00b" = [0x61, 0x00, 0x62]

v.iter() // 0x61, 0x00, 0x62
.flat_map(...) // 0x61, 0x00, 0xff, 0x62
// ^^^^^ 0x00 轉義為 0x00 0xff
.chain([0x00, 0x00]) // 0x61, 0x00, 0xff, 0x62, 0x00, 0x00
// ^^^^^ 終止符

// 最終輸出: [0x61, 0x00, 0xff, 0x62, 0x00, 0x00]

編碼規則:

  • 數據中的 0x00 → 編碼為 0x00 0xff
  • 其他字節 → 直接輸出
  • 字符串末尾 → 追加終止符 0x00 0x00

為什麼不能用長度前綴?

長度前綴會破壞字典序:

// 長度前綴編碼(錯誤)
"a" → [01 00 00 00 00 00 00 00 61]
"aa" → [02 00 00 00 00 00 00 00 61 61]
"b" → [01 00 00 00 00 00 00 00 62]

// 字節比較: "aa" vs "b" → 02 > 01 ❌ 錯誤!
// 正確順序應該: "aa" < "b"

null 終止編碼保持字典序:

"a"  → [61 00 00]        // 'a' + 終止符
"aa" → [61 61 00 00] // 'aa' + 終止符
"b" → [62 00 00] // 'b' + 終止符

// 字節比較:
// "a" vs "aa": [61 00] < [61 61] ✓ 正確
// "aa" vs "b": [61 61] < [62 00] ✓ 正確

為什麼要轉義 0x00?

問題:數據本身可能包含 0x00,會與終止符 0x00 0x00 混淆

// 如果不轉義(錯誤)
"a\x00b" → [61 00 62 00 00]
// ^^ 解碼器誤認為終止符!
// 只解碼出 "a",丟失 "b"

解決方案:轉義數據中的 0x00

// 正確轉義
"a\x00b" → [61 00 ff 62 00 00]
// ^^^^^ 轉義序列(數據中的 0x00)
// ^^^^^ 終止符(字符串結束)

編碼示例:

""           → [00 00]
"a" → [61 00 00]
"ab" → [61 62 00 00]
"a\x00b" → [61 00 ff 62 00 00]
"\x00" → [00 ff 00 00]
"\x00\x00" → [00 ff 00 ff 00 00]

解碼實現

源碼中解碼分為兩部分:公開方法調用內部輔助函數

公開方法(Serde trait 要求):

fn deserialize_bytes<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
let bytes = self.decode_next_bytes()?; // 調用輔助函數
visitor.visit_bytes(&bytes) // 將結果交給 visitor 處理
}

fn deserialize_byte_buf<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
let bytes = self.decode_next_bytes()?;
visitor.visit_byte_buf(bytes)
}
fn deserialize_string<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value> {
let bytes = self.decode_next_bytes()?;
visitor.visit_str(&String::from_utf8(bytes)?)
}

Visitor 模式說明:

visitor 是 Serde 的 Visitor 模式實現,用於將解碼後的數據轉換為目標類型:

// Serde 定義的 Visitor trait(簡化版)
pub trait Visitor<'de> {
type Value; // 最終返回的類型

// 借用字節切片
fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>;

// 擁有字節向量
fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E>;

// 借用字符串切片
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>;

// ... 其他 visit_* 方法
}

工作流程:

1.Deserializer 負責解碼字節:

let bytes = self.decode_next_bytes()?;  // [0x61, 0x00, 0x62] → "a\x00b"

2.Visitor 負責構造目標類型:

visitor.visit_bytes(&bytes)  // 將 &[u8] 轉換為目標類型

3.根據目標類型調用不同的 visit 方法:

// 如果目標是 Vec<u8>
visitor.visit_byte_buf(bytes) → Vec<u8>

// 如果目標是 String
visitor.visit_str(&String::from_utf8(bytes)?) → String

// 如果目標是 &[u8](借用)
visitor.visit_bytes(&bytes) → &[u8]

為什麼需要 Visitor?

這是 Serde 的兩階段解碼設計:

階段1: Deserializer 解析字節格式
↓
階段2: Visitor 構造目標類型

核心解碼邏輯(輔助函數):

/// Decodes and chops off the next encoded byte slice.
fn decode_next_bytes(&mut self) -> Result<Vec<u8>> {
let mut decoded = Vec::new();
let mut iter = self.input.iter().enumerate();
let taken = loop {
match iter.next() {
Some((_, 0x00)) => match iter.next() {
Some((i, 0x00)) => break i + 1, // 終止符,返回已讀位置
Some((_, 0xff)) => decoded.push(0x00), // 轉義,還原為 0x00
_ => return errdata!("invalid escape sequence"),
},
Some((_, b)) => decoded.push(*b), // 普通字節
None => return errdata!("unexpected end of input"),
}
};
self.input = &self.input[taken..]; // 更新輸入,跳過已解碼部分
Ok(decoded)
}

代碼詳解:

1.iter().enumerate(): 遍歷字節同時記錄位置

  • 為什麼需要位置?解碼完成後需要知道消費了多少字節

2.循環處理字節:

match iter.next() {
Some((_, 0x00)) => { /* 遇到可能的終止符或轉義 */ }
Some((_, b)) => { /* 普通字節 */ }
None => { /* 意外結束 */ }
}

3.遇到 0x00 時檢查下一字節:

Some((_, 0x00)) => match iter.next() {
Some((i, 0x00)) => break i + 1, // [00 00] → 終止符
Some((_, 0xff)) => decoded.push(0x00), // [00 ff] → 轉義的 0x00
_ => return errdata!("invalid escape sequence"),
}

4.break i + 1: 返回已消費的字節數

  • i 是第二個 0x00 的索引
  • i + 1 是需要跳過的總字節數(包括兩個終止符)

5.self.input = &self.input[taken..]: 更新輸入切片

  • 跳過已解碼的字節
  • 為下一次解碼準備

解碼示例:

// 輸入: [61 00 ff 62 00 00]
// 解碼 "a\x00b"

iter.next() → (0, 0x61) → decoded.push(0x61) // 'a'
iter.next() → (1, 0x00) → 遇到 0x00,檢查下一個
iter.next() → (2, 0xff) → decoded.push(0x00) // 轉義,還原為 \x00
iter.next() → (3, 0x62) → decoded.push(0x62) // 'b'
iter.next() → (4, 0x00) → 遇到 0x00,檢查下一個
iter.next() → (5, 0x00) → break 6 // 終止符,返回位置 6
// decoded = [0x61, 0x00, 0x62] = "a\x00b"
// self.input 更新:跳過前 6 個字節

--

--