Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added ability to de/serialize from/to avro container. #119

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
146 changes: 146 additions & 0 deletions src/AvroConvert/AvroConvert.DeserializeContainer.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
#region license
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The default AvroConvert.Deserialize() method handles objects serialized in this way correctly. Could you please revert the changes done in the deserialization part?

/**Copyright (c) 2021 Adrian Strugala
*
* Licensed under the CC BY-NC-SA 3.0 License(the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://creativecommons.org/licenses/by-nc-sa/3.0/
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* You are free to use or modify the code for personal usage.
* For commercial usage purchase the product at
*
* https://xabe.net/product/avroconvert/
*/
#endregion

using System;
using System.Collections;
using System.IO;
using SolTechnology.Avro.AvroObjectServices.BuildSchema;
using SolTechnology.Avro.Features.Deserialize;
using SolTechnology.Avro.Infrastructure.Exceptions;
using SolTechnology.Avro.Infrastructure.Extensions;

namespace SolTechnology.Avro
{
public static partial class AvroConvert
{
/// <summary>
/// Deserializes Avro data from a byte array into a specified .NET type.
/// </summary>
/// <typeparam name="T">The type of object to deserialize into.</typeparam>
/// <param name="avroBytes">The byte array containing the Avro data to be deserialized.</param>
/// <returns>The deserialized object of the specified type.</returns>
/// <remarks>
/// This method takes a byte array containing Avro data and deserializes it into an object of the specified type (generic parameter T).
/// </remarks>
public static T DeserializeContainer<T>(byte[] avroBytes)
where T: IEnumerable
{
var type = GetEnumerableType<T>();

using (var stream = new MemoryStream(avroBytes))
{
var decoder = new Decoder();
var deserialized = decoder.Decode<T>(
stream,
Schema.Create(type)
);
return deserialized;
}
}

/// <summary>
/// Deserializes Avro data from a byte array into a specified .NET type using the provided Avro conversion options.
/// </summary>
/// <typeparam name="T">The type of object to deserialize into.</typeparam>
/// <param name="avroBytes">The byte array containing the Avro data to be deserialized.</param>
/// <param name="options">The Avro conversion options that control the deserialization process.</param>
/// <returns>The deserialized object of the specified type.</returns>
/// <remarks>
/// This method takes a byte array containing Avro data and deserializes it into an object of the specified type (generic parameter T).
/// The deserialization process is controlled by the provided Avro conversion options.
/// </remarks>
public static T DeserializeContainer<T>(byte[] avroBytes, AvroConvertOptions options)
where T: IEnumerable
{
var type = GetEnumerableType<T>();

using (var stream = new MemoryStream(avroBytes))
{
var decoder = new Decoder(options);
var deserialized = decoder.Decode<T>(
stream,
Schema.Create(type)
);
return deserialized;
}
}

/// <summary>
/// Deserializes Avro data from a byte array into an object of the specified target type using reflection.
/// </summary>
/// <param name="avroBytes">The byte array containing the Avro data to be deserialized.</param>
/// <param name="targetType">The target type into which the Avro data should be deserialized.</param>
/// <returns>The deserialized object of the specified target type.</returns>
/// <remarks>
/// This method uses reflection to dynamically invoke the generic <see cref="DeserializeContainer{T}(byte[])"/> method
/// to deserialize Avro data from a byte array into an object of the specified target type.
/// </remarks>
public static dynamic DeserializeContainer(byte[] avroBytes, Type targetType)
{
object result = typeof(AvroConvert)
.GetMethod(nameof(DeserializeContainer), new[] { typeof(byte[]) })
?.MakeGenericMethod(targetType)
.Invoke(null, new object[] { avroBytes });

return result;
}


/// <summary>
/// Deserializes Avro data from a <see cref="ReadOnlySpan{T}"/> of bytes into an object of the specified type.
/// </summary>
/// <typeparam name="T">The type of object to deserialize into.</typeparam>
/// <param name="avroBytes">The <see cref="ReadOnlySpan{T}"/> of bytes containing the Avro data to be deserialized.</param>
/// <returns>The deserialized object of the specified type.</returns>
/// <remarks>
/// This method performs Avro data deserialization from a <see cref="ReadOnlySpan{T}"/> of bytes into an object of the specified type.
/// It is suitable for scenarios where minimizing memory allocation is crucial.
/// </remarks>
public static unsafe T DeserializeContainer<T>(ReadOnlySpan<byte> avroBytes)
where T: IEnumerable
{
var type = GetEnumerableType<T>();

fixed (byte* ptr = avroBytes)
{
using UnmanagedMemoryStream stream = new(ptr, avroBytes.Length);
var decoder = new Decoder();
var obj = decoder.Decode<T>(
stream,
Schema.Create(type)
);

return obj;
}
}

private static Type GetEnumerableType<T>()
{
var type = typeof(T);

if (!type.IsEnumerable())
throw new AvroException("[IEnumerable] required to deserialize container but found " + type);

return type.GetEnumeratedType();
}
}
}
87 changes: 87 additions & 0 deletions src/AvroConvert/AvroConvert.SerializeContainer.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
#region license
/**Copyright (c) 2020 Adrian Strugała
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#endregion

using System.Collections.Generic;
using System.IO;
using SolTechnology.Avro.AvroObjectServices.BuildSchema;
using SolTechnology.Avro.Features.Serialize;

namespace SolTechnology.Avro
{
public static partial class AvroConvert
{
/// <summary>
/// Serializes the given <see cref="IEnumerable{T}"/> into Avro container format (including header with metadata)
/// </summary>
public static byte[] SerializeContainer<T>(IEnumerable<T> items)
{
return SerializeContainer(items, CodecType.Null);
}

/// <summary>
/// Serializes the given <see cref="IEnumerable{T}"/> into Avro container format (including header with metadata)
/// Choosing <paramref name="codecType"/> reduces output object size
/// </summary>
public static byte[] SerializeContainer<T>(IEnumerable<T> items, CodecType codecType)
where T : notnull
{
using (MemoryStream resultStream = new MemoryStream())
{
var schema = Schema.Create(typeof(T));

using (var writer = new Encoder(schema, resultStream, codecType))
{
foreach (var item in items)
{
writer.Append(item);
}
}

byte[] result = resultStream.ToArray();
return result;
}
}

/// <summary>
/// Serializes the given <see cref="IEnumerable{T}"/> into Avro container format (including header with metadata) and returns the serialized data as a byte array.
/// </summary>
/// <param name="items">The items to be serialized into Avro container format.</param>
/// <param name="options">The Avro conversion options that control the serialization process.</param>
/// <returns>A byte array containing the serialized Avro data.</returns>
/// <remarks>
/// This method takes an <see cref="IEnumerable{T}"/> and serializes it into Avro container format based on the provided Avro conversion options.
/// The resulting serialized data is returned as a byte array.
/// </remarks>
public static byte[] SerializeContainer<T>(IEnumerable<T> items, AvroConvertOptions options)
where T : notnull
{
using (MemoryStream resultStream = new MemoryStream())
{
var schema = Schema.Create(typeof(T), options);
using (var writer = new Encoder(schema, resultStream, options.Codec, options))
{
foreach (var item in items)
{
writer.Append(item);
}
}
byte[] result = resultStream.ToArray();
return result;
}
}
}
}
6 changes: 5 additions & 1 deletion src/AvroConvert/AvroObjectServices/Read/Resolvers/Array.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,11 @@ internal object ResolveArray(TypeSchema writerSchema, TypeSchema readerSchema, I
{
writerSchema = ((ArraySchema)writerSchema).ItemSchema;
}
readerSchema = ((ArraySchema)readerSchema).ItemSchema;

if (readerSchema is ArraySchema arraySchema)
{
readerSchema = arraySchema.ItemSchema;
}

if (type.IsDictionary())
{
Expand Down
5 changes: 5 additions & 0 deletions src/AvroConvert/Infrastructure/Extensions/TypeExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -417,6 +417,11 @@ internal static bool IsList(this Type type)
return typeof(IList).IsAssignableFrom(type);
}

internal static bool IsEnumerable(this Type type)
{
return typeof(IEnumerable).IsAssignableFrom(type);
}

internal static bool IsGuid(this Type type)
{
return type == typeof(Guid);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
using System;
using System.Collections.Generic;
using System.Linq;
using AutoFixture;
using Xunit;

namespace AvroConvertComponentTests.FullSerializationAndDeserialization
{
public class ContainerTests
{
private readonly Fixture _fixture = new();

[Theory]
[MemberData(nameof(TestEngine.ContainerOnly), MemberType = typeof(TestEngine))]
public void AvroMap(Func<object, Type, dynamic> engine)
{
//Arrange
List<int> expected = new List<int>() { 1, 2, 3, 5, 8, 13 };


//Act
var actual = engine.Invoke(expected, typeof(List<int>));


//Assert
Assert.NotNull(actual);
Assert.Equal(expected, actual);
}

[Theory]
[MemberData(nameof(TestEngine.ContainerOnly), MemberType = typeof(TestEngine))]
public void List_of_class_map(Func<object, Type, dynamic> engine)
{
//Arrange
List<ExtendedBaseTestClass> expected = _fixture.CreateMany<ExtendedBaseTestClass>(5).ToList();


//Act
var actual = engine.Invoke(expected, typeof(List<ExtendedBaseTestClass>));


//Assert
Assert.NotNull(actual);
Assert.Equal(expected, actual);
}

[Theory]
[MemberData(nameof(TestEngine.ContainerOnly), MemberType = typeof(TestEngine))]
public void Array_of_class_map(Func<object, Type, dynamic> engine)
{
//Arrange
ExtendedBaseTestClass[] expected = _fixture.CreateMany<ExtendedBaseTestClass>(5).ToArray();


//Act
var actual = engine.Invoke(expected, typeof(ExtendedBaseTestClass[]));


//Assert
Assert.NotNull(actual);
Assert.Equal(expected, actual);
}

[Theory]
[MemberData(nameof(TestEngine.ContainerOnly), MemberType = typeof(TestEngine))]
public void Enumerable_of_class_map_to_list(Func<object, Type, dynamic> engine)
{
//Arrange
IEnumerable<ExtendedBaseTestClass> expected = _fixture.CreateMany<ExtendedBaseTestClass>(5);


//Act
var actual = engine.Invoke(expected, typeof(List<ExtendedBaseTestClass>));


//Assert
Assert.NotNull(actual);
Assert.Equal(expected, actual);
}

[Theory]
[MemberData(nameof(TestEngine.ContainerOnly), MemberType = typeof(TestEngine))]
public void Enumerable_of_class_map_to_array(Func<object, Type, dynamic> engine)
{
//Arrange
IEnumerable<ExtendedBaseTestClass> expected = _fixture.CreateMany<ExtendedBaseTestClass>(5);


//Act
var actual = engine.Invoke(expected, typeof(ExtendedBaseTestClass[]));


//Assert
Assert.NotNull(actual);
Assert.Equal(expected, actual);
}
}
}
Loading