Exemplo n.º 1
0
        public static ReadOnlySpan <U> Cast <[Primitive] T, [Primitive] U>(this ReadOnlySpan <T> slice)
            where T : struct
            where U : struct
        {
            int countOfU;

            /// This comparison is a jittime constant
            if (UnsafeUtilities.SizeOf <T>() > UnsafeUtilities.SizeOf <U>())
            {
                IntPtr count = UnsafeUtilities.CountOfU <T, U>((uint)slice.Length);
                unsafe
                {
                    // We can't compare IntPtrs, so have to resort to pointer comparison
                    bool fits = (byte *)count <= (byte *)int.MaxValue;
                    Contract.Requires(fits);
                    countOfU = (int)count.ToPointer();
                }
            }
            else
            {
                countOfU = slice.Length * UnsafeUtilities.SizeOf <T>() / UnsafeUtilities.SizeOf <U>();
            }

            object  obj    = slice.Object;
            UIntPtr offset = slice.Offset;

            if (countOfU == 0)
            {
                obj    = null;
                offset = (UIntPtr)0;
            }

            return(new ReadOnlySpan <U>(obj, offset, countOfU));
        }