public void WriteTo(IIonWriter writer) { if (!(writer is IPrivateWriter privateWriter)) { throw new InvalidOperationException(); } if (writer.IsInStruct && !privateWriter.IsFieldNameSet()) { if (FieldNameSymbol == default) { throw new IonException("Field name is not set"); } writer.SetFieldNameSymbol(FieldNameSymbol); } privateWriter.ClearTypeAnnotations(); if (_annotations != null) { foreach (var a in _annotations) { privateWriter.AddTypeAnnotationSymbol(a); } } // privateWriter.SetTypeAnnotation(GetTypeAnnotations()); WriteBodyTo(privateWriter); }
private byte[] GetBytes(IonType type, dynamic value, bool isNull) { if (isNull) { byte typeCode = (byte)type; return(new byte[] { (byte)(typeCode << 4 | 0x0F) }); } else if (type == IonType.Float && value == 0 && BitConverter.DoubleToInt64Bits(value) >= 0) { // value is 0.0, not -0.0 return(new byte[] { 0x40 }); } else { using (MemoryStream stream = new MemoryStream()) { using (IIonWriter writer = IonBinaryWriterBuilder.Build(stream, forceFloat64: true)) { Serializers(type, value, writer); writer.Finish(); } return(stream.ToArray().Skip(4).ToArray()); } } }
/// <summary> /// Serialize long value. /// </summary> /// /// <param name="writer">The Ion writer to be used for serialization.</param> /// <param name="item">The long value to serialize.</param> public override void Serialize(IIonWriter writer, long item) { writer.SetTypeAnnotations(new List <string>() { ANNOTATION }); writer.WriteInt(item); }
internal override IIonReader GetIonReader(IIonValue ionValue) { MemoryStream ms = new MemoryStream(); IIonWriter writer = IonBinaryWriterBuilder.Build(ms); ionValue.WriteTo(writer); writer.Flush(); return(IonReaderBuilder.Build(ms.ToArray())); }
public override void Serialize(IIonWriter writer, Course item) { writer.StepIn(IonType.Struct); writer.SetFieldName("Sections"); writer.WriteInt(updateCourseSections.RemoveSections(item.Sections)); writer.SetFieldName("MeetingTime"); writer.WriteString(updateCourseSections.ShowNewTime()); writer.StepOut(); }
/// <inheritdoc/> public override void Serialize(IIonWriter writer, IList item) { writer.StepIn(IonType.List); foreach (var i in item) { this.serializer.Serialize(writer, i); } writer.StepOut(); }
protected override void WriteBodyTo(IIonWriter writer, ISymbolTableProvider symbolTableProvider) { if (IsNullValue()) { writer.WriteNull(IonType.Bool); return; } writer.WriteBool(IsBoolTrue()); }
/// <summary> /// Write the object to the writer, don't care the level/container, don't know the type /// </summary> internal static void WriteObject(IIonWriter writer, object obj, IScalarWriter scalarWriter) { if (obj == null) { writer.WriteNull(); return; } WriteObject(writer, obj, obj.GetType(), scalarWriter); }
/// <summary> /// Write the name/version/maxid of an imported table. /// </summary> /// <param name="writer">Current writer.</param> /// <param name="importedTable">Imported table.</param> /// <remarks>This assumes the writer is in the import list.</remarks> internal static void WriteImportTable(this IIonWriter writer, ISymbolTable importedTable) { writer.StepIn(IonType.Struct); // {name:'a', version: 1, max_id: 33} writer.SetFieldNameSymbol(GetSystemSymbol(SystemSymbols.NameSid)); writer.WriteString(importedTable.Name); writer.SetFieldNameSymbol(GetSystemSymbol(SystemSymbols.VersionSid)); writer.WriteInt(importedTable.Version); writer.SetFieldNameSymbol(GetSystemSymbol(SystemSymbols.MaxIdSid)); writer.WriteInt(importedTable.MaxId); writer.StepOut(); }
public override void Serialize(IIonWriter writer, Unicorn item) { writer.StepIn(IonType.Struct); writer.SetFieldName("Status"); writer.WriteString(item.Status); writer.SetFieldName("Drop"); writer.WriteString(this.drop); writer.SetFieldName("IsHorned"); writer.WriteBool(item.IsHorned); writer.StepOut(); }
/// <summary> /// Serializes an IDictionary into an Ion Struct where the Key is the struct field name /// and the Value is the struct field value. /// </summary> /// /// <param name="writer">The Ion writer to be used for serialization.</param> /// <param name="item">The dictionary value to serialize.</param> public override void Serialize(IIonWriter writer, IDictionary item) { writer.StepIn(IonType.Struct); foreach (DictionaryEntry nameValuePair in item) { writer.SetFieldName((string)nameValuePair.Key); this.serializer.Serialize(writer, nameValuePair.Value); } writer.StepOut(); }
/// <summary> /// Serialize value to Ion. /// </summary> /// /// <param name="stream">The stream to be written with serialized Ion.</param> /// <param name="item">The value to serialize.</param> /// <typeparam name="T">The type of data to serialize.</typeparam> public void Serialize <T>(Stream stream, T item) { IIonWriter writer = this.options.WriterFactory.Create(this.options, stream); this.Serialize(writer, item); // We use `IIonWriter.Flush` instead of `IIonWriter.Finish` here. Although the `Finish` method // documentation says "all written values will be flushed", that's only true for Ion binary writer. // For Ion text writer, the `Finish` method is empty and only the `Flush` method calls the implemented // `TextWriter.Flush` method that causes any buffered data to be written to the underlying device. writer.Flush(); }
/// <summary> /// Serialize Guid value. /// </summary> /// /// <param name="writer">The Ion writer to be used for serialization.</param> /// <param name="item">The Guid value to serialize.</param> public override void Serialize(IIonWriter writer, Guid item) { if (this.options.AnnotateGuids) { writer.SetTypeAnnotations(new List <string>() { ANNOTATION }); } writer.WriteBlob(item.ToByteArray()); }
internal override void Traverse(IIonReader reader, TestIonHasherProvider hasherProvider) { this.hasherProvider = hasherProvider; MemoryStream ms = new MemoryStream(); StreamWriter sw = new StreamWriter(ms); IIonWriter writer = IonTextWriterBuilder.Build(sw); IIonHashWriter ihw = new IonHashWriter(writer, this.hasherProvider); ihw.WriteValues(reader); ihw.Digest(); ihw.Dispose(); }
protected override void WriteBodyTo(IIonWriter writer, ISymbolTableProvider symbolTableProvider) { if (IsNullValue()) { writer.WriteNull(IonType.Int); } else if (_bigInteger != null) { writer.WriteInt(_bigInteger.Value); } else { writer.WriteInt(_longValue); } }
/// <inheritdoc/> public void Apply(IonSerializationOptions options, IIonWriter writer, Type type) { IonAnnotateTypeAttribute annotateType = this.ShouldAnnotate(type, type); if (annotateType == null && options.IncludeTypeInformation) { // the serializer insists on type information being included annotateType = new IonAnnotateTypeAttribute(); } if (annotateType != null) { writer.AddTypeAnnotation(options.AnnotationConvention.Apply(options, annotateType, type)); } }
private static void Serializers(IonType type, dynamic value, IIonWriter writer) { switch (type) { case IonType.Bool: writer.WriteBool(value); break; case IonType.Blob: writer.WriteBlob(value); break; case IonType.Clob: writer.WriteClob(value); break; case IonType.Decimal: writer.WriteDecimal(value); break; case IonType.Float: writer.WriteFloat(value); break; case IonType.Int: writer.WriteInt(value); break; case IonType.String: writer.WriteString(value); break; case IonType.Symbol: writer.WriteString(value.Text); break; case IonType.Timestamp: writer.WriteTimestamp(value); break; case IonType.Null: writer.WriteNull(value); break; default: throw new InvalidOperationException("Unexpected type '" + type + "'"); } }
/// <summary> /// Serialize value to Ion using serializer identified by <see cref="IonAnnotateTypeAttribute"/>. /// </summary> /// /// <param name="writer">The Ion writer to be used for serialization.</param> /// <param name="item">The value to serialize.</param> /// <param name="annotationAttribute">The <see cref="IonAnnotateTypeAttribute"/> to identify custom serializer for serialization.</param> /// <typeparam name="T">The type of data to serialize.</typeparam> /// /// <returns>True if the value is serialized to Ion using AnnotatedIonSerializer. Otherwise return false.</returns> internal bool TryAnnotatedIonSerializer <T>(IIonWriter writer, T item, IonAnnotateTypeAttribute annotationAttribute) { if (this.options.AnnotatedIonSerializers != null) { string standardizedAnnotation = this.options.AnnotationConvention.Apply(this.options, annotationAttribute, item.GetType()); if (this.options.AnnotatedIonSerializers.ContainsKey(standardizedAnnotation)) { var serializer = this.options.AnnotatedIonSerializers[standardizedAnnotation]; writer.AddTypeAnnotation(standardizedAnnotation); serializer.Serialize(writer, item); return(true); } } return(false); }
private byte[] ExerciseWriter(IIonReader reader, bool useHashWriter, Action <IIonReader, IIonWriter> lambda) { using (MemoryStream memoryStream = new MemoryStream()) { IIonWriter writer = IonBinaryWriterBuilder.Build(memoryStream); if (useHashWriter) { writer = IonHashWriterBuilder .Standard() .WithHasherProvider(new IdentityIonHasherProvider()) .WithWriter(writer) .Build(); } lambda(reader, writer); writer.Finish(); return(memoryStream.ToArray()); } }
private static bool TryWriteByteArray(IIonWriter writer, object obj, Type type) { if (obj == null) { if (!typeof(byte[]).IsAssignableFrom(type) && !typeof(IEnumerable <byte>).IsAssignableFrom(type)) { return(false); } writer.WriteNull(IonType.Blob); return(true); } if (type == typeof(byte[])) { //fast path, just check directly for byte array writer.WriteBlob((byte[])obj); return(true); } if (type == typeof(ReadOnlyMemory <byte>)) { //fast path 2 writer.WriteBlob(((ReadOnlyMemory <byte>)obj).Span); return(true); } if (type == typeof(Memory <byte>)) { //fast path 3 writer.WriteBlob(((Memory <byte>)obj).Span); return(true); } //slow path, does anyone really use List<byte> ??? if (!(obj is IEnumerable <byte> enumerable)) { return(false); } writer.WriteBlob(enumerable.ToArray()); return(true); }
/// <summary> /// Just write a bunch of scalar values /// </summary> private static List <(string key, object value)> WriteFlat(IIonWriter writer) { var kvps = new List <(string key, object value)>(); void writeAndAdd <T>(string fieldName, T value, Action <T> writeAction) { writer.SetFieldName(fieldName); writeAction(value); kvps.Add((fieldName, value)); } writeAndAdd("boolean", true, writer.WriteBool); writeAndAdd("cstring", "somestring", writer.WriteString); writeAndAdd("int", 123456, i => writer.WriteInt(i)); writeAndAdd("long", long.MaxValue / 10000, writer.WriteInt); writeAndAdd("datetime", new Timestamp(new DateTime(2000, 11, 11, 11, 11, 11, DateTimeKind.Utc)), writer.WriteTimestamp); writeAndAdd("decimal", 6.34233242123123123423m, writer.WriteDecimal); writeAndAdd("float", 231236.321312f, d => writer.WriteFloat(d)); writeAndAdd("double", 231345.325667d * 133.346432d, writer.WriteFloat); return(kvps); }
public void WriteTo(IIonWriter writer) { if (!(writer is IPrivateWriter privateWriter)) { throw new InvalidOperationException(); } if (writer.IsInStruct && !privateWriter.IsFieldNameSet()) { if (FieldNameSymbol == default) { throw new IonException("Field name is not set"); } writer.SetFieldNameSymbol(FieldNameSymbol); } var annotations = GetTypeAnnotations(); privateWriter.SetTypeAnnotations(annotations); // privateWriter.SetTypeAnnotation(GetTypeAnnotations()); WriteBodyTo(privateWriter); }
/// <inheritdoc/> public override void Serialize(IIonWriter writer, object item) { this.options.TypeAnnotator.Apply(this.options, writer, this.targetType); writer.StepIn(IonType.Struct); var serializedIonFields = new HashSet <string>(); // Serialize the values returned from IonPropertyGetter annotated getter methods. foreach (var(method, ionPropertyName) in this.GetGetters()) { var getValue = method.Invoke(item, Array.Empty <object>()); writer.SetFieldName(ionPropertyName); this.ionSerializer.Serialize(writer, getValue); serializedIonFields.Add(ionPropertyName); } // Serialize any properties that satisfy the options/attributes. foreach (var property in this.GetValidProperties(true)) { var ionPropertyName = this.IonFieldNameFromProperty(property); if (serializedIonFields.Contains(ionPropertyName)) { // This Ion property name was already serialized. continue; } if (this.options.IgnoreReadOnlyProperties && IsReadOnlyProperty(property)) { continue; } var propertyValue = property.GetValue(item); if (this.options.IgnoreNulls && propertyValue == null) { continue; } if (this.options.IgnoreDefaults && propertyValue == default) { continue; } writer.SetFieldName(ionPropertyName); var ionAnnotateType = (IonAnnotateTypeAttribute)Attribute.GetCustomAttribute(property, typeof(IonAnnotateTypeAttribute), false); if (ionAnnotateType != null) { if (this.ionSerializer.TryAnnotatedIonSerializer(writer, propertyValue, ionAnnotateType)) { continue; } // Use the actual type of property at runtime to handle dynamic type var propertyType = propertyValue != null?propertyValue.GetType() : property.PropertyType; writer.AddTypeAnnotation(this.options.AnnotationConvention.Apply(this.options, ionAnnotateType, propertyType)); } this.ionSerializer.Serialize(writer, propertyValue); serializedIonFields.Add(ionPropertyName); } // Serialize any fields that satisfy the options/attributes. foreach (var field in this.Fields()) { var ionFieldName = GetFieldName(field); if (serializedIonFields.Contains(ionFieldName)) { // This Ion field name was already serialized. continue; } if (this.options.IgnoreReadOnlyFields && field.IsInitOnly) { continue; } var fieldValue = field.GetValue(item); if (this.options.IgnoreNulls && fieldValue == null) { continue; } if (this.options.IgnoreDefaults && fieldValue == default) { continue; } writer.SetFieldName(ionFieldName); var ionAnnotateType = (IonAnnotateTypeAttribute)Attribute.GetCustomAttribute(field, typeof(IonAnnotateTypeAttribute), false); if (ionAnnotateType != null && this.ionSerializer.TryAnnotatedIonSerializer(writer, fieldValue, ionAnnotateType)) { continue; } this.ionSerializer.Serialize(writer, fieldValue); } writer.StepOut(); }
/// <summary> /// Serialize boolean value. /// </summary> /// /// <param name="writer">The Ion writer to be used for serialization.</param> /// <param name="item">The boolean value to serialize.</param> public override void Serialize(IIonWriter writer, bool item) { writer.WriteBool(item); }
public void WriteTo(IIonWriter writer) { throw new NotImplementedException(); }
/// <summary> /// Serialize date time value. /// </summary> /// /// <param name="writer">The Ion writer to be used for serialization.</param> /// <param name="item">The date time value to serialize.</param> public override void Serialize(IIonWriter writer, DateTime item) { writer.WriteTimestamp(new Timestamp(item)); }
private static bool TryWriteScalar(IIonWriter writer, object obj, Type type, IScalarWriter scalarWriter) { if (type.IsEnum) { var propValue = Enum.GetName(type, obj); writer.WriteSymbol(propValue); return(true); } if (type == typeof(string)) { var propValue = (string)obj; writer.WriteString(propValue); return(true); } if (type == typeof(int)) { var propValue = (int)obj; writer.WriteInt(propValue); return(true); } if (type == typeof(long)) { var propValue = (long)obj; writer.WriteInt(propValue); return(true); } if (type == typeof(bool)) { var propValue = (bool)obj; writer.WriteBool(propValue); return(true); } if (type == typeof(float)) { var propValue = (float)obj; writer.WriteFloat(propValue); return(true); } if (type == typeof(double)) { var propValue = (double)obj; writer.WriteFloat(propValue); return(true); } if (type == typeof(DateTime)) { var propValue = (DateTime)obj; writer.WriteTimestamp(new Timestamp(propValue)); return(true); } if (type == typeof(DateTimeOffset)) { var propValue = (DateTimeOffset)obj; writer.WriteTimestamp(new Timestamp(propValue)); return(true); } if (type == typeof(decimal)) { var propValue = (decimal)obj; writer.WriteDecimal(propValue); return(true); } //try to see if we can write use the scalar writer if (scalarWriter != null) { var method = scalarWriter.GetType().GetMethod(nameof(IScalarWriter.TryWriteValue)); var genericMethod = method.MakeGenericMethod(type); return((bool)genericMethod.Invoke(scalarWriter, new[] { writer, obj })); } return(false); }
/// <summary> /// Serialize null value. /// </summary> /// /// <param name="writer">The Ion writer to be used for serialization.</param> /// <param name="item">The null object to serialize.</param> public override void Serialize(IIonWriter writer, object item) { writer.WriteNull(); }
/// <summary> /// Write object knowing the (intended) type /// </summary> private static void WriteObject(IIonWriter writer, object obj, Type type, IScalarWriter scalarWriter) { Debug.Assert(obj == null || obj.GetType() == type, $"objType: {obj?.GetType()}, type:{type}"); if (TryWriteScalar(writer, obj, type, scalarWriter)) { return; } if (typeof(IEnumerable).IsAssignableFrom(type)) { //special case of byte[] if (TryWriteByteArray(writer, obj, type)) { return; } //is this a null.list? if (obj == null) { writer.WriteNull(IonType.List); return; } //Write everything to list now var enumerable = (IEnumerable)obj; writer.StepIn(IonType.List); foreach (var item in enumerable) { WriteObject(writer, item, scalarWriter); } writer.StepOut(); return; } //not scalar, not list, must be a struct if (obj == null) { writer.WriteNull(); return; } writer.StepIn(IonType.Struct); var properties = GetPublicProperties(type); foreach (var propertyInfo in properties) { if (!propertyInfo.CanRead) { continue; } //with property, we have to be careful because they have type declaration which might carry intention //for writer.SetFieldName(propertyInfo.Name); WriteObject(writer, propertyInfo.GetValue(obj), propertyInfo.PropertyType, scalarWriter); } writer.StepOut(); }
protected override void WriteBodyTo(IIonWriter writer, ISymbolTableProvider symbolTableProvider) { throw new System.NotImplementedException(); }