示例#1
0
        public object GetFieldValue(FieldDescriptorProto field_desc)
        {
            lastError.Clear();

            object ret;

            if (fieldData.TryGetValue(field_desc.number, out ret))
            {
                if (ret is List <object> )
                {
                    lastError.AddLast(string.Format("field {0} is repeated", field_desc.number));
                    return(null);
                }
                return(ret);
            }

            FieldDescriptorProto field;

            if (msgDescriptor.FieldIdIndex.TryGetValue(field_desc.number, out field))
            {
                return(defaultValue(field));
            }

            return(null);
        }
    private static string GenerateInitialString(FieldDescriptorProto fieldDescriptorProto, string tempString)
    {
        string rightVariableString;

        if (fieldDescriptorProto.Type.Equals(FieldDescriptorProto.Types.Type.TYPE_MESSAGE))
        {
            rightVariableString = $"new {tempString}()";
        }
        else if (fieldDescriptorProto.Type.Equals(FieldDescriptorProto.Types.Type.TYPE_BYTES))
        {
            rightVariableString = $"new byte[0]";
        }
        else if (fieldDescriptorProto.Type.Equals(FieldDescriptorProto.Types.Type.TYPE_ENUM))
        {
            rightVariableString = $"({tempString})0";
        }
        else if (fieldDescriptorProto.Type.Equals(FieldDescriptorProto.Types.Type.TYPE_STRING))
        {
            rightVariableString = $"\"\"";
        }
        else if (fieldDescriptorProto.Type.Equals(FieldDescriptorProto.Types.Type.TYPE_BOOL))
        {
            rightVariableString = $"false";
        }
        else
        {
            rightVariableString = $"0";
        }
        return(rightVariableString);
    }
示例#3
0
        /// <summary>
        /// 转储数据
        /// </summary>
        /// <param name="writer">写出目标</param>
        /// <returns>全部成功返回true,部分失败或全失败返回false,这时候可以通过LastError获取失败信息</returns>
        public bool Serialize(ProtoWriter writer)
        {
            buildIndex();
            lastError.Clear();

            foreach (var field in fieldData)
            {
                FieldDescriptorProto field_desc = null;
                // 不认识的值,直接忽略
                if (false == msgDescriptor.FieldIdIndex.TryGetValue(field.Key, out field_desc))
                {
                    continue;
                }

                if (field_desc.label == FieldDescriptorProto.Label.LABEL_REPEATED)
                {
                    foreach (var obj in (List <object>)field.Value)
                    {
                        write_object(writer, obj, field_desc);
                    }
                }
                else
                {
                    write_object(writer, field.Value, field_desc);
                }
            }

            return(0 == lastError.Count);
        }
示例#4
0
        private static bool UseArray(FieldDescriptorProto field)
        {
            //LiYu 不再使用数组 统统有List,方便操作
            bool v = true;

            if (v)
            {
                return(false);
            }
            switch (field.type)
            {
            case FieldDescriptorProto.Type.TypeBool:
            case FieldDescriptorProto.Type.TypeDouble:
            case FieldDescriptorProto.Type.TypeFixed32:
            case FieldDescriptorProto.Type.TypeFixed64:
            case FieldDescriptorProto.Type.TypeFloat:
            case FieldDescriptorProto.Type.TypeInt32:
            case FieldDescriptorProto.Type.TypeInt64:
            case FieldDescriptorProto.Type.TypeSfixed32:
            case FieldDescriptorProto.Type.TypeSfixed64:
            case FieldDescriptorProto.Type.TypeSint32:
            case FieldDescriptorProto.Type.TypeSint64:
            case FieldDescriptorProto.Type.TypeUint32:
            case FieldDescriptorProto.Type.TypeUint64:
                return(true);

            default:
                return(false);
            }
        }
示例#5
0
        public static WireType ToWireType(this FieldDescriptorProto proto)
        {
            switch (proto.type)
            {
            case FieldDescriptorProto.Type.TypeBool:

            case FieldDescriptorProto.Type.TypeEnum:

            case FieldDescriptorProto.Type.TypeInt32:
            case FieldDescriptorProto.Type.TypeUint32:
            case FieldDescriptorProto.Type.TypeSint32:

            case FieldDescriptorProto.Type.TypeInt64:
            case FieldDescriptorProto.Type.TypeUint64:
            case FieldDescriptorProto.Type.TypeSint64:
                return(WireType.Varint);

            case FieldDescriptorProto.Type.TypeString:
            case FieldDescriptorProto.Type.TypeBytes:
            case FieldDescriptorProto.Type.TypeMessage:
                return(WireType.LengthDelimited);

            case FieldDescriptorProto.Type.TypeFloat:
            case FieldDescriptorProto.Type.TypeFixed32:
                return(WireType.Bit32);

            case FieldDescriptorProto.Type.TypeDouble:
            case FieldDescriptorProto.Type.TypeFixed64:
                return(WireType.Bit64);

            default: throw new NotSupportedException("Deprecated features not supported.");
            }
        }
