示例#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 (PtrUtils.SizeOf <T>() > PtrUtils.SizeOf <U>())
            {
                IntPtr count = PtrUtils.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 * PtrUtils.SizeOf <T>() / PtrUtils.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));
        }