Ejemplo n.º 1
0
 public static bool TryWriteUInt16LittleEndian(Span <byte> destination, ushort value)
 {
     if (!BitConverter.IsLittleEndian)
     {
         value = ReverseEndianness(value);
     }
     return(MemoryMarshal.TryWrite(destination, ref value));
 }
 public void MemoryMarshalTryWrite()
 {
     for (int i = 0; i < Ops; i++)
     {
         var netInt = IPAddress.HostToNetworkOrder(i);
         MemoryMarshal.TryWrite(forMemoryBuffer, ref netInt);
     }
 }
Ejemplo n.º 3
0
        public static bool TryWriteSingleBigEndian(Span <byte> destination, float value)
        {
            if (BitConverter.IsLittleEndian)
            {
                int tmp = ReverseEndianness(BitConverter.SingleToInt32Bits(value));
                return(MemoryMarshal.TryWrite(destination, ref tmp));
            }

            return(MemoryMarshal.TryWrite(destination, ref value));
        }
Ejemplo n.º 4
0
        public static bool TryWriteDoubleBigEndian(Span <byte> destination, double value)
        {
            if (BitConverter.IsLittleEndian)
            {
                long tmp = ReverseEndianness(BitConverter.DoubleToInt64Bits(value));
                return(MemoryMarshal.TryWrite(destination, ref tmp));
            }

            return(MemoryMarshal.TryWrite(destination, ref value));
        }
Ejemplo n.º 5
0
        public static bool TryWriteHalfBigEndian(Span <byte> destination, Half value)
        {
            if (BitConverter.IsLittleEndian)
            {
                short tmp = ReverseEndianness(BitConverter.HalfToInt16Bits(value));
                return(MemoryMarshal.TryWrite(destination, ref tmp));
            }

            return(MemoryMarshal.TryWrite(destination, ref value));
        }
Ejemplo n.º 6
0
        public static bool TryWriteUInt64LittleEndian(Span <byte> destination, ulong value)
        {
            if (!BitConverter.IsLittleEndian)
            {
                ulong tmp = ReverseEndianness(value);
                return(MemoryMarshal.TryWrite(destination, ref tmp));
            }

            return(MemoryMarshal.TryWrite(destination, ref value));
        }