示例#6
0
        internal FieldDescriptor(FieldDescriptorProto proto, FileDescriptor file,
                                 MessageDescriptor parent, int index, string propertyName, Extension extension)
            : base(file, file.ComputeFullName(parent, proto.Name), index)
        {
            Proto = proto;
            if (proto.Type != 0)
            {
                fieldType = GetFieldTypeFromProtoType(proto.Type);
            }

            if (FieldNumber <= 0)
            {
                throw new DescriptorValidationException(this, "Field numbers must be positive integers.");
            }
            ContainingType = parent;
            if (proto.HasOneofIndex)
            {
                if (proto.OneofIndex < 0 || proto.OneofIndex >= parent.Proto.OneofDecl.Count)
                {
                    throw new DescriptorValidationException(this,
                                                            $"FieldDescriptorProto.oneof_index is out of range for type {parent.Name}");
                }
                ContainingOneof = parent.Oneofs[proto.OneofIndex];
            }

            file.DescriptorPool.AddSymbol(this);
            // We can't create the accessor until we've cross-linked, unfortunately, as we
            // may not know whether the type of the field is a map or not. Remember the property name
            // for later.
            // We could trust the generated code and check whether the type of the property is
            // a MapField, but that feels a tad nasty.
            this.propertyName = propertyName;
            Extension         = extension;
            JsonName          = Proto.JsonName == "" ? JsonFormatter.ToJsonName(Proto.Name) : Proto.JsonName;
        }
示例#7
0
        /// <summary>
        /// Write an extension
        /// </summary>
        protected override void WriteExtension(GeneratorContext ctx, FieldDescriptorProto field)
        {
            var type = GetTypeName(ctx, field, out string dataFormat, out bool isMap);

            if (isMap)
            {
                ctx.WriteLine("#error map extensions not yet implemented");
            }
            else if (field.label == FieldDescriptorProto.Label.LabelRepeated)
            {
                ctx.WriteLine("#error repeated extensions not yet implemented");
            }
            else
            {
                var msg      = ctx.TryFind <DescriptorProto>(field.Extendee);
                var extendee = MakeRelativeName(field, msg, ctx.NameNormalizer);

                var    @this = field.Parent is FileDescriptorProto ? "this " : "";
                string name  = field.Name;
                var    tw    = ctx.WriteLine($"{GetAccess(GetAccess(field))} static {type} Get{name}({@this}{extendee} obj)")
                               .Write($"=> obj == null ? default({type}) : global::ProtoBuf.Extensible.GetValue<{type}>(obj, {field.Number}");
                if (!string.IsNullOrEmpty(dataFormat))
                {
                    tw.Write($", global::ProtoBuf.DataFormat.{dataFormat}");
                }
                tw.WriteLine(");");
                ctx.WriteLine();
                //  GetValue<TValue>(IExtensible instance, int tag, DataFormat format)
            }
        }
