Exemple #1
0
        public unsafe void WriteArray <T>(ReadOnlySpan <T> data) where T : unmanaged
        {
            if (data.Length == 0)
            {
                return;
            }

            FlushBits();

            var elementSize = Unsafe.SizeOf <T>();
            var size        = elementSize * data.Length;

            if (size == 1 || !IsSwappingNeeded())
            {
                // Write bytes directly
                WriteBytesCore(MemoryMarshal.Cast <T, byte>(data));
            }
            else
            {
                // Swap each element then write
                for (int i = 0; i < data.Length; i++)
                {
                    // Make sure to make a copy here
                    // Don't want to overwrite
                    var element = data[i];
                    BinaryOperations <T> .Reverse(ref element);

#if NETSTANDARD2_1
                    WriteBytesCore(MemoryMarshal.Cast <T, byte>(MemoryMarshal.CreateReadOnlySpan(ref element, 1)));
#else
                    WriteBytesCore(MemoryMarshal.Cast <T, byte>(new ReadOnlySpan <T>(Unsafe.AsPointer(ref element), 1)));
#endif
                }
            }
        }
Exemple #2
0
        /// <summary>
        /// Writes a value in big endian format regardless of specified or native endianness.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value"></param>
        public unsafe void WriteBig <T>(T value) where T : unmanaged
        {
            FlushBits();

            if (typeof(T) == typeof(byte) || typeof(T) == typeof(sbyte))
            {
                // Optimise for byte/sbyte
                WriteByteCore(Unsafe.As <T, byte>(ref value));
                return;
            }

            if (Unsafe.SizeOf <T>() != 1 && BitConverter.IsLittleEndian)
            {
                BinaryOperations <T> .Reverse(ref value);
            }

#if NETSTANDARD2_1
            WriteBytesCore(MemoryMarshal.Cast <T, byte>(MemoryMarshal.CreateReadOnlySpan(ref value, 1)));
#else
            WriteBytesCore(MemoryMarshal.Cast <T, byte>(new ReadOnlySpan <T>(Unsafe.AsPointer(ref value), 1)));
#endif
        }