AdrianStrugala / AvroConvert

Rapid Avro serializer for C# .NET
Other
97 stars 27 forks source link

Allow Decoder and Schema to be public #116

Closed shargon closed 10 months ago

shargon commented 11 months ago

Describe the solution you'd like I tried to use ReadOnlySpan<byte> for Decode, but the only way is using .ToArray(), because some classes are not public

Describe implementation idea

        /// <summary>
        /// Object from Avro 
        /// </summary>
        /// <typeparam name="T">Type</typeparam>
        /// <param name="data">Data</param>
        /// <returns>Type</returns>
        public unsafe static T? ObjectFromAvro<T>(this ReadOnlySpan<byte> data)
        {
            fixed (byte* ptr = data)
            {
                using UnmanagedMemoryStream stream = new(ptr, data.Length);
                var decoder = new Decoder();
                var obj = decoder.Decode<T>(
                    stream,
                    Schema.Create(typeof(T))
                );

                return obj;
            }
        }

Additional context Is not possible because Decoder is not public, also I would like to Cache the Schema in order to improve the code, so Schema should be nice to be public to

AdrianStrugala commented 11 months ago

Hi,

Sure this can be done. But first, I would like to understand your use case. Maybe it is something, that we can include in the library itself. So, you lack an overload for Decode method that takes ReadOnlySpan as an argument?

Regards, Adrian

AdrianStrugala commented 11 months ago

Hello @shargon I've decided to create an overload for AvroConvert.Deserialize taking your use case into consideration:

        /// Deserializes Avro object to .NET type
        /// </summary>
        public static unsafe T Deserialize<T>(ReadOnlySpan<byte> avroBytes)
        {
            fixed (byte* ptr = avroBytes)
            {
                using UnmanagedMemoryStream stream = new(ptr, avroBytes.Length);
                var decoder = new Decoder();
                var obj = decoder.Decode<T>(
                    stream,
                    Schema.Create(typeof(T))
                );

                return obj;
            }
        }

Please let me know if it solves your problem. I would like to learn more about your ideas.

Regards, Adrian