Ejemplo n.º 7
0
        public void SpanWriteFail()
        {
            byte   byteValue   = 1;
            sbyte  sbyteValue  = 1;
            short  shortValue  = 1;
            ushort ushortValue = 1;
            int    intValue    = 1;
            uint   uintValue   = 1;
            long   longValue   = 1;
            ulong  ulongValue  = 1;

            Span <byte> span = new byte[1];

            MemoryMarshal.Write <byte>(span, ref byteValue);
            byte read = MemoryMarshal.Read <byte>(span);

            Assert.Equal <byte>(byteValue, read);

            span.Clear();
            Assert.True(MemoryMarshal.TryWrite <byte>(span, ref byteValue));
            read = MemoryMarshal.Read <byte>(span);
            Assert.Equal <byte>(byteValue, read);

            MemoryMarshal.Write <sbyte>(span, ref sbyteValue);
            sbyte readSbyte = MemoryMarshal.Read <sbyte>(span);

            Assert.Equal <sbyte>(sbyteValue, readSbyte);

            span.Clear();
            Assert.True(MemoryMarshal.TryWrite <sbyte>(span, ref sbyteValue));
            readSbyte = MemoryMarshal.Read <sbyte>(span);
            Assert.Equal <sbyte>(sbyteValue, readSbyte);

            MemoryTestHelpers.AssertThrows <ArgumentOutOfRangeException, byte>(span, (_span) => MemoryMarshal.Write <short>(_span, ref shortValue));
            Assert.False(MemoryMarshal.TryWrite <short>(span, ref shortValue));
            MemoryTestHelpers.AssertThrows <ArgumentOutOfRangeException, byte>(span, (_span) => MemoryMarshal.Write <int>(_span, ref intValue));
            Assert.False(MemoryMarshal.TryWrite <int>(span, ref intValue));
            MemoryTestHelpers.AssertThrows <ArgumentOutOfRangeException, byte>(span, (_span) => MemoryMarshal.Write <long>(_span, ref longValue));
            Assert.False(MemoryMarshal.TryWrite <long>(span, ref longValue));

            MemoryTestHelpers.AssertThrows <ArgumentOutOfRangeException, byte>(span, (_span) => MemoryMarshal.Write <ushort>(_span, ref ushortValue));
            Assert.False(MemoryMarshal.TryWrite <ushort>(span, ref ushortValue));
            MemoryTestHelpers.AssertThrows <ArgumentOutOfRangeException, byte>(span, (_span) => MemoryMarshal.Write <uint>(_span, ref uintValue));
            Assert.False(MemoryMarshal.TryWrite <uint>(span, ref uintValue));
            MemoryTestHelpers.AssertThrows <ArgumentOutOfRangeException, byte>(span, (_span) => MemoryMarshal.Write <ulong>(_span, ref ulongValue));
            Assert.False(MemoryMarshal.TryWrite <ulong>(span, ref ulongValue));

            var structValue = new MemoryTestHelpers.TestValueTypeWithReference {
                I = 1, S = "1"
            };

            MemoryTestHelpers.AssertThrows <ArgumentException, byte>(span, (_span) => MemoryMarshal.Write <MemoryTestHelpers.TestValueTypeWithReference>(_span, ref structValue));
            MemoryTestHelpers.AssertThrows <ArgumentException, byte>(span, (_span) => MemoryMarshal.TryWrite <MemoryTestHelpers.TestValueTypeWithReference>(_span, ref structValue));
        }
Ejemplo n.º 8
0
        public void TryWrite()
        {
            Span <byte> buffer = new byte[4];
            uint        value  = uint.MaxValue;

            Assert.True(MemoryMarshal.TryWrite(buffer, ref value));
            for (var i = 0; i < buffer.Length; i++)
            {
                Assert.Equal(255, buffer[i]);
            }

            buffer = buffer.Slice(1);
            Assert.False(MemoryMarshal.TryWrite(buffer, ref value));
        }
Ejemplo n.º 9
0
        public bool TryPush <T>(ref T data) where T : struct
        {
            if (!(data is Message))
            {
                throw new ArgumentException();
            }

            var writeSpan = GetWriteSpan();

            if (MemoryMarshal.TryWrite(writeSpan, ref data))
            {
                Commit(Marshal.SizeOf(data));
                return(true);
            }

            return(false);
        }
