コード例 #1
0
        public object Bitcast(object type, object value)
        {
            if (type == null)
            {
                throw new ArgumentNullException(nameof(type));
            }

            var bytes = AsBytes(value);

            if (bytes == null)
            {
                return(null);
            }

            switch (type)
            {
            case byte vbyte:
                UnsafeHelpers.BitCast(ref vbyte, 1, bytes);
                return(vbyte);

            case sbyte vsbyte:
                UnsafeHelpers.BitCast(ref vsbyte, 1, bytes);
                return(vsbyte);

            case short vshort:
                UnsafeHelpers.BitCast(ref vshort, 2, bytes);
                return(vshort);

            case ushort vushort:
                UnsafeHelpers.BitCast(ref vushort, 2, bytes);
                return(vushort);

            case int vint:
                UnsafeHelpers.BitCast(ref vint, 4, bytes);
                return(vint);

            case uint vuint:
                UnsafeHelpers.BitCast(ref vuint, 4, bytes);
                return((long)vuint);

            case ulong vulong:
                UnsafeHelpers.BitCast(ref vulong, 8, bytes);
                return(vulong);

            case long vlong:
                UnsafeHelpers.BitCast(ref vlong, 8, bytes);
                return(vlong);

            case float _:
                int vfloat = 0;
                UnsafeHelpers.BitCast(ref vfloat, 4, bytes);
                return(BitConverter.Int32BitsToSingle(vfloat));

            case KalkHalf vhalf:
                UnsafeHelpers.BitCast(ref vhalf, 2, bytes);
                return(vhalf);

            case double _:
                long vdouble = 0;
                UnsafeHelpers.BitCast(ref vdouble, 8, bytes);
                return(BitConverter.Int64BitsToDouble(vdouble));

            case KalkValue kalkValue:
                var dest = (KalkValue)kalkValue.Clone(true);
                dest.BitCastFrom(bytes.AsSpan());
                return(dest);

            default:
                throw new ArgumentException($"The destination type `{Engine.GetTypeName(type)}` is not supported.", nameof(value));
            }
        }