This is an automated email from the ASF dual-hosted git repository. chaokunyang pushed a commit to branch fix_build_error in repository https://gitbox.apache.org/repos/asf/fory-site.git
commit e16f906edc13570344f2d9f890fa32818ea31fd9 Author: chaokunyang <[email protected]> AuthorDate: Tue Jul 28 19:06:49 2026 +0800 fix(docs): sync manual serializer translations --- .../translate-docs-zh/references/terminology.md | 1 + .../current/guide/csharp/index.md | 2 +- ...custom-serializers.md => manual-serializers.md} | 20 +- .../current/guide/csharp/type-registration.md | 2 +- .../current/guide/rust/basic-serialization.md | 2 +- .../current/guide/rust/custom-serializers.md | 147 ----------- .../current/guide/rust/manual-serializers.md | 183 ++++++++++++++ .../current/guide/rust/type-registration.md | 2 +- .../current/guide/swift/custom-serializers.md | 84 ------- .../current/guide/swift/index.md | 2 +- .../current/guide/swift/manual-serializers.md | 278 +++++++++++++++++++++ 11 files changed, 481 insertions(+), 242 deletions(-) diff --git a/.claude/skills/translate-docs-zh/references/terminology.md b/.claude/skills/translate-docs-zh/references/terminology.md index f7ecbf4c59..a40c6fa98b 100644 --- a/.claude/skills/translate-docs-zh/references/terminology.md +++ b/.claude/skills/translate-docs-zh/references/terminology.md @@ -40,6 +40,7 @@ Use these terms consistently across all translated docs. | object graph | 对象图 | Use for graph-shaped data models with identity, shared refs, or cycles. | | domain object | 领域对象 | Use for generated host-language models used directly in application code. | | sum type | 和类型 | Prefer when describing `union`-style algebraic variants across languages. | +| manual serializer | 手动序列化器 | Use for explicitly implemented serializers selected or registered by application code. | ## Terms to Avoid (Unless User Explicitly Requests) diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/guide/csharp/index.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/guide/csharp/index.md index 16e2cdd0bb..c971b27915 100644 --- a/i18n/zh-CN/docusaurus-plugin-content-docs/current/guide/csharp/index.md +++ b/i18n/zh-CN/docusaurus-plugin-content-docs/current/guide/csharp/index.md @@ -88,7 +88,7 @@ User decoded = fory.Deserialize<User>(payload); | [配置](configuration.md) | 构建器选项与运行时模式 | | [基础序列化](basic-serialization.md) | 强类型和动态序列化 API | | [类型注册](type-registration.md) | 注册用户类型和自定义序列化器 | -| [自定义序列化器](custom-serializers.md) | 实现 `Serializer<T>` | +| [手动序列化器](manual-serializers.md) | 实现 `Serializer<T>` | | [字段配置](schema-metadata.md) | `[Field]` 特性与整数编码选项 | | [引用](references.md) | 共享引用与循环引用处理 | | [Schema 演进](schema-evolution.md) | 兼容模式行为 | diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/guide/csharp/custom-serializers.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/guide/csharp/manual-serializers.md similarity index 70% rename from i18n/zh-CN/docusaurus-plugin-content-docs/current/guide/csharp/custom-serializers.md rename to i18n/zh-CN/docusaurus-plugin-content-docs/current/guide/csharp/manual-serializers.md index af684393c2..80e3bf1541 100644 --- a/i18n/zh-CN/docusaurus-plugin-content-docs/current/guide/csharp/custom-serializers.md +++ b/i18n/zh-CN/docusaurus-plugin-content-docs/current/guide/csharp/manual-serializers.md @@ -1,7 +1,7 @@ --- -title: 自定义序列化器 -sidebar_position: 4 -id: custom_serializers +title: 手动序列化器 +sidebar_position: 11 +id: manual_serializers license: | Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with @@ -19,7 +19,9 @@ license: | limitations under the License. --- -当某个类型不是通过 `[ForyStruct]` 生成,或者需要专门的编码方式时,可以使用自定义序列化器。 +当某个类型不是通过 `[ForyStruct]` 生成,或者需要专门的编码方式时,可以使用手动序列化器。 + +[外部类型序列化](external-types.md)可为可变的第三方目标类型生成序列化器,包括精确映射私有字段或已重命名字段。对于不可变、仅能通过构造函数或工厂创建、包含 `readonly` 或 `init-only` 成员、需要类型转换或采用自定义编码格式的目标类型,请使用手动序列化器。在 .NET 8 上,如果某个外部私有编码字段的声明所在类型或访问器签名使用了泛型,也需要使用手动序列化器。只用于存储的精确映射不会生成私有访问器。 ## 实现 `Serializer<T>` @@ -64,6 +66,12 @@ byte[] payload = fory.Serialize(value); Point decoded = fory.Deserialize<Point>(payload); ``` +当对端使用类型名称而不是数字 ID 来标识类型时,请使用接受名称参数的重载: + +```csharp +fory.Register<Point, PointSerializer>("com.example.Point"); +``` + ## 序列化器行为说明 - `WriteData` / `ReadData` 只负责处理载荷内容。 @@ -74,11 +82,11 @@ Point decoded = fory.Deserialize<Point>(payload); 1. 保持序列化器逻辑确定且读写对称。 2. 对整数密集型载荷要有意识地选择 varint、fixed 或 tagged 编码。 -3. 在所有读写端都注册自定义序列化器。 +3. 在所有读写端都注册手动序列化器。 4. 对常规领域模型优先使用 `[ForyStruct]` 生成的序列化器。 ## 相关主题 - [类型注册](type-registration.md) -- [字段配置](schema-metadata.md) +- [Schema 元数据](schema-metadata.md) - [故障排查](troubleshooting.md) diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/guide/csharp/type-registration.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/guide/csharp/type-registration.md index cd8af14949..b6e11d7399 100644 --- a/i18n/zh-CN/docusaurus-plugin-content-docs/current/guide/csharp/type-registration.md +++ b/i18n/zh-CN/docusaurus-plugin-content-docs/current/guide/csharp/type-registration.md @@ -78,5 +78,5 @@ fory.Register<Order>(101); ## 相关主题 - [基础序列化](basic-serialization.md) -- [自定义序列化器](custom-serializers.md) +- [手动序列化器](manual-serializers.md) - [跨语言](xlang-serialization.md) diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/guide/rust/basic-serialization.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/guide/rust/basic-serialization.md index 2813e34dab..f4e51ae80a 100644 --- a/i18n/zh-CN/docusaurus-plugin-content-docs/current/guide/rust/basic-serialization.md +++ b/i18n/zh-CN/docusaurus-plugin-content-docs/current/guide/rust/basic-serialization.md @@ -188,4 +188,4 @@ let decoded: MyStruct = fory.deserialize_from(&mut reader)?; - [类型注册](type-registration.md) - 注册类型 - [引用](references.md) - 共享引用和循环引用 -- [自定义序列化器](custom-serializers.md) - 手动序列化 +- [手动序列化器](manual-serializers.md) - 手动序列化 diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/guide/rust/custom-serializers.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/guide/rust/custom-serializers.md deleted file mode 100644 index a51d0b9b3b..0000000000 --- a/i18n/zh-CN/docusaurus-plugin-content-docs/current/guide/rust/custom-serializers.md +++ /dev/null @@ -1,147 +0,0 @@ ---- -title: 自定义序列化器 -sidebar_position: 4 -id: custom_serializers -license: | - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. ---- - -对于不支持 `#[derive(ForyObject)]` 的类型,可以手动实现 `Serializer` trait。 - -## 何时使用自定义序列化器 - -- 来自其他 crate 的外部类型 -- 具有特殊序列化要求的类型 -- 旧数据格式兼容性 -- 性能关键的自定义编码 - -## 实现 Serializer Trait - -```rust -use fory::{Fory, ReadContext, WriteContext, Serializer, ForyDefault, Error}; -use std::any::Any; - -#[derive(Debug, PartialEq)] -struct CustomType { - value: i32, - name: String, -} - -impl Serializer for CustomType { - fn fory_write_data(&self, context: &mut WriteContext, is_field: bool) { - context.writer.write_i32(self.value); - context.writer.write_varuint32(self.name.len() as u32); - context.writer.write_utf8_string(&self.name); - } - - fn fory_read_data(context: &mut ReadContext, is_field: bool) -> Result<Self, Error> { - let value = context.reader.read_i32(); - let len = context.reader.read_varuint32() as usize; - let name = context.reader.read_utf8_string(len); - Ok(Self { value, name }) - } - - fn fory_type_id_dyn(&self, type_resolver: &TypeResolver) -> u32 { - Self::fory_get_type_id(type_resolver) - } - - fn as_any(&self) -> &dyn Any { - self - } -} - -impl ForyDefault for CustomType { - fn fory_default() -> Self { - Self::default() - } -} -``` - -## 注册自定义序列化器 - -```rust -let mut fory = Fory::default(); -fory.register_serializer::<CustomType>(100); - -let custom = CustomType { - value: 42, - name: "test".to_string(), -}; -let bytes = fory.serialize(&custom); -let decoded: CustomType = fory.deserialize(&bytes)?; -assert_eq!(custom, decoded); -``` - -## WriteContext 和 ReadContext - -`WriteContext` 和 `ReadContext` 提供对以下内容的访问: - -- **writer/reader**:二进制缓冲区操作 -- **type_resolver**:类型注册信息 -- **ref_resolver**:引用跟踪(用于共享/循环引用) - -### 常用 Writer 方法 - -```rust -// 原始类型 -context.writer.write_i8(value); -context.writer.write_i16(value); -context.writer.write_i32(value); -context.writer.write_i64(value); -context.writer.write_f32(value); -context.writer.write_f64(value); -context.writer.write_bool(value); - -// 变长整数 -context.writer.write_varint32(value); -context.writer.write_varuint32(value); - -// 字符串 -context.writer.write_utf8_string(&string); -``` - -### 常用 Reader 方法 - -```rust -// 原始类型 -let value = context.reader.read_i8(); -let value = context.reader.read_i16(); -let value = context.reader.read_i32(); -let value = context.reader.read_i64(); -let value = context.reader.read_f32(); -let value = context.reader.read_f64(); -let value = context.reader.read_bool(); - -// 变长整数 -let value = context.reader.read_varint32(); -let value = context.reader.read_varuint32(); - -// 字符串 -let string = context.reader.read_utf8_string(len); -``` - -## 最佳实践 - -1. **使用变长编码**:对可能较小的整数使用变长编码 -2. **首先写入长度**:对变长数据先写入长度 -3. **正确处理错误**:在 read 方法中正确处理错误 -4. **实现 ForyDefault**:以支持 schema 演化 - -## 相关主题 - -- [类型注册](type-registration.md) - 注册序列化器 -- [基础序列化](basic-serialization.md) - 使用 ForyObject derive -- [Schema 演化](schema-evolution.md) - Compatible 模式 diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/guide/rust/manual-serializers.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/guide/rust/manual-serializers.md new file mode 100644 index 0000000000..4efe1ef78f --- /dev/null +++ b/i18n/zh-CN/docusaurus-plugin-content-docs/current/guide/rust/manual-serializers.md @@ -0,0 +1,183 @@ +--- +title: 手动序列化器 +sidebar_position: 10 +id: manual_serializers +license: | + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +--- + +当派生宏无法表达类型的序列化表示,或者需要特意使用不透明编码时,请使用手动序列化器。序列化器是一种类型级实现,通过 `Target` 指定其处理的值类型。 + +对于需要保持结构化 Schema 的公开第三方结构体或枚举,优先使用[外部类型序列化](external-types.md)。 + +## 实现手动序列化器 + +以下示例使用本地类型自身作为序列化器: + +```rust +use fory::{Error, Fory, ReadContext, Serializer, WriteContext}; + +#[derive(Debug, PartialEq)] +struct Point { + value: i32, +} + +impl Serializer for Point { + type Target = Self; + + fn write_data(value: &Self, context: &mut WriteContext) -> Result<(), Error> { + context.writer.write_i32(value.value); + Ok(()) + } + + fn read_data(context: &mut ReadContext) -> Result<Self, Error> { + Ok(Self { + value: context.reader.read_i32()?, + }) + } + + fn default_value(_context: &mut ReadContext) -> Result<Self, Error> { + Ok(Self { value: 0 }) + } +} + +let mut fory = Fory::builder().xlang(false).build(); +fory.register_serializer::<Point>(100)?; + +let value = Point { value: 42 }; +let bytes = fory.serialize(&value)?; +let decoded: Point = fory.deserialize(&bytes)?; +assert_eq!(decoded, value); +# Ok::<(), Error>(()) +``` + +`write_data` 和 `read_data` 处理 EXT 主体。Fory 的完整值 `write` 和 `read` 操作会为根值或字段补充引用帧和类型信息帧。 + +`default_value` 是可选的。仅当兼容字段为空或缺失时存在有意义的取值,才实现此方法。它会接收当前的 `ReadContext`,因此需要分配内存的默认值可以应用与普通读取相同的反序列化限制。 + +## 序列化第三方不透明类型 + +可以用独立的序列化器处理其他 crate 中的类型: + +```rust +use fory::{Error, ReadContext, Serializer, WriteContext}; + +struct UuidSerializer; + +#[cold] +#[inline(never)] +fn invalid_uuid(error: uuid::Error) -> Error { + Error::invalid_data(error.to_string()) +} + +impl Serializer for UuidSerializer { + type Target = uuid::Uuid; + + fn write_data( + value: &uuid::Uuid, + context: &mut WriteContext, + ) -> Result<(), Error> { + context.writer.write_bytes(value.as_bytes()); + Ok(()) + } + + fn read_data(context: &mut ReadContext) -> Result<uuid::Uuid, Error> { + let bytes = context.reader.read_bytes(16)?; + uuid::Uuid::from_slice(bytes).map_err(invalid_uuid) + } +} +``` + +注册序列化器,然后在根值或字段上选择使用它: + +```rust +fory.register_serializer::<UuidSerializer>(101)?; + +let bytes = fory.serialize_with::<UuidSerializer>(&uuid)?; +let decoded = + fory.deserialize_with::<UuidSerializer>(&bytes)?; +``` + +```rust +#[derive(ForyStruct)] +struct Request { + #[fory(with = UuidSerializer)] + id: uuid::Uuid, +} +``` + +手动序列化器的主体是不透明的。兼容模式不会映射其中的字段。 + +## 支持 `Arc<dyn Any + Send + Sync>` + +如果必须将手动序列化器的目标具体化为 `Arc<dyn Any + Send + Sync>`,或具体化为某种同步的应用程序 trait,请实现 `read_arc_any`: + +```rust +use std::any::Any; +use std::sync::Arc; + +impl Serializer for Point { + type Target = Self; + + // 按照上面的方式实现 write_data、read_data 和所需的默认值。 + + fn read_arc_any( + context: &mut ReadContext, + ) -> Result<Arc<dyn Any + Send + Sync>, Error> { + Ok(Arc::new(Self::read_data(context)?)) + } +} +``` + +目标必须实现 `Send + Sync`。如果省略此方法,带具体类型的操作以及 `Box`、`Rc` 操作仍然可用,而将值具体化为同步 `Arc` 时会返回错误。 + +## 按名称注册 + +当序列化后的标识是限定名称时,请使用名称注册: + +```rust +fory.register_serializer_by_name::<UuidSerializer>( + "example.Uuid", +)?; +``` + +对于同一个目标,一个 `Fory` 实例最多只能注册一个序列化器。 + +## 上下文访问 + +`WriteContext` 和 `ReadContext` 会公开二进制 writer 和 reader: + +```rust +context.writer.write_i8(value); +context.writer.write_i32(value); +context.writer.write_var_u32(value); +context.writer.write_f64(value); + +let value = context.reader.read_i8()?; +let value = context.reader.read_i32()?; +let value = context.reader.read_var_u32()?; +let value = context.reader.read_f64()?; +``` + +对于大小可变的主体,请先验证可读字节数和对象图内存限制,再根据编码后的长度分配内存。 + +当手动序列化器被用作大小可变容器的子项时,容器必须在元素数或映射条目数之后,按总量计算为每个已声明的元素或映射条目至少写入一个字节。如果容器的完整头部、元数据、帧和子项主体的总长度小于该计数,Fory 会拒绝序列化,从而绝不会写出与之配对的分配安全检查无法读取的字节。定长数组不受此限制,因为其经过验证的计数不控制内存分配;`Vec`、`VecDeque` 和 `BinaryHeap` 中的零大小元素也不受此限制,因为这些容器不会为它们分配后备存储空间。 + +## 相关主题 + +- [外部类型序列化](external-types.md) +- [类型注册](type-registration.md) +- [Schema 演进](schema-evolution.md) diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/guide/rust/type-registration.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/guide/rust/type-registration.md index 0401ad2b1b..0360725c22 100644 --- a/i18n/zh-CN/docusaurus-plugin-content-docs/current/guide/rust/type-registration.md +++ b/i18n/zh-CN/docusaurus-plugin-content-docs/current/guide/rust/type-registration.md @@ -123,4 +123,4 @@ let handles: Vec<_> = (0..4) - [配置](configuration.md) - Fory 构建器选项 - [跨语言](xlang-serialization.md) - XLANG 模式注册 -- [自定义序列化器](custom-serializers.md) - 自定义序列化 +- [手动序列化器](manual-serializers.md) - 手动序列化 diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/guide/swift/custom-serializers.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/guide/swift/custom-serializers.md deleted file mode 100644 index e5c47e340d..0000000000 --- a/i18n/zh-CN/docusaurus-plugin-content-docs/current/guide/swift/custom-serializers.md +++ /dev/null @@ -1,84 +0,0 @@ ---- -title: 自定义序列化器 -sidebar_position: 4 -id: custom_serializers -license: | - Licensed to the Apache Software Foundation (ASF) under one or more - contributor license agreements. See the NOTICE file distributed with - this work for additional information regarding copyright ownership. - The ASF licenses this file to You under the Apache License, Version 2.0 - (the "License"); you may not use this file except in compliance with - the License. You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. ---- - -对于不适合使用 `@ForyObject` 的类型,或需要特殊编码逻辑的场景,可以手动实现 `Serializer`。 - -## 适用场景 - -- 外部类型需要严格的编码兼容性 -- 需要更紧凑或特殊的编码布局 -- 旧载荷迁移路径 -- 性能敏感的热点路径 - -## 实现 `Serializer` - -```swift -import Foundation -import Fory - -struct UUIDBox: Serializer, Equatable { - var value: UUID = UUID(uuidString: "00000000-0000-0000-0000-000000000000")! - - static func foryDefault() -> UUIDBox { - UUIDBox() - } - - static var staticTypeId: ForyTypeId { - .ext - } - - func foryWriteData(_ context: WriteContext, hasGenerics: Bool) throws { - _ = hasGenerics - try value.uuidString.foryWriteData(context, hasGenerics: false) - } - - static func foryReadData(_ context: ReadContext) throws -> UUIDBox { - let raw = try String.foryReadData(context) - guard let uuid = UUID(uuidString: raw) else { - throw ForyError.invalidData("invalid UUID string: \\(raw)") - } - return UUIDBox(value: uuid) - } -} -``` - -## 注册并使用 - -```swift -let fory = Fory() -fory.register(UUIDBox.self, id: 300) - -let input = UUIDBox(value: UUID()) -let data = try fory.serialize(input) -let output: UUIDBox = try fory.deserialize(data) - -assert(input == output) -``` - -## 如何选择 `staticTypeId` - -手动实现的自定义类型,需要让 `staticTypeId` 与实际编码形态匹配。 - -常见选择: - -- `.structType`:常规结构化对象 -- `.enumType` / `.typedUnion`:枚举或联合类型 -- `.ext`:扩展或自定义类型 diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/guide/swift/index.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/guide/swift/index.md index 0015c91036..28ec5759aa 100644 --- a/i18n/zh-CN/docusaurus-plugin-content-docs/current/guide/swift/index.md +++ b/i18n/zh-CN/docusaurus-plugin-content-docs/current/guide/swift/index.md @@ -53,7 +53,7 @@ targets: [ - [配置](configuration.md) - [基础序列化](basic-serialization.md) - [类型注册](type-registration.md) -- [自定义序列化器](custom-serializers.md) +- [手动序列化器](manual-serializers.md) - [字段配置](schema-metadata.md) - [共享引用与循环引用](references.md) - [多态与动态类型](polymorphism.md) diff --git a/i18n/zh-CN/docusaurus-plugin-content-docs/current/guide/swift/manual-serializers.md b/i18n/zh-CN/docusaurus-plugin-content-docs/current/guide/swift/manual-serializers.md new file mode 100644 index 0000000000..52aa89069d --- /dev/null +++ b/i18n/zh-CN/docusaurus-plugin-content-docs/current/guide/swift/manual-serializers.md @@ -0,0 +1,278 @@ +--- +title: 手动序列化器 +sidebar_position: 10 +id: manual_serializers +license: | + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +--- + +当目标类型需要自定义编码,或无法满足[外部结构化序列化器](external-types.md)的直接访问要求时,请使用手动序列化器。 + +手动序列化器并非只能用于外部类型: + +- 如果目标类型自身遵循 `Serializer`,并且 `Target == Self`,则该实现会在所有位置被隐式选中。 +- 如果单独定义的序列化器以另一种类型作为 `Target`,则必须在每个需要它的位置显式选择该序列化器。 + +根值、生成字段、可选值、数组、集合和字典都遵循相同的选择规则。请注册单独定义的序列化器,并在使用它的位置显式选择它。 + +## 何时使用手动序列化器 + +- 目标类型包含私有或不可变状态。 +- 目标类型必须强制执行构造不变量。 +- 目标类型需要专用的紧凑编码。 +- 目标类型需要自定义校验或构造逻辑。 +- 外部枚举无法进行穷尽式 `switch`。 +- 外部联合类型无法表示 `UnknownCase`。 + +## 用户自有的目标类型 + +如果目标类型由你维护,请让目标类型自身实现 `Serializer`,并将 `Target` 设为相同类型: + +```swift +import Fory + +struct AccountID: Serializer, Equatable { + typealias Target = AccountID + + let rawValue: UInt64 + + static var staticTypeId: TypeId { + .ext + } + + static func writeData( + _ value: AccountID, + _ context: WriteContext + ) throws { + try UInt64.writeData(value.rawValue, context) + } + + static func readData( + _ context: ReadContext + ) throws -> AccountID { + AccountID(rawValue: try UInt64.readData(context)) + } +} +``` + +通过常规的根值 API 注册并使用该类型: + +```swift +let fory = Fory() +try fory.register(AccountID.self, id: 300) + +let input = AccountID(rawValue: 42) +let data = try fory.serialize(input) +let output: AccountID = try fory.deserialize(data) + +assert(input == output) +``` + +由于 `AccountID.Target == AccountID`,因此不需要 `with:` 参数。 + +## 为外部类型定义一个全局序列化器 + +Swift 允许应用通过追溯遵循(retroactive conformance)让外部类型实现 `Serializer`: + +```swift +import Foundation +import Fory + +extension UUID: @retroactive Serializer { + public typealias Target = UUID + + public static var staticTypeId: TypeId { + .ext + } + + public static func defaultValue( + _ context: ReadContext + ) throws -> UUID { + _ = context + return UUID( + uuidString: "00000000-0000-0000-0000-000000000000" + )! + } + + public static func writeData( + _ value: UUID, + _ context: WriteContext + ) throws { + try String.writeData(value.uuidString, context) + } + + public static func readData( + _ context: ReadContext + ) throws -> UUID { + let raw = try String.readData(context) + guard let uuid = UUID(uuidString: raw) else { + throw ForyError.invalidData("invalid UUID string: \(raw)") + } + return uuid + } +} +``` + +注册外部类型本身: + +```swift +try fory.register(UUID.self, id: 300) + +let input = UUID() +let data = try fory.serialize(input) +let output: UUID = try fory.deserialize(data) +``` + +由于 `UUID.Target == UUID`,没有添加注解的生成字段和普通容器也会选用该实现: + +```swift +@ForyStruct +struct Request { + var requestID: UUID +} + +let input = [UUID(), UUID()] +let data = try fory.serialize(input) +let output: [UUID] = try fory.deserialize(data) +``` + +追溯遵循会作用于整个进程。对于一个给定类型,Swift 只允许存在一个 `Serializer` 遵循;`@retroactive` 只是表明你已知晓编译器警告,并不能让相互冲突的多个遵循变得安全。只有当应用有意选择唯一的全局实现时,才应采用这种形式。公共库通常应改为提供单独定义的序列化器。 + +## 单独定义的序列化器 + +当公共库不应声明作用于整个进程的遵循,或应用需要多个实现或替代实现时,请单独定义序列化器。目标类型既可以是外部类型,也可以是用户自有类型: + +```swift +import Foundation +import Fory + +public enum UUIDStringSerializer: Serializer { + public typealias Target = UUID + + public static var staticTypeId: TypeId { + .ext + } + + public static func defaultValue( + _ context: ReadContext + ) throws -> UUID { + _ = context + return UUID( + uuidString: "00000000-0000-0000-0000-000000000000" + )! + } + + public static func writeData( + _ value: UUID, + _ context: WriteContext + ) throws { + try String.writeData(value.uuidString, context) + } + + public static func readData( + _ context: ReadContext + ) throws -> UUID { + let raw = try String.readData(context) + guard let uuid = UUID(uuidString: raw) else { + throw ForyError.invalidData("invalid UUID string: \(raw)") + } + return uuid + } +} +``` + +注册单独定义的序列化器,并在根值处显式选择它: + +```swift +let fory = Fory() +try fory.register(UUIDStringSerializer.self, id: 300) + +let input = UUID() +let data = try fory.serialize(input, with: UUIDStringSerializer.self) +let output = try fory.deserialize(data, with: UUIDStringSerializer.self) + +assert(input == output) +``` + +另一个声明(例如 `UUIDBytesSerializer`)可以使用不同的主体编码处理同一目标类型。Fory 无法自动在多个单独定义的序列化器中进行选择。请在根值处通过 `with:` 选择所需的序列化器,并在字段上使用与之匹配的注解。一个 `Fory` 实例只能为该目标类型注册一种实现。 + +直接以 `Any` 和 `AnyObject` 作为根值的便捷 API 仍然是动态操作。以 `Any` 形式传入具体值时,可能会使用已经注册的序列化器,但使用静态类型的根值和字段仍然需要通过 `with:` 指定单独定义的序列化器。 + +## 字段和容器 + +如果字段类型直接实现了 `Serializer`,并且 `Target == Self`,则无需指定选择器: + +```swift +@ForyStruct +struct Request { + var accountID: AccountID +} +``` + +单独定义的序列化器必须显式选择: + +```swift +@ForyStruct +struct ExternalRequest { + @ForyField(with: UUIDStringSerializer.self) + var requestID: UUID +} +``` + +如果普通容器所包含的类型直接实现了 `Serializer`,则无需指定选择器。这也包括有意添加的追溯遵循: + +```swift +let accountIDs = [ + AccountID(rawValue: 1), + AccountID(rawValue: 2), +] +let data = try fory.serialize(accountIDs) +let output: [AccountID] = try fory.deserialize(data) +``` + +如果元素使用单独定义的序列化器,请在容器注解中指定该序列化器: + +```swift +@ListField(element: .with(UUIDStringSerializer.self)) +var requestIDs: [UUID] +``` + +在根值处,请使用与之匹配的容器序列化器: + +```swift +let data = try fory.serialize( + requestIDs, + with: ArraySerializer<UUIDStringSerializer>.self +) +``` + +## 手动序列化器规则 + +手动序列化器的 `staticTypeId` 必须返回 `.ext`。`.structType`、`.enumType` 和 `.typedUnion` 分别保留给 `@ForyStruct`、`@ForyEnum` 和 `@ForyUnion`。 + +`writeData` 和 `readData` 只处理目标值的编码主体。请勿在这两个操作中调用根值的 `serialize` 或 `deserialize` 方法。 + +## 默认值 + +仅当目标类型存在可用于空字段或缺失字段的有效值时,才实现 `defaultValue(_:)`。 + +## 输入校验 + +请使用适当的 `ForyError` 拒绝无效输入。 + +## 手动类序列化器 + +对于存在循环引用的类,请重写读取完整值的 `read` 操作,并使用 Fory 的引用 API,以确保重复引用解析为同一个对象。 --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