示例#8
0
        static bool ExtractType(IExtensible data, FieldDescriptorProto field, out string value)
        {
            switch (field.type)
            {
            case FieldDescriptorProto.Type.TYPE_INT32:
            case FieldDescriptorProto.Type.TYPE_UINT32:
            case FieldDescriptorProto.Type.TYPE_FIXED32:
                if (Extensible.TryGetValue(data, field.number, out uint int32))
                {
                    value = Convert.ToString(int32);
                    return(true);
                }
                break;

            case FieldDescriptorProto.Type.TYPE_INT64:
            case FieldDescriptorProto.Type.TYPE_UINT64:
            case FieldDescriptorProto.Type.TYPE_FIXED64:
                if (Extensible.TryGetValue(data, field.number, out ulong int64))
                {
                    value = Convert.ToString(int64);
                    return(true);
                }
                break;

            case FieldDescriptorProto.Type.TYPE_SINT32:
            case FieldDescriptorProto.Type.TYPE_SFIXED32:
                if (Extensible.TryGetValue(data, field.number, out int sint32))
                {
                    value = Convert.ToString(sint32);
                    return(true);
                }
                break;

            case FieldDescriptorProto.Type.TYPE_SINT64:
            case FieldDescriptorProto.Type.TYPE_SFIXED64:
                if (Extensible.TryGetValue(data, field.number, out long sint64))
                {
                    value = Convert.ToString(sint64);
                    return(true);
                }
                break;

            case FieldDescriptorProto.Type.TYPE_STRING:
                if (Extensible.TryGetValue(data, field.number, out string str))
                {
                    value = $"\"{str}\"";
                    return(true);
                }
                break;

            case FieldDescriptorProto.Type.TYPE_BOOL:
                if (Extensible.TryGetValue(data, field.number, out bool boolean))
                {
                    value = boolean ? "true" : "false";
                    return(true);
                }
                break;

            case FieldDescriptorProto.Type.TYPE_BYTES:
                if (Extensible.TryGetValue(data, field.number, out byte[] bytes))
    private void ItemToLuaTableKVP(ref StringBuilder sb, FieldDescriptorProto infoAttr)
    {
        var itemType = ProtoTypeCSharType(infoAttr);
        var itemName = infoAttr.Name;

        sb.Append("\t\t\t");
        sb.Append(LUA_API);
        sb.Append(".lua_pushstring(L, \"");
        sb.Append(itemName);
        sb.Append("\");\r\n");

        //TypeToPushCode(ref sb, itemType, itemName);
        sb.Append("\t\t\t");
        var code = PushByType(itemType, "msg." + itemName,
                              infoAttr.type == FieldDescriptorProto.Type.TypeGroup || infoAttr.label == FieldDescriptorProto.Label.LabelRepeated);

        if (string.IsNullOrEmpty(code))
        {
            sb.Append(LUA_API);
            sb.Append(".lua_pushnil(L);\r\n");
        }
        else
        {
            sb.Append(code);
        }
        sb.Append("\t\t\t");
        sb.Append(LUA_API);
        sb.Append(".xlua_psettable(L, -3);\r\n");
    }
示例#10
0
        private string BuildDescriptorDeclaration(FileDescriptorProto source, FieldDescriptorProto field,
                                                  bool emitFieldLabel = true)
        {
            PushDescriptorName(field);

            var type    = ResolveType(field);
            var options = new Dictionary <string, string>();

            if (!string.IsNullOrEmpty(field.default_value))
            {
                var defaultValue = field.default_value;

                if (field.type == FieldDescriptorProto.Type.TYPE_STRING)
                {
                    defaultValue = $"\"{defaultValue}\"";
                }

                options.Add("default", defaultValue);
            }
            else if (field.type == FieldDescriptorProto.Type.TYPE_ENUM &&
                     field.label != FieldDescriptorProto.Label.LABEL_REPEATED)
            {
                var lookup = _protobufTypeMap[field.type_name];

                if (lookup.Source is EnumDescriptorProto enumDescriptor && enumDescriptor.value.Count > 0)
                {
                    options.Add("default", enumDescriptor.value[0].name);
                }
            }

            var fieldOptions = DumpOptions(source, field.options);

            foreach (var(key, value) in fieldOptions)
            {
                options[key] = value;
            }

            var parameters = string.Empty;

            if (options.Count > 0)
            {
                parameters = $" [{string.Join(", ", options.Select(kvp => $"{kvp.Key} = {kvp.Value}"))}]";
            }

            PopDescriptorName();

            var descriptorDeclarationBuilder = new StringBuilder();

            if (emitFieldLabel)
            {
                descriptorDeclarationBuilder.Append(GetLabel(field.label));
                descriptorDeclarationBuilder.Append(" ");
            }

            descriptorDeclarationBuilder.Append($"{type} {field.name} = {field.number}{parameters};");

            return(descriptorDeclarationBuilder.ToString());
        }
示例#11
0
        private string ResolveType(FieldDescriptorProto field)
        {
            if (field.type == FieldDescriptorProto.Type.TYPE_ENUM || field.type == FieldDescriptorProto.Type.TYPE_MESSAGE)
            {
                return(field.type_name);
            }

            return(GetType(field.type));
        }
示例#12
0
        /// <summary>
        /// If the field is an enum, add an Attribute to tell JsonConvert.SerializeObject() to write the enum name, not the int value.
        /// </summary>
        /// <param name="ctx"></param>
        /// <param name="obj"></param>
        /// <param name="state"></param>
        /// <param name="oneOfs"></param>
        protected override void WriteField(GeneratorContext ctx, FieldDescriptorProto obj, ref object state, OneOfStub[] oneOfs)
        {
            if (obj.type == FieldDescriptorProto.Type.TypeEnum && obj.label != FieldDescriptorProto.Label.LabelRepeated)
            {
                ctx.WriteLine("[Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))]");
            }

            base.WriteField(ctx, obj, ref state, oneOfs);
        }
示例#13
0
        /// <summary>
        /// Write a field
        /// </summary>
        protected override void WriteField(GeneratorContext ctx, FieldDescriptorProto obj, ref object state, OneOfStub[] oneOfs)
        {
            //var name = ctx.NameNormalizer.GetName(obj);
            var tw = ctx.Output;

            bool isOptional = obj.label == FieldDescriptorProto.Label.LabelOptional;
            bool isRepeated = obj.label == FieldDescriptorProto.Label.LabelRepeated;

            OneOfStub oneOf = obj.ShouldSerializeOneofIndex() ? oneOfs?[obj.OneofIndex] : null;

            if (oneOf != null && oneOf.CountTotal == 1)
            {
                oneOf = null; // not really a one-of, then!
            }
            bool explicitValues = isOptional && oneOf == null && ctx.Syntax == FileDescriptorProto.SyntaxProto2 &&
                                  obj.type != FieldDescriptorProto.Type.TypeMessage &&
                                  obj.type != FieldDescriptorProto.Type.TypeGroup;


            string defaultValue             = null;
            bool   suppressDefaultAttribute = !isOptional;
            var    typeName = GetTypeName(ctx, obj, out var dataFormat, out var isMap);

            defaultValue = GetDefaltValue(ctx, obj, typeName);
            if (isRepeated)
            {
                var mapMsgType = isMap ? ctx.TryFind <DescriptorProto>(obj.TypeName) : null;
                if (mapMsgType != null)
                {
                    var keyTypeName = GetTypeName(ctx, mapMsgType.Fields.Single(x => x.Number == 1),
                                                  out var keyDataFormat, out var _);
                    var valueTypeName = GetTypeName(ctx, mapMsgType.Fields.Single(x => x.Number == 2),
                                                    out var valueDataFormat, out var _);
                    ctx.WriteLine($"{GetAccess(GetAccess(obj))} System.Collections.Generic.Dictionary<{keyTypeName}, {valueTypeName}> {Escape(obj.Name)} = new System.Collections.Generic.Dictionary<{keyTypeName}, {valueTypeName}>();");
                }
                // else if (UseArray(obj))
                //  {
                // ctx.WriteLine($"{GetAccess(GetAccess(obj))} {typeName}[] {Escape(name)} ;");
                //  }
                else
                {
                    ctx.WriteLine($"{GetAccess(GetAccess(obj))} System.Collections.Generic.List<{typeName}> {Escape(obj.Name)} = new System.Collections.Generic.List<{typeName}>();");
                }
            }
            else
            {
                if (!string.IsNullOrEmpty(defaultValue))
                {
                    ctx.WriteLine($"{GetAccess(GetAccess(obj))} {typeName} {obj.Name} = {defaultValue};");
                }
                else
                {
                    ctx.WriteLine($"{GetAccess(GetAccess(obj))} {typeName} {obj.Name} ;");
                }
            }
        }
示例#14
0
        private string pickMsgName(FieldDescriptorProto desc)
        {
            string msg_name = desc.type_name;

            if (msg_name.Length > 0 && '.' == msg_name[0])
            {
                msg_name = msg_name.Substring(1);
            }
            return(msg_name);
        }
示例#15
0
        protected void WriteFileRead(GeneratorContext ctx, FieldDescriptorProto obj, OneOfStub[] oneOfs)
        {
            bool isRepeated = obj.label == FieldDescriptorProto.Label.LabelRepeated;
            var  typeName   = GetTypeName(ctx, obj, out var dataFormat, out var isMap);

            Google.Protobuf.WireFormat.WireType ttwtype = ProtoTool.ILHelper.GetWireType(obj.type);
            uint ttag = Google.Protobuf.WireFormat.MakeTag(obj.Number, ttwtype);

            ctx.WriteLine($"case {ttag}:").Indent();
            ReaderString(ctx, obj);
            ctx.WriteLine("break;").Outdent();
        }
示例#16
0
        private string BuildDescriptorDeclaration(FieldDescriptorProto field, bool emitFieldLabel = true)
        {
            PushDescriptorName(field);

            string type = ResolveType(field);
            Dictionary <string, string> options = new Dictionary <string, string>();

            if (!String.IsNullOrEmpty(field.default_value))
            {
                string default_value = field.default_value;

                if (field.type == FieldDescriptorProto.Type.TYPE_STRING)
                {
                    default_value = String.Format("\"{0}\"", default_value);
                }

                options.Add("default", default_value);
            }
            else if (field.type == FieldDescriptorProto.Type.TYPE_ENUM && field.label != FieldDescriptorProto.Label.LABEL_REPEATED)
            {
                options.Add("default", ResolveOrDeferEnumDefaultValue(type));
            }

            Dictionary <string, string> fieldOptions = DumpOptions(field.options);

            foreach (var pair in fieldOptions)
            {
                options[pair.Key] = pair.Value;
            }

            string parameters = String.Empty;

            if (options.Count > 0)
            {
                parameters = " [" + String.Join(", ", options.Select(kvp => String.Format("{0} = {1}", kvp.Key, kvp.Value))) + "]";
            }

            PopDescriptorName();

            var descriptorDeclarationBuilder = new StringBuilder();

            if (emitFieldLabel)
            {
                descriptorDeclarationBuilder.Append(GetLabel(field.label));
                descriptorDeclarationBuilder.Append(" ");
            }


            descriptorDeclarationBuilder.AppendFormat("{0} {1} = {2}{3};", type.TrimStart('.'), field.name, field.number, parameters);

            return(descriptorDeclarationBuilder.ToString());
        }
示例#17
0
        /// <summary>
        /// 创见一个动态Message,和当前的Message共享同一个类型描述集
        /// </summary>
        /// <param name="desc">field描述</param>
        /// <returns>新创建的Message,如果创建失败返回null</returns>
        public DynamicMessage CreateMessage(FieldDescriptorProto desc)
        {
            if (null == desc)
            {
                lastError.Clear();
                lastError.AddLast("FieldDescriptorProto can not be null");
                return(null);
            }

            string msg_name = pickMsgName(desc);

            return(CreateMessage(msg_name));
        }
示例#18
0
        private string BuildDescriptorDeclaration(FieldDescriptorProto field, ProtoExtensionDefs extensions, bool emitFieldLabel = true)
        {
            PushDescriptorName(field);

            var type    = ResolveType(field);
            var options = new Dictionary <string, string>();

            if (!string.IsNullOrEmpty(field.default_value))
            {
                var default_value = field.default_value;

                if (field.type == FieldDescriptorProto.Type.TYPE_STRING)
                {
                    default_value = $"\"{default_value}\"";
                }

                options.Add("default", default_value);
            }
            else if (field.type == FieldDescriptorProto.Type.TYPE_ENUM && field.label != FieldDescriptorProto.Label.LABEL_REPEATED)
            {
                options.Add("default", ResolveOrDeferEnumDefaultValue(type));
            }

            var fieldOptions = DumpOptions(field.options, extensions);

            foreach (var pair in fieldOptions)
            {
                options[pair.Key] = pair.Value;
            }

            var parameters = string.Empty;

            if (options.Count > 0)
            {
                parameters = $" [{string.Join(", ", options.Select(kvp => $"{kvp.Key} = {kvp.Value}"))}]";
            }

            PopDescriptorName();

            var descriptorDeclarationBuilder = new StringBuilder();

            if (emitFieldLabel)
            {
                descriptorDeclarationBuilder.Append(GetLabel(field.label));
                descriptorDeclarationBuilder.Append(" ");
            }

            descriptorDeclarationBuilder.Append($"{type} {field.name} = {field.number}{parameters};");

            return(descriptorDeclarationBuilder.ToString());
        }
示例#19
0
        /// <summary>
        /// Emit code initializing field values inside a constructor, if one is required
        /// </summary>
        protected override void WriteInitField(GeneratorContext ctx, FieldDescriptorProto obj, ref object state, OneOfStub[] oneOfs)
        {
            var       name       = ctx.NameNormalizer.GetName(obj);
            bool      isOptional = obj.label == FieldDescriptorProto.Label.LabelOptional;
            bool      isRepeated = obj.label == FieldDescriptorProto.Label.LabelRepeated;
            string    dataFormat;
            bool      isMap;
            var       typeName       = GetTypeName(ctx, obj, out dataFormat, out isMap);
            OneOfStub oneOf          = obj.ShouldSerializeOneofIndex() ? oneOfs?[obj.OneofIndex] : null;
            bool      explicitValues = isOptional && oneOf == null && ctx.Syntax == FileDescriptorProto.SyntaxProto2 &&
                                       obj.type != FieldDescriptorProto.Type.TypeMessage &&
                                       obj.type != FieldDescriptorProto.Type.TypeGroup;

            string defaultValue = GetDefaultValue(ctx, obj, typeName);

            if (isRepeated)
            {
                var mapMsgType = isMap ? ctx.TryFind <DescriptorProto>(obj.TypeName) : null;
                if (mapMsgType != null)
                {
                    string keyDataFormat;
                    string valueDataFormat;
                    bool   _;
                    var    keyTypeName = GetTypeName(ctx, mapMsgType.Fields.Single(x => x.Number == 1),
                                                     out keyDataFormat, out _);
                    var valueTypeName = GetTypeName(ctx, mapMsgType.Fields.Single(x => x.Number == 2),
                                                    out valueDataFormat, out _);
                    ctx.WriteLine($"{Escape(name)} = new global::System.Collections.Generic.Dictionary<{keyTypeName}, {valueTypeName}>();");
                }
                else if (UseArray(obj))
                {
                }   // nothing needed
                else
                {
                    ctx.WriteLine($"{Escape(name)} = new global::System.Collections.Generic.List<{typeName}>();");
                }
            }
            else if (oneOf != null)
            {
            }   // nothing to do
            else if (explicitValues)
            {
            }   // nothing to do
            else
            {
                if (!string.IsNullOrWhiteSpace(defaultValue))
                {
                    ctx.WriteLine($"{Escape(name)} = {defaultValue};");
                }
            }
        }
示例#20
0
        private object defaultValue(FieldDescriptorProto desc)
        {
            switch (desc.type)
            {
            case FieldDescriptorProto.Type.TYPE_DOUBLE:
                return((double)0.0);

            case FieldDescriptorProto.Type.TYPE_FLOAT:
                return((float)0.0);

            case FieldDescriptorProto.Type.TYPE_INT64:
            case FieldDescriptorProto.Type.TYPE_SFIXED64:
            case FieldDescriptorProto.Type.TYPE_SINT64:
                return((long)0);

            case FieldDescriptorProto.Type.TYPE_FIXED64:
            case FieldDescriptorProto.Type.TYPE_UINT64:
                return((ulong)0);

            case FieldDescriptorProto.Type.TYPE_INT32:
            case FieldDescriptorProto.Type.TYPE_SINT32:
            case FieldDescriptorProto.Type.TYPE_SFIXED32:
                return((int)0);

            case FieldDescriptorProto.Type.TYPE_FIXED32:
            case FieldDescriptorProto.Type.TYPE_UINT32:
                return((uint)0);

            case FieldDescriptorProto.Type.TYPE_BOOL:
                return(false);

            case FieldDescriptorProto.Type.TYPE_STRING:
                return("");

            case FieldDescriptorProto.Type.TYPE_GROUP:
                return(null);

            case FieldDescriptorProto.Type.TYPE_MESSAGE:
                return(null);

            case FieldDescriptorProto.Type.TYPE_BYTES:
                return(new byte[0]);

            case FieldDescriptorProto.Type.TYPE_ENUM:
                return((int)0);

            default:
                return(null);
            }
        }
示例#21
0
        /// <summary>
        /// 添加字段,如果是repeated会追加的末尾,否则是覆盖
        /// </summary>
        /// <param name="desc">key的描述信息</param>
        /// <param name="obj">值</param>
        /// <returns>返回是否成功</returns>
        public bool AddField(FieldDescriptorProto desc, object obj)
        {
            if (null == desc)
            {
                return(false);
            }

            if (desc.label == FieldDescriptorProto.Label.LABEL_REPEATED)
            {
                return(AddFieldList(desc, obj));
            }

            return(SetFieldValue(desc, obj));
        }
示例#22
0
        /// <summary>
        /// 添加List类型数据
        /// </summary>
        /// <param name="desc">key的描述信息</param>
        /// <param name="obj">值</param>
        /// <returns>返回是否成功</returns>
        public bool AddFieldList(FieldDescriptorProto desc, object obj)
        {
            if (null == desc)
            {
                return(false);
            }

            buildIndex();
            lastError.Clear();

            if (desc.label != FieldDescriptorProto.Label.LABEL_REPEATED)
            {
                lastError.AddLast(string.Format("field {0} is repeated, can only use SetFieldValue", desc.name));
                return(false);
            }

            if (!verifyField(desc, ref obj))
            {
                lastError.AddLast(string.Format("field {0} type error, must match {1}", desc.name, desc.type.ToString()));
                return(false);
            }

            // 对枚举类型特殊处理
            if (desc.type == FieldDescriptorProto.Type.TYPE_ENUM && obj is string)
            {
                EnumValueDescriptorProto enum_desc;
                if (!descriptors.EnumValueDescriptors.TryGetValue((string)obj, out enum_desc))
                {
                    lastError.AddLast(string.Format("enum value path {0} not found", obj));
                    return(false);
                }

                obj = enum_desc.number;
            }

            object old_val;

            if (fieldData.TryGetValue(desc.number, out old_val))
            {
                ((List <object>)old_val).Add(obj);
            }
            else
            {
                fieldData.Add(desc.number, new List <object> {
                    obj
                });
            }
            return(true);
        }
示例#23
0
        public static ZField From(this FieldDescriptorProto proto, string @namespace)
        {
            var fieldName  = proto.Name.Pascalize();
            var index      = proto.Number;
            var cSharpType = proto.ToSourceType(@namespace);

            var options = new ZFieldOptions
            {
                Deprecated = proto.Options?.Deprecated == true ? true : false
            };

            var wireType = proto.ToWireType();
            var serializationImplementation = proto.ToSerializationImplementation();

            return(new ZField(fieldName, index, cSharpType, options, wireType, serializationImplementation));
        }
示例#24
0
        /// <summary>
        /// Suggest a normalized identifier
        /// </summary>
        public virtual string GetName(FieldDescriptorProto definition)
        {
            var name = definition?.Options?.GetOptions()?.Name;

            if (!string.IsNullOrWhiteSpace(name))
            {
                return(name);
            }
            var preferred = GetName(definition.Name);

            if (definition.label == FieldDescriptorProto.Label.LabelRepeated)
            {
                preferred = Pluralize(preferred);
            }
            return(GetName(definition.Parent as DescriptorProto, preferred, definition.Name, true));
        }
示例#25
0
        private void DumpOptionsFieldRecursive(FieldDescriptorProto field, IExtensible options,
                                               IDictionary <string, string> optionsKv, string path)
        {
            var key = string.IsNullOrEmpty(path) ? $"({field.name})" : $"{path}.{field.name}";

            if (IsNamedType(field.type) && !string.IsNullOrEmpty(field.type_name))
            {
                var fieldData = _protobufTypeMap[field.type_name].Source;

                switch (fieldData)
                {
                case EnumDescriptorProto enumProto:
                {
                    if (Extensible.TryGetValue(options, field.number, out int idx))
                    {
                        var value = enumProto.value.Find(x => x.number == idx);

                        optionsKv.Add(key, value.name);
                    }

                    break;
                }

                case DescriptorProto messageProto:
                {
                    var extension = Extensible.GetValue <ExtensionPlaceholder>(options, field.number);

                    if (extension != null)
                    {
                        foreach (var subField in messageProto.field)
                        {
                            DumpOptionsFieldRecursive(subField, extension, optionsKv, key);
                        }
                    }

                    break;
                }
                }
            }
            else
            {
                if (ExtractType(options, field, out var value))
                {
                    optionsKv.Add(key, value);
                }
            }
        }
        private string MakeRelativeName(FieldDescriptorProto field, IType target, NameNormalizer normalizer)
        {
            if (target == null)
            {
                return(Escape(field.TypeName));                // the only thing we know
            }
            var declaringType = field.Parent;

            if (declaringType is IType type)
            {
                var name = FindNameFromCommonAncestor(type, target, normalizer);
                if (!string.IsNullOrWhiteSpace(name))
                {
                    return(name);
                }
            }
            return(Escape(field.TypeName)); // give up!
        }
    private static string GenerateOutputString(FieldDescriptorProto fieldDescriptorProto, string tempString)
    {
        string rightVariableString;

        if (fieldDescriptorProto.Type.Equals(FieldDescriptorProto.Types.Type.TYPE_MESSAGE))
        {
            rightVariableString = $"{tempString}.OutputBaseFromWrapper()";
        }
        else if (fieldDescriptorProto.Type.Equals(FieldDescriptorProto.Types.Type.TYPE_BYTES))
        {
            rightVariableString = $"Google.Protobuf.ByteString.CopyFrom({tempString})";
        }
        else
        {
            rightVariableString = $"{tempString}";
        }
        return(rightVariableString);
    }
示例#28
0
        public DynamicMessage GetFieldMessage(FieldDescriptorProto desc)
        {
            if (desc.type != FieldDescriptorProto.Type.TYPE_MESSAGE)
            {
                lastError.Clear();
                lastError.AddLast(string.Format("field {0}.{1} is not a message", msgDescriptor.Protocol.name, desc.name));
                return(null);
            }


            object ret = GetFieldValue(desc);

            if (ret is DynamicMessage)
            {
                return((DynamicMessage)ret);
            }
            return(null);
        }
示例#29
0
        public List <object> GetFieldList(FieldDescriptorProto field_desc)
        {
            lastError.Clear();

            object ret;

            if (fieldData.TryGetValue(field_desc.number, out ret))
            {
                if (!(ret is List <object>))
                {
                    lastError.AddLast(string.Format("field {1} is not repeated", field_desc.number));
                    return(null);
                }

                return((List <object>)ret);
            }

            return(new List <object>());
        }
示例#30
0
        private dynamic GetFiledDefaultValue(FieldDescriptorProto field, List <DescriptorProto> messageTypes)
        {
            switch (field.type)
            {
            case FieldDescriptorProto.Type.TypeDouble:
            case FieldDescriptorProto.Type.TypeFloat:
            case FieldDescriptorProto.Type.TypeInt64:
            case FieldDescriptorProto.Type.TypeUint64:
            case FieldDescriptorProto.Type.TypeInt32:
            case FieldDescriptorProto.Type.TypeFixed64:
            case FieldDescriptorProto.Type.TypeFixed32:
            case FieldDescriptorProto.Type.TypeUint32:
            case FieldDescriptorProto.Type.TypeEnum:
            case FieldDescriptorProto.Type.TypeSfixed32:
            case FieldDescriptorProto.Type.TypeSfixed64:
            case FieldDescriptorProto.Type.TypeSint32:
            case FieldDescriptorProto.Type.TypeSint64:
                return(0);

            case FieldDescriptorProto.Type.TypeBool:
                return(true);

            case FieldDescriptorProto.Type.TypeString:
            case FieldDescriptorProto.Type.TypeBytes:
            case FieldDescriptorProto.Type.TypeGroup:
                return("");

            case FieldDescriptorProto.Type.TypeMessage:
                var typeName = field.TypeName.Split('.').Last();
                var type     = messageTypes.FirstOrDefault(p => p.Name == typeName);
                if (type != null)
                {
                    return(type.Fields.ToDictionary(p => p.Name, p => GetFiledDefaultValue(p, messageTypes)));
                }
                else
                {
                    return("");
                }

            default:
                return("");
            }
        }
示例#31
0
 /// <summary>Helper: put the buffer into a MemoryStream and create a new instance to deserializing into</summary>
 public static FieldDescriptorProto Deserialize(byte[] buffer)
 {
     FieldDescriptorProto instance = new FieldDescriptorProto();
     using (var ms = new MemoryStream(buffer))
         Deserialize(ms, instance);
     return instance;
 }
示例#32
0
 /// <summary>Helper: Serialize into a MemoryStream and return its byte array</summary>
 public static byte[] SerializeToBytes(FieldDescriptorProto instance)
 {
     using (var ms = new MemoryStream())
     {
         Serialize(ms, instance);
         return ms.ToArray();
     }
 }
示例#33
0
 /// <summary>Helper: Serialize with a varint length prefix</summary>
 public static void SerializeLengthDelimited(Stream stream, FieldDescriptorProto instance)
 {
     var data = SerializeToBytes(instance);
     global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt32(stream, (uint)data.Length);
     stream.Write(data, 0, data.Length);
 }
示例#34
0
        /// <summary>Serialize the instance into the stream</summary>
        public static void Serialize(Stream stream, FieldDescriptorProto instance)
        {
            if (instance.Name != null)
            {
                // Key for field: 1, LengthDelimited
                stream.WriteByte(10);
                global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteBytes(stream, Encoding.UTF8.GetBytes(instance.Name));
            }
            // Key for field: 3, Varint
            stream.WriteByte(24);
            global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt64(stream,(ulong)instance.Number);
            // Key for field: 4, Varint
            stream.WriteByte(32);
            global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt64(stream,(ulong)instance.label);
            // Key for field: 5, Varint
            stream.WriteByte(40);
            global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt64(stream,(ulong)instance.type);
            if (instance.TypeName != null)
            {
                // Key for field: 6, LengthDelimited
                stream.WriteByte(50);
                global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteBytes(stream, Encoding.UTF8.GetBytes(instance.TypeName));
            }
            if (instance.Extendee != null)
            {
                // Key for field: 2, LengthDelimited
                stream.WriteByte(18);
                global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteBytes(stream, Encoding.UTF8.GetBytes(instance.Extendee));
            }
            if (instance.DefaultValue != null)
            {
                // Key for field: 7, LengthDelimited
                stream.WriteByte(58);
                global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteBytes(stream, Encoding.UTF8.GetBytes(instance.DefaultValue));
            }
            if (instance.Options != null)
            {
                // Key for field: 8, LengthDelimited
                stream.WriteByte(66);
                using (var ms8 = new MemoryStream())
                {
                    Google.protobuf.FieldOptions.Serialize(ms8, instance.Options);
                    // Length delimited byte array
                    uint ms8Length = (uint)ms8.Length;
                    global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt32(stream, ms8Length);
                    stream.Write(ms8.GetBuffer(), 0, (int)ms8Length);
                }

            }
        }
示例#35
0
 /// <summary>Helper: create a new instance to deserializing into</summary>
 public static FieldDescriptorProto DeserializeLengthDelimited(Stream stream)
 {
     FieldDescriptorProto instance = new FieldDescriptorProto();
     DeserializeLengthDelimited(stream, instance);
     return instance;
 }
示例#36
0
 /// <summary>Helper: create a new instance to deserializing into</summary>
 public static FieldDescriptorProto DeserializeLength(Stream stream, int length)
 {
     FieldDescriptorProto instance = new FieldDescriptorProto();
     DeserializeLength(stream, length, instance);
     return instance;
 }
        /// <summary>Serialize the instance into the stream</summary>
        public static void Serialize(Stream stream, FieldDescriptorProto instance)
        {
            var msField = global::SilentOrbit.ProtocolBuffers.ProtocolParser.Stack.Pop();
            if (instance.Name != null)
            {
                // Key for field: 1, LengthDelimited
                stream.WriteByte(10);
                global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteBytes(stream, Encoding.UTF8.GetBytes(instance.Name));
            }
            // Key for field: 3, Varint
            stream.WriteByte(24);
            global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt64(stream,(ulong)instance.Number);
            // Key for field: 4, Varint
            stream.WriteByte(32);
            global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt64(stream,(ulong)instance.label);
            // Key for field: 5, Varint
            stream.WriteByte(40);
            global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt64(stream,(ulong)instance.type);
            if (instance.TypeName != null)
            {
                // Key for field: 6, LengthDelimited
                stream.WriteByte(50);
                global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteBytes(stream, Encoding.UTF8.GetBytes(instance.TypeName));
            }
            if (instance.Extendee != null)
            {
                // Key for field: 2, LengthDelimited
                stream.WriteByte(18);
                global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteBytes(stream, Encoding.UTF8.GetBytes(instance.Extendee));
            }
            if (instance.DefaultValue != null)
            {
                // Key for field: 7, LengthDelimited
                stream.WriteByte(58);
                global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteBytes(stream, Encoding.UTF8.GetBytes(instance.DefaultValue));
            }
            if (instance.Options != null)
            {
                // Key for field: 8, LengthDelimited
                stream.WriteByte(66);
                msField.SetLength(0);
                Google.Protobuf.FieldOptions.Serialize(msField, instance.Options);
                // Length delimited byte array
                uint length8 = (uint)msField.Length;
                global::SilentOrbit.ProtocolBuffers.ProtocolParser.WriteUInt32(stream, length8);
                msField.WriteTo(stream);

            }
            global::SilentOrbit.ProtocolBuffers.ProtocolParser.Stack.Push(msField);
        }
 /// <summary>Helper: create a new instance to deserializing into</summary>
 public static FieldDescriptorProto Deserialize(Stream stream)
 {
     var instance = new FieldDescriptorProto();
     Deserialize(stream, instance);
     return instance;
 }