using System;
namespace Unity.Collections.LowLevel.Unsafe.NotBurstCompatible
{
    /// 
    /// Provides some extension methods for various collections.
    /// 
    public static class Extensions
    {
        /// 
        /// Returns a new managed array with all the elements copied from a set.
        /// 
        /// The type of elements.
        /// The set whose elements are copied to the array.
        /// A new managed array with all the elements copied from a set.
        public static T[] ToArray(this UnsafeParallelHashSet set)
            where T : unmanaged, IEquatable
        {
            var array = set.ToNativeArray(Allocator.TempJob);
            var managed = array.ToArray();
            array.Dispose();
            return managed;
        }
        /// 
        /// Adds the content of a string to this append buffer.
        /// 
        /// The length of the string is written as an int to the buffer before the characters are written.
        /// The buffer to which to add the string.
        /// The string to copy.
        [ExcludeFromBurstCompatTesting("Takes managed string")]
        public static unsafe void AddNBC(ref this UnsafeAppendBuffer buffer, string value)
        {
            if (value != null)
            {
                buffer.Add(value.Length);
                fixed (char* ptr = value)
                {
                    buffer.Add(ptr, sizeof(char) * value.Length);
                }
            }
            else
            {
                buffer.Add(-1);
            }
        }
        /// 
        /// Returns an unmanaged byte array with a copy of this buffer's contents.
        /// 
        /// This buffer.
        /// An unmanaged byte array with a copy of this buffer's contents.
        [ExcludeFromBurstCompatTesting("Returns managed array")]
        public static unsafe byte[] ToBytesNBC(ref this UnsafeAppendBuffer buffer)
        {
            var dst = new byte[buffer.Length];
            fixed (byte* dstPtr = dst)
            {
                UnsafeUtility.MemCpy(dstPtr, buffer.Ptr, buffer.Length);
            }
            return dst;
        }
        /// 
        /// Reads a string from this buffer reader.
        /// 
        /// Outputs the string.
        /// This reader.
        [ExcludeFromBurstCompatTesting("Managed string out argument")]
        public static unsafe void ReadNextNBC(ref this UnsafeAppendBuffer.Reader reader, out string value)
        {
            int length;
            reader.ReadNext(out length);
            if (length != -1)
            {
                value = new string('0', length);
                fixed (char* buf = value)
                {
                    int bufLen = length * sizeof(char);
                    UnsafeUtility.MemCpy(buf, reader.ReadNext(bufLen), bufLen);
                }
            }
            else
            {
                value = null;
            }
        }
    }
}