├── .gitignore ├── LICENSE ├── README.md ├── output ├── templates │ ├── csharp_buffer.ftl │ ├── csharp_class.ftl │ ├── ts_buffer.ftl │ └── ts_class.ftl ├── test.xb ├── testCsharp.bat ├── testTypescript.bat ├── xbuffer_parser.exe └── xbuffer_runtime.dll ├── test_result.png ├── xbuffer.sln ├── xbuffer_parser ├── Config.cs ├── Parser.cs ├── Program.cs ├── Properties │ └── AssemblyInfo.cs ├── Proto.cs ├── XTemplate.cs └── xbuffer_parser.csproj ├── xbuffer_runtime ├── Properties │ └── AssemblyInfo.cs ├── Serializer.cs ├── XSteam.cs ├── boolBuffer.cs ├── byteBuffer.cs ├── floatBuffer.cs ├── intBuffer.cs ├── longBuffer.cs ├── stringBuffer.cs ├── uintBuffer.cs ├── utils.cs └── xbuffer_runtime.csproj └── xbuffer_test ├── App.config ├── FlatBuffers ├── ByteBuffer.cs ├── FlatBufferBuilder.cs ├── FlatBufferConstants.cs ├── IFlatbufferObject.cs ├── Offset.cs ├── Struct.cs └── Table.cs ├── Program.cs ├── Properties └── AssemblyInfo.cs ├── output_csharp_buffer ├── ABuffer.cs └── EBuffer.cs ├── output_csharp_class ├── A.cs └── E.cs ├── protobuf-net ├── BclHelpers.cs ├── BufferExtension.cs ├── BufferPool.cs ├── CallbackAttributes.cs ├── Compiler │ ├── CompilerContext.cs │ ├── CompilerDelegates.cs │ └── Local.cs ├── DataFormat.cs ├── Extensible.cs ├── ExtensibleUtil.cs ├── GlobalSuppressions.cs ├── Helpers.cs ├── IExtensible.cs ├── IExtension.cs ├── ImplicitFields.cs ├── KeyValuePairProxy.cs ├── Meta │ ├── AttributeMap.cs │ ├── BasicList.cs │ ├── CallbackSet.cs │ ├── MetaType.cs │ ├── RuntimeTypeModel.cs │ ├── SubType.cs │ ├── TypeFormatEventArgs.cs │ ├── TypeModel.cs │ └── ValueMember.cs ├── NetObjectCache.cs ├── PrefixStyle.cs ├── ProtoContractAttribute.cs ├── ProtoConverterAttribute.cs ├── ProtoEnumAttribute.cs ├── ProtoException.cs ├── ProtoIgnoreAttribute.cs ├── ProtoIncludeAttribute.cs ├── ProtoMemberAttribute.cs ├── ProtoReader.cs ├── ProtoWriter.cs ├── SerializationContext.cs ├── Serializer.cs ├── Serializers │ ├── ArrayDecorator.cs │ ├── BlobSerializer.cs │ ├── BooleanSerializer.cs │ ├── ByteSerializer.cs │ ├── CharSerializer.cs │ ├── CompiledSerializer.cs │ ├── DateTimeSerializer.cs │ ├── DecimalSerializer.cs │ ├── DefaultValueDecorator.cs │ ├── DoubleSerializer.cs │ ├── EnumSerializer.cs │ ├── FieldDecorator.cs │ ├── GuidSerializer.cs │ ├── IProtoSerializer.cs │ ├── IProtoTypeSerializer.cs │ ├── ISerializerProxy.cs │ ├── ImmutableCollectionDecorator.cs │ ├── Int16Serializer.cs │ ├── Int32Serializer.cs │ ├── Int64Serializer.cs │ ├── KeyValuePairDecorator.cs │ ├── ListDecorator.cs │ ├── MemberSpecifiedDecorator.cs │ ├── NetObjectSerializer.cs │ ├── NullDecorator.cs │ ├── ParseableSerializer.cs │ ├── PropertyDecorator.cs │ ├── ProtoDecoratorBase.cs │ ├── SByteSerializer.cs │ ├── SingleSerializer.cs │ ├── StringSerializer.cs │ ├── SubItemSerializer.cs │ ├── SurrogateSerializer.cs │ ├── SystemTypeSerializer.cs │ ├── TagDecorator.cs │ ├── TimeSpanSerializer.cs │ ├── TupleSerializer.cs │ ├── TypeSerializer.cs │ ├── UInt16Serializer.cs │ ├── UInt32Serializer.cs │ ├── UInt64Serializer.cs │ └── UriDecorator.cs ├── ServiceModel │ ├── ProtoBehaviorAttribute.cs │ ├── ProtoBehaviorExtensionElement.cs │ ├── ProtoEndpointBehavior.cs │ ├── ProtoOperationBehavior.cs │ └── XmlProtoSerializer.cs ├── SubItemToken.cs └── WireType.cs ├── test.xb ├── test_flat.cs ├── test_flat.fbs ├── test_proto.cs ├── test_proto.proto └── xbuffer_test.csproj /.gitignore: -------------------------------------------------------------------------------- 1 | obj 2 | .vs 3 | /xbuffer_test/bin 4 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # xbuffer 2 | 一种简化版本的 flatbuffer 序列化库 3 | 4 | ## 与其他序列化库的简单对比 5 | - protobuffer 6 | - 相同点:使用方便(创建结构,生成文件,仅两个调用接口) 7 | - 优势: `protobuf`使用了大量的反射,序列化和反序列化效率均较低 8 | - flatbuffer 9 | - 相同点:序列化和反序列化效率上极高 10 | - 优势: `flatbuf`使用结构及其麻烦,需要自己实现部分序列化和反序列化的代码 11 | - 优势: `flatbufs`反序列化之后的数据结构无法在运行时中进行修改,并且每次获取任意数据均会经过大量的数据转换 12 | 13 | - 对比测试图 14 | - ![](test_result.png) 15 | - 序列化速度是 pb的15倍, fb的7倍 16 | - 反序列化的速度是 pb的6倍 fb的0或3倍 17 | - `flatbuf`的反序列化时间有两个原因是会在具体获取数据的时候才产生耗时操作 18 | - 实际项目使用中相同数据输出文件大小 (protobuf:100mb flatbuf:22mb xbuffer:20mb) 19 | - 图中`flatbuf`内存占用过高是因为使用了 `MemoryStream`, 我在`xbuffer`中拒绝了该模式,原因是我希望有一个固定的预期内存分配 20 | - 在 `xbuffer` 中我提供了 普通模式和泛型模式两种接口方案,普通模式在调用中完全是显示的(所以效率是最高的),而泛型模式相比`protobuf`会把反射调用集中到只有一个顶层类型来(但是方便使用)。这样可以在不同的用途时使用不同的模式,例如底层的网络库,对业务逻辑来说开放成泛型模式会让业务层逻辑更简洁,而一些本地很大的数据例如动画文件等,可以使用普通模式来达成更高的效率。 21 | 22 | ## 后续 23 | - 多语言版本(理论上只需要添加对应的模板文件和基础类型库即可) 24 | - 变量注释等 25 | 26 | ## 使用示例 27 | 1. 使用类似 `flatbuf` 的idl语言写一个结构描述文件, 任意后缀名 28 | ``` 29 | class A 30 | { 31 | a:[bool]; 32 | b:[int]; 33 | c:[float]; 34 | d:[string]; 35 | e:[E]; 36 | } 37 | 38 | class E 39 | { 40 | a:bool; 41 | b:int; 42 | c:float; 43 | d:string; 44 | } 45 | ``` 46 | 1. 将该文件拖动到 `xbuffer_parser.exe` 文件上,程序会根据 `templates` 文件夹下的所有模板文件(任意后缀),生成对应目录的代码文件 47 | 1. 将生成的代码挪到自己的项目中 48 | 1. 将运行时 `xbuffer_runtime.dll` 挪到自己的项目中 49 | - 普通模式序列化代码 50 | ``` 51 | byte[] buffer;; 52 | int offset = 0; 53 | 54 | ABuffer.serialize(data, buffer, ref offset); 55 | ``` 56 | 这里使用一个`buffer`来存储需要序列化的数据,`offset`标记从数组的哪个位置开始存储,这样一来可以项目中共用同一个比较大的byte[]来减少频繁的内存分配. 57 | - 普通模式反序列化代码 58 | ``` 59 | byte[] buffer; 60 | int offset = 0; 61 | 62 | ABuffer.deserialize(buffer, ref offset); 63 | ``` 64 | 这里的`buffer`可以是从任意地方读取过来的序列化数据,`offset`标记从哪里开始读取. 65 | - 泛型模式序列化代码 66 | ``` 67 | Serializer.serialize(T value, byte[] buffer) 68 | ``` 69 | - 泛型模式反序列化代码 70 | ``` 71 | T value = Serializer.deserialize(byte[] buffer) 72 | ``` -------------------------------------------------------------------------------- /output/templates/csharp_buffer.ftl: -------------------------------------------------------------------------------- 1 | namespace xbuffer 2 | { 3 | public static class #CLASS_NAME#Buffer 4 | { 5 | public static #CLASS_NAME# deserialize(byte[] buffer, ref int offset) 6 | { 7 | #IF_DESERIALIZE_CLASS# 8 | // null 9 | bool _null = boolBuffer.deserialize(buffer, ref offset); 10 | if (_null) return null; 11 | #END_DESERIALIZE_CLASS# 12 | #DESERIALIZE_PROCESS# 13 | // #VAR_NAME# 14 | #IF_SINGLE# 15 | #VAR_TYPE# _#VAR_NAME# = #VAR_TYPE#Buffer.deserialize(buffer, ref offset); 16 | #END_SINGLE# 17 | #IF_ARRAY# 18 | int _#VAR_NAME#_length = intBuffer.deserialize(buffer, ref offset); 19 | #VAR_TYPE#[] _#VAR_NAME# = new #VAR_TYPE#[_#VAR_NAME#_length]; 20 | for (int i = 0; i < _#VAR_NAME#_length; i++) 21 | { 22 | _#VAR_NAME#[i] = #VAR_TYPE#Buffer.deserialize(buffer, ref offset); 23 | } 24 | #END_ARRAY# 25 | #DESERIALIZE_PROCESS# 26 | 27 | // value 28 | return new #CLASS_NAME#() { 29 | #DESERIALIZE_RETURN# 30 | #VAR_NAME# = _#VAR_NAME#, 31 | #DESERIALIZE_RETURN# 32 | }; 33 | } 34 | 35 | public static void serialize(#CLASS_NAME# value, byte[] buffer, ref int offset) 36 | { 37 | #IF_SERIALIZE_CLASS# 38 | // null 39 | boolBuffer.serialize(value == null, buffer, ref offset); 40 | if (value == null) return; 41 | #END_SERIALIZE_CLASS# 42 | #SERIALIZE_PROCESS# 43 | // #VAR_NAME# 44 | #IF_SINGLE# 45 | #VAR_TYPE#Buffer.serialize(value.#VAR_NAME#, buffer, ref offset); 46 | #END_SINGLE# 47 | #IF_ARRAY# 48 | intBuffer.serialize(value.#VAR_NAME#.Length, buffer, ref offset); 49 | for (int i = 0; i < value.#VAR_NAME#.Length; i++) 50 | { 51 | #VAR_TYPE#Buffer.serialize(value.#VAR_NAME#[i], buffer, ref offset); 52 | } 53 | #END_ARRAY# 54 | #SERIALIZE_PROCESS# 55 | } 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /output/templates/csharp_class.ftl: -------------------------------------------------------------------------------- 1 | // #CLASS_COMMENT# 2 | public partial #CLASS_TYPE# #CLASS_NAME# 3 | { 4 | #VARIABLES# 5 | #IF_SINGLE# 6 | public #VAR_TYPE# #VAR_NAME#; // #VAR_COMMENT# 7 | #END_SINGLE# 8 | #IF_ARRAY# 9 | public #VAR_TYPE#[] #VAR_NAME#; // #VAR_COMMENT# 10 | #END_ARRAY# 11 | #VARIABLES# 12 | } -------------------------------------------------------------------------------- /output/templates/ts_buffer.ftl: -------------------------------------------------------------------------------- 1 | #IF_HEAD# 2 | import {numberBuffer, booleanBuffer, stringBuffer} from './xbuffer' 3 | import * as proto from './proto_class' 4 | #END_HEAD# 5 | 6 | export class #CLASS_NAME#Buffer 7 | { 8 | public static deserialize(data:DataView, offset:number) : [proto.#CLASS_NAME#, number] 9 | { 10 | let value = new proto.#CLASS_NAME#(); 11 | #DESERIALIZE_PROCESS# 12 | // #VAR_NAME# 13 | #IF_SINGLE# 14 | [value.#VAR_NAME#, offset] = #VAR_TYPE#Buffer.deserialize(data, offset); 15 | #END_SINGLE# 16 | #IF_ARRAY# 17 | let _#VAR_NAME#_length:number; 18 | [_#VAR_NAME#_length, offset] = numberBuffer.deserialize(data, offset); 19 | for (let i = 0; i < _#VAR_NAME#_length; i++) 20 | { 21 | [value.#VAR_NAME#[i], offset] = #VAR_TYPE#Buffer.deserialize(data, offset); 22 | } 23 | #END_ARRAY# 24 | #DESERIALIZE_PROCESS# 25 | 26 | return [value, offset]; 27 | } 28 | 29 | public static serialize(value:proto.#CLASS_NAME#, data:DataView, offset:number) : number 30 | { 31 | #SERIALIZE_PROCESS# 32 | // #VAR_NAME# 33 | #IF_SINGLE# 34 | offset = #VAR_TYPE#Buffer.serialize(value.#VAR_NAME#, data, offset); 35 | #END_SINGLE# 36 | #IF_ARRAY# 37 | offset = numberBuffer.serialize(value.#VAR_NAME#.length, data, offset); 38 | for (let i = 0; i < value.#VAR_NAME#.length; i++) 39 | { 40 | offset = #VAR_TYPE#Buffer.serialize(value.#VAR_NAME#[i], data, offset); 41 | } 42 | #END_ARRAY# 43 | #SERIALIZE_PROCESS# 44 | 45 | return offset; 46 | } 47 | } -------------------------------------------------------------------------------- /output/templates/ts_class.ftl: -------------------------------------------------------------------------------- 1 | // #CLASS_COMMENT# 2 | export #CLASS_TYPE# #CLASS_NAME# 3 | { 4 | #VARIABLES# 5 | #IF_SINGLE# 6 | public #VAR_NAME#:#VAR_TYPE#; // #VAR_COMMENT# 7 | #END_SINGLE# 8 | #IF_ARRAY# 9 | public #VAR_NAME#:#VAR_TYPE#[]; // #VAR_COMMENT# 10 | #END_ARRAY# 11 | #VARIABLES# 12 | } -------------------------------------------------------------------------------- /output/test.xb: -------------------------------------------------------------------------------- 1 | // A注释02 2 | class A 3 | { 4 | a:[bool]; // 啊啊啊啊啊啊啊 5 | b:[int]; // 棒棒棒棒棒棒棒棒棒棒棒棒 6 | c:[float]; // 才擦擦擦擦擦擦擦擦擦擦 7 | d:[string]; // 顶顶顶顶顶顶顶顶顶 8 | e:[E]; // 呃呃呃呃呃呃呃呃呃 9 | } 10 | 11 | // E注释02 12 | class E 13 | { 14 | a:bool; // 阿爸爸爸爸 15 | b:int; // 哎哎哎 16 | c:float; // 春风吹日此番 17 | d:string; // 多少多少多少的速度 18 | } -------------------------------------------------------------------------------- /output/testCsharp.bat: -------------------------------------------------------------------------------- 1 | xbuffer_parser.exe input=test.xb template="templates/csharp_class.ftl" output_dir="output/csharp/csharp_class/" suffix=".cs" 2 | xbuffer_parser.exe input=test.xb template="templates/csharp_buffer.ftl" output_dir="output/csharp/csharp_buffer/" suffix="Buffer.cs" 3 | pause -------------------------------------------------------------------------------- /output/testTypescript.bat: -------------------------------------------------------------------------------- 1 | xbuffer_parser.exe input=test.xb template="templates/ts_class.ftl" output_file="output/typescript/test" suffix=".ts" 2 | xbuffer_parser.exe input=test.xb template="templates/ts_buffer.ftl" output_file="output/typescript/test" suffix="Buffer.ts" 3 | pause -------------------------------------------------------------------------------- /output/xbuffer_parser.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/CodeZeg/xbuffer/fc81d33154d1444e9643caacaf0a72cb1e7e9ba3/output/xbuffer_parser.exe -------------------------------------------------------------------------------- /output/xbuffer_runtime.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/CodeZeg/xbuffer/fc81d33154d1444e9643caacaf0a72cb1e7e9ba3/output/xbuffer_runtime.dll -------------------------------------------------------------------------------- /test_result.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/CodeZeg/xbuffer/fc81d33154d1444e9643caacaf0a72cb1e7e9ba3/test_result.png -------------------------------------------------------------------------------- /xbuffer.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 15 4 | VisualStudioVersion = 15.0.26430.16 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "xbuffer_runtime", "xbuffer_runtime\xbuffer_runtime.csproj", "{304D8131-C14A-4CEB-B053-2ED2649777EC}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "xbuffer_parser", "xbuffer_parser\xbuffer_parser.csproj", "{00CF1D92-56BD-4048-8F4B-017775DD8C5B}" 9 | EndProject 10 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "xbuffer_test", "xbuffer_test\xbuffer_test.csproj", "{F2948537-984A-4DD4-A15E-58B597C379A0}" 11 | EndProject 12 | Global 13 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 14 | Debug|Any CPU = Debug|Any CPU 15 | Release|Any CPU = Release|Any CPU 16 | EndGlobalSection 17 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 18 | {304D8131-C14A-4CEB-B053-2ED2649777EC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 19 | {304D8131-C14A-4CEB-B053-2ED2649777EC}.Debug|Any CPU.Build.0 = Debug|Any CPU 20 | {304D8131-C14A-4CEB-B053-2ED2649777EC}.Release|Any CPU.ActiveCfg = Release|Any CPU 21 | {304D8131-C14A-4CEB-B053-2ED2649777EC}.Release|Any CPU.Build.0 = Release|Any CPU 22 | {00CF1D92-56BD-4048-8F4B-017775DD8C5B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 23 | {00CF1D92-56BD-4048-8F4B-017775DD8C5B}.Debug|Any CPU.Build.0 = Debug|Any CPU 24 | {00CF1D92-56BD-4048-8F4B-017775DD8C5B}.Release|Any CPU.ActiveCfg = Release|Any CPU 25 | {00CF1D92-56BD-4048-8F4B-017775DD8C5B}.Release|Any CPU.Build.0 = Release|Any CPU 26 | {F2948537-984A-4DD4-A15E-58B597C379A0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 27 | {F2948537-984A-4DD4-A15E-58B597C379A0}.Debug|Any CPU.Build.0 = Debug|Any CPU 28 | {F2948537-984A-4DD4-A15E-58B597C379A0}.Release|Any CPU.ActiveCfg = Release|Any CPU 29 | {F2948537-984A-4DD4-A15E-58B597C379A0}.Release|Any CPU.Build.0 = Release|Any CPU 30 | EndGlobalSection 31 | GlobalSection(SolutionProperties) = preSolution 32 | HideSolutionNode = FALSE 33 | EndGlobalSection 34 | EndGlobal 35 | -------------------------------------------------------------------------------- /xbuffer_parser/Config.cs: -------------------------------------------------------------------------------- 1 | namespace xbuffer 2 | { 3 | class Config 4 | { 5 | public static string input = ""; // 输入文件 6 | public static string template = ""; // 模板文件 7 | public static string output_dir = ""; // 输出目录 8 | public static string output_file = ""; // 输出文件 (仅在打包成单个文件时需要) 9 | public static string suffix = ".cs"; // 文件后缀 10 | 11 | public static bool load(string[] args) 12 | { 13 | foreach (var line in args) 14 | { 15 | var strs = line.Split('='); 16 | if (strs.Length < 2) 17 | continue; 18 | 19 | var key = strs[0]; 20 | var value = strs[1]; 21 | 22 | if (key == "input") input = value; 23 | else if (key == "template") template = value; 24 | else if (key == "output_dir") output_dir = value; 25 | else if (key == "output_file") output_file = value; 26 | else if (key == "suffix") suffix = value; 27 | 28 | //System.Console.WriteLine(key + " = " + value); 29 | } 30 | 31 | if (input == "" || template == "" || (output_dir == "" && output_file == "") || suffix == "") 32 | return false; 33 | 34 | return true; 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /xbuffer_parser/Parser.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * File Name: Parser.cs 3 | * 4 | * Description: 将类对象转化成代码文本 5 | * Author: lisiyu <576603306@qq.com> 6 | * Create Date: 2017/10/25 7 | */ 8 | 9 | namespace xbuffer 10 | { 11 | public class Parser 12 | { 13 | /// 14 | /// 将类对象转化成代码文本 15 | /// 16 | /// 类结构 17 | /// 模板文本 18 | /// 19 | public static string parse(Proto_Class proto_class, string template_str, bool showHead) 20 | { 21 | var template = new XTemplate(template_str); 22 | 23 | template.setCondition("HEAD", showHead); 24 | template.setValue("#CLASS_TYPE#", proto_class.Class_Type); 25 | template.setValue("#CLASS_NAME#", proto_class.Class_Name); 26 | template.setValue("#CLASS_COMMENT#", proto_class.Class_Comment); 27 | 28 | template.setCondition("DESERIALIZE_CLASS", proto_class.Class_Type == "class"); 29 | template.setCondition("SERIALIZE_CLASS", proto_class.Class_Type == "class"); 30 | 31 | if (template.beginLoop("#VARIABLES#")) 32 | { 33 | foreach (var item in proto_class.Class_Variables) 34 | { 35 | template.setCondition("SINGLE", !item.IsArray); 36 | template.setCondition("ARRAY", item.IsArray); 37 | template.setValue("#VAR_TYPE#", item.Var_Type); 38 | template.setValue("#VAR_NAME#", item.Var_Name); 39 | template.setValue("#VAR_COMMENT#", item.Var_Comment); 40 | template.nextLoop(); 41 | } 42 | template.endLoop(); 43 | } 44 | 45 | if (template.beginLoop("#DESERIALIZE_PROCESS#")) 46 | { 47 | foreach (var item in proto_class.Class_Variables) 48 | { 49 | template.setCondition("SINGLE", !item.IsArray); 50 | template.setCondition("ARRAY", item.IsArray); 51 | template.setValue("#VAR_TYPE#", item.Var_Type); 52 | template.setValue("#VAR_NAME#", item.Var_Name); 53 | template.setValue("#VAR_COMMENT#", item.Var_Comment); 54 | template.nextLoop(); 55 | } 56 | template.endLoop(); 57 | } 58 | 59 | if (template.beginLoop("#DESERIALIZE_RETURN#")) 60 | { 61 | foreach (var item in proto_class.Class_Variables) 62 | { 63 | template.setValue("#VAR_TYPE#", item.Var_Type); 64 | template.setValue("#VAR_NAME#", item.Var_Name); 65 | template.setValue("#VAR_COMMENT#", item.Var_Comment); 66 | template.nextLoop(); 67 | } 68 | template.endLoop(); 69 | } 70 | 71 | if (template.beginLoop("#SERIALIZE_PROCESS#")) 72 | { 73 | foreach (var item in proto_class.Class_Variables) 74 | { 75 | template.setCondition("SINGLE", !item.IsArray); 76 | template.setCondition("ARRAY", item.IsArray); 77 | template.setValue("#VAR_TYPE#", item.Var_Type); 78 | template.setValue("#VAR_NAME#", item.Var_Name); 79 | template.setValue("#VAR_COMMENT#", item.Var_Comment); 80 | template.nextLoop(); 81 | } 82 | template.endLoop(); 83 | } 84 | 85 | return template.getContent(); 86 | } 87 | } 88 | } -------------------------------------------------------------------------------- /xbuffer_parser/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | 4 | namespace xbuffer 5 | { 6 | internal class Program 7 | { 8 | private static void Main(string[] args) 9 | { 10 | if (!Config.load(args)) 11 | { 12 | Console.WriteLine("请输入正确的参数!"); 13 | return; 14 | } 15 | 16 | if (!File.Exists(Config.input)) 17 | { 18 | Console.WriteLine("请输入正确的描述文件路径"); 19 | return; 20 | } 21 | 22 | if (!File.Exists(Config.template)) 23 | { 24 | Console.WriteLine("请输入正确的模板文件路径"); 25 | return; 26 | } 27 | 28 | var proto = File.ReadAllText(Config.input); 29 | var proto_classs = new Proto(proto).class_protos; 30 | 31 | var template_str = File.ReadAllText(Config.template); 32 | var template_name = Path.GetFileNameWithoutExtension(Config.template); 33 | 34 | if (Config.output_file == "") 35 | { 36 | Directory.CreateDirectory(Config.output_dir); 37 | } 38 | else 39 | { 40 | Directory.CreateDirectory(Path.GetDirectoryName(Config.output_file)); 41 | } 42 | 43 | var output = ""; 44 | var showHead = true; 45 | foreach (var proto_class in proto_classs) 46 | { 47 | if (Config.output_file == "") 48 | { 49 | output = Parser.parse(proto_class, template_str, showHead); 50 | showHead = false; 51 | File.WriteAllText(Config.output_dir + "/" + proto_class.Class_Name + Config.suffix, output); 52 | } 53 | else 54 | { 55 | output += Parser.parse(proto_class, template_str, showHead); 56 | output += "\n\n"; 57 | showHead = false; 58 | } 59 | } 60 | if (Config.output_file != "") 61 | File.WriteAllText(Config.output_file + Config.suffix, output); 62 | 63 | Console.WriteLine(string.Format("生成完毕 input:{0}, template:{1}", Path.GetFileName(Config.input), Path.GetFileName(Config.template))); 64 | } 65 | } 66 | } -------------------------------------------------------------------------------- /xbuffer_parser/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.InteropServices; 3 | 4 | // 有关程序集的一般信息由以下 控制。更改这些特性值可修改 与程序集关联的信息。 5 | [assembly: AssemblyTitle("xbuffer_parser")] 6 | [assembly: AssemblyDescription("")] 7 | [assembly: AssemblyConfiguration("")] 8 | [assembly: AssemblyCompany("Microsoft")] 9 | [assembly: AssemblyProduct("xbuffer_parser")] 10 | [assembly: AssemblyCopyright("Copyright © Microsoft 2017")] 11 | [assembly: AssemblyTrademark("")] 12 | [assembly: AssemblyCulture("")] 13 | 14 | // 将 ComVisible 设置为 false 会使此程序集中的类型 15 | //对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型 16 | //请将此类型的 ComVisible 特性设置为 true。 17 | [assembly: ComVisible(false)] 18 | 19 | // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID 20 | [assembly: Guid("00cf1d92-56bd-4048-8f4b-017775dd8c5b")] 21 | 22 | // 程序集的版本信息由下列四个值组成: 23 | // 24 | // 主版本 次版本 生成号 修订号 25 | // 26 | // 可以指定所有值,也可以使用以下所示的 "*" 预置版本号和修订号 方法是按如下所示使用“*”: : [assembly: AssemblyVersion("1.0.*")] 27 | [assembly: AssemblyVersion("1.0.0.0")] 28 | [assembly: AssemblyFileVersion("1.0.0.0")] -------------------------------------------------------------------------------- /xbuffer_parser/Proto.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * File Name: Proto.cs 3 | * 4 | * Description: 原型语法解析工具 5 | * Author: lisiyu <576603306@qq.com> 6 | * Create Date: 2017/10/25 7 | */ 8 | 9 | using System.Text.RegularExpressions; 10 | 11 | namespace xbuffer 12 | { 13 | public class Proto 14 | { 15 | public Proto_Class[] class_protos; 16 | 17 | public Proto(string proto) 18 | { 19 | var matchs = Regex.Matches(proto, @"//\s*(\S*)\s*((class)|(struct))\s*(\w+)\s*{\s*((\w+):([\[|\]|\w]+);\s*//\s*(\S*)\s*)*}"); 20 | class_protos = new Proto_Class[matchs.Count]; 21 | for (int i = 0; i < matchs.Count; i++) 22 | { 23 | class_protos[i] = new Proto_Class(matchs[i]); 24 | } 25 | } 26 | } 27 | 28 | /// 29 | /// 变量结构 30 | /// 31 | public class Proto_Variable 32 | { 33 | public string Var_Type; // 变量类型 34 | public string Var_Name; // 变量名 35 | public bool IsArray; // 是否是数组 36 | public string Var_Comment; // 变量注释 37 | 38 | public Proto_Variable(string name, string type, string comment) 39 | { 40 | Var_Name = name; 41 | if (type.Contains("[")) 42 | { 43 | Var_Type = type.Substring(1, type.Length - 2); 44 | IsArray = true; 45 | } 46 | else 47 | { 48 | Var_Type = type; 49 | IsArray = false; 50 | } 51 | Var_Comment = comment; 52 | } 53 | } 54 | 55 | /// 56 | /// 类结构 57 | /// 58 | public class Proto_Class 59 | { 60 | public string Class_Comment; // 注释 61 | public string Class_Type; // 类型 例如 class struct 62 | public string Class_Name; // 类名 63 | public Proto_Variable[] Class_Variables; // 变量列表 64 | 65 | public Proto_Class(Match match) 66 | { 67 | Class_Comment = match.Groups[1].Value; 68 | Class_Type = match.Groups[2].Value; 69 | Class_Name = match.Groups[5].Value; 70 | 71 | var varNames = match.Groups[7].Captures; 72 | var varTypes = match.Groups[8].Captures; 73 | var varComments = match.Groups[9].Captures; 74 | Class_Variables = new Proto_Variable[varNames.Count]; 75 | for (int i = 0; i < Class_Variables.Length; i++) 76 | { 77 | Class_Variables[i] = new Proto_Variable(varNames[i].Value, varTypes[i].Value, varComments[i].Value); 78 | } 79 | } 80 | } 81 | } -------------------------------------------------------------------------------- /xbuffer_parser/XTemplate.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * File Name: XTemplate.cs 3 | * 4 | * Description: 模板处理 简化生成代码的过程 5 | * Author: lisiyu <576603306@qq.com> 6 | * Create Date: 2017/10/25 7 | */ 8 | 9 | using System.Text.RegularExpressions; 10 | public class XTemplate 11 | { 12 | private string mContent; // 当前内容 13 | 14 | private bool mIsLooping; // 处于循环中 15 | private string mLoopTemplate_Cell; // 循环的内容模板 16 | private string mLoopContent_Cell; // 循环的内容(单元) 17 | private string mLoopContent_All; // 循环内容容器(全部) 18 | 19 | private const string LOOPHOLDER = "#TEMP_LOOP_HOLDER#"; // 循环占位符 20 | 21 | public XTemplate(string template) 22 | { 23 | mContent = template; 24 | mIsLooping = false; 25 | mLoopTemplate_Cell = ""; 26 | mLoopContent_Cell = ""; 27 | mLoopContent_All = ""; 28 | } 29 | 30 | /// 31 | /// 返回结果 32 | /// 33 | /// 34 | public string getContent() 35 | { 36 | return mContent; 37 | } 38 | 39 | /// 40 | /// 设置值 41 | /// 42 | /// 需要替换的key 43 | /// 需要赋值的value 44 | public void setValue(string key, string value) 45 | { 46 | if (mIsLooping) 47 | { 48 | mLoopContent_Cell = mLoopContent_Cell.Replace(key, value); 49 | } 50 | else 51 | { 52 | mContent = mContent.Replace(key, value); 53 | } 54 | } 55 | 56 | /// 57 | /// 设置条件 不满足条件将被剔除 58 | /// 59 | /// 条件key 60 | /// 条件值 61 | public void setCondition(string condition, bool value) 62 | { 63 | if (mIsLooping) 64 | { 65 | mLoopContent_Cell = Regex.Replace(mLoopContent_Cell, string.Format(@"#IF_{0}#((\S|\s)*)#END_{0}#", condition), (match) => 66 | { 67 | if (value) 68 | { 69 | return match.Groups[1].Value; 70 | } 71 | else 72 | { 73 | return ""; 74 | } 75 | }); 76 | } 77 | else 78 | { 79 | mContent = Regex.Replace(mContent, string.Format(@"#IF_{0}#((\S|\s)*)#END_{0}#", condition), (match) => 80 | { 81 | if (value) 82 | { 83 | return match.Groups[1].Value; 84 | } 85 | else 86 | { 87 | return ""; 88 | } 89 | }); 90 | } 91 | } 92 | 93 | /// 94 | /// 开始循环 95 | /// 96 | /// 97 | public bool beginLoop(string key) 98 | { 99 | if (!Regex.IsMatch(mContent, string.Format(@"{0}(\s*(\S|\s)*)\s*{0}", key))) 100 | return false; 101 | 102 | mContent = Regex.Replace(mContent, string.Format(@"{0}(\s*(\S|\s)*)\s*{0}", key), (match) => 103 | { 104 | mLoopTemplate_Cell = match.Groups[1].Value; 105 | return LOOPHOLDER; 106 | }); 107 | 108 | mIsLooping = true; 109 | mLoopContent_All = ""; 110 | mLoopContent_Cell = mLoopTemplate_Cell; 111 | return true; 112 | } 113 | 114 | /// 115 | /// 循环下一步 116 | /// 117 | public void nextLoop() 118 | { 119 | mLoopContent_All += mLoopContent_Cell; 120 | mLoopContent_Cell = mLoopTemplate_Cell; 121 | } 122 | 123 | /// 124 | /// 终止循环 125 | /// 126 | public void endLoop() 127 | { 128 | mIsLooping = false; 129 | mLoopContent_All = mLoopContent_All.Replace("\r\n\r\n", "\r\n"); 130 | mLoopContent_All = mLoopContent_All.Replace("\r\n\r\n", "\r\n"); 131 | mLoopContent_All = mLoopContent_All.Replace("\r\n\r\n", "\r\n"); 132 | mLoopContent_All = mLoopContent_All.TrimStart("\r\n".ToCharArray()); 133 | mLoopContent_All = mLoopContent_All.TrimEnd("\r\n".ToCharArray()); 134 | setValue(LOOPHOLDER, mLoopContent_All); 135 | mLoopTemplate_Cell = ""; 136 | mLoopContent_Cell = ""; 137 | mLoopContent_All = ""; 138 | } 139 | } -------------------------------------------------------------------------------- /xbuffer_parser/xbuffer_parser.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {00CF1D92-56BD-4048-8F4B-017775DD8C5B} 8 | Exe 9 | xbuffer_parser 10 | xbuffer_parser 11 | v4.5.2 12 | 512 13 | true 14 | 15 | 16 | AnyCPU 17 | true 18 | full 19 | false 20 | ..\output\ 21 | DEBUG;TRACE 22 | prompt 23 | 4 24 | 25 | 26 | AnyCPU 27 | none 28 | true 29 | ..\output\ 30 | 31 | 32 | none 33 | 4 34 | true 35 | Off 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | -------------------------------------------------------------------------------- /xbuffer_runtime/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.InteropServices; 3 | 4 | // 有关程序集的一般信息由以下 控制。更改这些特性值可修改 与程序集关联的信息。 5 | [assembly: AssemblyTitle("xbuffer_runtime")] 6 | [assembly: AssemblyDescription("")] 7 | [assembly: AssemblyConfiguration("")] 8 | [assembly: AssemblyCompany("Microsoft")] 9 | [assembly: AssemblyProduct("xbuffer_runtime")] 10 | [assembly: AssemblyCopyright("Copyright © Microsoft 2017")] 11 | [assembly: AssemblyTrademark("")] 12 | [assembly: AssemblyCulture("")] 13 | 14 | // 将 ComVisible 设置为 false 会使此程序集中的类型 15 | //对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型 16 | //请将此类型的 ComVisible 特性设置为 true。 17 | [assembly: ComVisible(false)] 18 | 19 | // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID 20 | [assembly: Guid("304d8131-c14a-4ceb-b053-2ed2649777ec")] 21 | 22 | // 程序集的版本信息由下列四个值组成: 23 | // 24 | // 主版本 25 | // 次版本 26 | // 生成号 27 | // 修订号 28 | // 29 | // 可以指定所有值,也可以使用以下所示的 "*" 预置版本号和修订号 30 | //通过使用 "*",如下所示: 31 | // [assembly: AssemblyVersion("1.0.*")] 32 | [assembly: AssemblyVersion("1.0.0.0")] 33 | [assembly: AssemblyFileVersion("1.0.0.0")] -------------------------------------------------------------------------------- /xbuffer_runtime/Serializer.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * File Name: Serializer.cs 3 | * 4 | * Description: 泛型接口 5 | * Author: lisiyu <576603306@qq.com> 6 | * Create Date: 2017/10/25 7 | */ 8 | 9 | using System; 10 | 11 | namespace xbuffer 12 | { 13 | public class Serializer 14 | { 15 | public static XSteam cachedSteam; 16 | 17 | public static void serialize(T value) 18 | { 19 | if (cachedSteam == null) 20 | throw new NullReferenceException(); 21 | 22 | cachedSteam.index_cell = 0; 23 | cachedSteam.index_group = 0; 24 | 25 | var bufferType = typeof(T).Assembly.GetType(string.Format("xbuffer.{0}Buffer", typeof(T).FullName)); 26 | var method = bufferType.GetMethod("serialize", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public); 27 | var args = new object[] { value, cachedSteam }; 28 | method.Invoke(null, args); 29 | } 30 | 31 | 32 | public static T deserialize(byte[] buffer) 33 | { 34 | uint offset = 0; 35 | return deserialize(buffer, ref offset); 36 | } 37 | 38 | public static T deserialize(byte[] buffer, ref uint offset) 39 | { 40 | var bufferType = typeof(T).Assembly.GetType(string.Format("xbuffer.{0}Buffer", typeof(T).FullName)); 41 | var method = bufferType.GetMethod("deserialize", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public); 42 | var args = new object[] { buffer, offset }; 43 | var ret = (T)method.Invoke(null, args); 44 | offset = (uint)args[1]; 45 | return ret; 46 | } 47 | } 48 | } -------------------------------------------------------------------------------- /xbuffer_runtime/XSteam.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * File Name: XSteam.cs 3 | * 4 | * Description: 一个简单的内存流实现 用于精准的控制内存管理 5 | * Author: lisiyu <576603306@qq.com> 6 | * Create Date: 2018/04/09 7 | */ 8 | 9 | namespace xbuffer 10 | { 11 | public class XSteam 12 | { 13 | public uint index_group; // 当前组别序号 行 14 | public uint index_cell; // 当前单元序号 列 15 | 16 | public uint capacity_group; // 行的数量 17 | public uint capacity_cell; // 列的数量 18 | public byte[][] contents; // 内容列表 19 | public uint[] wastes; // 浪费列表 对应每一行 20 | 21 | public XSteam(uint capacity_group, uint capacity_cell) 22 | { 23 | this.capacity_group = capacity_group; 24 | this.capacity_cell = capacity_cell; 25 | 26 | contents = new byte[capacity_group][]; 27 | for (int i = 0; i < capacity_group; i++) 28 | { 29 | contents[i] = new byte[capacity_cell]; 30 | } 31 | wastes = new uint[capacity_group]; 32 | } 33 | 34 | /// 35 | /// 申请空间 36 | /// 基本策略是不够了就申请一倍 37 | /// 38 | /// 39 | public void applySize(uint size) 40 | { 41 | if (index_cell + size > capacity_cell) 42 | { 43 | wastes[index_group] = capacity_cell - index_cell; 44 | index_cell = 0; 45 | index_group++; 46 | if (index_group >= capacity_group) 47 | { 48 | var nCapacity_Group = capacity_group + 1; 49 | 50 | var nContents = new byte[nCapacity_Group][]; 51 | for (uint i = 0; i < nCapacity_Group; i++) 52 | { 53 | if (i < capacity_group) 54 | nContents[i] = contents[i]; 55 | else 56 | nContents[i] = new byte[capacity_cell]; 57 | } 58 | contents = nContents; 59 | 60 | var nWastes = new uint[nCapacity_Group]; 61 | for (uint i = 0; i < capacity_group; i++) 62 | { 63 | nWastes[i] = wastes[i]; 64 | } 65 | wastes = nWastes; 66 | 67 | capacity_group = nCapacity_Group; 68 | } 69 | } 70 | } 71 | 72 | /// 73 | /// 返回输出字节流 74 | /// 75 | /// 76 | public byte[] getBytes() 77 | { 78 | var len = index_group * capacity_cell + index_cell; 79 | for (int i = 0; i < index_group; i++) 80 | { 81 | len -= wastes[i]; 82 | } 83 | 84 | var ret = new byte[len]; 85 | var idx = 0; 86 | for (int i = 0; i < index_group; i++) 87 | { 88 | for (int j = 0; j < capacity_cell - wastes[i]; j++) 89 | { 90 | ret[idx++] = contents[i][j]; 91 | } 92 | } 93 | for (int i = 0; i < index_cell; i++) 94 | { 95 | ret[idx++] = contents[index_group][i]; 96 | } 97 | 98 | return ret; 99 | } 100 | } 101 | } -------------------------------------------------------------------------------- /xbuffer_runtime/boolBuffer.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * File Name: boolBuffer.cs 3 | * 4 | * Description: 基本类型处理 5 | * Author: lisiyu <576603306@qq.com> 6 | * Create Date: 2017/10/25 7 | */ 8 | 9 | namespace xbuffer 10 | { 11 | public class boolBuffer 12 | { 13 | private static readonly uint size = sizeof(bool); 14 | 15 | public unsafe static bool deserialize(byte[] buffer, ref uint offset) 16 | { 17 | fixed (byte* ptr = buffer) 18 | { 19 | var value = *(bool*)(ptr + offset); 20 | offset += size; 21 | return value; 22 | } 23 | } 24 | 25 | public unsafe static void serialize(bool value, XSteam steam) 26 | { 27 | steam.applySize(size); 28 | fixed (byte* ptr = steam.contents[steam.index_group]) 29 | { 30 | *(bool*)(ptr + steam.index_cell) = value; 31 | steam.index_cell += size; 32 | } 33 | } 34 | } 35 | } -------------------------------------------------------------------------------- /xbuffer_runtime/byteBuffer.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * File Name: byteBuffer.cs 3 | * 4 | * Description: 基本类型处理 5 | * Author: lisiyu <576603306@qq.com> 6 | * Create Date: 2017/11/09 7 | */ 8 | 9 | namespace xbuffer 10 | { 11 | public class byteBuffer 12 | { 13 | private static readonly uint size = sizeof(byte); 14 | 15 | public unsafe static byte deserialize(byte[] buffer, ref uint offset) 16 | { 17 | var value = buffer[offset]; 18 | offset += size; 19 | return value; 20 | } 21 | 22 | public unsafe static void serialize(byte value, XSteam steam) 23 | { 24 | steam.applySize(size); 25 | steam.contents[steam.index_group][steam.index_cell] = value; 26 | steam.index_cell += size; 27 | } 28 | } 29 | } -------------------------------------------------------------------------------- /xbuffer_runtime/floatBuffer.cs: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/CodeZeg/xbuffer/fc81d33154d1444e9643caacaf0a72cb1e7e9ba3/xbuffer_runtime/floatBuffer.cs -------------------------------------------------------------------------------- /xbuffer_runtime/intBuffer.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * File Name: intBuffer.cs 3 | * 4 | * Description: 基本类型处理 5 | * Author: lisiyu <576603306@qq.com> 6 | * Create Date: 2017/10/25 7 | */ 8 | 9 | using System; 10 | 11 | namespace xbuffer 12 | { 13 | public class intBuffer 14 | { 15 | private static readonly uint size = sizeof(int); 16 | 17 | public unsafe static int deserialize(byte[] buffer, ref uint offset) 18 | { 19 | fixed (byte* ptr = buffer) 20 | { 21 | var value = *(int*)(ptr + offset); 22 | offset += size; 23 | return BitConverter.IsLittleEndian ? value : (int)utils.toLittleEndian((uint)value); 24 | } 25 | } 26 | 27 | public unsafe static void serialize(int value, XSteam steam) 28 | { 29 | steam.applySize(size); 30 | fixed (byte* ptr = steam.contents[steam.index_group]) 31 | { 32 | *(int*)(ptr + steam.index_cell) = BitConverter.IsLittleEndian ? value : (int)utils.toLittleEndian((uint)value); 33 | steam.index_cell += size; 34 | } 35 | } 36 | } 37 | } -------------------------------------------------------------------------------- /xbuffer_runtime/longBuffer.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * File Name: longBuffer.cs 3 | * 4 | * Description: 基本类型处理 5 | * Author: lisiyu <576603306@qq.com> 6 | * Create Date: 2017/10/25 7 | */ 8 | 9 | using System; 10 | 11 | namespace xbuffer 12 | { 13 | public class longBuffer 14 | { 15 | private static readonly uint size = sizeof(long); 16 | 17 | public unsafe static long deserialize(byte[] buffer, ref uint offset) 18 | { 19 | fixed (byte* ptr = buffer) 20 | { 21 | var value = *(long*)(ptr + offset); 22 | offset += size; 23 | return BitConverter.IsLittleEndian ? value : (long)utils.toLittleEndian((ulong)value); 24 | } 25 | } 26 | 27 | public unsafe static void serialize(long value, XSteam steam) 28 | { 29 | steam.applySize(size); 30 | fixed (byte* ptr = steam.contents[steam.index_group]) 31 | { 32 | *(long*)(ptr + steam.index_cell) = BitConverter.IsLittleEndian ? value : (long)utils.toLittleEndian((ulong)value); 33 | steam.index_cell += size; 34 | } 35 | } 36 | } 37 | } -------------------------------------------------------------------------------- /xbuffer_runtime/stringBuffer.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * File Name: stringBuffer.cs 3 | * 4 | * Description: 基本类型处理 5 | * Author: lisiyu <576603306@qq.com> 6 | * Create Date: 2017/10/25 7 | */ 8 | 9 | using System.Text; 10 | 11 | namespace xbuffer 12 | { 13 | public class stringBuffer 14 | { 15 | public unsafe static string deserialize(byte[] buffer, ref uint offset) 16 | { 17 | fixed (byte* ptr = buffer) 18 | { 19 | uint byteCount = uintBuffer.deserialize(buffer, ref offset); 20 | string value = Encoding.UTF8.GetString(buffer, (int)offset, (int)byteCount); 21 | offset += byteCount; 22 | return value; 23 | } 24 | } 25 | 26 | public unsafe static void serialize(string value, XSteam steam) 27 | { 28 | var bytes = Encoding.UTF8.GetBytes(value); 29 | uintBuffer.serialize((uint)bytes.Length, steam); 30 | for (int i = 0; i < bytes.Length; i++) 31 | { 32 | steam.applySize(1); 33 | steam.contents[steam.index_group][steam.index_cell] = bytes[i]; 34 | steam.index_cell += 1; 35 | } 36 | } 37 | } 38 | } -------------------------------------------------------------------------------- /xbuffer_runtime/uintBuffer.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * File Name: uintBuffer.cs 3 | * 4 | * Description: 基本类型处理 5 | * Author: lisiyu <576603306@qq.com> 6 | * Create Date: 2017/10/25 7 | */ 8 | 9 | using System; 10 | 11 | namespace xbuffer 12 | { 13 | public class uintBuffer 14 | { 15 | private static readonly uint size = sizeof(uint); 16 | 17 | public unsafe static uint deserialize(byte[] buffer, ref uint offset) 18 | { 19 | fixed (byte* ptr = buffer) 20 | { 21 | var value = *(uint*)(ptr + offset); 22 | offset += size; 23 | return BitConverter.IsLittleEndian ? value : utils.toLittleEndian(value); 24 | } 25 | } 26 | 27 | public unsafe static void serialize(uint value, XSteam steam) 28 | { 29 | steam.applySize(size); 30 | fixed (byte* ptr = steam.contents[steam.index_group]) 31 | { 32 | *(uint*)(ptr + steam.index_cell) = BitConverter.IsLittleEndian ? value : utils.toLittleEndian(value); 33 | steam.index_cell += size; 34 | } 35 | } 36 | } 37 | } -------------------------------------------------------------------------------- /xbuffer_runtime/utils.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * File Name: utils.cs 3 | * 4 | * Description: 基本工具集 用于处理大小端等逻辑 5 | * Author: lisiyu <576603306@qq.com> 6 | * Create Date: 2017/10/25 7 | */ 8 | 9 | namespace xbuffer 10 | { 11 | public class utils 12 | { 13 | public static uint toLittleEndian(uint value) 14 | { 15 | return ((value & 0x000000FFU) << 24) | 16 | ((value & 0x0000FF00U) << 8) | 17 | ((value & 0x00FF0000U) >> 8) | 18 | ((value & 0xFF000000U) >> 24); 19 | } 20 | 21 | public static ulong toLittleEndian(ulong value) 22 | { 23 | return (((value & 0x00000000000000FFUL) << 56) | 24 | ((value & 0x000000000000FF00UL) << 40) | 25 | ((value & 0x0000000000FF0000UL) << 24) | 26 | ((value & 0x00000000FF000000UL) << 8) | 27 | ((value & 0x000000FF00000000UL) >> 8) | 28 | ((value & 0x0000FF0000000000UL) >> 24) | 29 | ((value & 0x00FF000000000000UL) >> 40) | 30 | ((value & 0xFF00000000000000UL) >> 56)); 31 | } 32 | } 33 | } -------------------------------------------------------------------------------- /xbuffer_runtime/xbuffer_runtime.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {304D8131-C14A-4CEB-B053-2ED2649777EC} 8 | Library 9 | Properties 10 | xbuffer_runtime 11 | xbuffer_runtime 12 | v3.5 13 | 512 14 | Unity Full v3.5 15 | 16 | 17 | true 18 | full 19 | true 20 | ..\output\ 21 | TRACE;DEBUG 22 | prompt 23 | 4 24 | true 25 | 26 | 27 | none 28 | true 29 | ..\output\ 30 | 31 | 32 | none 33 | 4 34 | true 35 | Off 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | -------------------------------------------------------------------------------- /xbuffer_test/App.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /xbuffer_test/FlatBuffers/FlatBufferConstants.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 Google Inc. All rights reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | namespace FlatBuffers 18 | { 19 | public static class FlatBufferConstants 20 | { 21 | public const int FileIdentifierLength = 4; 22 | } 23 | } -------------------------------------------------------------------------------- /xbuffer_test/FlatBuffers/IFlatbufferObject.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 Google Inc. All rights reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | namespace FlatBuffers 18 | { 19 | /// 20 | /// This is the base for both structs and tables. 21 | /// 22 | public interface IFlatbufferObject 23 | { 24 | void __init(int _i, ByteBuffer _bb); 25 | 26 | ByteBuffer ByteBuffer { get; } 27 | } 28 | } -------------------------------------------------------------------------------- /xbuffer_test/FlatBuffers/Offset.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 Google Inc. All rights reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | namespace FlatBuffers 18 | { 19 | /// 20 | /// Offset class for typesafe assignments. 21 | /// 22 | public struct Offset where T : class 23 | { 24 | public int Value; 25 | 26 | public Offset(int value) 27 | { 28 | Value = value; 29 | } 30 | } 31 | 32 | public struct StringOffset 33 | { 34 | public int Value; 35 | 36 | public StringOffset(int value) 37 | { 38 | Value = value; 39 | } 40 | } 41 | 42 | public struct VectorOffset 43 | { 44 | public int Value; 45 | 46 | public VectorOffset(int value) 47 | { 48 | Value = value; 49 | } 50 | } 51 | } -------------------------------------------------------------------------------- /xbuffer_test/FlatBuffers/Struct.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 Google Inc. All rights reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | namespace FlatBuffers 18 | { 19 | /// 20 | /// All structs in the generated code derive from this class, and add their own accessors. 21 | /// 22 | public abstract class Struct 23 | { 24 | public int bb_pos; 25 | public ByteBuffer bb; 26 | } 27 | } -------------------------------------------------------------------------------- /xbuffer_test/FlatBuffers/Table.cs: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2014 Google Inc. All rights reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | using System; 18 | using System.Text; 19 | 20 | namespace FlatBuffers 21 | { 22 | /// 23 | /// All tables in the generated code derive from this struct, and add their own accessors. 24 | /// 25 | public abstract class Table 26 | { 27 | public int bb_pos; 28 | public ByteBuffer bb; 29 | 30 | public ByteBuffer ByteBuffer { get { return bb; } } 31 | 32 | // Look up a field in the vtable, return an offset into the object, or 0 if the field is not present. 33 | public int __offset(int vtableOffset) 34 | { 35 | int vtable = bb_pos - bb.GetInt(bb_pos); 36 | return vtableOffset < bb.GetShort(vtable) ? (int)bb.GetShort(vtable + vtableOffset) : 0; 37 | } 38 | 39 | public static int __offset(int vtableOffset, int offset, ByteBuffer bb) 40 | { 41 | int vtable = bb.Length - offset; 42 | return (int)bb.GetShort(vtable + vtableOffset - bb.GetInt(vtable)) + vtable; 43 | } 44 | 45 | // Retrieve the relative offset stored at "offset" 46 | public int __indirect(int offset) 47 | { 48 | return offset + bb.GetInt(offset); 49 | } 50 | 51 | public static int __indirect(int offset, ByteBuffer bb) 52 | { 53 | return offset + bb.GetInt(offset); 54 | } 55 | 56 | // Create a .NET String from UTF-8 data stored inside the flatbuffer. 57 | public string __string(int offset) 58 | { 59 | offset += bb.GetInt(offset); 60 | var len = bb.GetInt(offset); 61 | var startPos = offset + sizeof(int); 62 | return Encoding.UTF8.GetString(bb.Data, startPos, len); 63 | } 64 | 65 | // Get the length of a vector whose offset is stored at "offset" in this object. 66 | public int __vector_len(int offset) 67 | { 68 | offset += bb_pos; 69 | offset += bb.GetInt(offset); 70 | return bb.GetInt(offset); 71 | } 72 | 73 | // Get the start of data of a vector whose offset is stored at "offset" in this object. 74 | public int __vector(int offset) 75 | { 76 | offset += bb_pos; 77 | return offset + bb.GetInt(offset) + sizeof(int); // data starts after the length 78 | } 79 | 80 | // Get the data of a vector whoses offset is stored at "offset" in this object as an 81 | // ArraySegment<byte>. If the vector is not present in the ByteBuffer, then a null 82 | // value will be returned. 83 | public ArraySegment? __vector_as_arraysegment(int offset) 84 | { 85 | var o = this.__offset(offset); 86 | if (0 == o) 87 | { 88 | return null; 89 | } 90 | 91 | var pos = this.__vector(o); 92 | var len = this.__vector_len(o); 93 | return new ArraySegment(this.bb.Data, pos, len); 94 | } 95 | 96 | // Initialize any Table-derived type to point to the union at the given offset. 97 | public T __union(int offset) where T : struct, IFlatbufferObject 98 | { 99 | offset += bb_pos; 100 | T t = new T(); 101 | t.__init(offset + bb.GetInt(offset), bb); 102 | return t; 103 | } 104 | 105 | public static bool __has_identifier(ByteBuffer bb, string ident) 106 | { 107 | if (ident.Length != FlatBufferConstants.FileIdentifierLength) 108 | throw new ArgumentException("FlatBuffers: file identifier must be length " + FlatBufferConstants.FileIdentifierLength, "ident"); 109 | 110 | for (var i = 0; i < FlatBufferConstants.FileIdentifierLength; i++) 111 | { 112 | if (ident[i] != (char)bb.Get(bb.Position + sizeof(int) + i)) return false; 113 | } 114 | 115 | return true; 116 | } 117 | 118 | // Compare strings in the ByteBuffer. 119 | public static int CompareStrings(int offset_1, int offset_2, ByteBuffer bb) 120 | { 121 | offset_1 += bb.GetInt(offset_1); 122 | offset_2 += bb.GetInt(offset_2); 123 | var len_1 = bb.GetInt(offset_1); 124 | var len_2 = bb.GetInt(offset_2); 125 | var startPos_1 = offset_1 + sizeof(int); 126 | var startPos_2 = offset_2 + sizeof(int); 127 | var len = Math.Min(len_1, len_2); 128 | byte[] bbArray = bb.Data; 129 | for (int i = 0; i < len; i++) 130 | { 131 | if (bbArray[i + startPos_1] != bbArray[i + startPos_2]) 132 | return bbArray[i + startPos_1] - bbArray[i + startPos_2]; 133 | } 134 | return len_1 - len_2; 135 | } 136 | 137 | // Compare string from the ByteBuffer with the string object 138 | public static int CompareStrings(int offset_1, byte[] key, ByteBuffer bb) 139 | { 140 | offset_1 += bb.GetInt(offset_1); 141 | var len_1 = bb.GetInt(offset_1); 142 | var len_2 = key.Length; 143 | var startPos_1 = offset_1 + sizeof(int); 144 | var len = Math.Min(len_1, len_2); 145 | byte[] bbArray = bb.Data; 146 | for (int i = 0; i < len; i++) 147 | { 148 | if (bbArray[i + startPos_1] != key[i]) 149 | return bbArray[i + startPos_1] - key[i]; 150 | } 151 | return len_1 - len_2; 152 | } 153 | } 154 | } -------------------------------------------------------------------------------- /xbuffer_test/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.InteropServices; 3 | 4 | // 有关程序集的一般信息由以下 控制。更改这些特性值可修改 与程序集关联的信息。 5 | [assembly: AssemblyTitle("xbuffer_test")] 6 | [assembly: AssemblyDescription("")] 7 | [assembly: AssemblyConfiguration("")] 8 | [assembly: AssemblyCompany("Microsoft")] 9 | [assembly: AssemblyProduct("xbuffer_test")] 10 | [assembly: AssemblyCopyright("Copyright © Microsoft 2017")] 11 | [assembly: AssemblyTrademark("")] 12 | [assembly: AssemblyCulture("")] 13 | 14 | // 将 ComVisible 设置为 false 会使此程序集中的类型 15 | //对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型 16 | //请将此类型的 ComVisible 特性设置为 true。 17 | [assembly: ComVisible(false)] 18 | 19 | // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID 20 | [assembly: Guid("f2948537-984a-4dd4-a15e-58b597c379a0")] 21 | 22 | // 程序集的版本信息由下列四个值组成: 23 | // 24 | // 主版本 次版本 生成号 修订号 25 | // 26 | // 可以指定所有值,也可以使用以下所示的 "*" 预置版本号和修订号 方法是按如下所示使用“*”: : [assembly: AssemblyVersion("1.0.*")] 27 | [assembly: AssemblyVersion("1.0.0.0")] 28 | [assembly: AssemblyFileVersion("1.0.0.0")] -------------------------------------------------------------------------------- /xbuffer_test/output_csharp_buffer/ABuffer.cs: -------------------------------------------------------------------------------- 1 | namespace xbuffer 2 | { 3 | public static class ABuffer 4 | { 5 | public static A deserialize(byte[] buffer, ref uint offset) 6 | { 7 | // null 8 | bool _null = boolBuffer.deserialize(buffer, ref offset); 9 | if (_null) return null; 10 | 11 | // a 12 | int _a_length = intBuffer.deserialize(buffer, ref offset); 13 | bool[] _a = new bool[_a_length]; 14 | for (int i = 0; i < _a_length; i++) 15 | { 16 | _a[i] = boolBuffer.deserialize(buffer, ref offset); 17 | } 18 | // b 19 | int _b_length = intBuffer.deserialize(buffer, ref offset); 20 | int[] _b = new int[_b_length]; 21 | for (int i = 0; i < _b_length; i++) 22 | { 23 | _b[i] = intBuffer.deserialize(buffer, ref offset); 24 | } 25 | // c 26 | int _c_length = intBuffer.deserialize(buffer, ref offset); 27 | float[] _c = new float[_c_length]; 28 | for (int i = 0; i < _c_length; i++) 29 | { 30 | _c[i] = floatBuffer.deserialize(buffer, ref offset); 31 | } 32 | // d 33 | int _d_length = intBuffer.deserialize(buffer, ref offset); 34 | string[] _d = new string[_d_length]; 35 | for (int i = 0; i < _d_length; i++) 36 | { 37 | _d[i] = stringBuffer.deserialize(buffer, ref offset); 38 | } 39 | // e 40 | int _e_length = intBuffer.deserialize(buffer, ref offset); 41 | E[] _e = new E[_e_length]; 42 | for (int i = 0; i < _e_length; i++) 43 | { 44 | _e[i] = EBuffer.deserialize(buffer, ref offset); 45 | } 46 | 47 | // value 48 | return new A() 49 | { 50 | a = _a, 51 | b = _b, 52 | c = _c, 53 | d = _d, 54 | e = _e, 55 | }; 56 | } 57 | 58 | public static void serialize(A value, XSteam steam) 59 | { 60 | // null 61 | boolBuffer.serialize(value == null, steam); 62 | if (value == null) return; 63 | 64 | // a 65 | intBuffer.serialize(value.a.Length, steam); 66 | for (int i = 0; i < value.a.Length; i++) 67 | { 68 | boolBuffer.serialize(value.a[i], steam); 69 | } 70 | // b 71 | intBuffer.serialize(value.b.Length, steam); 72 | for (int i = 0; i < value.b.Length; i++) 73 | { 74 | intBuffer.serialize(value.b[i], steam); 75 | } 76 | // c 77 | intBuffer.serialize(value.c.Length, steam); 78 | for (int i = 0; i < value.c.Length; i++) 79 | { 80 | floatBuffer.serialize(value.c[i], steam); 81 | } 82 | // d 83 | intBuffer.serialize(value.d.Length, steam); 84 | for (int i = 0; i < value.d.Length; i++) 85 | { 86 | stringBuffer.serialize(value.d[i], steam); 87 | } 88 | // e 89 | intBuffer.serialize(value.e.Length, steam); 90 | for (int i = 0; i < value.e.Length; i++) 91 | { 92 | EBuffer.serialize(value.e[i], steam); 93 | } 94 | } 95 | } 96 | } -------------------------------------------------------------------------------- /xbuffer_test/output_csharp_buffer/EBuffer.cs: -------------------------------------------------------------------------------- 1 | namespace xbuffer 2 | { 3 | public static class EBuffer 4 | { 5 | public static E deserialize(byte[] buffer, ref uint offset) 6 | { 7 | // null 8 | bool _null = boolBuffer.deserialize(buffer, ref offset); 9 | if (_null) return null; 10 | 11 | // a 12 | bool _a = boolBuffer.deserialize(buffer, ref offset); 13 | // b 14 | int _b = intBuffer.deserialize(buffer, ref offset); 15 | // c 16 | float _c = floatBuffer.deserialize(buffer, ref offset); 17 | // d 18 | string _d = stringBuffer.deserialize(buffer, ref offset); 19 | 20 | // value 21 | return new E() 22 | { 23 | a = _a, 24 | b = _b, 25 | c = _c, 26 | d = _d, 27 | }; 28 | } 29 | 30 | public static void serialize(E value, XSteam steam) 31 | { 32 | // null 33 | boolBuffer.serialize(value == null, steam); 34 | if (value == null) return; 35 | 36 | // a 37 | boolBuffer.serialize(value.a, steam); 38 | // b 39 | intBuffer.serialize(value.b, steam); 40 | // c 41 | floatBuffer.serialize(value.c, steam); 42 | // d 43 | stringBuffer.serialize(value.d, steam); 44 | } 45 | } 46 | } -------------------------------------------------------------------------------- /xbuffer_test/output_csharp_class/A.cs: -------------------------------------------------------------------------------- 1 | public partial class A 2 | { 3 | public bool[] a; 4 | public int[] b; 5 | public float[] c; 6 | public string[] d; 7 | public E[] e; 8 | } -------------------------------------------------------------------------------- /xbuffer_test/output_csharp_class/E.cs: -------------------------------------------------------------------------------- 1 | public partial class E 2 | { 3 | public bool a; 4 | public int b; 5 | public float c; 6 | public string d; 7 | } -------------------------------------------------------------------------------- /xbuffer_test/protobuf-net/BufferExtension.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.IO; 3 | 4 | namespace ProtoBuf 5 | { 6 | /// 7 | /// Provides a simple buffer-based implementation of an extension object. 8 | /// 9 | public sealed class BufferExtension : IExtension 10 | { 11 | private byte[] buffer; 12 | 13 | int IExtension.GetLength() 14 | { 15 | return buffer == null ? 0 : buffer.Length; 16 | } 17 | 18 | Stream IExtension.BeginAppend() 19 | { 20 | return new MemoryStream(); 21 | } 22 | 23 | void IExtension.EndAppend(Stream stream, bool commit) 24 | { 25 | using (stream) 26 | { 27 | int len; 28 | if (commit && (len = (int)stream.Length) > 0) 29 | { 30 | MemoryStream ms = (MemoryStream)stream; 31 | 32 | if (buffer == null) 33 | { // allocate new buffer 34 | buffer = ms.ToArray(); 35 | } 36 | else 37 | { // resize and copy the data 38 | // note: Array.Resize not available on CF 39 | int offset = buffer.Length; 40 | byte[] tmp = new byte[offset + len]; 41 | Helpers.BlockCopy(buffer, 0, tmp, 0, offset); 42 | 43 | #if PORTABLE || WINRT // no GetBuffer() - fine, we'll use Read instead 44 | int bytesRead; 45 | long oldPos = ms.Position; 46 | ms.Position = 0; 47 | while (len > 0 && (bytesRead = ms.Read(tmp, offset, len)) > 0) 48 | { 49 | len -= bytesRead; 50 | offset += bytesRead; 51 | } 52 | if(len != 0) throw new EndOfStreamException(); 53 | ms.Position = oldPos; 54 | #else 55 | Helpers.BlockCopy(ms.GetBuffer(), 0, tmp, offset, len); 56 | #endif 57 | buffer = tmp; 58 | } 59 | } 60 | } 61 | } 62 | 63 | Stream IExtension.BeginQuery() 64 | { 65 | return buffer == null ? Stream.Null : new MemoryStream(buffer); 66 | } 67 | 68 | void IExtension.EndQuery(Stream stream) 69 | { 70 | using (stream) { } // just clean up 71 | } 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /xbuffer_test/protobuf-net/BufferPool.cs: -------------------------------------------------------------------------------- 1 |  2 | using System.Threading; 3 | namespace ProtoBuf 4 | { 5 | internal sealed class BufferPool 6 | { 7 | internal static void Flush() 8 | { 9 | #if PLAT_NO_INTERLOCKED 10 | lock(pool) 11 | { 12 | for (int i = 0; i < pool.Length; i++) pool[i] = null; 13 | } 14 | #else 15 | for (int i = 0; i < pool.Length; i++) 16 | { 17 | Interlocked.Exchange(ref pool[i], null); // and drop the old value on the floor 18 | } 19 | #endif 20 | } 21 | private BufferPool() { } 22 | const int PoolSize = 20; 23 | internal const int BufferLength = 1024; 24 | private static readonly object[] pool = new object[PoolSize]; 25 | 26 | internal static byte[] GetBuffer() 27 | { 28 | object tmp; 29 | #if PLAT_NO_INTERLOCKED 30 | lock(pool) 31 | { 32 | for (int i = 0; i < pool.Length; i++) 33 | { 34 | if((tmp = pool[i]) != null) 35 | { 36 | pool[i] = null; 37 | return (byte[])tmp; 38 | } 39 | } 40 | } 41 | #else 42 | for (int i = 0; i < pool.Length; i++) 43 | { 44 | if ((tmp = Interlocked.Exchange(ref pool[i], null)) != null) return (byte[])tmp; 45 | } 46 | #endif 47 | return new byte[BufferLength]; 48 | } 49 | internal static void ResizeAndFlushLeft(ref byte[] buffer, int toFitAtLeastBytes, int copyFromIndex, int copyBytes) 50 | { 51 | Helpers.DebugAssert(buffer != null); 52 | Helpers.DebugAssert(toFitAtLeastBytes > buffer.Length); 53 | Helpers.DebugAssert(copyFromIndex >= 0); 54 | Helpers.DebugAssert(copyBytes >= 0); 55 | 56 | // try doubling, else match 57 | int newLength = buffer.Length * 2; 58 | if (newLength < toFitAtLeastBytes) newLength = toFitAtLeastBytes; 59 | 60 | byte[] newBuffer = new byte[newLength]; 61 | if (copyBytes > 0) 62 | { 63 | Helpers.BlockCopy(buffer, copyFromIndex, newBuffer, 0, copyBytes); 64 | } 65 | if (buffer.Length == BufferPool.BufferLength) 66 | { 67 | BufferPool.ReleaseBufferToPool(ref buffer); 68 | } 69 | buffer = newBuffer; 70 | } 71 | internal static void ReleaseBufferToPool(ref byte[] buffer) 72 | { 73 | if (buffer == null) return; 74 | if (buffer.Length == BufferLength) 75 | { 76 | #if PLAT_NO_INTERLOCKED 77 | lock (pool) 78 | { 79 | for (int i = 0; i < pool.Length; i++) 80 | { 81 | if(pool[i] == null) 82 | { 83 | pool[i] = buffer; 84 | break; 85 | } 86 | } 87 | } 88 | #else 89 | for (int i = 0; i < pool.Length; i++) 90 | { 91 | if (Interlocked.CompareExchange(ref pool[i], buffer, null) == null) 92 | { 93 | break; // found a null; swapped it in 94 | } 95 | } 96 | #endif 97 | } 98 | // if no space, just drop it on the floor 99 | buffer = null; 100 | } 101 | 102 | } 103 | } -------------------------------------------------------------------------------- /xbuffer_test/protobuf-net/CallbackAttributes.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.ComponentModel; 3 | 4 | namespace ProtoBuf 5 | { 6 | /// Specifies a method on the root-contract in an hierarchy to be invoked before serialization. 7 | [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] 8 | #if !CF && !SILVERLIGHT && !MONODROID && !WINRT && !IOS && !PORTABLE 9 | [ImmutableObject(true)] 10 | #endif 11 | public sealed class ProtoBeforeSerializationAttribute : Attribute { } 12 | 13 | /// Specifies a method on the root-contract in an hierarchy to be invoked after serialization. 14 | [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] 15 | #if !CF && !SILVERLIGHT && !MONODROID && !WINRT && !IOS && !PORTABLE 16 | [ImmutableObject(true)] 17 | #endif 18 | public sealed class ProtoAfterSerializationAttribute : Attribute { } 19 | 20 | /// Specifies a method on the root-contract in an hierarchy to be invoked before deserialization. 21 | [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] 22 | #if !CF && !SILVERLIGHT && !MONODROID && !WINRT && !IOS && !PORTABLE 23 | [ImmutableObject(true)] 24 | #endif 25 | public sealed class ProtoBeforeDeserializationAttribute : Attribute { } 26 | 27 | /// Specifies a method on the root-contract in an hierarchy to be invoked after deserialization. 28 | [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] 29 | #if !CF && !SILVERLIGHT && !MONODROID && !WINRT && !IOS && !PORTABLE 30 | [ImmutableObject(true)] 31 | #endif 32 | public sealed class ProtoAfterDeserializationAttribute : Attribute { } 33 | } 34 | -------------------------------------------------------------------------------- /xbuffer_test/protobuf-net/Compiler/CompilerDelegates.cs: -------------------------------------------------------------------------------- 1 | #if FEAT_COMPILER 2 | namespace ProtoBuf.Compiler 3 | { 4 | internal delegate void ProtoSerializer(object value, ProtoWriter dest); 5 | internal delegate object ProtoDeserializer(object value, ProtoReader source); 6 | } 7 | #endif -------------------------------------------------------------------------------- /xbuffer_test/protobuf-net/Compiler/Local.cs: -------------------------------------------------------------------------------- 1 | #if FEAT_COMPILER 2 | using System; 3 | #if FEAT_IKVM 4 | using IKVM.Reflection.Emit; 5 | using Type = IKVM.Reflection.Type; 6 | #else 7 | using System.Reflection.Emit; 8 | #endif 9 | 10 | namespace ProtoBuf.Compiler 11 | { 12 | internal sealed class Local : IDisposable 13 | { 14 | // public static readonly Local InputValue = new Local(null, null); 15 | LocalBuilder value; 16 | public Type Type { get { return type; } } 17 | public Local AsCopy() 18 | { 19 | if (ctx == null) return this; // can re-use if context-free 20 | return new Local(value, this.type); 21 | } 22 | internal LocalBuilder Value 23 | { 24 | get 25 | { 26 | if (value == null) 27 | { 28 | throw new ObjectDisposedException(GetType().Name); 29 | } 30 | return value; 31 | } 32 | } 33 | CompilerContext ctx; 34 | public void Dispose() 35 | { 36 | if (ctx != null) 37 | { 38 | // only *actually* dispose if this is context-bound; note that non-bound 39 | // objects are cheekily re-used, and *must* be left intact agter a "using" etc 40 | ctx.ReleaseToPool(value); 41 | value = null; 42 | ctx = null; 43 | } 44 | 45 | } 46 | private Local(LocalBuilder value, Type type) 47 | { 48 | this.value = value; 49 | this.type = type; 50 | } 51 | private readonly Type type; 52 | internal Local(Compiler.CompilerContext ctx, Type type) 53 | { 54 | this.ctx = ctx; 55 | if (ctx != null) { value = ctx.GetFromPool(type); } 56 | this.type = type; 57 | } 58 | 59 | internal bool IsSame(Local other) 60 | { 61 | if((object)this == (object)other) return true; 62 | 63 | object ourVal = value; // use prop to ensure obj-disposed etc 64 | return other != null && ourVal == (object)(other.value); 65 | } 66 | } 67 | 68 | 69 | } 70 | #endif -------------------------------------------------------------------------------- /xbuffer_test/protobuf-net/DataFormat.cs: -------------------------------------------------------------------------------- 1 |  2 | namespace ProtoBuf 3 | { 4 | /// 5 | /// Sub-format to use when serializing/deserializing data 6 | /// 7 | public enum DataFormat 8 | { 9 | /// 10 | /// Uses the default encoding for the data-type. 11 | /// 12 | Default, 13 | 14 | /// 15 | /// When applied to signed integer-based data (including Decimal), this 16 | /// indicates that zigzag variant encoding will be used. This means that values 17 | /// with small magnitude (regardless of sign) take a small amount 18 | /// of space to encode. 19 | /// 20 | ZigZag, 21 | 22 | /// 23 | /// When applied to signed integer-based data (including Decimal), this 24 | /// indicates that two's-complement variant encoding will be used. 25 | /// This means that any -ve number will take 10 bytes (even for 32-bit), 26 | /// so should only be used for compatibility. 27 | /// 28 | TwosComplement, 29 | 30 | /// 31 | /// When applied to signed integer-based data (including Decimal), this 32 | /// indicates that a fixed amount of space will be used. 33 | /// 34 | FixedSize, 35 | 36 | /// 37 | /// When applied to a sub-message, indicates that the value should be treated 38 | /// as group-delimited. 39 | /// 40 | Group 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /xbuffer_test/protobuf-net/ExtensibleUtil.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections; 3 | #if !NO_GENERICS 4 | using System.Collections.Generic; 5 | #endif 6 | using System.IO; 7 | using ProtoBuf.Meta; 8 | 9 | namespace ProtoBuf 10 | { 11 | /// 12 | /// This class acts as an internal wrapper allowing us to do a dynamic 13 | /// methodinfo invoke; an't put into Serializer as don't want on public 14 | /// API; can't put into Serializer<T> since we need to invoke 15 | /// accross classes, which isn't allowed in Silverlight) 16 | /// 17 | internal 18 | #if FX11 19 | sealed 20 | #else 21 | static 22 | #endif 23 | class ExtensibleUtil 24 | { 25 | #if FX11 26 | private ExtensibleUtil() { } // not a static class for C# 1.2 reasons 27 | #endif 28 | 29 | #if !NO_RUNTIME && !NO_GENERICS 30 | /// 31 | /// All this does is call GetExtendedValuesTyped with the correct type for "instance"; 32 | /// this ensures that we don't get issues with subclasses declaring conflicting types - 33 | /// the caller must respect the fields defined for the type they pass in. 34 | /// 35 | internal static IEnumerable GetExtendedValues(IExtensible instance, int tag, DataFormat format, bool singleton, bool allowDefinedTag) 36 | { 37 | foreach (TValue value in GetExtendedValues(RuntimeTypeModel.Default, typeof(TValue), instance, tag, format, singleton, allowDefinedTag)) 38 | { 39 | yield return value; 40 | } 41 | } 42 | #endif 43 | /// 44 | /// All this does is call GetExtendedValuesTyped with the correct type for "instance"; 45 | /// this ensures that we don't get issues with subclasses declaring conflicting types - 46 | /// the caller must respect the fields defined for the type they pass in. 47 | /// 48 | internal static IEnumerable GetExtendedValues(TypeModel model, Type type, IExtensible instance, int tag, DataFormat format, bool singleton, bool allowDefinedTag) 49 | { 50 | #if FEAT_IKVM 51 | throw new NotSupportedException(); 52 | #else 53 | 54 | if (instance == null) throw new ArgumentNullException("instance"); 55 | if (tag <= 0) throw new ArgumentOutOfRangeException("tag"); 56 | IExtension extn = instance.GetExtensionObject(false); 57 | 58 | if (extn == null) 59 | { 60 | #if FX11 61 | return new object[0]; 62 | #else 63 | yield break; 64 | #endif 65 | } 66 | 67 | #if FX11 68 | BasicList result = new BasicList(); 69 | #endif 70 | Stream stream = extn.BeginQuery(); 71 | object value = null; 72 | ProtoReader reader = null; 73 | try { 74 | SerializationContext ctx = new SerializationContext(); 75 | reader = ProtoReader.Create(stream, model, ctx, ProtoReader.TO_EOF); 76 | while (model.TryDeserializeAuxiliaryType(reader, format, tag, type, ref value, true, false, false, false) && value != null) 77 | { 78 | if (!singleton) 79 | { 80 | #if FX11 81 | result.Add(value); 82 | #else 83 | yield return value; 84 | #endif 85 | value = null; // fresh item each time 86 | } 87 | } 88 | if (singleton && value != null) 89 | { 90 | #if FX11 91 | result.Add(value); 92 | #else 93 | yield return value; 94 | #endif 95 | } 96 | #if FX11 97 | object[] resultArr = new object[result.Count]; 98 | result.CopyTo(resultArr, 0); 99 | return resultArr; 100 | #endif 101 | } finally { 102 | ProtoReader.Recycle(reader); 103 | extn.EndQuery(stream); 104 | } 105 | #endif 106 | } 107 | 108 | internal static void AppendExtendValue(TypeModel model, IExtensible instance, int tag, DataFormat format, object value) 109 | { 110 | #if FEAT_IKVM 111 | throw new NotSupportedException(); 112 | #else 113 | if(instance == null) throw new ArgumentNullException("instance"); 114 | if(value == null) throw new ArgumentNullException("value"); 115 | 116 | // TODO 117 | //model.CheckTagNotInUse(tag); 118 | 119 | // obtain the extension object and prepare to write 120 | IExtension extn = instance.GetExtensionObject(true); 121 | if (extn == null) throw new InvalidOperationException("No extension object available; appended data would be lost."); 122 | bool commit = false; 123 | Stream stream = extn.BeginAppend(); 124 | try { 125 | using(ProtoWriter writer = new ProtoWriter(stream, model, null)) { 126 | model.TrySerializeAuxiliaryType(writer, null, format, tag, value, false); 127 | writer.Close(); 128 | } 129 | commit = true; 130 | } 131 | finally { 132 | extn.EndAppend(stream, commit); 133 | } 134 | #endif 135 | } 136 | //#if !NO_GENERICS 137 | // /// 138 | // /// Stores the given value into the instance's stream; the serializer 139 | // /// is inferred from TValue and format. 140 | // /// 141 | // /// Needs to be public to be callable thru reflection in Silverlight 142 | // public static void AppendExtendValueTyped( 143 | // TypeModel model, TSource instance, int tag, DataFormat format, TValue value) 144 | // where TSource : class, IExtensible 145 | // { 146 | // AppendExtendValue(model, instance, tag, format, value); 147 | // } 148 | //#endif 149 | } 150 | 151 | } -------------------------------------------------------------------------------- /xbuffer_test/protobuf-net/GlobalSuppressions.cs: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/CodeZeg/xbuffer/fc81d33154d1444e9643caacaf0a72cb1e7e9ba3/xbuffer_test/protobuf-net/GlobalSuppressions.cs -------------------------------------------------------------------------------- /xbuffer_test/protobuf-net/IExtensible.cs: -------------------------------------------------------------------------------- 1 |  2 | namespace ProtoBuf 3 | { 4 | 5 | 6 | /// 7 | /// Indicates that the implementing type has support for protocol-buffer 8 | /// extensions. 9 | /// 10 | /// Can be implemented by deriving from Extensible. 11 | public interface IExtensible 12 | { 13 | /// 14 | /// Retrieves the extension object for the current 15 | /// instance, optionally creating it if it does not already exist. 16 | /// 17 | /// Should a new extension object be 18 | /// created if it does not already exist? 19 | /// The extension object if it exists (or was created), or null 20 | /// if the extension object does not exist or is not available. 21 | /// The createIfMissing argument is false during serialization, 22 | /// and true during deserialization upon encountering unexpected fields. 23 | IExtension GetExtensionObject(bool createIfMissing); 24 | } 25 | 26 | 27 | } 28 | -------------------------------------------------------------------------------- /xbuffer_test/protobuf-net/IExtension.cs: -------------------------------------------------------------------------------- 1 |  2 | using System.IO; 3 | namespace ProtoBuf 4 | { 5 | /// 6 | /// Provides addition capability for supporting unexpected fields during 7 | /// protocol-buffer serialization/deserialization. This allows for loss-less 8 | /// round-trip/merge, even when the data is not fully understood. 9 | /// 10 | public interface IExtension 11 | { 12 | /// 13 | /// Requests a stream into which any unexpected fields can be persisted. 14 | /// 15 | /// A new stream suitable for storing data. 16 | Stream BeginAppend(); 17 | 18 | /// 19 | /// Indicates that all unexpected fields have now been stored. The 20 | /// implementing class is responsible for closing the stream. If 21 | /// "commit" is not true the data may be discarded. 22 | /// 23 | /// The stream originally obtained by BeginAppend. 24 | /// True if the append operation completed successfully. 25 | void EndAppend(Stream stream, bool commit); 26 | 27 | /// 28 | /// Requests a stream of the unexpected fields previously stored. 29 | /// 30 | /// A prepared stream of the unexpected fields. 31 | Stream BeginQuery(); 32 | 33 | /// 34 | /// Indicates that all unexpected fields have now been read. The 35 | /// implementing class is responsible for closing the stream. 36 | /// 37 | /// The stream originally obtained by BeginQuery. 38 | void EndQuery(Stream stream); 39 | 40 | /// 41 | /// Requests the length of the raw binary stream; this is used 42 | /// when serializing sub-entities to indicate the expected size. 43 | /// 44 | /// The length of the binary stream representing unexpected data. 45 | int GetLength(); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /xbuffer_test/protobuf-net/ImplicitFields.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace ProtoBuf 4 | { 5 | /// 6 | /// Specifies the method used to infer field tags for members of the type 7 | /// under consideration. Tags are deduced using the invariant alphabetic 8 | /// sequence of the members' names; this makes implicit field tags very brittle, 9 | /// and susceptible to changes such as field names (normally an isolated 10 | /// change). 11 | /// 12 | public enum ImplicitFields 13 | { 14 | /// 15 | /// No members are serialized implicitly; all members require a suitable 16 | /// attribute such as [ProtoMember]. This is the recmomended mode for 17 | /// most scenarios. 18 | /// 19 | None = 0, 20 | /// 21 | /// Public properties and fields are eligible for implicit serialization; 22 | /// this treats the public API as a contract. Ordering beings from ImplicitFirstTag. 23 | /// 24 | AllPublic= 1, 25 | /// 26 | /// Public and non-public fields are eligible for implicit serialization; 27 | /// this acts as a state/implementation serializer. Ordering beings from ImplicitFirstTag. 28 | /// 29 | AllFields = 2 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /xbuffer_test/protobuf-net/KeyValuePairProxy.cs: -------------------------------------------------------------------------------- 1 | //#if !NO_GENERICS 2 | //using System.Collections.Generic; 3 | 4 | //namespace ProtoBuf 5 | //{ 6 | // /// 7 | // /// Mutable version of the common key/value pair struct; used during serialization. This type is intended for internal use only and should not 8 | // /// be used by calling code; it is required to be public for implementation reasons. 9 | // /// 10 | // [ProtoContract] 11 | // public struct KeyValuePairSurrogate 12 | // { 13 | // private TKey key; 14 | // private TValue value; 15 | // /// 16 | // /// The key of the pair. 17 | // /// 18 | // [ProtoMember(1, IsRequired = true)] 19 | // public TKey Key { get { return key; } set { key = value; } } 20 | // /// 21 | // /// The value of the pair. 22 | // /// 23 | // [ProtoMember(2)] 24 | // public TValue Value{ get { return value; } set { this.value = value; } } 25 | // private KeyValuePairSurrogate(TKey key, TValue value) 26 | // { 27 | // this.key = key; 28 | // this.value = value; 29 | // } 30 | // /// 31 | // /// Convert a surrogate instance to a standard pair instance. 32 | // /// 33 | // public static implicit operator KeyValuePair (KeyValuePairSurrogate value) 34 | // { 35 | // return new KeyValuePair(value.key, value.value); 36 | // } 37 | // /// 38 | // /// Convert a standard pair instance to a surrogate instance. 39 | // /// 40 | // public static implicit operator KeyValuePairSurrogate(KeyValuePair value) 41 | // { 42 | // return new KeyValuePairSurrogate(value.Key, value.Value); 43 | // } 44 | // } 45 | //} 46 | //#endif -------------------------------------------------------------------------------- /xbuffer_test/protobuf-net/Meta/CallbackSet.cs: -------------------------------------------------------------------------------- 1 | #if !NO_RUNTIME 2 | using System; 3 | 4 | #if FEAT_IKVM 5 | using Type = IKVM.Reflection.Type; 6 | using IKVM.Reflection; 7 | #else 8 | using System.Reflection; 9 | #endif 10 | 11 | namespace ProtoBuf.Meta 12 | { 13 | /// 14 | /// Represents the set of serialization callbacks to be used when serializing/deserializing a type. 15 | /// 16 | public class CallbackSet 17 | { 18 | private readonly MetaType metaType; 19 | internal CallbackSet(MetaType metaType) 20 | { 21 | if (metaType == null) throw new ArgumentNullException("metaType"); 22 | this.metaType = metaType; 23 | } 24 | internal MethodInfo this[TypeModel.CallbackType callbackType] 25 | { 26 | get 27 | { 28 | switch (callbackType) 29 | { 30 | case TypeModel.CallbackType.BeforeSerialize: return beforeSerialize; 31 | case TypeModel.CallbackType.AfterSerialize: return afterSerialize; 32 | case TypeModel.CallbackType.BeforeDeserialize: return beforeDeserialize; 33 | case TypeModel.CallbackType.AfterDeserialize: return afterDeserialize; 34 | default: throw new ArgumentException("Callback type not supported: " + callbackType.ToString(), "callbackType"); 35 | } 36 | } 37 | } 38 | internal static bool CheckCallbackParameters(TypeModel model, MethodInfo method) 39 | { 40 | ParameterInfo[] args = method.GetParameters(); 41 | for (int i = 0; i < args.Length; i++) 42 | { 43 | Type paramType = args[i].ParameterType; 44 | if(paramType == model.MapType(typeof(SerializationContext))) {} 45 | else if(paramType == model.MapType(typeof(System.Type))) {} 46 | #if PLAT_BINARYFORMATTER 47 | else if(paramType == model.MapType(typeof(System.Runtime.Serialization.StreamingContext))) {} 48 | #endif 49 | else return false; 50 | } 51 | return true; 52 | } 53 | private MethodInfo SanityCheckCallback(TypeModel model, MethodInfo callback) 54 | { 55 | metaType.ThrowIfFrozen(); 56 | if (callback == null) return callback; // fine 57 | if (callback.IsStatic) throw new ArgumentException("Callbacks cannot be static", "callback"); 58 | if (callback.ReturnType != model.MapType(typeof(void)) 59 | || !CheckCallbackParameters(model, callback)) 60 | { 61 | throw CreateInvalidCallbackSignature(callback); 62 | } 63 | return callback; 64 | } 65 | internal static Exception CreateInvalidCallbackSignature(MethodInfo method) 66 | { 67 | return new NotSupportedException("Invalid callback signature in " + method.DeclaringType.FullName + "." + method.Name); 68 | } 69 | private MethodInfo beforeSerialize, afterSerialize, beforeDeserialize, afterDeserialize; 70 | /// Called before serializing an instance 71 | public MethodInfo BeforeSerialize 72 | { 73 | get { return beforeSerialize; } 74 | set { beforeSerialize = SanityCheckCallback(metaType.Model, value); } 75 | } 76 | /// Called before deserializing an instance 77 | public MethodInfo BeforeDeserialize 78 | { 79 | get { return beforeDeserialize; } 80 | set { beforeDeserialize = SanityCheckCallback(metaType.Model, value); } 81 | } 82 | /// Called after serializing an instance 83 | public MethodInfo AfterSerialize 84 | { 85 | get { return afterSerialize; } 86 | set { afterSerialize = SanityCheckCallback(metaType.Model, value); } 87 | } 88 | /// Called after deserializing an instance 89 | public MethodInfo AfterDeserialize 90 | { 91 | get { return afterDeserialize; } 92 | set { afterDeserialize = SanityCheckCallback(metaType.Model, value); } 93 | } 94 | /// 95 | /// True if any callback is set, else False 96 | /// 97 | public bool NonTrivial 98 | { 99 | get 100 | { 101 | return beforeSerialize != null || beforeDeserialize != null 102 | || afterSerialize != null || afterDeserialize != null; 103 | } 104 | } 105 | } 106 | } 107 | #endif -------------------------------------------------------------------------------- /xbuffer_test/protobuf-net/Meta/SubType.cs: -------------------------------------------------------------------------------- 1 | #if !NO_RUNTIME 2 | using System; 3 | using ProtoBuf.Serializers; 4 | 5 | namespace ProtoBuf.Meta 6 | { 7 | /// 8 | /// Represents an inherited type in a type hierarchy. 9 | /// 10 | public sealed class SubType 11 | { 12 | internal sealed class Comparer : System.Collections.IComparer 13 | #if !NO_GENERICS 14 | , System.Collections.Generic.IComparer 15 | #endif 16 | { 17 | public static readonly Comparer Default = new Comparer(); 18 | public int Compare(object x, object y) 19 | { 20 | return Compare(x as SubType, y as SubType); 21 | } 22 | public int Compare(SubType x, SubType y) 23 | { 24 | if (ReferenceEquals(x, y)) return 0; 25 | if (x == null) return -1; 26 | if (y == null) return 1; 27 | 28 | return x.FieldNumber.CompareTo(y.FieldNumber); 29 | } 30 | } 31 | private readonly int fieldNumber; 32 | /// 33 | /// The field-number that is used to encapsulate the data (as a nested 34 | /// message) for the derived dype. 35 | /// 36 | public int FieldNumber { get { return fieldNumber; } } 37 | /// 38 | /// The sub-type to be considered. 39 | /// 40 | public MetaType DerivedType { get { return derivedType; } } 41 | private readonly MetaType derivedType; 42 | 43 | /// 44 | /// Creates a new SubType instance. 45 | /// 46 | /// The field-number that is used to encapsulate the data (as a nested 47 | /// message) for the derived dype. 48 | /// The sub-type to be considered. 49 | /// Specific encoding style to use; in particular, Grouped can be used to avoid buffering, but is not the default. 50 | public SubType(int fieldNumber, MetaType derivedType, DataFormat format) 51 | { 52 | if (derivedType == null) throw new ArgumentNullException("derivedType"); 53 | if (fieldNumber <= 0) throw new ArgumentOutOfRangeException("fieldNumber"); 54 | this.fieldNumber = fieldNumber; 55 | this.derivedType = derivedType; 56 | this.dataFormat = format; 57 | } 58 | 59 | private readonly DataFormat dataFormat; 60 | 61 | private IProtoSerializer serializer; 62 | internal IProtoSerializer Serializer 63 | { 64 | get 65 | { 66 | if (serializer == null) serializer = BuildSerializer(); 67 | return serializer; 68 | } 69 | } 70 | 71 | private IProtoSerializer BuildSerializer() 72 | { 73 | // note the caller here is MetaType.BuildSerializer, which already has the sync-lock 74 | WireType wireType = WireType.String; 75 | if(dataFormat == DataFormat.Group) wireType = WireType.StartGroup; // only one exception 76 | 77 | IProtoSerializer ser = new SubItemSerializer(derivedType.Type, derivedType.GetKey(false, false), derivedType, false); 78 | return new TagDecorator(fieldNumber, wireType, false, ser); 79 | } 80 | } 81 | } 82 | #endif -------------------------------------------------------------------------------- /xbuffer_test/protobuf-net/Meta/TypeFormatEventArgs.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace ProtoBuf.Meta 4 | { 5 | /// 6 | /// Event arguments needed to perform type-formatting functions; this could be resolving a Type to a string suitable for serialization, or could 7 | /// be requesting a Type from a string. If no changes are made, a default implementation will be used (from the assembly-qualified names). 8 | /// 9 | public class TypeFormatEventArgs : EventArgs 10 | { 11 | private Type type; 12 | private string formattedName; 13 | private readonly bool typeFixed; 14 | /// 15 | /// The type involved in this map; if this is initially null, a Type is expected to be provided for the string in FormattedName. 16 | /// 17 | public Type Type 18 | { 19 | get { return type; } 20 | set 21 | { 22 | if(type != value) 23 | { 24 | if (typeFixed) throw new InvalidOperationException("The type is fixed and cannot be changed"); 25 | type = value; 26 | } 27 | } 28 | } 29 | /// 30 | /// The formatted-name involved in this map; if this is initially null, a formatted-name is expected from the type in Type. 31 | /// 32 | public string FormattedName 33 | { 34 | get { return formattedName; } 35 | set 36 | { 37 | if (formattedName != value) 38 | { 39 | if (!typeFixed) throw new InvalidOperationException("The formatted-name is fixed and cannot be changed"); 40 | formattedName = value; 41 | } 42 | } 43 | } 44 | internal TypeFormatEventArgs(string formattedName) 45 | { 46 | if (Helpers.IsNullOrEmpty(formattedName)) throw new ArgumentNullException("formattedName"); 47 | this.formattedName = formattedName; 48 | // typeFixed = false; <== implicit 49 | } 50 | internal TypeFormatEventArgs(System.Type type) 51 | { 52 | if (type == null) throw new ArgumentNullException("type"); 53 | this.type = type; 54 | typeFixed = true; 55 | } 56 | 57 | } 58 | /// 59 | /// Delegate type used to perform type-formatting functions; the sender originates as the type-model. 60 | /// 61 | public delegate void TypeFormatEventHandler(object sender, TypeFormatEventArgs args); 62 | } 63 | -------------------------------------------------------------------------------- /xbuffer_test/protobuf-net/PrefixStyle.cs: -------------------------------------------------------------------------------- 1 |  2 | namespace ProtoBuf 3 | { 4 | /// 5 | /// Specifies the type of prefix that should be applied to messages. 6 | /// 7 | public enum PrefixStyle 8 | { 9 | /// 10 | /// No length prefix is applied to the data; the data is terminated only be the end of the stream. 11 | /// 12 | None, 13 | /// 14 | /// A base-128 length prefix is applied to the data (efficient for short messages). 15 | /// 16 | Base128, 17 | /// 18 | /// A fixed-length (little-endian) length prefix is applied to the data (useful for compatibility). 19 | /// 20 | Fixed32, 21 | /// 22 | /// A fixed-length (big-endian) length prefix is applied to the data (useful for compatibility). 23 | /// 24 | Fixed32BigEndian 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /xbuffer_test/protobuf-net/ProtoContractAttribute.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace ProtoBuf 4 | { 5 | /// 6 | /// Indicates that a type is defined for protocol-buffer serialization. 7 | /// 8 | [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Interface, 9 | AllowMultiple = false, Inherited = false)] 10 | public sealed class ProtoContractAttribute : Attribute 11 | { 12 | /// 13 | /// Gets or sets the defined name of the type. 14 | /// 15 | public string Name { get { return name; } set { name = value; } } 16 | private string name; 17 | 18 | /// 19 | /// Gets or sets the fist offset to use with implicit field tags; 20 | /// only uesd if ImplicitFields is set. 21 | /// 22 | public int ImplicitFirstTag 23 | { 24 | get { return implicitFirstTag; } 25 | set 26 | { 27 | if (value < 1) throw new ArgumentOutOfRangeException("ImplicitFirstTag"); 28 | implicitFirstTag = value; 29 | } 30 | } 31 | private int implicitFirstTag; 32 | 33 | /// 34 | /// If specified, alternative contract markers (such as markers for XmlSerailizer or DataContractSerializer) are ignored. 35 | /// 36 | public bool UseProtoMembersOnly 37 | { 38 | get { return HasFlag(OPTIONS_UseProtoMembersOnly); } 39 | set { SetFlag(OPTIONS_UseProtoMembersOnly, value); } 40 | } 41 | 42 | /// 43 | /// If specified, do NOT treat this type as a list, even if it looks like one. 44 | /// 45 | public bool IgnoreListHandling 46 | { 47 | get { return HasFlag(OPTIONS_IgnoreListHandling); } 48 | set { SetFlag(OPTIONS_IgnoreListHandling, value); } 49 | } 50 | 51 | 52 | /// 53 | /// Gets or sets the mechanism used to automatically infer field tags 54 | /// for members. This option should be used in advanced scenarios only. 55 | /// Please review the important notes against the ImplicitFields enumeration. 56 | /// 57 | public ImplicitFields ImplicitFields { get { return implicitFields; } set { implicitFields = value; } } 58 | private ImplicitFields implicitFields; 59 | 60 | 61 | /// 62 | /// Enables/disables automatic tag generation based on the existing name / order 63 | /// of the defined members. This option is not used for members marked 64 | /// with ProtoMemberAttribute, as intended to provide compatibility with 65 | /// WCF serialization. WARNING: when adding new fields you must take 66 | /// care to increase the Order for new elements, otherwise data corruption 67 | /// may occur. 68 | /// 69 | /// If not explicitly specified, the default is assumed from Serializer.GlobalOptions.InferTagFromName. 70 | public bool InferTagFromName 71 | { 72 | get { return HasFlag(OPTIONS_InferTagFromName); } 73 | set { 74 | SetFlag(OPTIONS_InferTagFromName, value); 75 | SetFlag(OPTIONS_InferTagFromNameHasValue, true); 76 | } 77 | } 78 | 79 | /// 80 | /// Has a InferTagFromName value been explicitly set? if not, the default from the type-model is assumed. 81 | /// 82 | internal bool InferTagFromNameHasValue 83 | { // note that this property is accessed via reflection and should not be removed 84 | get { return HasFlag(OPTIONS_InferTagFromNameHasValue); } 85 | } 86 | 87 | private int dataMemberOffset; 88 | 89 | /// 90 | /// Specifies an offset to apply to [DataMember(Order=...)] markers; 91 | /// this is useful when working with mex-generated classes that have 92 | /// a different origin (usually 1 vs 0) than the original data-contract. 93 | /// 94 | /// This value is added to the Order of each member. 95 | /// 96 | public int DataMemberOffset 97 | { 98 | get { return dataMemberOffset; } 99 | set { dataMemberOffset = value; } 100 | } 101 | 102 | 103 | /// 104 | /// If true, the constructor for the type is bypassed during deserialization, meaning any field initializers 105 | /// or other initialization code is skipped. 106 | /// 107 | public bool SkipConstructor 108 | { 109 | get { return HasFlag(OPTIONS_SkipConstructor); } 110 | set { SetFlag(OPTIONS_SkipConstructor, value); } 111 | } 112 | 113 | /// 114 | /// Should this type be treated as a reference by default? Please also see the implications of this, 115 | /// as recorded on ProtoMemberAttribute.AsReference 116 | /// 117 | public bool AsReferenceDefault 118 | { 119 | get { return HasFlag(OPTIONS_AsReferenceDefault); } 120 | set { 121 | SetFlag(OPTIONS_AsReferenceDefault, value); 122 | } 123 | } 124 | 125 | private bool HasFlag(byte flag) { return (flags & flag) == flag; } 126 | private void SetFlag(byte flag, bool value) 127 | { 128 | if (value) flags |= flag; 129 | else flags = (byte)(flags & ~flag); 130 | } 131 | 132 | private byte flags; 133 | 134 | private const byte 135 | OPTIONS_InferTagFromName = 1, 136 | OPTIONS_InferTagFromNameHasValue = 2, 137 | OPTIONS_UseProtoMembersOnly = 4, 138 | OPTIONS_SkipConstructor = 8, 139 | OPTIONS_IgnoreListHandling = 16, 140 | OPTIONS_AsReferenceDefault = 32, 141 | OPTIONS_EnumPassthru = 64, 142 | OPTIONS_EnumPassthruHasValue = 128; 143 | 144 | /// 145 | /// Applies only to enums (not to DTO classes themselves); gets or sets a value indicating that an enum should be treated directly as an int/short/etc, rather 146 | /// than enforcing .proto enum rules. This is useful *in particul* for [Flags] enums. 147 | /// 148 | public bool EnumPassthru 149 | { 150 | get { return HasFlag(OPTIONS_EnumPassthru); } 151 | set { 152 | SetFlag(OPTIONS_EnumPassthru, value); 153 | SetFlag(OPTIONS_EnumPassthruHasValue, true); 154 | } 155 | } 156 | 157 | /// 158 | /// Has a EnumPassthru value been explicitly set? 159 | /// 160 | internal bool EnumPassthruHasValue 161 | { // note that this property is accessed via reflection and should not be removed 162 | get { return HasFlag(OPTIONS_EnumPassthruHasValue); } 163 | } 164 | } 165 | } -------------------------------------------------------------------------------- /xbuffer_test/protobuf-net/ProtoConverterAttribute.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace ProtoBuf 4 | { 5 | /// 6 | /// Indicates that a static member should be considered the same as though 7 | /// were an implicit / explicit conversion operator; in particular, this 8 | /// is useful for conversions that operator syntax does not allow, such as 9 | /// to/from interface types. 10 | /// 11 | [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)] 12 | public class ProtoConverterAttribute : Attribute {} 13 | } -------------------------------------------------------------------------------- /xbuffer_test/protobuf-net/ProtoEnumAttribute.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace ProtoBuf 4 | { 5 | /// 6 | /// Used to define protocol-buffer specific behavior for 7 | /// enumerated values. 8 | /// 9 | [AttributeUsage(AttributeTargets.Field, AllowMultiple = false)] 10 | public sealed class ProtoEnumAttribute : Attribute 11 | { 12 | /// 13 | /// Gets or sets the specific value to use for this enum during serialization. 14 | /// 15 | public int Value 16 | { 17 | get { return enumValue; } 18 | set { this.enumValue = value; hasValue = true; } 19 | } 20 | 21 | /// 22 | /// Indicates whether this instance has a customised value mapping 23 | /// 24 | /// true if a specific value is set 25 | public bool HasValue() { return hasValue; } 26 | 27 | private bool hasValue; 28 | private int enumValue; 29 | 30 | /// 31 | /// Gets or sets the defined name of the enum, as used in .proto 32 | /// (this name is not used during serialization). 33 | /// 34 | public string Name { get { return name; } set { name = value; } } 35 | private string name; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /xbuffer_test/protobuf-net/ProtoException.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | #if PLAT_BINARYFORMATTER && !(WINRT || PHONE8) 4 | using System.Runtime.Serialization; 5 | #endif 6 | namespace ProtoBuf 7 | { 8 | /// 9 | /// Indicates an error during serialization/deserialization of a proto stream. 10 | /// 11 | #if PLAT_BINARYFORMATTER && !(WINRT || PHONE8) 12 | [Serializable] 13 | #endif 14 | public class ProtoException : Exception 15 | { 16 | /// Creates a new ProtoException instance. 17 | public ProtoException() { } 18 | 19 | /// Creates a new ProtoException instance. 20 | public ProtoException(string message) : base(message) { } 21 | 22 | /// Creates a new ProtoException instance. 23 | public ProtoException(string message, Exception innerException) : base(message, innerException) { } 24 | 25 | #if PLAT_BINARYFORMATTER && !(WINRT || PHONE8) 26 | /// Creates a new ProtoException instance. 27 | protected ProtoException(SerializationInfo info, StreamingContext context) : base(info, context) { } 28 | #endif 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /xbuffer_test/protobuf-net/ProtoIgnoreAttribute.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace ProtoBuf 4 | { 5 | /// 6 | /// Indicates that a member should be excluded from serialization; this 7 | /// is only normally used when using implict fields. 8 | /// 9 | [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, 10 | AllowMultiple = false, Inherited = true)] 11 | public class ProtoIgnoreAttribute : Attribute {} 12 | 13 | /// 14 | /// Indicates that a member should be excluded from serialization; this 15 | /// is only normally used when using implict fields. This allows 16 | /// ProtoIgnoreAttribute usage 17 | /// even for partial classes where the individual members are not 18 | /// under direct control. 19 | /// 20 | [AttributeUsage(AttributeTargets.Class, 21 | AllowMultiple = true, Inherited = false)] 22 | public sealed class ProtoPartialIgnoreAttribute : ProtoIgnoreAttribute 23 | { 24 | /// 25 | /// Creates a new ProtoPartialIgnoreAttribute instance. 26 | /// 27 | /// Specifies the member to be ignored. 28 | public ProtoPartialIgnoreAttribute(string memberName) 29 | : base() 30 | { 31 | if (Helpers.IsNullOrEmpty(memberName)) throw new ArgumentNullException("memberName"); 32 | this.memberName = memberName; 33 | } 34 | /// 35 | /// The name of the member to be ignored. 36 | /// 37 | public string MemberName { get { return memberName; } } 38 | private readonly string memberName; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /xbuffer_test/protobuf-net/ProtoIncludeAttribute.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.ComponentModel; 3 | 4 | using ProtoBuf.Meta; 5 | #if FEAT_IKVM 6 | using Type = IKVM.Reflection.Type; 7 | using IKVM.Reflection; 8 | #else 9 | using System.Reflection; 10 | #endif 11 | namespace ProtoBuf 12 | { 13 | /// 14 | /// Indicates the known-types to support for an individual 15 | /// message. This serializes each level in the hierarchy as 16 | /// a nested message to retain wire-compatibility with 17 | /// other protocol-buffer implementations. 18 | /// 19 | [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = true, Inherited = false)] 20 | public sealed class ProtoIncludeAttribute : Attribute 21 | { 22 | /// 23 | /// Creates a new instance of the ProtoIncludeAttribute. 24 | /// 25 | /// The unique index (within the type) that will identify this data. 26 | /// The additional type to serialize/deserialize. 27 | public ProtoIncludeAttribute(int tag, System.Type knownType) 28 | : this(tag, knownType == null ? "" : knownType.AssemblyQualifiedName) { } 29 | 30 | /// 31 | /// Creates a new instance of the ProtoIncludeAttribute. 32 | /// 33 | /// The unique index (within the type) that will identify this data. 34 | /// The additional type to serialize/deserialize. 35 | public ProtoIncludeAttribute(int tag, string knownTypeName) 36 | { 37 | if (tag <= 0) throw new ArgumentOutOfRangeException("tag", "Tags must be positive integers"); 38 | if (Helpers.IsNullOrEmpty(knownTypeName)) throw new ArgumentNullException("knownTypeName", "Known type cannot be blank"); 39 | this.tag = tag; 40 | this.knownTypeName = knownTypeName; 41 | } 42 | 43 | /// 44 | /// Gets the unique index (within the type) that will identify this data. 45 | /// 46 | public int Tag { get { return tag; } } 47 | private readonly int tag; 48 | 49 | /// 50 | /// Gets the additional type to serialize/deserialize. 51 | /// 52 | public string KnownTypeName { get { return knownTypeName; } } 53 | private readonly string knownTypeName; 54 | 55 | /// 56 | /// Gets the additional type to serialize/deserialize. 57 | /// 58 | public Type KnownType 59 | { 60 | get 61 | { 62 | return TypeModel.ResolveKnownType(KnownTypeName, null, null); 63 | } 64 | } 65 | 66 | /// 67 | /// Specifies whether the inherited sype's sub-message should be 68 | /// written with a length-prefix (default), or with group markers. 69 | /// 70 | [DefaultValue(DataFormat.Default)] 71 | public DataFormat DataFormat 72 | { 73 | get { return dataFormat; } 74 | set { dataFormat = value; } 75 | } 76 | private DataFormat dataFormat = DataFormat.Default; 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /xbuffer_test/protobuf-net/SerializationContext.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace ProtoBuf 4 | { 5 | /// 6 | /// Additional information about a serialization operation 7 | /// 8 | public sealed class SerializationContext 9 | { 10 | private bool frozen; 11 | internal void Freeze() { frozen = true;} 12 | private void ThrowIfFrozen() { if (frozen) throw new InvalidOperationException("The serialization-context cannot be changed once it is in use"); } 13 | private object context; 14 | /// 15 | /// Gets or sets a user-defined object containing additional information about this serialization/deserialization operation. 16 | /// 17 | public object Context 18 | { 19 | get { return context; } 20 | set { if (context != value) { ThrowIfFrozen(); context = value; } } 21 | } 22 | 23 | private static readonly SerializationContext @default; 24 | static SerializationContext() 25 | { 26 | @default = new SerializationContext(); 27 | @default.Freeze(); 28 | } 29 | /// 30 | /// A default SerializationContext, with minimal information. 31 | /// 32 | internal static SerializationContext Default { get {return @default;}} 33 | #if PLAT_BINARYFORMATTER || (SILVERLIGHT && NET_4_0) 34 | 35 | #if !(WINRT || PHONE7 || PHONE8) 36 | private System.Runtime.Serialization.StreamingContextStates state = System.Runtime.Serialization.StreamingContextStates.Persistence; 37 | /// 38 | /// Gets or sets the source or destination of the transmitted data. 39 | /// 40 | public System.Runtime.Serialization.StreamingContextStates State 41 | { 42 | get { return state; } 43 | set { if (state != value) { ThrowIfFrozen(); state = value; } } 44 | } 45 | #endif 46 | /// 47 | /// Convert a SerializationContext to a StreamingContext 48 | /// 49 | public static implicit operator System.Runtime.Serialization.StreamingContext(SerializationContext ctx) 50 | { 51 | #if WINRT || PHONE7 || PHONE8 52 | return new System.Runtime.Serialization.StreamingContext(); 53 | #else 54 | if (ctx == null) return new System.Runtime.Serialization.StreamingContext(System.Runtime.Serialization.StreamingContextStates.Persistence); 55 | return new System.Runtime.Serialization.StreamingContext(ctx.state, ctx.context); 56 | #endif 57 | } 58 | /// 59 | /// Convert a StreamingContext to a SerializationContext 60 | /// 61 | public static implicit operator SerializationContext (System.Runtime.Serialization.StreamingContext ctx) 62 | { 63 | SerializationContext result = new SerializationContext(); 64 | #if !(WINRT || PHONE7 || PHONE8) 65 | result.Context = ctx.Context; 66 | result.State = ctx.State; 67 | #endif 68 | return result; 69 | } 70 | #endif 71 | } 72 | 73 | } 74 | -------------------------------------------------------------------------------- /xbuffer_test/protobuf-net/Serializers/BlobSerializer.cs: -------------------------------------------------------------------------------- 1 | #if !NO_RUNTIME 2 | using System; 3 | #if FEAT_COMPILER 4 | using System.Reflection.Emit; 5 | #endif 6 | 7 | #if FEAT_IKVM 8 | using Type = IKVM.Reflection.Type; 9 | #endif 10 | 11 | 12 | namespace ProtoBuf.Serializers 13 | { 14 | sealed class BlobSerializer : IProtoSerializer 15 | { 16 | public Type ExpectedType { get { return expectedType; } } 17 | 18 | #if FEAT_IKVM 19 | readonly Type expectedType; 20 | #else 21 | static readonly Type expectedType = typeof(byte[]); 22 | #endif 23 | public BlobSerializer(ProtoBuf.Meta.TypeModel model, bool overwriteList) 24 | { 25 | #if FEAT_IKVM 26 | expectedType = model.MapType(typeof(byte[])); 27 | #endif 28 | this.overwriteList = overwriteList; 29 | } 30 | private readonly bool overwriteList; 31 | #if !FEAT_IKVM 32 | public object Read(object value, ProtoReader source) 33 | { 34 | return ProtoReader.AppendBytes(overwriteList ? null : (byte[])value, source); 35 | } 36 | public void Write(object value, ProtoWriter dest) 37 | { 38 | ProtoWriter.WriteBytes((byte[])value, dest); 39 | } 40 | #endif 41 | bool IProtoSerializer.RequiresOldValue { get { return !overwriteList; } } 42 | bool IProtoSerializer.ReturnsValue { get { return true; } } 43 | #if FEAT_COMPILER 44 | void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) 45 | { 46 | ctx.EmitBasicWrite("WriteBytes", valueFrom); 47 | } 48 | void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) 49 | { 50 | if (overwriteList) 51 | { 52 | ctx.LoadNullRef(); 53 | } 54 | else 55 | { 56 | ctx.LoadValue(valueFrom); 57 | } 58 | ctx.LoadReaderWriter(); 59 | ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("AppendBytes")); 60 | } 61 | #endif 62 | } 63 | } 64 | #endif -------------------------------------------------------------------------------- /xbuffer_test/protobuf-net/Serializers/BooleanSerializer.cs: -------------------------------------------------------------------------------- 1 | #if !NO_RUNTIME 2 | using System; 3 | 4 | #if FEAT_IKVM 5 | using Type = IKVM.Reflection.Type; 6 | using IKVM.Reflection; 7 | #else 8 | using System.Reflection; 9 | #endif 10 | 11 | 12 | 13 | 14 | 15 | namespace ProtoBuf.Serializers 16 | { 17 | sealed class BooleanSerializer : IProtoSerializer 18 | { 19 | #if FEAT_IKVM 20 | readonly Type expectedType; 21 | #else 22 | static readonly Type expectedType = typeof(bool); 23 | #endif 24 | public BooleanSerializer(ProtoBuf.Meta.TypeModel model) 25 | { 26 | #if FEAT_IKVM 27 | expectedType = model.MapType(typeof(bool)); 28 | #endif 29 | } 30 | public Type ExpectedType { get { return expectedType; } } 31 | 32 | #if !FEAT_IKVM 33 | public void Write(object value, ProtoWriter dest) 34 | { 35 | ProtoWriter.WriteBoolean((bool)value, dest); 36 | } 37 | public object Read(object value, ProtoReader source) 38 | { 39 | Helpers.DebugAssert(value == null); // since replaces 40 | return source.ReadBoolean(); 41 | } 42 | #endif 43 | bool IProtoSerializer.RequiresOldValue { get { return false; } } 44 | bool IProtoSerializer.ReturnsValue { get { return true; } } 45 | #if FEAT_COMPILER 46 | void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) 47 | { 48 | ctx.EmitBasicWrite("WriteBoolean", valueFrom); 49 | } 50 | void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) 51 | { 52 | ctx.EmitBasicRead("ReadBoolean", ExpectedType); 53 | } 54 | #endif 55 | } 56 | } 57 | #endif -------------------------------------------------------------------------------- /xbuffer_test/protobuf-net/Serializers/ByteSerializer.cs: -------------------------------------------------------------------------------- 1 | #if !NO_RUNTIME 2 | using System; 3 | 4 | #if FEAT_IKVM 5 | using Type = IKVM.Reflection.Type; 6 | #endif 7 | 8 | 9 | 10 | namespace ProtoBuf.Serializers 11 | { 12 | sealed class ByteSerializer : IProtoSerializer 13 | { 14 | public Type ExpectedType { get { return expectedType; } } 15 | 16 | #if FEAT_IKVM 17 | readonly Type expectedType; 18 | #else 19 | static readonly Type expectedType = typeof(byte); 20 | #endif 21 | public ByteSerializer(ProtoBuf.Meta.TypeModel model) 22 | { 23 | #if FEAT_IKVM 24 | expectedType = model.MapType(typeof(byte)); 25 | #endif 26 | } 27 | bool IProtoSerializer.RequiresOldValue { get { return false; } } 28 | bool IProtoSerializer.ReturnsValue { get { return true; } } 29 | #if !FEAT_IKVM 30 | public void Write(object value, ProtoWriter dest) 31 | { 32 | ProtoWriter.WriteByte((byte)value, dest); 33 | } 34 | public object Read(object value, ProtoReader source) 35 | { 36 | Helpers.DebugAssert(value == null); // since replaces 37 | return source.ReadByte(); 38 | } 39 | #endif 40 | 41 | #if FEAT_COMPILER 42 | void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) 43 | { 44 | ctx.EmitBasicWrite("WriteByte", valueFrom); 45 | } 46 | void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) 47 | { 48 | ctx.EmitBasicRead("ReadByte", ExpectedType); 49 | } 50 | #endif 51 | 52 | } 53 | } 54 | #endif -------------------------------------------------------------------------------- /xbuffer_test/protobuf-net/Serializers/CharSerializer.cs: -------------------------------------------------------------------------------- 1 | #if !NO_RUNTIME 2 | using System; 3 | 4 | #if FEAT_IKVM 5 | using Type = IKVM.Reflection.Type; 6 | using IKVM.Reflection; 7 | #else 8 | using System.Reflection; 9 | #endif 10 | 11 | 12 | namespace ProtoBuf.Serializers 13 | { 14 | sealed class CharSerializer : UInt16Serializer 15 | { 16 | #if FEAT_IKVM 17 | readonly Type expectedType; 18 | #else 19 | static readonly Type expectedType = typeof(char); 20 | #endif 21 | public CharSerializer(ProtoBuf.Meta.TypeModel model) : base(model) 22 | { 23 | #if FEAT_IKVM 24 | expectedType = model.MapType(typeof(char)); 25 | #endif 26 | } 27 | public override Type ExpectedType { get { return expectedType; } } 28 | 29 | #if !FEAT_IKVM 30 | public override void Write(object value, ProtoWriter dest) 31 | { 32 | ProtoWriter.WriteUInt16((ushort)(char)value, dest); 33 | } 34 | public override object Read(object value, ProtoReader source) 35 | { 36 | Helpers.DebugAssert(value == null); // since replaces 37 | return (char)source.ReadUInt16(); 38 | } 39 | #endif 40 | // no need for any special IL here; ushort and char are 41 | // interchangeable as long as there is no boxing/unboxing 42 | } 43 | } 44 | #endif -------------------------------------------------------------------------------- /xbuffer_test/protobuf-net/Serializers/CompiledSerializer.cs: -------------------------------------------------------------------------------- 1 | #if FEAT_COMPILER && !(FX11 || FEAT_IKVM) 2 | using System; 3 | using ProtoBuf.Meta; 4 | 5 | 6 | 7 | namespace ProtoBuf.Serializers 8 | { 9 | sealed class CompiledSerializer : IProtoTypeSerializer 10 | { 11 | bool IProtoTypeSerializer.HasCallbacks(TypeModel.CallbackType callbackType) 12 | { 13 | return head.HasCallbacks(callbackType); // these routes only used when bits of the model not compiled 14 | } 15 | bool IProtoTypeSerializer.CanCreateInstance() 16 | { 17 | return head.CanCreateInstance(); 18 | } 19 | object IProtoTypeSerializer.CreateInstance(ProtoReader source) 20 | { 21 | return head.CreateInstance(source); 22 | } 23 | public void Callback(object value, TypeModel.CallbackType callbackType, SerializationContext context) 24 | { 25 | head.Callback(value, callbackType, context); // these routes only used when bits of the model not compiled 26 | } 27 | public static CompiledSerializer Wrap(IProtoTypeSerializer head, TypeModel model) 28 | { 29 | CompiledSerializer result = head as CompiledSerializer; 30 | if (result == null) 31 | { 32 | result = new CompiledSerializer(head, model); 33 | Helpers.DebugAssert(((IProtoTypeSerializer)result).ExpectedType == head.ExpectedType); 34 | } 35 | return result; 36 | } 37 | private readonly IProtoTypeSerializer head; 38 | private readonly Compiler.ProtoSerializer serializer; 39 | private readonly Compiler.ProtoDeserializer deserializer; 40 | private CompiledSerializer(IProtoTypeSerializer head, TypeModel model) 41 | { 42 | this.head = head; 43 | serializer = Compiler.CompilerContext.BuildSerializer(head, model); 44 | deserializer = Compiler.CompilerContext.BuildDeserializer(head, model); 45 | } 46 | bool IProtoSerializer.RequiresOldValue { get { return head.RequiresOldValue; } } 47 | bool IProtoSerializer.ReturnsValue { get { return head.ReturnsValue; } } 48 | 49 | Type IProtoSerializer.ExpectedType { get { return head.ExpectedType; } } 50 | 51 | void IProtoSerializer.Write(object value, ProtoWriter dest) 52 | { 53 | serializer(value, dest); 54 | } 55 | object IProtoSerializer.Read(object value, ProtoReader source) 56 | { 57 | return deserializer(value, source); 58 | } 59 | 60 | void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) 61 | { 62 | head.EmitWrite(ctx, valueFrom); 63 | } 64 | void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) 65 | { 66 | head.EmitRead(ctx, valueFrom); 67 | } 68 | void IProtoTypeSerializer.EmitCallback(Compiler.CompilerContext ctx, Compiler.Local valueFrom, TypeModel.CallbackType callbackType) 69 | { 70 | head.EmitCallback(ctx, valueFrom, callbackType); 71 | } 72 | void IProtoTypeSerializer.EmitCreateInstance(Compiler.CompilerContext ctx) 73 | { 74 | head.EmitCreateInstance(ctx); 75 | } 76 | } 77 | } 78 | #endif -------------------------------------------------------------------------------- /xbuffer_test/protobuf-net/Serializers/DateTimeSerializer.cs: -------------------------------------------------------------------------------- 1 | #if !NO_RUNTIME 2 | using System; 3 | 4 | #if FEAT_IKVM 5 | using Type = IKVM.Reflection.Type; 6 | using IKVM.Reflection; 7 | #else 8 | using System.Reflection; 9 | #endif 10 | 11 | namespace ProtoBuf.Serializers 12 | { 13 | sealed class DateTimeSerializer : IProtoSerializer 14 | { 15 | #if FEAT_IKVM 16 | readonly Type expectedType; 17 | #else 18 | static readonly Type expectedType = typeof(DateTime); 19 | #endif 20 | public Type ExpectedType { get { return expectedType; } } 21 | 22 | bool IProtoSerializer.RequiresOldValue { get { return false; } } 23 | bool IProtoSerializer.ReturnsValue { get { return true; } } 24 | 25 | public DateTimeSerializer(ProtoBuf.Meta.TypeModel model) 26 | { 27 | #if FEAT_IKVM 28 | expectedType = model.MapType(typeof(DateTime)); 29 | #endif 30 | } 31 | #if !FEAT_IKVM 32 | public object Read(object value, ProtoReader source) 33 | { 34 | Helpers.DebugAssert(value == null); // since replaces 35 | return BclHelpers.ReadDateTime(source); 36 | } 37 | public void Write(object value, ProtoWriter dest) 38 | { 39 | BclHelpers.WriteDateTime((DateTime)value, dest); 40 | } 41 | #endif 42 | #if FEAT_COMPILER 43 | void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) 44 | { 45 | ctx.EmitWrite(ctx.MapType(typeof(BclHelpers)), "WriteDateTime", valueFrom); 46 | } 47 | void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) 48 | { 49 | ctx.EmitBasicRead(ctx.MapType(typeof(BclHelpers)), "ReadDateTime", ExpectedType); 50 | } 51 | #endif 52 | 53 | } 54 | } 55 | #endif -------------------------------------------------------------------------------- /xbuffer_test/protobuf-net/Serializers/DecimalSerializer.cs: -------------------------------------------------------------------------------- 1 | #if !NO_RUNTIME 2 | using System; 3 | using ProtoBuf.Meta; 4 | 5 | #if FEAT_IKVM 6 | using Type = IKVM.Reflection.Type; 7 | using IKVM.Reflection; 8 | #else 9 | using System.Reflection; 10 | #endif 11 | 12 | 13 | 14 | namespace ProtoBuf.Serializers 15 | { 16 | sealed class DecimalSerializer : IProtoSerializer 17 | { 18 | #if FEAT_IKVM 19 | readonly Type expectedType; 20 | #else 21 | static readonly Type expectedType = typeof(decimal); 22 | #endif 23 | public DecimalSerializer(ProtoBuf.Meta.TypeModel model) 24 | { 25 | #if FEAT_IKVM 26 | expectedType = model.MapType(typeof(decimal)); 27 | #endif 28 | } 29 | public Type ExpectedType { get { return expectedType; } } 30 | 31 | bool IProtoSerializer.RequiresOldValue { get { return false; } } 32 | bool IProtoSerializer.ReturnsValue { get { return true; } } 33 | #if !FEAT_IKVM 34 | public object Read(object value, ProtoReader source) 35 | { 36 | Helpers.DebugAssert(value == null); // since replaces 37 | return BclHelpers.ReadDecimal(source); 38 | } 39 | public void Write(object value, ProtoWriter dest) 40 | { 41 | BclHelpers.WriteDecimal((decimal)value, dest); 42 | } 43 | #endif 44 | #if FEAT_COMPILER 45 | void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) 46 | { 47 | ctx.EmitWrite(ctx.MapType(typeof(BclHelpers)), "WriteDecimal", valueFrom); 48 | } 49 | void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) 50 | { 51 | ctx.EmitBasicRead(ctx.MapType(typeof(BclHelpers)), "ReadDecimal", ExpectedType); 52 | } 53 | #endif 54 | 55 | } 56 | } 57 | #endif -------------------------------------------------------------------------------- /xbuffer_test/protobuf-net/Serializers/DoubleSerializer.cs: -------------------------------------------------------------------------------- 1 | #if !NO_RUNTIME 2 | using System; 3 | using ProtoBuf.Meta; 4 | 5 | #if FEAT_IKVM 6 | using Type = IKVM.Reflection.Type; 7 | using IKVM.Reflection; 8 | #else 9 | using System.Reflection; 10 | #endif 11 | 12 | namespace ProtoBuf.Serializers 13 | { 14 | sealed class DoubleSerializer : IProtoSerializer 15 | { 16 | #if FEAT_IKVM 17 | readonly Type expectedType; 18 | #else 19 | static readonly Type expectedType = typeof(double); 20 | #endif 21 | public DoubleSerializer(ProtoBuf.Meta.TypeModel model) 22 | { 23 | #if FEAT_IKVM 24 | expectedType = model.MapType(typeof(double)); 25 | #endif 26 | } 27 | 28 | public Type ExpectedType { get { return expectedType; } } 29 | bool IProtoSerializer.RequiresOldValue { get { return false; } } 30 | bool IProtoSerializer.ReturnsValue { get { return true; } } 31 | #if !FEAT_IKVM 32 | public object Read(object value, ProtoReader source) 33 | { 34 | Helpers.DebugAssert(value == null); // since replaces 35 | return source.ReadDouble(); 36 | } 37 | public void Write(object value, ProtoWriter dest) 38 | { 39 | ProtoWriter.WriteDouble((double)value, dest); 40 | } 41 | #endif 42 | #if FEAT_COMPILER 43 | void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) 44 | { 45 | ctx.EmitBasicWrite("WriteDouble", valueFrom); 46 | } 47 | void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) 48 | { 49 | ctx.EmitBasicRead("ReadDouble", ExpectedType); 50 | } 51 | #endif 52 | } 53 | } 54 | #endif -------------------------------------------------------------------------------- /xbuffer_test/protobuf-net/Serializers/FieldDecorator.cs: -------------------------------------------------------------------------------- 1 | #if !NO_RUNTIME 2 | using System; 3 | 4 | using ProtoBuf.Meta; 5 | 6 | #if FEAT_IKVM 7 | using Type = IKVM.Reflection.Type; 8 | using IKVM.Reflection; 9 | #else 10 | using System.Reflection; 11 | #endif 12 | 13 | 14 | 15 | namespace ProtoBuf.Serializers 16 | { 17 | sealed class FieldDecorator : ProtoDecoratorBase 18 | { 19 | 20 | public override Type ExpectedType { get { return forType; } } 21 | private readonly FieldInfo field; 22 | private readonly Type forType; 23 | public override bool RequiresOldValue { get { return true; } } 24 | public override bool ReturnsValue { get { return false; } } 25 | public FieldDecorator(Type forType, FieldInfo field, IProtoSerializer tail) : base(tail) 26 | { 27 | Helpers.DebugAssert(forType != null); 28 | Helpers.DebugAssert(field != null); 29 | this.forType = forType; 30 | this.field = field; 31 | } 32 | #if !FEAT_IKVM 33 | public override void Write(object value, ProtoWriter dest) 34 | { 35 | Helpers.DebugAssert(value != null); 36 | value = field.GetValue(value); 37 | if(value != null) Tail.Write(value, dest); 38 | } 39 | public override object Read(object value, ProtoReader source) 40 | { 41 | Helpers.DebugAssert(value != null); 42 | object newValue = Tail.Read((Tail.RequiresOldValue ? field.GetValue(value) : null), source); 43 | if(newValue != null) field.SetValue(value,newValue); 44 | return null; 45 | } 46 | #endif 47 | 48 | #if FEAT_COMPILER 49 | protected override void EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) 50 | { 51 | ctx.LoadAddress(valueFrom, ExpectedType); 52 | ctx.LoadValue(field); 53 | ctx.WriteNullCheckedTail(field.FieldType, Tail, null); 54 | } 55 | protected override void EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) 56 | { 57 | using (Compiler.Local loc = ctx.GetLocalWithValue(ExpectedType, valueFrom)) 58 | { 59 | if (Tail.RequiresOldValue) 60 | { 61 | ctx.LoadAddress(loc, ExpectedType); 62 | ctx.LoadValue(field); 63 | } 64 | // value is either now on the stack or not needed 65 | ctx.ReadNullCheckedTail(field.FieldType, Tail, null); 66 | 67 | if (Tail.ReturnsValue) 68 | { 69 | using (Compiler.Local newVal = new Compiler.Local(ctx, field.FieldType)) 70 | { 71 | ctx.StoreValue(newVal); 72 | if (field.FieldType.IsValueType) 73 | { 74 | ctx.LoadAddress(loc, ExpectedType); 75 | ctx.LoadValue(newVal); 76 | ctx.StoreValue(field); 77 | } 78 | else 79 | { 80 | Compiler.CodeLabel allDone = ctx.DefineLabel(); 81 | ctx.LoadValue(newVal); 82 | ctx.BranchIfFalse(allDone, true); // interpret null as "don't assign" 83 | 84 | ctx.LoadAddress(loc, ExpectedType); 85 | ctx.LoadValue(newVal); 86 | ctx.StoreValue(field); 87 | 88 | ctx.MarkLabel(allDone); 89 | } 90 | } 91 | } 92 | } 93 | } 94 | #endif 95 | } 96 | } 97 | #endif -------------------------------------------------------------------------------- /xbuffer_test/protobuf-net/Serializers/GuidSerializer.cs: -------------------------------------------------------------------------------- 1 | #if !NO_RUNTIME 2 | using System; 3 | 4 | #if FEAT_IKVM 5 | using Type = IKVM.Reflection.Type; 6 | #endif 7 | 8 | 9 | namespace ProtoBuf.Serializers 10 | { 11 | sealed class GuidSerializer : IProtoSerializer 12 | { 13 | #if FEAT_IKVM 14 | readonly Type expectedType; 15 | #else 16 | static readonly Type expectedType = typeof(Guid); 17 | #endif 18 | public GuidSerializer(ProtoBuf.Meta.TypeModel model) 19 | { 20 | #if FEAT_IKVM 21 | expectedType = model.MapType(typeof(Guid)); 22 | #endif 23 | } 24 | 25 | public Type ExpectedType { get { return expectedType; } } 26 | 27 | bool IProtoSerializer.RequiresOldValue { get { return false; } } 28 | bool IProtoSerializer.ReturnsValue { get { return true; } } 29 | 30 | #if !FEAT_IKVM 31 | public void Write(object value, ProtoWriter dest) 32 | { 33 | BclHelpers.WriteGuid((Guid)value, dest); 34 | } 35 | public object Read(object value, ProtoReader source) 36 | { 37 | Helpers.DebugAssert(value == null); // since replaces 38 | return BclHelpers.ReadGuid(source); 39 | } 40 | #endif 41 | 42 | #if FEAT_COMPILER 43 | void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) 44 | { 45 | ctx.EmitWrite(ctx.MapType(typeof(BclHelpers)), "WriteGuid", valueFrom); 46 | } 47 | void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) 48 | { 49 | ctx.EmitBasicRead(ctx.MapType(typeof(BclHelpers)), "ReadGuid", ExpectedType); 50 | } 51 | #endif 52 | 53 | } 54 | } 55 | #endif -------------------------------------------------------------------------------- /xbuffer_test/protobuf-net/Serializers/IProtoSerializer.cs: -------------------------------------------------------------------------------- 1 | #if !NO_RUNTIME 2 | using System; 3 | 4 | #if FEAT_IKVM 5 | using Type = IKVM.Reflection.Type; 6 | #endif 7 | 8 | namespace ProtoBuf.Serializers 9 | { 10 | interface IProtoSerializer 11 | { 12 | /// 13 | /// The type that this serializer is intended to work for. 14 | /// 15 | Type ExpectedType { get; } 16 | 17 | #if !FEAT_IKVM 18 | /// 19 | /// Perform the steps necessary to serialize this data. 20 | /// 21 | /// The value to be serialized. 22 | /// The writer entity that is accumulating the output data. 23 | void Write(object value, ProtoWriter dest); 24 | 25 | /// 26 | /// Perform the steps necessary to deserialize this data. 27 | /// 28 | /// The current value, if appropriate. 29 | /// The reader providing the input data. 30 | /// The updated / replacement value. 31 | object Read(object value, ProtoReader source); 32 | #endif 33 | /// 34 | /// Indicates whether a Read operation replaces the existing value, or 35 | /// extends the value. If false, the "value" parameter to Read is 36 | /// discarded, and should be passed in as null. 37 | /// 38 | bool RequiresOldValue { get; } 39 | /// 40 | /// Now all Read operations return a value (although most do); if false no 41 | /// value should be expected. 42 | /// 43 | bool ReturnsValue { get; } 44 | 45 | #if FEAT_COMPILER 46 | 47 | 48 | 49 | /// Emit the IL necessary to perform the given actions 50 | /// to serialize this data. 51 | /// 52 | /// Details and utilities for the method being generated. 53 | /// The source of the data to work against; 54 | /// If the value is only needed once, then LoadValue is sufficient. If 55 | /// the value is needed multiple times, then note that a "null" 56 | /// means "the top of the stack", in which case you should create your 57 | /// own copy - GetLocalWithValue. 58 | void EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom); 59 | 60 | /// 61 | /// Emit the IL necessary to perform the given actions to deserialize this data. 62 | /// 63 | /// Details and utilities for the method being generated. 64 | /// For nested values, the instance holding the values; note 65 | /// that this is not always provided - a null means not supplied. Since this is always 66 | /// a variable or argument, it is not necessary to consume this value. 67 | void EmitRead(Compiler.CompilerContext ctx, Compiler.Local entity); 68 | #endif 69 | } 70 | } 71 | #endif -------------------------------------------------------------------------------- /xbuffer_test/protobuf-net/Serializers/IProtoTypeSerializer.cs: -------------------------------------------------------------------------------- 1 | #if !NO_RUNTIME 2 | using ProtoBuf.Meta; 3 | namespace ProtoBuf.Serializers 4 | { 5 | interface IProtoTypeSerializer : IProtoSerializer 6 | { 7 | bool HasCallbacks(TypeModel.CallbackType callbackType); 8 | bool CanCreateInstance(); 9 | #if !FEAT_IKVM 10 | object CreateInstance(ProtoReader source); 11 | void Callback(object value, TypeModel.CallbackType callbackType, SerializationContext context); 12 | #endif 13 | #if FEAT_COMPILER 14 | void EmitCallback(Compiler.CompilerContext ctx, Compiler.Local valueFrom, TypeModel.CallbackType callbackType); 15 | #endif 16 | #if FEAT_COMPILER 17 | void EmitCreateInstance(Compiler.CompilerContext ctx); 18 | #endif 19 | } 20 | } 21 | #endif -------------------------------------------------------------------------------- /xbuffer_test/protobuf-net/Serializers/ISerializerProxy.cs: -------------------------------------------------------------------------------- 1 | #if !NO_RUNTIME 2 | 3 | namespace ProtoBuf.Serializers 4 | { 5 | interface ISerializerProxy 6 | { 7 | IProtoSerializer Serializer { get; } 8 | } 9 | } 10 | #endif -------------------------------------------------------------------------------- /xbuffer_test/protobuf-net/Serializers/Int16Serializer.cs: -------------------------------------------------------------------------------- 1 | #if !NO_RUNTIME 2 | using System; 3 | 4 | #if FEAT_IKVM 5 | using Type = IKVM.Reflection.Type; 6 | using IKVM.Reflection; 7 | #else 8 | using System.Reflection; 9 | #endif 10 | 11 | namespace ProtoBuf.Serializers 12 | { 13 | sealed class Int16Serializer : IProtoSerializer 14 | { 15 | #if FEAT_IKVM 16 | readonly Type expectedType; 17 | #else 18 | static readonly Type expectedType = typeof(short); 19 | #endif 20 | public Int16Serializer(ProtoBuf.Meta.TypeModel model) 21 | { 22 | #if FEAT_IKVM 23 | expectedType = model.MapType(typeof(short)); 24 | #endif 25 | } 26 | public Type ExpectedType { get { return expectedType; } } 27 | 28 | bool IProtoSerializer.RequiresOldValue { get { return false; } } 29 | bool IProtoSerializer.ReturnsValue { get { return true; } } 30 | #if !FEAT_IKVM 31 | public object Read(object value, ProtoReader source) 32 | { 33 | Helpers.DebugAssert(value == null); // since replaces 34 | return source.ReadInt16(); 35 | } 36 | public void Write(object value, ProtoWriter dest) 37 | { 38 | ProtoWriter.WriteInt16((short)value, dest); 39 | } 40 | #endif 41 | #if FEAT_COMPILER 42 | void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) 43 | { 44 | ctx.EmitBasicWrite("WriteInt16", valueFrom); 45 | } 46 | void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) 47 | { 48 | ctx.EmitBasicRead("ReadInt16", ExpectedType); 49 | } 50 | #endif 51 | 52 | } 53 | } 54 | #endif -------------------------------------------------------------------------------- /xbuffer_test/protobuf-net/Serializers/Int32Serializer.cs: -------------------------------------------------------------------------------- 1 | #if !NO_RUNTIME 2 | using System; 3 | 4 | #if FEAT_IKVM 5 | using Type = IKVM.Reflection.Type; 6 | using IKVM.Reflection; 7 | #else 8 | using System.Reflection; 9 | #endif 10 | 11 | namespace ProtoBuf.Serializers 12 | { 13 | sealed class Int32Serializer : IProtoSerializer 14 | { 15 | #if FEAT_IKVM 16 | readonly Type expectedType; 17 | #else 18 | static readonly Type expectedType = typeof(int); 19 | #endif 20 | public Int32Serializer(ProtoBuf.Meta.TypeModel model) 21 | { 22 | #if FEAT_IKVM 23 | expectedType = model.MapType(typeof(int)); 24 | #endif 25 | } 26 | public Type ExpectedType { get { return expectedType; } } 27 | 28 | bool IProtoSerializer.RequiresOldValue { get { return false; } } 29 | bool IProtoSerializer.ReturnsValue { get { return true; } } 30 | #if !FEAT_IKVM 31 | public object Read(object value, ProtoReader source) 32 | { 33 | Helpers.DebugAssert(value == null); // since replaces 34 | return source.ReadInt32(); 35 | } 36 | public void Write(object value, ProtoWriter dest) 37 | { 38 | ProtoWriter.WriteInt32((int)value, dest); 39 | } 40 | #endif 41 | #if FEAT_COMPILER 42 | void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) 43 | { 44 | ctx.EmitBasicWrite("WriteInt32", valueFrom); 45 | } 46 | void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) 47 | { 48 | ctx.EmitBasicRead("ReadInt32", ExpectedType); 49 | } 50 | #endif 51 | 52 | } 53 | } 54 | #endif -------------------------------------------------------------------------------- /xbuffer_test/protobuf-net/Serializers/Int64Serializer.cs: -------------------------------------------------------------------------------- 1 | #if !NO_RUNTIME 2 | using System; 3 | using ProtoBuf.Meta; 4 | 5 | #if FEAT_IKVM 6 | using Type = IKVM.Reflection.Type; 7 | using IKVM.Reflection; 8 | #else 9 | using System.Reflection; 10 | #endif 11 | 12 | namespace ProtoBuf.Serializers 13 | { 14 | sealed class Int64Serializer : IProtoSerializer 15 | { 16 | #if FEAT_IKVM 17 | readonly Type expectedType; 18 | #else 19 | static readonly Type expectedType = typeof(long); 20 | #endif 21 | public Int64Serializer(ProtoBuf.Meta.TypeModel model) 22 | { 23 | #if FEAT_IKVM 24 | expectedType = model.MapType(typeof(long)); 25 | #endif 26 | } 27 | 28 | public Type ExpectedType { get { return expectedType; } } 29 | 30 | bool IProtoSerializer.RequiresOldValue { get { return false; } } 31 | bool IProtoSerializer.ReturnsValue { get { return true; } } 32 | #if !FEAT_IKVM 33 | public object Read(object value, ProtoReader source) 34 | { 35 | Helpers.DebugAssert(value == null); // since replaces 36 | return source.ReadInt64(); 37 | } 38 | public void Write(object value, ProtoWriter dest) 39 | { 40 | ProtoWriter.WriteInt64((long)value, dest); 41 | } 42 | #endif 43 | #if FEAT_COMPILER 44 | void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) 45 | { 46 | ctx.EmitBasicWrite("WriteInt64", valueFrom); 47 | } 48 | void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) 49 | { 50 | ctx.EmitBasicRead("ReadInt64", ExpectedType); 51 | } 52 | #endif 53 | } 54 | } 55 | #endif -------------------------------------------------------------------------------- /xbuffer_test/protobuf-net/Serializers/KeyValuePairDecorator.cs: -------------------------------------------------------------------------------- 1 |  2 | namespace ProtoBuf.Serializers 3 | { 4 | /* 5 | sealed class KeyValuePairDecorator : IProtoSerializer 6 | { 7 | private readonly Type pairType; 8 | private readonly IProtoSerializer keyTail, valueTail; 9 | public KeyValuePairDecorator(Type pairType, IProtoSerializer keyTail, IProtoSerializer valueTail) { 10 | Helpers.DebugAssert(pairType != null); 11 | Helpers.DebugAssert(keyTail != null); 12 | Helpers.DebugAssert(valueTail != null); 13 | Helpers.DebugAssert(pairType == typeof(System.Collections.Generic.KeyValuePair<,>).MakeGenericType(keyTail.ExpectedType,valueTail.ExpectedType), "Key/value type mismatch"); 14 | this.pairType = pairType; 15 | this.keyTail = keyTail; 16 | this.valueTail = valueTail; 17 | } 18 | 19 | public Type ExpectedType { get { return pairType;}} 20 | public bool ReturnsValue { get { return true; } } 21 | public bool RequiresOldValue { get { return true; } } 22 | public abstract void Write(object value, ProtoWriter dest) 23 | { 24 | 25 | } 26 | public abstract object Read(object value, ProtoReader source) 27 | { 28 | 29 | } 30 | #if FEAT_COMPILER 31 | void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) 32 | { 33 | throw new NotImplementedException(); 34 | } 35 | void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) { 36 | throw new NotImplementedException(); 37 | } 38 | #endif 39 | }*/ 40 | } 41 | -------------------------------------------------------------------------------- /xbuffer_test/protobuf-net/Serializers/MemberSpecifiedDecorator.cs: -------------------------------------------------------------------------------- 1 | #if !NO_RUNTIME 2 | using System; 3 | using ProtoBuf.Meta; 4 | 5 | #if FEAT_IKVM 6 | using Type = IKVM.Reflection.Type; 7 | using IKVM.Reflection; 8 | #else 9 | using System.Reflection; 10 | #endif 11 | 12 | 13 | 14 | namespace ProtoBuf.Serializers 15 | { 16 | sealed class MemberSpecifiedDecorator : ProtoDecoratorBase 17 | { 18 | 19 | public override Type ExpectedType { get { return Tail.ExpectedType; } } 20 | public override bool RequiresOldValue { get { return Tail.RequiresOldValue; } } 21 | public override bool ReturnsValue { get { return Tail.ReturnsValue; } } 22 | private readonly MethodInfo getSpecified, setSpecified; 23 | public MemberSpecifiedDecorator(MethodInfo getSpecified, MethodInfo setSpecified, IProtoSerializer tail) 24 | : base(tail) 25 | { 26 | if (getSpecified == null && setSpecified == null) throw new InvalidOperationException(); 27 | this.getSpecified = getSpecified; 28 | this.setSpecified = setSpecified; 29 | } 30 | #if !FEAT_IKVM 31 | public override void Write(object value, ProtoWriter dest) 32 | { 33 | if(getSpecified == null || (bool)getSpecified.Invoke(value, null)) 34 | { 35 | Tail.Write(value, dest); 36 | } 37 | } 38 | public override object Read(object value, ProtoReader source) 39 | { 40 | object result = Tail.Read(value, source); 41 | if (setSpecified != null) setSpecified.Invoke(value, new object[] { true }); 42 | return result; 43 | } 44 | #endif 45 | 46 | #if FEAT_COMPILER 47 | protected override void EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) 48 | { 49 | if (getSpecified == null) 50 | { 51 | Tail.EmitWrite(ctx, valueFrom); 52 | return; 53 | } 54 | using (Compiler.Local loc = ctx.GetLocalWithValue(ExpectedType, valueFrom)) 55 | { 56 | ctx.LoadAddress(loc, ExpectedType); 57 | ctx.EmitCall(getSpecified); 58 | Compiler.CodeLabel done = ctx.DefineLabel(); 59 | ctx.BranchIfFalse(done, false); 60 | Tail.EmitWrite(ctx, loc); 61 | ctx.MarkLabel(done); 62 | } 63 | 64 | } 65 | protected override void EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) 66 | { 67 | if (setSpecified == null) 68 | { 69 | Tail.EmitRead(ctx, valueFrom); 70 | return; 71 | } 72 | using (Compiler.Local loc = ctx.GetLocalWithValue(ExpectedType, valueFrom)) 73 | { 74 | Tail.EmitRead(ctx, loc); 75 | ctx.LoadAddress(loc, ExpectedType); 76 | ctx.LoadValue(1); // true 77 | ctx.EmitCall(setSpecified); 78 | } 79 | } 80 | #endif 81 | } 82 | } 83 | #endif -------------------------------------------------------------------------------- /xbuffer_test/protobuf-net/Serializers/NetObjectSerializer.cs: -------------------------------------------------------------------------------- 1 | #if !NO_RUNTIME 2 | using System; 3 | using ProtoBuf.Meta; 4 | 5 | #if FEAT_IKVM 6 | using Type = IKVM.Reflection.Type; 7 | using IKVM.Reflection; 8 | #else 9 | using System.Reflection; 10 | #endif 11 | 12 | namespace ProtoBuf.Serializers 13 | { 14 | 15 | sealed class NetObjectSerializer : IProtoSerializer 16 | { 17 | private readonly int key; 18 | private readonly Type type; 19 | 20 | private readonly BclHelpers.NetObjectOptions options; 21 | 22 | public NetObjectSerializer(TypeModel model, Type type, int key, BclHelpers.NetObjectOptions options) 23 | { 24 | bool dynamicType = (options & BclHelpers.NetObjectOptions.DynamicType) != 0; 25 | this.key = dynamicType ? -1 : key; 26 | this.type = dynamicType ? model.MapType(typeof(object)) : type; 27 | this.options = options; 28 | } 29 | 30 | public Type ExpectedType 31 | { 32 | get { return type; } 33 | } 34 | public bool ReturnsValue 35 | { 36 | get { return true; } 37 | } 38 | public bool RequiresOldValue 39 | { 40 | get { return true; } 41 | } 42 | #if !FEAT_IKVM 43 | public object Read(object value, ProtoReader source) 44 | { 45 | return BclHelpers.ReadNetObject(value, source, key, type == typeof(object) ? null : type, options); 46 | } 47 | public void Write(object value, ProtoWriter dest) 48 | { 49 | BclHelpers.WriteNetObject(value, dest, key, options); 50 | } 51 | #endif 52 | 53 | #if FEAT_COMPILER 54 | public void EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) 55 | { 56 | ctx.LoadValue(valueFrom); 57 | ctx.CastToObject(type); 58 | ctx.LoadReaderWriter(); 59 | ctx.LoadValue(ctx.MapMetaKeyToCompiledKey(key)); 60 | if (type == ctx.MapType(typeof(object))) ctx.LoadNullRef(); 61 | else ctx.LoadValue(type); 62 | ctx.LoadValue((int)options); 63 | ctx.EmitCall(ctx.MapType(typeof(BclHelpers)).GetMethod("ReadNetObject")); 64 | ctx.CastFromObject(type); 65 | } 66 | public void EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) 67 | { 68 | ctx.LoadValue(valueFrom); 69 | ctx.CastToObject(type); 70 | ctx.LoadReaderWriter(); 71 | ctx.LoadValue(ctx.MapMetaKeyToCompiledKey(key)); 72 | ctx.LoadValue((int)options); 73 | ctx.EmitCall(ctx.MapType(typeof(BclHelpers)).GetMethod("WriteNetObject")); 74 | } 75 | #endif 76 | } 77 | } 78 | #endif -------------------------------------------------------------------------------- /xbuffer_test/protobuf-net/Serializers/NullDecorator.cs: -------------------------------------------------------------------------------- 1 | #if !NO_RUNTIME 2 | using System; 3 | 4 | using ProtoBuf.Meta; 5 | 6 | #if FEAT_IKVM 7 | using Type = IKVM.Reflection.Type; 8 | using IKVM.Reflection; 9 | #else 10 | using System.Reflection; 11 | #endif 12 | 13 | namespace ProtoBuf.Serializers 14 | { 15 | sealed class NullDecorator : ProtoDecoratorBase 16 | { 17 | private readonly Type expectedType; 18 | public const int Tag = 1; 19 | public NullDecorator(TypeModel model, IProtoSerializer tail) : base(tail) 20 | { 21 | if (!tail.ReturnsValue) 22 | throw new NotSupportedException("NullDecorator only supports implementations that return values"); 23 | 24 | Type tailType = tail.ExpectedType; 25 | if (Helpers.IsValueType(tailType)) 26 | { 27 | #if NO_GENERICS 28 | throw new NotSupportedException("NullDecorator cannot be used with a struct without generics support"); 29 | #else 30 | expectedType = model.MapType(typeof(Nullable<>)).MakeGenericType(tailType); 31 | #endif 32 | } 33 | else 34 | { 35 | expectedType = tailType; 36 | } 37 | 38 | } 39 | 40 | public override Type ExpectedType 41 | { 42 | get { return expectedType; } 43 | } 44 | public override bool ReturnsValue 45 | { 46 | get { return true; } 47 | } 48 | public override bool RequiresOldValue 49 | { 50 | get { return true; } 51 | } 52 | #if FEAT_COMPILER 53 | protected override void EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) 54 | { 55 | using (Compiler.Local oldValue = ctx.GetLocalWithValue(expectedType, valueFrom)) 56 | using (Compiler.Local token = new Compiler.Local(ctx, ctx.MapType(typeof(SubItemToken)))) 57 | using (Compiler.Local field = new Compiler.Local(ctx, ctx.MapType(typeof(int)))) 58 | { 59 | ctx.LoadReaderWriter(); 60 | ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("StartSubItem")); 61 | ctx.StoreValue(token); 62 | 63 | Compiler.CodeLabel next = ctx.DefineLabel(), processField = ctx.DefineLabel(), end = ctx.DefineLabel(); 64 | 65 | ctx.MarkLabel(next); 66 | 67 | ctx.EmitBasicRead("ReadFieldHeader", ctx.MapType(typeof(int))); 68 | ctx.CopyValue(); 69 | ctx.StoreValue(field); 70 | ctx.LoadValue(Tag); // = 1 - process 71 | ctx.BranchIfEqual(processField, true); 72 | ctx.LoadValue(field); 73 | ctx.LoadValue(1); // < 1 - exit 74 | ctx.BranchIfLess(end, false); 75 | 76 | // default: skip 77 | ctx.LoadReaderWriter(); 78 | ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("SkipField")); 79 | ctx.Branch(next, true); 80 | 81 | // process 82 | ctx.MarkLabel(processField); 83 | if (Tail.RequiresOldValue) 84 | { 85 | if (expectedType.IsValueType) 86 | { 87 | ctx.LoadAddress(oldValue, expectedType); 88 | ctx.EmitCall(expectedType.GetMethod("GetValueOrDefault", Helpers.EmptyTypes)); 89 | } 90 | else 91 | { 92 | ctx.LoadValue(oldValue); 93 | } 94 | } 95 | Tail.EmitRead(ctx, null); 96 | // note we demanded always returns a value 97 | if (expectedType.IsValueType) 98 | { 99 | ctx.EmitCtor(expectedType, Tail.ExpectedType); // re-nullable it 100 | } 101 | ctx.StoreValue(oldValue); 102 | ctx.Branch(next, false); 103 | 104 | // outro 105 | ctx.MarkLabel(end); 106 | 107 | ctx.LoadValue(token); 108 | ctx.LoadReaderWriter(); 109 | ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("EndSubItem")); 110 | ctx.LoadValue(oldValue); // load the old value 111 | } 112 | } 113 | protected override void EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) 114 | { 115 | using(Compiler.Local valOrNull = ctx.GetLocalWithValue(expectedType, valueFrom)) 116 | using(Compiler.Local token = new Compiler.Local(ctx, ctx.MapType(typeof(SubItemToken)))) 117 | { 118 | ctx.LoadNullRef(); 119 | ctx.LoadReaderWriter(); 120 | ctx.EmitCall(ctx.MapType(typeof(ProtoWriter)).GetMethod("StartSubItem")); 121 | ctx.StoreValue(token); 122 | 123 | if (expectedType.IsValueType) 124 | { 125 | ctx.LoadAddress(valOrNull, expectedType); 126 | ctx.LoadValue(expectedType.GetProperty("HasValue")); 127 | } 128 | else 129 | { 130 | ctx.LoadValue(valOrNull); 131 | } 132 | Compiler.CodeLabel @end = ctx.DefineLabel(); 133 | ctx.BranchIfFalse(@end, false); 134 | if (expectedType.IsValueType) 135 | { 136 | ctx.LoadAddress(valOrNull, expectedType); 137 | ctx.EmitCall(expectedType.GetMethod("GetValueOrDefault", Helpers.EmptyTypes)); 138 | } 139 | else 140 | { 141 | ctx.LoadValue(valOrNull); 142 | } 143 | Tail.EmitWrite(ctx, null); 144 | 145 | ctx.MarkLabel(@end); 146 | 147 | ctx.LoadValue(token); 148 | ctx.LoadReaderWriter(); 149 | ctx.EmitCall(ctx.MapType(typeof(ProtoWriter)).GetMethod("EndSubItem")); 150 | } 151 | } 152 | #endif 153 | 154 | #if !FEAT_IKVM 155 | public override object Read(object value, ProtoReader source) 156 | { 157 | SubItemToken tok = ProtoReader.StartSubItem(source); 158 | int field; 159 | while((field = source.ReadFieldHeader()) > 0) 160 | { 161 | if(field == Tag) { 162 | value = Tail.Read(value, source); 163 | } else { 164 | source.SkipField(); 165 | } 166 | } 167 | ProtoReader.EndSubItem(tok, source); 168 | return value; 169 | } 170 | public override void Write(object value, ProtoWriter dest) 171 | { 172 | SubItemToken token = ProtoWriter.StartSubItem(null, dest); 173 | if(value != null) 174 | { 175 | Tail.Write(value, dest); 176 | } 177 | ProtoWriter.EndSubItem(token, dest); 178 | } 179 | #endif 180 | } 181 | } 182 | #endif -------------------------------------------------------------------------------- /xbuffer_test/protobuf-net/Serializers/ParseableSerializer.cs: -------------------------------------------------------------------------------- 1 | #if !NO_RUNTIME 2 | using System; 3 | using System.Net; 4 | using ProtoBuf.Meta; 5 | #if FEAT_IKVM 6 | using Type = IKVM.Reflection.Type; 7 | using IKVM.Reflection; 8 | #else 9 | using System.Reflection; 10 | #endif 11 | 12 | namespace ProtoBuf.Serializers 13 | { 14 | sealed class ParseableSerializer : IProtoSerializer 15 | { 16 | private readonly MethodInfo parse; 17 | public static ParseableSerializer TryCreate(Type type, TypeModel model) 18 | { 19 | if (type == null) throw new ArgumentNullException("type"); 20 | #if WINRT || PORTABLE 21 | MethodInfo method = null; 22 | 23 | #if WINRT 24 | foreach (MethodInfo tmp in type.GetTypeInfo().GetDeclaredMethods("Parse")) 25 | #else 26 | foreach (MethodInfo tmp in type.GetMethods(BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly)) 27 | #endif 28 | { 29 | ParameterInfo[] p; 30 | if (tmp.Name == "Parse" && tmp.IsPublic && tmp.IsStatic && tmp.DeclaringType == type && (p = tmp.GetParameters()) != null && p.Length == 1 && p[0].ParameterType == typeof(string)) 31 | { 32 | method = tmp; 33 | break; 34 | } 35 | } 36 | #else 37 | MethodInfo method = type.GetMethod("Parse", 38 | BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly, 39 | null, new Type[] { model.MapType(typeof(string)) }, null); 40 | #endif 41 | if (method != null && method.ReturnType == type) 42 | { 43 | if (Helpers.IsValueType(type)) 44 | { 45 | MethodInfo toString = GetCustomToString(type); 46 | if (toString == null || toString.ReturnType != model.MapType(typeof(string))) return null; // need custom ToString, fools 47 | } 48 | return new ParseableSerializer(method); 49 | } 50 | return null; 51 | } 52 | private static MethodInfo GetCustomToString(Type type) 53 | { 54 | #if WINRT 55 | foreach (MethodInfo method in type.GetTypeInfo().GetDeclaredMethods("ToString")) 56 | { 57 | if (method.IsPublic && !method.IsStatic && method.GetParameters().Length == 0) return method; 58 | } 59 | return null; 60 | #elif PORTABLE 61 | MethodInfo method = Helpers.GetInstanceMethod(type, "ToString", Helpers.EmptyTypes); 62 | if (method == null || !method.IsPublic || method.IsStatic || method.DeclaringType != type) return null; 63 | return method; 64 | #else 65 | 66 | return type.GetMethod("ToString", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly, 67 | null, Helpers.EmptyTypes, null); 68 | #endif 69 | } 70 | private ParseableSerializer(MethodInfo parse) 71 | { 72 | this.parse = parse; 73 | } 74 | public Type ExpectedType { get { return parse.DeclaringType; } } 75 | 76 | bool IProtoSerializer.RequiresOldValue { get { return false; } } 77 | bool IProtoSerializer.ReturnsValue { get { return true; } } 78 | 79 | #if !FEAT_IKVM 80 | public object Read(object value, ProtoReader source) 81 | { 82 | Helpers.DebugAssert(value == null); // since replaces 83 | return parse.Invoke(null, new object[] { source.ReadString() }); 84 | } 85 | public void Write(object value, ProtoWriter dest) 86 | { 87 | ProtoWriter.WriteString(value.ToString(), dest); 88 | } 89 | #endif 90 | 91 | #if FEAT_COMPILER 92 | void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) 93 | { 94 | Type type = ExpectedType; 95 | if (type.IsValueType) 96 | { // note that for structs, we've already asserted that a custom ToString 97 | // exists; no need to handle the box/callvirt scenario 98 | 99 | // force it to a variable if needed, so we can take the address 100 | using (Compiler.Local loc = ctx.GetLocalWithValue(type, valueFrom)) 101 | { 102 | ctx.LoadAddress(loc, type); 103 | ctx.EmitCall(GetCustomToString(type)); 104 | } 105 | } 106 | else { 107 | ctx.EmitCall(ctx.MapType(typeof(object)).GetMethod("ToString")); 108 | } 109 | ctx.EmitBasicWrite("WriteString", valueFrom); 110 | } 111 | void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) 112 | { 113 | ctx.EmitBasicRead("ReadString", ctx.MapType(typeof(string))); 114 | ctx.EmitCall(parse); 115 | } 116 | #endif 117 | 118 | } 119 | } 120 | #endif -------------------------------------------------------------------------------- /xbuffer_test/protobuf-net/Serializers/ProtoDecoratorBase.cs: -------------------------------------------------------------------------------- 1 | #if !NO_RUNTIME 2 | using System; 3 | using ProtoBuf.Meta; 4 | 5 | #if FEAT_IKVM 6 | using Type = IKVM.Reflection.Type; 7 | using IKVM.Reflection; 8 | #else 9 | using System.Reflection; 10 | #endif 11 | 12 | namespace ProtoBuf.Serializers 13 | { 14 | abstract class ProtoDecoratorBase : IProtoSerializer 15 | { 16 | public abstract Type ExpectedType { get; } 17 | protected readonly IProtoSerializer Tail; 18 | protected ProtoDecoratorBase(IProtoSerializer tail) { this.Tail = tail; } 19 | public abstract bool ReturnsValue { get; } 20 | public abstract bool RequiresOldValue { get; } 21 | #if !FEAT_IKVM 22 | public abstract void Write(object value, ProtoWriter dest); 23 | public abstract object Read(object value, ProtoReader source); 24 | #endif 25 | 26 | #if FEAT_COMPILER 27 | void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) { EmitWrite(ctx, valueFrom); } 28 | protected abstract void EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom); 29 | void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) { EmitRead(ctx, valueFrom); } 30 | protected abstract void EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom); 31 | #endif 32 | } 33 | } 34 | #endif -------------------------------------------------------------------------------- /xbuffer_test/protobuf-net/Serializers/SByteSerializer.cs: -------------------------------------------------------------------------------- 1 | #if !NO_RUNTIME 2 | using System; 3 | 4 | #if FEAT_IKVM 5 | using Type = IKVM.Reflection.Type; 6 | using IKVM.Reflection; 7 | #else 8 | using System.Reflection; 9 | #endif 10 | 11 | namespace ProtoBuf.Serializers 12 | { 13 | sealed class SByteSerializer : IProtoSerializer 14 | { 15 | #if FEAT_IKVM 16 | readonly Type expectedType; 17 | #else 18 | static readonly Type expectedType = typeof(sbyte); 19 | #endif 20 | public SByteSerializer(ProtoBuf.Meta.TypeModel model) 21 | { 22 | #if FEAT_IKVM 23 | expectedType = model.MapType(typeof(sbyte)); 24 | #endif 25 | } 26 | public Type ExpectedType { get { return expectedType; } } 27 | 28 | 29 | bool IProtoSerializer.RequiresOldValue { get { return false; } } 30 | bool IProtoSerializer.ReturnsValue { get { return true; } } 31 | #if !FEAT_IKVM 32 | public object Read(object value, ProtoReader source) 33 | { 34 | Helpers.DebugAssert(value == null); // since replaces 35 | return source.ReadSByte(); 36 | } 37 | public void Write(object value, ProtoWriter dest) 38 | { 39 | ProtoWriter.WriteSByte((sbyte)value, dest); 40 | } 41 | #endif 42 | #if FEAT_COMPILER 43 | void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) 44 | { 45 | ctx.EmitBasicWrite("WriteSByte", valueFrom); 46 | } 47 | void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) 48 | { 49 | ctx.EmitBasicRead("ReadSByte", ExpectedType); 50 | } 51 | #endif 52 | 53 | } 54 | } 55 | #endif -------------------------------------------------------------------------------- /xbuffer_test/protobuf-net/Serializers/SingleSerializer.cs: -------------------------------------------------------------------------------- 1 | #if !NO_RUNTIME 2 | using System; 3 | using ProtoBuf.Meta; 4 | 5 | #if FEAT_IKVM 6 | using Type = IKVM.Reflection.Type; 7 | using IKVM.Reflection; 8 | #else 9 | using System.Reflection; 10 | #endif 11 | 12 | 13 | namespace ProtoBuf.Serializers 14 | { 15 | sealed class SingleSerializer : IProtoSerializer 16 | { 17 | #if FEAT_IKVM 18 | readonly Type expectedType; 19 | #else 20 | static readonly Type expectedType = typeof(float); 21 | #endif 22 | public Type ExpectedType { get { return expectedType; } } 23 | 24 | public SingleSerializer(TypeModel model) 25 | { 26 | #if FEAT_IKVM 27 | expectedType = model.MapType(typeof(float)); 28 | #endif 29 | } 30 | bool IProtoSerializer.RequiresOldValue { get { return false; } } 31 | bool IProtoSerializer.ReturnsValue { get { return true; } } 32 | #if !FEAT_IKVM 33 | public object Read(object value, ProtoReader source) 34 | { 35 | Helpers.DebugAssert(value == null); // since replaces 36 | return source.ReadSingle(); 37 | } 38 | public void Write(object value, ProtoWriter dest) 39 | { 40 | ProtoWriter.WriteSingle((float)value, dest); 41 | } 42 | #endif 43 | 44 | #if FEAT_COMPILER 45 | void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) 46 | { 47 | ctx.EmitBasicWrite("WriteSingle", valueFrom); 48 | } 49 | void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) 50 | { 51 | ctx.EmitBasicRead("ReadSingle", ExpectedType); 52 | } 53 | #endif 54 | } 55 | } 56 | #endif -------------------------------------------------------------------------------- /xbuffer_test/protobuf-net/Serializers/StringSerializer.cs: -------------------------------------------------------------------------------- 1 | #if !NO_RUNTIME 2 | using System; 3 | 4 | using ProtoBuf.Meta; 5 | 6 | #if FEAT_IKVM 7 | using Type = IKVM.Reflection.Type; 8 | using IKVM.Reflection; 9 | #else 10 | using System.Reflection; 11 | #endif 12 | 13 | namespace ProtoBuf.Serializers 14 | { 15 | sealed class StringSerializer : IProtoSerializer 16 | { 17 | #if FEAT_IKVM 18 | readonly Type expectedType; 19 | #else 20 | static readonly Type expectedType = typeof(string); 21 | #endif 22 | public StringSerializer(ProtoBuf.Meta.TypeModel model) 23 | { 24 | #if FEAT_IKVM 25 | expectedType = model.MapType(typeof(string)); 26 | #endif 27 | } 28 | public Type ExpectedType { get { return expectedType; } } 29 | public void Write(object value, ProtoWriter dest) 30 | { 31 | ProtoWriter.WriteString((string)value, dest); 32 | } 33 | bool IProtoSerializer.RequiresOldValue { get { return false; } } 34 | bool IProtoSerializer.ReturnsValue { get { return true; } } 35 | 36 | public object Read(object value, ProtoReader source) 37 | { 38 | Helpers.DebugAssert(value == null); // since replaces 39 | return source.ReadString(); 40 | } 41 | #if FEAT_COMPILER 42 | void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) 43 | { 44 | ctx.EmitBasicWrite("WriteString", valueFrom); 45 | } 46 | void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) 47 | { 48 | ctx.EmitBasicRead("ReadString", ExpectedType); 49 | } 50 | #endif 51 | } 52 | } 53 | #endif -------------------------------------------------------------------------------- /xbuffer_test/protobuf-net/Serializers/SubItemSerializer.cs: -------------------------------------------------------------------------------- 1 | #if !NO_RUNTIME 2 | using System; 3 | using ProtoBuf.Meta; 4 | 5 | #if FEAT_COMPILER 6 | #if FEAT_IKVM 7 | using IKVM.Reflection.Emit; 8 | using Type = IKVM.Reflection.Type; 9 | #else 10 | using System.Reflection.Emit; 11 | #endif 12 | #endif 13 | 14 | namespace ProtoBuf.Serializers 15 | { 16 | sealed class SubItemSerializer : IProtoTypeSerializer 17 | { 18 | bool IProtoTypeSerializer.HasCallbacks(TypeModel.CallbackType callbackType) 19 | { 20 | return ((IProtoTypeSerializer)proxy.Serializer).HasCallbacks(callbackType); 21 | } 22 | bool IProtoTypeSerializer.CanCreateInstance() 23 | { 24 | return ((IProtoTypeSerializer)proxy.Serializer).CanCreateInstance(); 25 | } 26 | #if FEAT_COMPILER 27 | void IProtoTypeSerializer.EmitCallback(Compiler.CompilerContext ctx, Compiler.Local valueFrom, TypeModel.CallbackType callbackType) 28 | { 29 | ((IProtoTypeSerializer)proxy.Serializer).EmitCallback(ctx, valueFrom, callbackType); 30 | } 31 | void IProtoTypeSerializer.EmitCreateInstance(Compiler.CompilerContext ctx) 32 | { 33 | ((IProtoTypeSerializer)proxy.Serializer).EmitCreateInstance(ctx); 34 | } 35 | #endif 36 | #if !FEAT_IKVM 37 | void IProtoTypeSerializer.Callback(object value, TypeModel.CallbackType callbackType, SerializationContext context) 38 | { 39 | ((IProtoTypeSerializer)proxy.Serializer).Callback(value, callbackType, context); 40 | } 41 | object IProtoTypeSerializer.CreateInstance(ProtoReader source) 42 | { 43 | return ((IProtoTypeSerializer)proxy.Serializer).CreateInstance(source); 44 | } 45 | #endif 46 | 47 | private readonly int key; 48 | private readonly Type type; 49 | private readonly ISerializerProxy proxy; 50 | private readonly bool recursionCheck; 51 | public SubItemSerializer(Type type, int key, ISerializerProxy proxy, bool recursionCheck) 52 | { 53 | if (type == null) throw new ArgumentNullException("type"); 54 | if (proxy == null) throw new ArgumentNullException("proxy"); 55 | this.type = type; 56 | this.proxy= proxy; 57 | this.key = key; 58 | this.recursionCheck = recursionCheck; 59 | } 60 | Type IProtoSerializer.ExpectedType 61 | { 62 | get { return type; } 63 | } 64 | bool IProtoSerializer.RequiresOldValue { get { return true; } } 65 | bool IProtoSerializer.ReturnsValue { get { return true; } } 66 | 67 | #if !FEAT_IKVM 68 | void IProtoSerializer.Write(object value, ProtoWriter dest) 69 | { 70 | if (recursionCheck) 71 | { 72 | ProtoWriter.WriteObject(value, key, dest); 73 | } 74 | else 75 | { 76 | ProtoWriter.WriteRecursionSafeObject(value, key, dest); 77 | } 78 | } 79 | object IProtoSerializer.Read(object value, ProtoReader source) 80 | { 81 | return ProtoReader.ReadObject(value, key, source); 82 | } 83 | #endif 84 | 85 | #if FEAT_COMPILER 86 | bool EmitDedicatedMethod(Compiler.CompilerContext ctx, Compiler.Local valueFrom, bool read) 87 | { 88 | #if SILVERLIGHT 89 | return false; 90 | #else 91 | MethodBuilder method = ctx.GetDedicatedMethod(key, read); 92 | if (method == null) return false; 93 | 94 | using (Compiler.Local token = new ProtoBuf.Compiler.Local(ctx, ctx.MapType(typeof(SubItemToken)))) 95 | { 96 | Type rwType = ctx.MapType(read ? typeof(ProtoReader) : typeof(ProtoWriter)); 97 | ctx.LoadValue(valueFrom); 98 | if (!read) // write requires the object for StartSubItem; read doesn't 99 | { // (if recursion-check is disabled [subtypes] then null is fine too) 100 | if (type.IsValueType || !recursionCheck) { ctx.LoadNullRef(); } 101 | else { ctx.CopyValue(); } 102 | } 103 | ctx.LoadReaderWriter(); 104 | ctx.EmitCall(rwType.GetMethod("StartSubItem")); 105 | ctx.StoreValue(token); 106 | 107 | // note: value already on the stack 108 | ctx.LoadReaderWriter(); 109 | ctx.EmitCall(method); 110 | // handle inheritance (we will be calling the *base* version of things, 111 | // but we expect Read to return the "type" type) 112 | if (read && type != method.ReturnType) ctx.Cast(this.type); 113 | ctx.LoadValue(token); 114 | 115 | ctx.LoadReaderWriter(); 116 | ctx.EmitCall(rwType.GetMethod("EndSubItem")); 117 | } 118 | return true; 119 | #endif 120 | } 121 | void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) 122 | { 123 | if (!EmitDedicatedMethod(ctx, valueFrom, false)) 124 | { 125 | ctx.LoadValue(valueFrom); 126 | if (type.IsValueType) ctx.CastToObject(type); 127 | ctx.LoadValue(ctx.MapMetaKeyToCompiledKey(key)); // re-map for formality, but would expect identical, else dedicated method 128 | ctx.LoadReaderWriter(); 129 | ctx.EmitCall(ctx.MapType(typeof(ProtoWriter)).GetMethod(recursionCheck ? "WriteObject" : "WriteRecursionSafeObject")); 130 | } 131 | } 132 | void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) 133 | { 134 | if (!EmitDedicatedMethod(ctx, valueFrom, true)) 135 | { 136 | ctx.LoadValue(valueFrom); 137 | if (type.IsValueType) ctx.CastToObject(type); 138 | ctx.LoadValue(ctx.MapMetaKeyToCompiledKey(key)); // re-map for formality, but would expect identical, else dedicated method 139 | ctx.LoadReaderWriter(); 140 | ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod("ReadObject")); 141 | ctx.CastFromObject(type); 142 | } 143 | } 144 | #endif 145 | } 146 | } 147 | #endif -------------------------------------------------------------------------------- /xbuffer_test/protobuf-net/Serializers/SurrogateSerializer.cs: -------------------------------------------------------------------------------- 1 | #if !NO_RUNTIME 2 | using System; 3 | using ProtoBuf.Meta; 4 | 5 | #if FEAT_IKVM 6 | using Type = IKVM.Reflection.Type; 7 | using IKVM.Reflection; 8 | #else 9 | using System.Reflection; 10 | #endif 11 | 12 | namespace ProtoBuf.Serializers 13 | { 14 | sealed class SurrogateSerializer : IProtoTypeSerializer 15 | { 16 | bool IProtoTypeSerializer.HasCallbacks(ProtoBuf.Meta.TypeModel.CallbackType callbackType) { return false; } 17 | #if FEAT_COMPILER 18 | void IProtoTypeSerializer.EmitCallback(Compiler.CompilerContext ctx, Compiler.Local valueFrom, ProtoBuf.Meta.TypeModel.CallbackType callbackType) { } 19 | void IProtoTypeSerializer.EmitCreateInstance(Compiler.CompilerContext ctx) { throw new NotSupportedException(); } 20 | #endif 21 | bool IProtoTypeSerializer.CanCreateInstance() { return false; } 22 | #if !FEAT_IKVM 23 | object IProtoTypeSerializer.CreateInstance(ProtoReader source) { throw new NotSupportedException(); } 24 | void IProtoTypeSerializer.Callback(object value, ProtoBuf.Meta.TypeModel.CallbackType callbackType, SerializationContext context) { } 25 | #endif 26 | 27 | public bool ReturnsValue { get { return false; } } 28 | public bool RequiresOldValue { get { return true; } } 29 | public Type ExpectedType { get { return forType; } } 30 | private readonly Type forType, declaredType; 31 | private readonly MethodInfo toTail, fromTail; 32 | IProtoTypeSerializer rootTail; 33 | 34 | public SurrogateSerializer(TypeModel model, Type forType, Type declaredType, IProtoTypeSerializer rootTail) 35 | { 36 | Helpers.DebugAssert(forType != null, "forType"); 37 | Helpers.DebugAssert(declaredType != null, "declaredType"); 38 | Helpers.DebugAssert(rootTail != null, "rootTail"); 39 | Helpers.DebugAssert(rootTail.RequiresOldValue, "RequiresOldValue"); 40 | Helpers.DebugAssert(!rootTail.ReturnsValue, "ReturnsValue"); 41 | Helpers.DebugAssert(declaredType == rootTail.ExpectedType || Helpers.IsSubclassOf(declaredType, rootTail.ExpectedType)); 42 | this.forType = forType; 43 | this.declaredType = declaredType; 44 | this.rootTail = rootTail; 45 | toTail = GetConversion(model, true); 46 | fromTail = GetConversion(model, false); 47 | } 48 | private static bool HasCast(TypeModel model, Type type, Type from, Type to, out MethodInfo op) 49 | { 50 | #if WINRT 51 | System.Collections.Generic.List list = new System.Collections.Generic.List(); 52 | foreach (var item in type.GetRuntimeMethods()) 53 | { 54 | if (item.IsStatic) list.Add(item); 55 | } 56 | MethodInfo[] found = list.ToArray(); 57 | #else 58 | const BindingFlags flags = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic; 59 | MethodInfo[] found = type.GetMethods(flags); 60 | #endif 61 | ParameterInfo[] paramTypes; 62 | Type convertAttributeType = null; 63 | for (int i = 0; i < found.Length; i++) 64 | { 65 | MethodInfo m = found[i]; 66 | if (m.ReturnType != to) continue; 67 | paramTypes = m.GetParameters(); 68 | if(paramTypes.Length == 1 && paramTypes[0].ParameterType == from) 69 | { 70 | if (convertAttributeType == null) 71 | { 72 | convertAttributeType = model.MapType(typeof(ProtoConverterAttribute), false); 73 | if (convertAttributeType == null) 74 | { // attribute isn't defined in the source assembly: stop looking 75 | break; 76 | } 77 | } 78 | if (m.IsDefined(convertAttributeType, true)) 79 | { 80 | op = m; 81 | return true; 82 | } 83 | } 84 | } 85 | 86 | for(int i = 0 ; i < found.Length ; i++) 87 | { 88 | MethodInfo m = found[i]; 89 | if ((m.Name != "op_Implicit" && m.Name != "op_Explicit") || m.ReturnType != to) 90 | { 91 | continue; 92 | } 93 | paramTypes = m.GetParameters(); 94 | if(paramTypes.Length == 1 && paramTypes[0].ParameterType == from) 95 | { 96 | op = m; 97 | return true; 98 | } 99 | } 100 | op = null; 101 | return false; 102 | } 103 | 104 | public MethodInfo GetConversion(TypeModel model, bool toTail) 105 | { 106 | Type to = toTail ? declaredType : forType; 107 | Type from = toTail ? forType : declaredType; 108 | MethodInfo op; 109 | if (HasCast(model, declaredType, from, to, out op) || HasCast(model, forType, from, to, out op)) 110 | { 111 | return op; 112 | } 113 | throw new InvalidOperationException("No suitable conversion operator found for surrogate: " + 114 | forType.FullName + " / " + declaredType.FullName); 115 | } 116 | 117 | #if !FEAT_IKVM 118 | public void Write(object value, ProtoWriter writer) 119 | { 120 | rootTail.Write(toTail.Invoke(null, new object[] { value }), writer); 121 | } 122 | public object Read(object value, ProtoReader source) 123 | { 124 | // convert the incoming value 125 | object[] args = { value }; 126 | value = toTail.Invoke(null, args); 127 | 128 | // invoke the tail and convert the outgoing value 129 | args[0] = rootTail.Read(value, source); 130 | return fromTail.Invoke(null, args); 131 | } 132 | #endif 133 | 134 | #if FEAT_COMPILER 135 | void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) 136 | { 137 | Helpers.DebugAssert(valueFrom != null); // don't support stack-head for this 138 | using (Compiler.Local converted = new Compiler.Local(ctx, declaredType)) // declare/re-use local 139 | { 140 | ctx.LoadValue(valueFrom); // load primary onto stack 141 | ctx.EmitCall(toTail); // static convert op, primary-to-surrogate 142 | ctx.StoreValue(converted); // store into surrogate local 143 | 144 | rootTail.EmitRead(ctx, converted); // downstream processing against surrogate local 145 | 146 | ctx.LoadValue(converted); // load from surrogate local 147 | ctx.EmitCall(fromTail); // static convert op, surrogate-to-primary 148 | ctx.StoreValue(valueFrom); // store back into primary 149 | } 150 | } 151 | 152 | void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) 153 | { 154 | ctx.LoadValue(valueFrom); 155 | ctx.EmitCall(toTail); 156 | rootTail.EmitWrite(ctx, null); 157 | } 158 | #endif 159 | } 160 | } 161 | #endif -------------------------------------------------------------------------------- /xbuffer_test/protobuf-net/Serializers/SystemTypeSerializer.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | #if !NO_RUNTIME 4 | 5 | #if FEAT_IKVM 6 | using Type = IKVM.Reflection.Type; 7 | using IKVM.Reflection; 8 | #else 9 | using System.Reflection; 10 | #endif 11 | 12 | namespace ProtoBuf.Serializers 13 | { 14 | sealed class SystemTypeSerializer : IProtoSerializer 15 | { 16 | #if FEAT_IKVM 17 | readonly Type expectedType; 18 | #else 19 | static readonly Type expectedType = typeof(System.Type); 20 | #endif 21 | public SystemTypeSerializer(ProtoBuf.Meta.TypeModel model) 22 | { 23 | #if FEAT_IKVM 24 | expectedType = model.MapType(typeof(System.Type)); 25 | #endif 26 | } 27 | public Type ExpectedType { get { return expectedType; } } 28 | 29 | #if !FEAT_IKVM 30 | void IProtoSerializer.Write(object value, ProtoWriter dest) 31 | { 32 | ProtoWriter.WriteType((Type)value, dest); 33 | } 34 | 35 | object IProtoSerializer.Read(object value, ProtoReader source) 36 | { 37 | Helpers.DebugAssert(value == null); // since replaces 38 | return source.ReadType(); 39 | } 40 | #endif 41 | bool IProtoSerializer.RequiresOldValue { get { return false; } } 42 | bool IProtoSerializer.ReturnsValue { get { return true; } } 43 | 44 | #if FEAT_COMPILER 45 | void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) 46 | { 47 | ctx.EmitBasicWrite("WriteType", valueFrom); 48 | } 49 | void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) 50 | { 51 | ctx.EmitBasicRead("ReadType", ExpectedType); 52 | } 53 | #endif 54 | } 55 | } 56 | 57 | #endif 58 | -------------------------------------------------------------------------------- /xbuffer_test/protobuf-net/Serializers/TagDecorator.cs: -------------------------------------------------------------------------------- 1 | #if !NO_RUNTIME 2 | using System; 3 | 4 | using ProtoBuf.Meta; 5 | 6 | #if FEAT_IKVM 7 | using Type = IKVM.Reflection.Type; 8 | using IKVM.Reflection; 9 | #else 10 | using System.Reflection; 11 | #endif 12 | 13 | 14 | namespace ProtoBuf.Serializers 15 | { 16 | sealed class TagDecorator : ProtoDecoratorBase, IProtoTypeSerializer 17 | { 18 | 19 | public bool HasCallbacks(TypeModel.CallbackType callbackType) 20 | { 21 | IProtoTypeSerializer pts = Tail as IProtoTypeSerializer; 22 | return pts != null && pts.HasCallbacks(callbackType); 23 | } 24 | 25 | public bool CanCreateInstance() 26 | { 27 | IProtoTypeSerializer pts = Tail as IProtoTypeSerializer; 28 | return pts != null && pts.CanCreateInstance(); 29 | } 30 | #if !FEAT_IKVM 31 | public object CreateInstance(ProtoReader source) 32 | { 33 | return ((IProtoTypeSerializer)Tail).CreateInstance(source); 34 | } 35 | public void Callback(object value, TypeModel.CallbackType callbackType, SerializationContext context) 36 | { 37 | IProtoTypeSerializer pts = Tail as IProtoTypeSerializer; 38 | if (pts != null) pts.Callback(value, callbackType, context); 39 | } 40 | #endif 41 | #if FEAT_COMPILER 42 | public void EmitCallback(Compiler.CompilerContext ctx, Compiler.Local valueFrom, TypeModel.CallbackType callbackType) 43 | { 44 | // we only expect this to be invoked if HasCallbacks returned true, so implicitly Tail 45 | // **must** be of the correct type 46 | ((IProtoTypeSerializer)Tail).EmitCallback(ctx, valueFrom, callbackType); 47 | } 48 | public void EmitCreateInstance(Compiler.CompilerContext ctx) 49 | { 50 | ((IProtoTypeSerializer)Tail).EmitCreateInstance(ctx); 51 | } 52 | #endif 53 | public override Type ExpectedType 54 | { 55 | get { return Tail.ExpectedType; } 56 | } 57 | public TagDecorator(int fieldNumber, WireType wireType, bool strict, IProtoSerializer tail) 58 | : base(tail) 59 | { 60 | this.fieldNumber = fieldNumber; 61 | this.wireType = wireType; 62 | this.strict = strict; 63 | } 64 | public override bool RequiresOldValue { get { return Tail.RequiresOldValue; } } 65 | public override bool ReturnsValue { get { return Tail.ReturnsValue; } } 66 | private readonly bool strict; 67 | private readonly int fieldNumber; 68 | private readonly WireType wireType; 69 | 70 | private bool NeedsHint 71 | { 72 | get { return ((int)wireType & ~7) != 0; } 73 | } 74 | #if !FEAT_IKVM 75 | public override object Read(object value, ProtoReader source) 76 | { 77 | Helpers.DebugAssert(fieldNumber == source.FieldNumber); 78 | if (strict) { source.Assert(wireType); } 79 | else if (NeedsHint) { source.Hint(wireType); } 80 | return Tail.Read(value, source); 81 | } 82 | public override void Write(object value, ProtoWriter dest) 83 | { 84 | ProtoWriter.WriteFieldHeader(fieldNumber, wireType, dest); 85 | Tail.Write(value, dest); 86 | } 87 | #endif 88 | 89 | #if FEAT_COMPILER 90 | protected override void EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) 91 | { 92 | ctx.LoadValue((int)fieldNumber); 93 | ctx.LoadValue((int)wireType); 94 | ctx.LoadReaderWriter(); 95 | ctx.EmitCall(ctx.MapType(typeof(ProtoWriter)).GetMethod("WriteFieldHeader")); 96 | Tail.EmitWrite(ctx, valueFrom); 97 | } 98 | protected override void EmitRead(ProtoBuf.Compiler.CompilerContext ctx, ProtoBuf.Compiler.Local valueFrom) 99 | { 100 | if (strict || NeedsHint) 101 | { 102 | ctx.LoadReaderWriter(); 103 | ctx.LoadValue((int)wireType); 104 | ctx.EmitCall(ctx.MapType(typeof(ProtoReader)).GetMethod(strict ? "Assert" : "Hint")); 105 | } 106 | Tail.EmitRead(ctx, valueFrom); 107 | } 108 | #endif 109 | } 110 | 111 | } 112 | #endif -------------------------------------------------------------------------------- /xbuffer_test/protobuf-net/Serializers/TimeSpanSerializer.cs: -------------------------------------------------------------------------------- 1 | #if !NO_RUNTIME 2 | using System; 3 | 4 | #if FEAT_IKVM 5 | using Type = IKVM.Reflection.Type; 6 | using IKVM.Reflection; 7 | #else 8 | using System.Reflection; 9 | #endif 10 | 11 | 12 | 13 | namespace ProtoBuf.Serializers 14 | { 15 | sealed class TimeSpanSerializer : IProtoSerializer 16 | { 17 | #if FEAT_IKVM 18 | readonly Type expectedType; 19 | #else 20 | static readonly Type expectedType = typeof(TimeSpan); 21 | #endif 22 | public TimeSpanSerializer(ProtoBuf.Meta.TypeModel model) 23 | { 24 | #if FEAT_IKVM 25 | expectedType = model.MapType(typeof(TimeSpan)); 26 | #endif 27 | } 28 | public Type ExpectedType { get { return expectedType; } } 29 | 30 | bool IProtoSerializer.RequiresOldValue { get { return false; } } 31 | bool IProtoSerializer.ReturnsValue { get { return true; } } 32 | #if !FEAT_IKVM 33 | public object Read(object value, ProtoReader source) 34 | { 35 | Helpers.DebugAssert(value == null); // since replaces 36 | return BclHelpers.ReadTimeSpan(source); 37 | } 38 | public void Write(object value, ProtoWriter dest) 39 | { 40 | BclHelpers.WriteTimeSpan((TimeSpan)value, dest); 41 | } 42 | #endif 43 | #if FEAT_COMPILER 44 | void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) 45 | { 46 | ctx.EmitWrite(ctx.MapType(typeof(BclHelpers)), "WriteTimeSpan", valueFrom); 47 | } 48 | void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) 49 | { 50 | ctx.EmitBasicRead(ctx.MapType(typeof(BclHelpers)), "ReadTimeSpan", ExpectedType); 51 | } 52 | #endif 53 | 54 | } 55 | } 56 | #endif -------------------------------------------------------------------------------- /xbuffer_test/protobuf-net/Serializers/UInt16Serializer.cs: -------------------------------------------------------------------------------- 1 | #if !NO_RUNTIME 2 | using System; 3 | 4 | #if FEAT_IKVM 5 | using Type = IKVM.Reflection.Type; 6 | using IKVM.Reflection; 7 | #else 8 | using System.Reflection; 9 | #endif 10 | 11 | 12 | namespace ProtoBuf.Serializers 13 | { 14 | class UInt16Serializer : IProtoSerializer 15 | { 16 | #if FEAT_IKVM 17 | readonly Type expectedType; 18 | #else 19 | static readonly Type expectedType = typeof(ushort); 20 | #endif 21 | public UInt16Serializer(ProtoBuf.Meta.TypeModel model) 22 | { 23 | #if FEAT_IKVM 24 | expectedType = model.MapType(typeof(ushort)); 25 | #endif 26 | } 27 | public virtual Type ExpectedType { get { return expectedType; } } 28 | 29 | bool IProtoSerializer.RequiresOldValue { get { return false; } } 30 | bool IProtoSerializer.ReturnsValue { get { return true; } } 31 | #if !FEAT_IKVM 32 | public virtual object Read(object value, ProtoReader source) 33 | { 34 | Helpers.DebugAssert(value == null); // since replaces 35 | return source.ReadUInt16(); 36 | } 37 | public virtual void Write(object value, ProtoWriter dest) 38 | { 39 | ProtoWriter.WriteUInt16((ushort)value, dest); 40 | } 41 | #endif 42 | #if FEAT_COMPILER 43 | void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) 44 | { 45 | ctx.EmitBasicWrite("WriteUInt16", valueFrom); 46 | } 47 | void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) 48 | { 49 | ctx.EmitBasicRead("ReadUInt16", ctx.MapType(typeof(ushort))); 50 | } 51 | #endif 52 | } 53 | } 54 | #endif -------------------------------------------------------------------------------- /xbuffer_test/protobuf-net/Serializers/UInt32Serializer.cs: -------------------------------------------------------------------------------- 1 | #if !NO_RUNTIME 2 | using System; 3 | 4 | #if FEAT_IKVM 5 | using Type = IKVM.Reflection.Type; 6 | using IKVM.Reflection; 7 | #else 8 | using System.Reflection; 9 | #endif 10 | 11 | 12 | namespace ProtoBuf.Serializers 13 | { 14 | sealed class UInt32Serializer : IProtoSerializer 15 | { 16 | #if FEAT_IKVM 17 | readonly Type expectedType; 18 | #else 19 | static readonly Type expectedType = typeof(uint); 20 | #endif 21 | public UInt32Serializer(ProtoBuf.Meta.TypeModel model) 22 | { 23 | #if FEAT_IKVM 24 | expectedType = model.MapType(typeof(uint)); 25 | #endif 26 | } 27 | public Type ExpectedType { get { return expectedType; } } 28 | 29 | bool IProtoSerializer.RequiresOldValue { get { return false; } } 30 | bool IProtoSerializer.ReturnsValue { get { return true; } } 31 | #if !FEAT_IKVM 32 | public object Read(object value, ProtoReader source) 33 | { 34 | Helpers.DebugAssert(value == null); // since replaces 35 | return source.ReadUInt32(); 36 | } 37 | public void Write(object value, ProtoWriter dest) 38 | { 39 | ProtoWriter.WriteUInt32((uint)value, dest); 40 | } 41 | #endif 42 | #if FEAT_COMPILER 43 | void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) 44 | { 45 | ctx.EmitBasicWrite("WriteUInt32", valueFrom); 46 | } 47 | void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) 48 | { 49 | ctx.EmitBasicRead("ReadUInt32", ctx.MapType(typeof(uint))); 50 | } 51 | #endif 52 | } 53 | } 54 | #endif -------------------------------------------------------------------------------- /xbuffer_test/protobuf-net/Serializers/UInt64Serializer.cs: -------------------------------------------------------------------------------- 1 | #if !NO_RUNTIME 2 | using System; 3 | 4 | #if FEAT_IKVM 5 | using Type = IKVM.Reflection.Type; 6 | using IKVM.Reflection; 7 | #else 8 | using System.Reflection; 9 | #endif 10 | 11 | namespace ProtoBuf.Serializers 12 | { 13 | sealed class UInt64Serializer : IProtoSerializer 14 | { 15 | #if FEAT_IKVM 16 | readonly Type expectedType; 17 | #else 18 | static readonly Type expectedType = typeof(ulong); 19 | #endif 20 | public UInt64Serializer(ProtoBuf.Meta.TypeModel model) 21 | { 22 | #if FEAT_IKVM 23 | expectedType = model.MapType(typeof(ulong)); 24 | #endif 25 | } 26 | public Type ExpectedType { get { return expectedType; } } 27 | 28 | bool IProtoSerializer.RequiresOldValue { get { return false; } } 29 | bool IProtoSerializer.ReturnsValue { get { return true; } } 30 | 31 | #if !FEAT_IKVM 32 | public object Read(object value, ProtoReader source) 33 | { 34 | Helpers.DebugAssert(value == null); // since replaces 35 | return source.ReadUInt64(); 36 | } 37 | public void Write(object value, ProtoWriter dest) 38 | { 39 | ProtoWriter.WriteUInt64((ulong)value, dest); 40 | } 41 | #endif 42 | 43 | #if FEAT_COMPILER 44 | void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) 45 | { 46 | ctx.EmitBasicWrite("WriteUInt64", valueFrom); 47 | } 48 | void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) 49 | { 50 | ctx.EmitBasicRead("ReadUInt64", ExpectedType); 51 | } 52 | #endif 53 | } 54 | } 55 | #endif -------------------------------------------------------------------------------- /xbuffer_test/protobuf-net/Serializers/UriDecorator.cs: -------------------------------------------------------------------------------- 1 | #if !NO_RUNTIME 2 | using System; 3 | 4 | #if FEAT_IKVM 5 | using Type = IKVM.Reflection.Type; 6 | using IKVM.Reflection; 7 | #else 8 | using System.Reflection; 9 | #endif 10 | 11 | namespace ProtoBuf.Serializers 12 | { 13 | sealed class UriDecorator : ProtoDecoratorBase 14 | { 15 | #if FEAT_IKVM 16 | readonly Type expectedType; 17 | #else 18 | static readonly Type expectedType = typeof(Uri); 19 | #endif 20 | public UriDecorator(ProtoBuf.Meta.TypeModel model, IProtoSerializer tail) : base(tail) 21 | { 22 | #if FEAT_IKVM 23 | expectedType = model.MapType(typeof(Uri)); 24 | #endif 25 | } 26 | public override Type ExpectedType { get { return expectedType; } } 27 | public override bool RequiresOldValue { get { return false; } } 28 | public override bool ReturnsValue { get { return true; } } 29 | 30 | 31 | #if !FEAT_IKVM 32 | public override void Write(object value, ProtoWriter dest) 33 | { 34 | Tail.Write(((Uri)value).AbsoluteUri, dest); 35 | } 36 | public override object Read(object value, ProtoReader source) 37 | { 38 | Helpers.DebugAssert(value == null); // not expecting incoming 39 | string s = (string)Tail.Read(null, source); 40 | return s.Length == 0 ? null : new Uri(s); 41 | } 42 | #endif 43 | 44 | #if FEAT_COMPILER 45 | protected override void EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) 46 | { 47 | ctx.LoadValue(valueFrom); 48 | ctx.LoadValue(typeof(Uri).GetProperty("AbsoluteUri")); 49 | Tail.EmitWrite(ctx, null); 50 | } 51 | protected override void EmitRead(Compiler.CompilerContext ctx, Compiler.Local valueFrom) 52 | { 53 | Tail.EmitRead(ctx, valueFrom); 54 | ctx.CopyValue(); 55 | Compiler.CodeLabel @nonEmpty = ctx.DefineLabel(), @end = ctx.DefineLabel(); 56 | ctx.LoadValue(typeof(string).GetProperty("Length")); 57 | ctx.BranchIfTrue(@nonEmpty, true); 58 | ctx.DiscardValue(); 59 | ctx.LoadNullRef(); 60 | ctx.Branch(@end, true); 61 | ctx.MarkLabel(@nonEmpty); 62 | ctx.EmitCtor(ctx.MapType(typeof(Uri)), ctx.MapType(typeof(string))); 63 | ctx.MarkLabel(@end); 64 | 65 | } 66 | #endif 67 | } 68 | } 69 | #endif 70 | -------------------------------------------------------------------------------- /xbuffer_test/protobuf-net/ServiceModel/ProtoBehaviorAttribute.cs: -------------------------------------------------------------------------------- 1 | #if FEAT_SERVICEMODEL && PLAT_XMLSERIALIZER 2 | using System; 3 | using System.ServiceModel.Description; 4 | using System.ServiceModel.Dispatcher; 5 | 6 | namespace ProtoBuf.ServiceModel 7 | { 8 | /// 9 | /// Uses protocol buffer serialization on the specified operation; note that this 10 | /// must be enabled on both the client and server. 11 | /// 12 | [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] 13 | public sealed class ProtoBehaviorAttribute : Attribute, IOperationBehavior 14 | { 15 | void IOperationBehavior.AddBindingParameters(OperationDescription operationDescription, System.ServiceModel.Channels.BindingParameterCollection bindingParameters) 16 | { } 17 | 18 | void IOperationBehavior.ApplyClientBehavior(OperationDescription operationDescription, ClientOperation clientOperation) 19 | { 20 | IOperationBehavior innerBehavior = new ProtoOperationBehavior(operationDescription); 21 | innerBehavior.ApplyClientBehavior(operationDescription, clientOperation); 22 | } 23 | 24 | void IOperationBehavior.ApplyDispatchBehavior(OperationDescription operationDescription, DispatchOperation dispatchOperation) 25 | { 26 | IOperationBehavior innerBehavior = new ProtoOperationBehavior(operationDescription); 27 | innerBehavior.ApplyDispatchBehavior(operationDescription, dispatchOperation); 28 | } 29 | 30 | void IOperationBehavior.Validate(OperationDescription operationDescription) 31 | { } 32 | } 33 | } 34 | #endif -------------------------------------------------------------------------------- /xbuffer_test/protobuf-net/ServiceModel/ProtoBehaviorExtensionElement.cs: -------------------------------------------------------------------------------- 1 | #if FEAT_SERVICEMODEL && PLAT_XMLSERIALIZER 2 | using System; 3 | using System.ServiceModel.Configuration; 4 | 5 | namespace ProtoBuf.ServiceModel 6 | { 7 | /// 8 | /// Configuration element to swap out DatatContractSerilaizer with the XmlProtoSerializer for a given endpoint. 9 | /// 10 | /// 11 | public class ProtoBehaviorExtension : BehaviorExtensionElement 12 | { 13 | /// 14 | /// Creates a new ProtoBehaviorExtension instance. 15 | /// 16 | public ProtoBehaviorExtension() 17 | { 18 | } 19 | 20 | /// 21 | /// Gets the type of behavior. 22 | /// 23 | public override Type BehaviorType 24 | { 25 | get 26 | { 27 | return typeof(ProtoEndpointBehavior); 28 | } 29 | } 30 | 31 | /// 32 | /// Creates a behavior extension based on the current configuration settings. 33 | /// 34 | /// The behavior extension. 35 | protected override object CreateBehavior() 36 | { 37 | return new ProtoEndpointBehavior(); 38 | } 39 | } 40 | } 41 | #endif -------------------------------------------------------------------------------- /xbuffer_test/protobuf-net/ServiceModel/ProtoEndpointBehavior.cs: -------------------------------------------------------------------------------- 1 | #if FEAT_SERVICEMODEL && PLAT_XMLSERIALIZER 2 | using System.ServiceModel.Description; 3 | 4 | namespace ProtoBuf.ServiceModel 5 | { 6 | /// 7 | /// Behavior to swap out DatatContractSerilaizer with the XmlProtoSerializer for a given endpoint. 8 | /// 9 | /// Add the following to the server and client app.config in the system.serviceModel section: 10 | /// 11 | /// 12 | /// 13 | /// 14 | /// 15 | /// 16 | /// 17 | /// 18 | /// 19 | /// 20 | /// 21 | /// 22 | /// 23 | /// Configure your endpoints to have a behaviorConfiguration as follows: 24 | /// 25 | /// 26 | /// 28 | /// 29 | /// 30 | /// 33 | /// 34 | /// 35 | /// 36 | public class ProtoEndpointBehavior : IEndpointBehavior 37 | { 38 | #region IEndpointBehavior Members 39 | 40 | void IEndpointBehavior.AddBindingParameters(ServiceEndpoint endpoint, System.ServiceModel.Channels.BindingParameterCollection bindingParameters) 41 | { 42 | } 43 | 44 | void IEndpointBehavior.ApplyClientBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.ClientRuntime clientRuntime) 45 | { 46 | ReplaceDataContractSerializerOperationBehavior(endpoint); 47 | } 48 | 49 | void IEndpointBehavior.ApplyDispatchBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.EndpointDispatcher endpointDispatcher) 50 | { 51 | ReplaceDataContractSerializerOperationBehavior(endpoint); 52 | } 53 | 54 | void IEndpointBehavior.Validate(ServiceEndpoint endpoint) 55 | { 56 | } 57 | 58 | private static void ReplaceDataContractSerializerOperationBehavior(ServiceEndpoint serviceEndpoint) 59 | { 60 | foreach (OperationDescription operationDescription in serviceEndpoint.Contract.Operations) 61 | { 62 | ReplaceDataContractSerializerOperationBehavior(operationDescription); 63 | } 64 | } 65 | 66 | 67 | private static void ReplaceDataContractSerializerOperationBehavior(OperationDescription description) 68 | { 69 | DataContractSerializerOperationBehavior dcsOperationBehavior = description.Behaviors.Find(); 70 | if (dcsOperationBehavior != null) 71 | { 72 | description.Behaviors.Remove(dcsOperationBehavior); 73 | 74 | ProtoOperationBehavior newBehavior = new ProtoOperationBehavior(description); 75 | newBehavior.MaxItemsInObjectGraph = dcsOperationBehavior.MaxItemsInObjectGraph; 76 | description.Behaviors.Add(newBehavior); 77 | } 78 | } 79 | 80 | 81 | #endregion 82 | } 83 | 84 | } 85 | #endif -------------------------------------------------------------------------------- /xbuffer_test/protobuf-net/ServiceModel/ProtoOperationBehavior.cs: -------------------------------------------------------------------------------- 1 | #if FEAT_SERVICEMODEL && PLAT_XMLSERIALIZER && !NO_GENERICS 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Runtime.Serialization; 5 | using System.ServiceModel.Description; 6 | using System.Xml; 7 | using ProtoBuf.Meta; 8 | 9 | namespace ProtoBuf.ServiceModel 10 | { 11 | /// 12 | /// Describes a WCF operation behaviour that can perform protobuf serialization 13 | /// 14 | public sealed class ProtoOperationBehavior : DataContractSerializerOperationBehavior 15 | { 16 | private TypeModel model; 17 | /// 18 | /// The type-model that should be used with this behaviour 19 | /// 20 | public TypeModel Model 21 | { 22 | get { return model; } 23 | set { 24 | if (value == null) throw new ArgumentNullException("Model"); 25 | model = value; 26 | } 27 | 28 | } 29 | /// 30 | /// Create a new ProtoOperationBehavior instance 31 | /// 32 | public ProtoOperationBehavior(OperationDescription operation) : base(operation) 33 | { 34 | #if !NO_RUNTIME 35 | model = RuntimeTypeModel.Default; 36 | #endif 37 | } 38 | //public ProtoOperationBehavior(OperationDescription operation, DataContractFormatAttribute dataContractFormat) : base(operation, dataContractFormat) { } 39 | 40 | /// 41 | /// Creates a protobuf serializer if possible (falling back to the default WCF serializer) 42 | /// 43 | public override XmlObjectSerializer CreateSerializer(Type type, System.Xml.XmlDictionaryString name, System.Xml.XmlDictionaryString ns, IList knownTypes) 44 | { 45 | if (model == null) throw new InvalidOperationException("No Model instance has been assigned to the ProtoOperationBehavior"); 46 | return XmlProtoSerializer.TryCreate(model, type) ?? base.CreateSerializer(type, name, ns, knownTypes); 47 | } 48 | } 49 | } 50 | #endif -------------------------------------------------------------------------------- /xbuffer_test/protobuf-net/SubItemToken.cs: -------------------------------------------------------------------------------- 1 |  2 | namespace ProtoBuf 3 | { 4 | /// 5 | /// Used to hold particulars relating to nested objects. This is opaque to the caller - simply 6 | /// give back the token you are given at the end of an object. 7 | /// 8 | public struct SubItemToken 9 | { 10 | internal readonly int value; 11 | internal SubItemToken(int value) { 12 | this.value = value; 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /xbuffer_test/protobuf-net/WireType.cs: -------------------------------------------------------------------------------- 1 | namespace ProtoBuf 2 | { 3 | /// 4 | /// Indicates the encoding used to represent an individual value in a protobuf stream 5 | /// 6 | public enum WireType 7 | { 8 | /// 9 | /// Represents an error condition 10 | /// 11 | None = -1, 12 | 13 | /// 14 | /// Base-128 variant-length encoding 15 | /// 16 | Variant = 0, 17 | 18 | /// 19 | /// Fixed-length 8-byte encoding 20 | /// 21 | Fixed64 = 1, 22 | 23 | /// 24 | /// Length-variant-prefixed encoding 25 | /// 26 | String = 2, 27 | 28 | /// 29 | /// Indicates the start of a group 30 | /// 31 | StartGroup = 3, 32 | 33 | /// 34 | /// Indicates the end of a group 35 | /// 36 | EndGroup = 4, 37 | 38 | /// 39 | /// Fixed-length 4-byte encoding 40 | /// 10 41 | Fixed32 = 5, 42 | 43 | /// 44 | /// This is not a formal wire-type in the "protocol buffers" spec, but 45 | /// denotes a variant integer that should be interpreted using 46 | /// zig-zag semantics (so -ve numbers aren't a significant overhead) 47 | /// 48 | SignedVariant = WireType.Variant | (1 << 3), 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /xbuffer_test/test.xb: -------------------------------------------------------------------------------- 1 | class A 2 | { 3 | a:[bool]; 4 | b:[int]; 5 | c:[float]; 6 | d:[string]; 7 | e:[E]; 8 | } 9 | 10 | class E 11 | { 12 | a:bool; 13 | b:int; 14 | c:float; 15 | d:string; 16 | } -------------------------------------------------------------------------------- /xbuffer_test/test_flat.fbs: -------------------------------------------------------------------------------- 1 | table A 2 | { 3 | a:[bool]; 4 | b:[int]; 5 | c:[float]; 6 | d:[string]; 7 | e:[E]; 8 | } 9 | 10 | table E 11 | { 12 | a:bool; 13 | b:int; 14 | c:float; 15 | d:string; 16 | } -------------------------------------------------------------------------------- /xbuffer_test/test_proto.cs: -------------------------------------------------------------------------------- 1 | //------------------------------------------------------------------------------ 2 | // 3 | // This code was generated by a tool. 4 | // 5 | // Changes to this file may cause incorrect behavior and will be lost if 6 | // the code is regenerated. 7 | // 8 | //------------------------------------------------------------------------------ 9 | 10 | // Generated from: proto/test_proto.proto 11 | namespace proto.test_proto 12 | { 13 | [global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"proto_a")] 14 | public partial class proto_a : global::ProtoBuf.IExtensible 15 | { 16 | public proto_a() {} 17 | 18 | private readonly global::System.Collections.Generic.List _a = new global::System.Collections.Generic.List(); 19 | [global::ProtoBuf.ProtoMember(1, Name=@"a", DataFormat = global::ProtoBuf.DataFormat.Default)] 20 | public global::System.Collections.Generic.List a 21 | { 22 | get { return _a; } 23 | } 24 | 25 | private readonly global::System.Collections.Generic.List _b = new global::System.Collections.Generic.List(); 26 | [global::ProtoBuf.ProtoMember(2, Name=@"b", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)] 27 | public global::System.Collections.Generic.List b 28 | { 29 | get { return _b; } 30 | } 31 | 32 | private readonly global::System.Collections.Generic.List _c = new global::System.Collections.Generic.List(); 33 | [global::ProtoBuf.ProtoMember(3, Name=@"c", DataFormat = global::ProtoBuf.DataFormat.FixedSize)] 34 | public global::System.Collections.Generic.List c 35 | { 36 | get { return _c; } 37 | } 38 | 39 | private readonly global::System.Collections.Generic.List _d = new global::System.Collections.Generic.List(); 40 | [global::ProtoBuf.ProtoMember(4, Name=@"d", DataFormat = global::ProtoBuf.DataFormat.Default)] 41 | public global::System.Collections.Generic.List d 42 | { 43 | get { return _d; } 44 | } 45 | 46 | private readonly global::System.Collections.Generic.List _e = new global::System.Collections.Generic.List(); 47 | [global::ProtoBuf.ProtoMember(5, Name=@"e", DataFormat = global::ProtoBuf.DataFormat.Default)] 48 | public global::System.Collections.Generic.List e 49 | { 50 | get { return _e; } 51 | } 52 | 53 | private global::ProtoBuf.IExtension extensionObject; 54 | global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing) 55 | { return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); } 56 | } 57 | 58 | [global::System.Serializable, global::ProtoBuf.ProtoContract(Name=@"proto_e")] 59 | public partial class proto_e : global::ProtoBuf.IExtensible 60 | { 61 | public proto_e() {} 62 | 63 | private bool _a = default(bool); 64 | [global::ProtoBuf.ProtoMember(1, IsRequired = false, Name=@"a", DataFormat = global::ProtoBuf.DataFormat.Default)] 65 | [global::System.ComponentModel.DefaultValue(default(bool))] 66 | public bool a 67 | { 68 | get { return _a; } 69 | set { _a = value; } 70 | } 71 | private int _b = default(int); 72 | [global::ProtoBuf.ProtoMember(2, IsRequired = false, Name=@"b", DataFormat = global::ProtoBuf.DataFormat.TwosComplement)] 73 | [global::System.ComponentModel.DefaultValue(default(int))] 74 | public int b 75 | { 76 | get { return _b; } 77 | set { _b = value; } 78 | } 79 | private float _c = default(float); 80 | [global::ProtoBuf.ProtoMember(3, IsRequired = false, Name=@"c", DataFormat = global::ProtoBuf.DataFormat.FixedSize)] 81 | [global::System.ComponentModel.DefaultValue(default(float))] 82 | public float c 83 | { 84 | get { return _c; } 85 | set { _c = value; } 86 | } 87 | private string _d = ""; 88 | [global::ProtoBuf.ProtoMember(4, IsRequired = false, Name=@"d", DataFormat = global::ProtoBuf.DataFormat.Default)] 89 | [global::System.ComponentModel.DefaultValue("")] 90 | public string d 91 | { 92 | get { return _d; } 93 | set { _d = value; } 94 | } 95 | private global::ProtoBuf.IExtension extensionObject; 96 | global::ProtoBuf.IExtension global::ProtoBuf.IExtensible.GetExtensionObject(bool createIfMissing) 97 | { return global::ProtoBuf.Extensible.GetExtensionObject(ref extensionObject, createIfMissing); } 98 | } 99 | 100 | } -------------------------------------------------------------------------------- /xbuffer_test/test_proto.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto2"; 2 | 3 | message proto_a 4 | { 5 | repeated bool a = 1; 6 | repeated int32 b = 2; 7 | repeated float c = 3; 8 | repeated string d = 4; 9 | repeated proto_e e = 5; 10 | } 11 | 12 | message proto_e 13 | { 14 | optional bool a = 1; 15 | optional int32 b = 2; 16 | optional float c = 3; 17 | optional string d = 4; 18 | } --------------------------------------------------------------------------------