Ejemplo n.º 10
0
        private static void WriteBase64GuidUnrolled(Span <char> chars, Guid toWrite)
        {
            // custom Url safe Base64 format, last two chars changed
            const string Base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-";

            Span <byte> guidBytes = stackalloc byte[16];

            // write bytes from the Guid
            MemoryMarshal.TryWrite(guidBytes, ref toWrite);

            /*
             * Base64 encoding algorithm, it turns 3 bytes into 4 chars.
             * This goes from last to first, so the compiler can remove bounds checking from the Span's
             * This is could be done in a loop, but it is Unrolled for performance
             */

            // last two bytes to encode. Add no Base64 padding "=="
            chars[21] = Base64Chars[(guidBytes[15] & 0x03) << 4];
            chars[20] = Base64Chars[guidBytes[15] >> 2];

            chars[19] = Base64Chars[guidBytes[14] & 0x3f];
            chars[18] = Base64Chars[((guidBytes[13] & 0x0f) << 2) | (guidBytes[14] >> 6)];
            chars[17] = Base64Chars[((guidBytes[12] & 0x03) << 4) | (guidBytes[13] >> 4)];
            chars[16] = Base64Chars[guidBytes[12] >> 2];

            chars[15] = Base64Chars[guidBytes[11] & 0x3f];
            chars[14] = Base64Chars[((guidBytes[10] & 0x0f) << 2) | (guidBytes[11] >> 6)];
            chars[13] = Base64Chars[((guidBytes[9] & 0x03) << 4) | (guidBytes[10] >> 4)];
            chars[12] = Base64Chars[guidBytes[9] >> 2];

            chars[11] = Base64Chars[guidBytes[8] & 0x3f];
            chars[10] = Base64Chars[((guidBytes[7] & 0x0f) << 2) | (guidBytes[8] >> 6)];
            chars[09] = Base64Chars[((guidBytes[6] & 0x03) << 4) | (guidBytes[7] >> 4)];
            chars[08] = Base64Chars[guidBytes[6] >> 2];

            chars[07] = Base64Chars[guidBytes[5] & 0x3f];
            chars[06] = Base64Chars[((guidBytes[4] & 0x0f) << 2) | (guidBytes[5] >> 6)];
            chars[05] = Base64Chars[((guidBytes[3] & 0x03) << 4) | (guidBytes[4] >> 4)];
            chars[04] = Base64Chars[guidBytes[3] >> 2];

            chars[03] = Base64Chars[guidBytes[2] & 0x3f];
            chars[02] = Base64Chars[((guidBytes[1] & 0x0f) << 2) | (guidBytes[2] >> 6)];
            chars[01] = Base64Chars[((guidBytes[0] & 0x03) << 4) | (guidBytes[1] >> 4)];
            chars[00] = Base64Chars[guidBytes[0] >> 2];
        }
Ejemplo n.º 11
0
        public static string ToBase64(this Guid guid)
        {
            Span <byte> raw  = stackalloc byte[16];
            Span <byte> utf8 = stackalloc byte[24];

            MemoryMarshal.TryWrite(raw, ref guid);
            Base64.EncodeToUtf8(raw, utf8, out _, out _);
            Span <char> b64 = stackalloc char[22];

            for (var i = 0; i < 22; i++)
            {
                b64[i] = utf8[i] switch
                {
                    ForwardSlashByte => Underscore,
                    PlusByte => Dash,
                    _ => (char)utf8[i]
                };
            }
            return(new string(b64));
        }
        public void RentWholeArray()
        {
            var bufferForGuid = ArrayPool <byte> .Shared.Rent(16 *Elements);

            try
            {
                for (var i = 0; i < Elements; i++)
                {
                    var guid = Guid.NewGuid();
                    if (!MemoryMarshal.TryWrite(bufferForGuid.AsSpan(i * 16, 16), ref guid))
                    {
                        guid.ToByteArray().AsSpan().CopyTo(bufferForGuid);
                    }
                    consumer.Consume(new ArraySegment <byte>(bufferForGuid, i * 16, 16));
                }
            }
            finally
            {
                ArrayPool <byte> .Shared.Return(bufferForGuid);
            }
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Encodes GUID to Base64 string.
        /// <note>
        /// Inspired by https://www.stevejgordon.co.uk/using-high-performance-dotnetcore-csharp-techniques-to-base64-encode-a-guid
        /// </note>
        /// </summary>
        /// <param name="guid">The <see cref="T:System.Guid">Guid</see> to encode.</param>
        /// <param name="replaceForwardSlashWith">Character that will replace forward slash '/'.</param>
        /// <param name="replacePlusWith">Character that will replace plus '+'.</param>
        /// <returns>Base64 version of <see cref="T:System.Guid"></see>.</returns>
        public static string EncodeBase64String(this Guid guid, char replaceForwardSlashWith = '_',
                                                char replacePlusWith = '-')
        {
            Span <byte> guidBytes = stackalloc byte[16];

            MemoryMarshal.TryWrite(guidBytes, ref guid);

            Span <byte> encodedBytes = stackalloc byte[24];

            Base64.EncodeToUtf8(guidBytes, encodedBytes, out _, out _);

            Span <char> chars = stackalloc char[22];

            const byte forwardSlashByte = (byte)'/';
            const byte plusByte         = (byte)'+';

            // Replace any characters which are not URL safe.
            // Skip the final two bytes as these will be '==' padding we don't need.
            for (var i = 0; i < 22; i++)
            {
                chars[i] = encodedBytes[i] switch
                {
                    forwardSlashByte => replaceForwardSlashWith,
                    plusByte => replacePlusWith,
                    _ => (char)encodedBytes[i]
                };
            }

#if NETSTANDARD2_0 // TODO: Delete when Unity will support at least .net standard 2.1
            var final = new string(chars.ToArray());
#else
            var final = new string(chars);
#endif
            return(final);
        }
    }
        public static string EncodeBase64String(this Guid guid)
        {
            Span <byte> guidBytes    = stackalloc byte[16];
            Span <byte> encodedBytes = stackalloc byte[24];

            MemoryMarshal.TryWrite(guidBytes, ref guid);
            Base64.EncodeToUtf8(guidBytes, encodedBytes, out _, out _);

            Span <char> chars = stackalloc char[22];

            for (var i = 0; i < 22; i++)
            {
                chars[i] = (encodedBytes[i]) switch
                {
                    ForwardSlashByte => Dash,
                    PlusByte => Underscore,
                    _ => (char)encodedBytes[i],
                };
            }

            var final = new string(chars);

            return(final);
        }
