using System;
using System.Buffers;

namespace AyCode.Core.Serializers.Binaries;

public static partial class AcBinarySerializer
{
    public sealed class BinarySerializationResult : IDisposable
    {
        private readonly bool _pooled;
        private bool _disposed;

        internal BinarySerializationResult(byte[] buffer, int length, bool pooled)
        {
            Buffer = buffer;
            Length = length;
            _pooled = pooled;
        }

        public byte[] Buffer { get; }
        public int Length { get; }
        public ReadOnlySpan<byte> Span => Buffer.AsSpan(0, Length);
        public ReadOnlyMemory<byte> Memory => new(Buffer, 0, Length);

        public byte[] ToArray()
        {
            var result = GC.AllocateUninitializedArray<byte>(Length);
            Buffer.AsSpan(0, Length).CopyTo(result);
            return result;
        }

        public void Dispose()
        {
            if (_disposed)
            {
                return;
            }

            _disposed = true;

            if (_pooled)
            {
                ArrayPool<byte>.Shared.Return(Buffer);
            }
        }

        internal static BinarySerializationResult FromImmutable(byte[] buffer)
            => new(buffer, buffer.Length, pooled: false);
    }
}