Ejemplo n.º 15
0
        public static bool TryGetBytes(char typecode, object obj, Span <byte> dest)
        {
            switch (typecode)
            {
            case 'c':
                var bytecharVal = (byte)((Bytes)obj)[0];
                return(MemoryMarshal.TryWrite(dest, ref bytecharVal));

            case 'b':
                var sbyteVal = (byte)Convert.ToSByte(obj);
                return(MemoryMarshal.TryWrite(dest, ref sbyteVal));

            case 'B':
                var byteVal = Convert.ToByte(obj);
                return(MemoryMarshal.TryWrite(dest, ref byteVal));

            case '?':
                var boolVal = PythonOps.IsTrue(obj);
                return(MemoryMarshal.TryWrite(dest, ref boolVal));

            case 'h':
                var shortVal = Convert.ToInt16(obj);
                return(MemoryMarshal.TryWrite(dest, ref shortVal));

            case 'H':
                var ushortVal = Convert.ToUInt16(obj);
                return(MemoryMarshal.TryWrite(dest, ref ushortVal));

            case 'l':
            case 'i':
            case 'n':
                var intVal = Convert.ToInt32(obj);
                return(MemoryMarshal.TryWrite(dest, ref intVal));

            case 'L':
            case 'I':
            case 'N':
                var uintVal = Convert.ToUInt32(obj);
                return(MemoryMarshal.TryWrite(dest, ref uintVal));

            case 'f':
                var singleVal = Convert.ToSingle(obj);
                return(MemoryMarshal.TryWrite(dest, ref singleVal));

            case 'd':
                var doubleVal = Convert.ToDouble(obj);
                return(MemoryMarshal.TryWrite(dest, ref doubleVal));

            case 'q':
                var longVal = Convert.ToInt64(obj);
                return(MemoryMarshal.TryWrite(dest, ref longVal));

            case 'Q':
                var ulongVal = Convert.ToUInt64(obj);
                return(MemoryMarshal.TryWrite(dest, ref ulongVal));

            case 'P':
                var bi = (BigInteger)obj;
                if (UIntPtr.Size == 4)
                {
                    if (bi < 0)
                    {
                        bi += new BigInteger(UInt32.MaxValue) + 1;
                    }
                    var ptrVal = (uint)bi;
                    return(MemoryMarshal.TryWrite(dest, ref ptrVal));
                }
                else
                {
                    if (bi < 0)
                    {
                        bi += new BigInteger(UInt64.MaxValue) + 1;
                    }
                    var ptrVal = (ulong)bi;
                    return(MemoryMarshal.TryWrite(dest, ref ptrVal));
                }

            case 'r':
                var iptrVal = (IntPtr)obj;
                return(MemoryMarshal.TryWrite(dest, ref iptrVal));

            case 'R':
                var uptrVal = (UIntPtr)obj;
                return(MemoryMarshal.TryWrite(dest, ref uptrVal));

            default:
                return(false);
            }
        }
        public void SpanWrite()
        {
            Assert.True(BitConverter.IsLittleEndian);

            Span <byte> span = new byte[8];

            byte byteValue = 0x11;

            MemoryMarshal.Write <byte>(span, ref byteValue);
            TestHelpers.Validate <byte>(span, byteValue);
            Assert.True(MemoryMarshal.TryWrite <byte>(span, ref byteValue));
            TestHelpers.Validate <byte>(span, byteValue);

            sbyte sbyteValue = 0x11;

            MemoryMarshal.Write <sbyte>(span, ref sbyteValue);
            TestHelpers.Validate <sbyte>(span, sbyteValue);
            Assert.True(MemoryMarshal.TryWrite <sbyte>(span, ref sbyteValue));
            TestHelpers.Validate <sbyte>(span, sbyteValue);

            ushort ushortValue = 0x1122;

            MemoryMarshal.Write <ushort>(span, ref ushortValue);
            TestHelpers.Validate <ushort>(span, ushortValue);
            Assert.True(MemoryMarshal.TryWrite <ushort>(span, ref ushortValue));
            TestHelpers.Validate <ushort>(span, ushortValue);

            uint uintValue = 0x11223344;

            MemoryMarshal.Write <uint>(span, ref uintValue);
            TestHelpers.Validate <uint>(span, uintValue);
            Assert.True(MemoryMarshal.TryWrite <uint>(span, ref uintValue));
            TestHelpers.Validate <uint>(span, uintValue);

            ulong ulongValue = 0x1122334455667788;

            MemoryMarshal.Write <ulong>(span, ref ulongValue);
            TestHelpers.Validate <ulong>(span, ulongValue);
            Assert.True(MemoryMarshal.TryWrite <ulong>(span, ref ulongValue));
            TestHelpers.Validate <ulong>(span, ulongValue);

            short shortValue = 0x1122;

            MemoryMarshal.Write <short>(span, ref shortValue);
            TestHelpers.Validate <short>(span, shortValue);
            Assert.True(MemoryMarshal.TryWrite <short>(span, ref shortValue));
            TestHelpers.Validate <short>(span, shortValue);

            int intValue = 0x11223344;

            MemoryMarshal.Write <int>(span, ref intValue);
            TestHelpers.Validate <int>(span, intValue);
            Assert.True(MemoryMarshal.TryWrite <int>(span, ref intValue));
            TestHelpers.Validate <int>(span, intValue);

            long longValue = 0x1122334455667788;

            MemoryMarshal.Write <long>(span, ref longValue);
            TestHelpers.Validate <long>(span, longValue);
            Assert.True(MemoryMarshal.TryWrite <long>(span, ref longValue));
            TestHelpers.Validate <long>(span, longValue);

            float floatValue = BitConverter.Int32BitsToSingle(0x11223344);

            MemoryMarshal.Write <float>(span, ref floatValue);
            TestHelpers.Validate <float>(span, floatValue);
            Assert.True(MemoryMarshal.TryWrite <float>(span, ref floatValue));
            TestHelpers.Validate <float>(span, floatValue);

            double doubleValue = BitConverter.Int64BitsToDouble(0x1122334455667788);

            MemoryMarshal.Write <double>(span, ref doubleValue);
            TestHelpers.Validate <double>(span, doubleValue);
            Assert.True(MemoryMarshal.TryWrite <double>(span, ref doubleValue));
            TestHelpers.Validate <double>(span, doubleValue);
        }