summaryrefslogtreecommitdiff
path: root/src/mscorlib/src/System/Runtime/InteropServices/WindowsRuntime/CLRIPropertyValueImpl.cs
blob: 702e0c9e52125a109e967060afb4a371cbe4d9ad (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

//

using System;
using System.Diagnostics.Contracts;
using System.Runtime.CompilerServices;
using System.Security;

namespace System.Runtime.InteropServices.WindowsRuntime
{
    internal class CLRIPropertyValueImpl : IPropertyValue
    {
        private PropertyType _type;
        private Object _data;

        // Numeric scalar types which participate in coersion
        private static volatile Tuple<Type, PropertyType>[] s_numericScalarTypes;

        internal CLRIPropertyValueImpl(PropertyType type, Object data)
        {
            _type = type;
            _data = data;
        }

        private static Tuple<Type, PropertyType>[] NumericScalarTypes {
            get {
                if (s_numericScalarTypes == null) {
                    Tuple<Type, PropertyType>[] numericScalarTypes = new Tuple<Type, PropertyType>[] {
                        new Tuple<Type, PropertyType>(typeof(Byte), PropertyType.UInt8),
                        new Tuple<Type, PropertyType>(typeof(Int16), PropertyType.Int16),
                        new Tuple<Type, PropertyType>(typeof(UInt16), PropertyType.UInt16),
                        new Tuple<Type, PropertyType>(typeof(Int32), PropertyType.Int32),
                        new Tuple<Type, PropertyType>(typeof(UInt32), PropertyType.UInt32),
                        new Tuple<Type, PropertyType>(typeof(Int64), PropertyType.Int64),
                        new Tuple<Type, PropertyType>(typeof(UInt64), PropertyType.UInt64),
                        new Tuple<Type, PropertyType>(typeof(Single), PropertyType.Single),
                        new Tuple<Type, PropertyType>(typeof(Double), PropertyType.Double)
                    };

                    s_numericScalarTypes = numericScalarTypes;
                }

                return s_numericScalarTypes;
            }
        }

        public PropertyType Type {
            [Pure]
            get { return _type; }
        }

        public bool IsNumericScalar {
            [Pure]
            get {
                return IsNumericScalarImpl(_type, _data);
            }
        }

        public override string ToString()
        {
            if (_data != null)
            {
                return _data.ToString();
            }
            else
            {
                return base.ToString();
            }
        }

        [Pure]
        public Byte GetUInt8()
        {
            return CoerceScalarValue<Byte>(PropertyType.UInt8);
        }

        [Pure]
        public Int16 GetInt16()
        {
            return CoerceScalarValue<Int16>(PropertyType.Int16);
        }

        public UInt16 GetUInt16()
        {
            return CoerceScalarValue<UInt16>(PropertyType.UInt16);
        }

        [Pure]
        public Int32 GetInt32()
        {
            return CoerceScalarValue<Int32>(PropertyType.Int32);
        }

        [Pure]
        public UInt32 GetUInt32()
        {
            return CoerceScalarValue<UInt32>(PropertyType.UInt32);
        }

        [Pure]
        public Int64 GetInt64()
        {
            return CoerceScalarValue<Int64>(PropertyType.Int64);
        }

        [Pure]
        public UInt64 GetUInt64()
        {
            return CoerceScalarValue<UInt64>(PropertyType.UInt64);
        }

        [Pure]
        public Single GetSingle()
        {
            return CoerceScalarValue<Single>(PropertyType.Single);
        }

        [Pure]
        public Double GetDouble()
        {
            return CoerceScalarValue<Double>(PropertyType.Double);
        }

        [Pure]
        public char GetChar16()
        {
            if (this.Type != PropertyType.Char16)
                throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", this.Type, "Char16"), __HResults.TYPE_E_TYPEMISMATCH);
            Contract.EndContractBlock();
            return (char)_data;
        }

        [Pure]
        public Boolean GetBoolean()
        {
            if (this.Type != PropertyType.Boolean)
                throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", this.Type, "Boolean"), __HResults.TYPE_E_TYPEMISMATCH);
            Contract.EndContractBlock();
            return (bool)_data;
        }

        [Pure]
        public String GetString()
        {
            return CoerceScalarValue<String>(PropertyType.String);
        }

        [Pure]
        public Object GetInspectable()
        {
            if (this.Type != PropertyType.Inspectable)
                throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", this.Type, "Inspectable"), __HResults.TYPE_E_TYPEMISMATCH);
            Contract.EndContractBlock();
            return _data;
        }


        [Pure]
        public Guid GetGuid()
        {
            return CoerceScalarValue<Guid>(PropertyType.Guid);
        }


        [Pure]
        public DateTimeOffset GetDateTime()
        {
            if (this.Type != PropertyType.DateTime)
                throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", this.Type, "DateTime"), __HResults.TYPE_E_TYPEMISMATCH);
            Contract.EndContractBlock();
            return (DateTimeOffset)_data;
        }

        [Pure]
        public TimeSpan GetTimeSpan()
        {
            if (this.Type != PropertyType.TimeSpan)
                throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", this.Type, "TimeSpan"), __HResults.TYPE_E_TYPEMISMATCH);
            Contract.EndContractBlock();
            return (TimeSpan)_data;
        }

        [Pure]
        public Point GetPoint()
        {
            if (this.Type != PropertyType.Point)
                throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", this.Type, "Point"), __HResults.TYPE_E_TYPEMISMATCH);
            Contract.EndContractBlock();

            return Unbox<Point>(IReferenceFactory.s_pointType);
        }

        [Pure]
        public Size GetSize()
        {
            if (this.Type != PropertyType.Size)
                throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", this.Type, "Size"), __HResults.TYPE_E_TYPEMISMATCH);
            Contract.EndContractBlock();
            
            return Unbox<Size>(IReferenceFactory.s_sizeType);
        }

        [Pure]
        public Rect GetRect()
        {
            if (this.Type != PropertyType.Rect)
                throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", this.Type, "Rect"), __HResults.TYPE_E_TYPEMISMATCH);
            Contract.EndContractBlock();
            
            return Unbox<Rect>(IReferenceFactory.s_rectType);
        }

        [Pure]
        public Byte[] GetUInt8Array()
        {
            return CoerceArrayValue<Byte>(PropertyType.UInt8Array);
        }

        [Pure]
        public Int16[] GetInt16Array()
        {
            return CoerceArrayValue<Int16>(PropertyType.Int16Array);
        }

        [Pure]
        public UInt16[] GetUInt16Array()
        {
            return CoerceArrayValue<UInt16>(PropertyType.UInt16Array);
        }

        [Pure]
        public Int32[] GetInt32Array()
        {
            return CoerceArrayValue<Int32>(PropertyType.Int32Array);
        }

        [Pure]
        public UInt32[] GetUInt32Array()
        {
            return CoerceArrayValue<UInt32>(PropertyType.UInt32Array);
        }

        [Pure]
        public Int64[] GetInt64Array()
        {
            return CoerceArrayValue<Int64>(PropertyType.Int64Array);
        }

        [Pure]
        public UInt64[] GetUInt64Array()
        {
            return CoerceArrayValue<UInt64>(PropertyType.UInt64Array);
        }

        [Pure]
        public Single[] GetSingleArray()
        {
            return CoerceArrayValue<Single>(PropertyType.SingleArray);
        }

        [Pure]
        public Double[] GetDoubleArray()
        {
            return CoerceArrayValue<Double>(PropertyType.DoubleArray);
        }

        [Pure]
        public char[] GetChar16Array()
        {
            if (this.Type != PropertyType.Char16Array)
                throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", this.Type, "Char16[]"), __HResults.TYPE_E_TYPEMISMATCH);
            Contract.EndContractBlock();
            return (char[])_data;
        }

        [Pure]
        public Boolean[] GetBooleanArray()
        {
            if (this.Type != PropertyType.BooleanArray)
                throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", this.Type, "Boolean[]"), __HResults.TYPE_E_TYPEMISMATCH);
            Contract.EndContractBlock();
            return (bool[])_data;
        }

        [Pure]
        public String[] GetStringArray()
        {
            return CoerceArrayValue<String>(PropertyType.StringArray);
        }

        [Pure]
        public Object[] GetInspectableArray()
        {
            if (this.Type != PropertyType.InspectableArray)
                throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", this.Type, "Inspectable[]"), __HResults.TYPE_E_TYPEMISMATCH);
            Contract.EndContractBlock();
            return (Object[])_data;
        }

        [Pure]
        public Guid[] GetGuidArray()
        {
            return CoerceArrayValue<Guid>(PropertyType.GuidArray);
        }

        [Pure]
        public DateTimeOffset[] GetDateTimeArray()
        {
            if (this.Type != PropertyType.DateTimeArray)
                throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", this.Type, "DateTimeOffset[]"), __HResults.TYPE_E_TYPEMISMATCH);
            Contract.EndContractBlock();
            return (DateTimeOffset[])_data;
        }

        [Pure]
        public TimeSpan[] GetTimeSpanArray()
        {
            if (this.Type != PropertyType.TimeSpanArray)
                throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", this.Type, "TimeSpan[]"), __HResults.TYPE_E_TYPEMISMATCH);
            Contract.EndContractBlock();
            return (TimeSpan[])_data;
        }

        [Pure]
        public Point[] GetPointArray()
        {
            if (this.Type != PropertyType.PointArray)
                throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", this.Type, "Point[]"), __HResults.TYPE_E_TYPEMISMATCH);
            Contract.EndContractBlock();
            
            return UnboxArray<Point>(IReferenceFactory.s_pointType);
        }

        [Pure]
        public Size[] GetSizeArray()
        {
            if (this.Type != PropertyType.SizeArray)
                throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", this.Type, "Size[]"), __HResults.TYPE_E_TYPEMISMATCH);
            Contract.EndContractBlock();


            return UnboxArray<Size>(IReferenceFactory.s_sizeType);
        }

        [Pure]
        public Rect[] GetRectArray()
        {
            if (this.Type != PropertyType.RectArray)
                throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", this.Type, "Rect[]"), __HResults.TYPE_E_TYPEMISMATCH);
            Contract.EndContractBlock();

            return UnboxArray<Rect>(IReferenceFactory.s_rectType);
        }

        private T[] CoerceArrayValue<T>(PropertyType unboxType) {
            // If we contain the type being looked for directly, then take the fast-path
            if (Type == unboxType) {
                return (T[])_data;
            }

            // Make sure we have an array to begin with
            Array dataArray = _data as Array;
            if (dataArray == null) {
                throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", this.Type, typeof(T).MakeArrayType().Name), __HResults.TYPE_E_TYPEMISMATCH);
            }

            // Array types are 1024 larger than their equivilent scalar counterpart
            BCLDebug.Assert((int)Type > 1024, "Unexpected array PropertyType value");
            PropertyType scalarType = Type - 1024;

            // If we do not have the correct array type, then we need to convert the array element-by-element
            // to a new array of the requested type
            T[] coercedArray = new T[dataArray.Length];
            for (int i = 0; i < dataArray.Length; ++i) {
                try {
                    coercedArray[i] = CoerceScalarValue<T>(scalarType, dataArray.GetValue(i));
                } catch (InvalidCastException elementCastException) {
                    Exception e = new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueArrayCoersion", this.Type, typeof(T).MakeArrayType().Name, i, elementCastException.Message), elementCastException);
                    e.SetErrorCode(elementCastException._HResult);
                    throw e;
                }
            }

            return coercedArray;
        }

        private T CoerceScalarValue<T>(PropertyType unboxType)
        {
            // If we are just a boxed version of the requested type, then take the fast path out
            if (Type == unboxType) {
                return (T)_data;
            }

            return CoerceScalarValue<T>(Type, _data);
        }

        private static T CoerceScalarValue<T>(PropertyType type, object value) {
            // If the property type is neither one of the coercable numeric types nor IInspectable, we
            // should not attempt coersion, even if the underlying value is technically convertable
            if (!IsCoercable(type, value) && type != PropertyType.Inspectable) {
                throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", type, typeof(T).Name), __HResults.TYPE_E_TYPEMISMATCH);
            }

            try {
                // Try to coerce:
                //  * String <--> Guid
                //  * Numeric scalars
                if (type == PropertyType.String && typeof(T) == typeof(Guid)) {
                    return (T)(object)Guid.Parse((string)value);
                }
                else if (type == PropertyType.Guid && typeof(T) == typeof(String)) {
                    return  (T)(object)((Guid)value).ToString("D", System.Globalization.CultureInfo.InvariantCulture);
                }
                else {
                    // Iterate over the numeric scalars, to see if we have a match for one of the known conversions
                    foreach (Tuple<Type, PropertyType> numericScalar in NumericScalarTypes) {
                        if (numericScalar.Item1 == typeof(T)) {
                            return (T)Convert.ChangeType(value, typeof(T), System.Globalization.CultureInfo.InvariantCulture);
                        }
                    }
                }
            }
            catch (FormatException) {
                throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", type, typeof(T).Name), __HResults.TYPE_E_TYPEMISMATCH);
            }
            catch (InvalidCastException) {
                throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", type, typeof(T).Name), __HResults.TYPE_E_TYPEMISMATCH);
            }
            catch (OverflowException) {
                throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueCoersion", type, value, typeof(T).Name), __HResults.DISP_E_OVERFLOW);
            }

            // If the property type is IInspectable, and we have a nested IPropertyValue, then we need
            // to pass along the request to coerce the value.
            IPropertyValue ipv = value as IPropertyValue;
            if (type == PropertyType.Inspectable && ipv != null) {
                if (typeof(T) == typeof(Byte)) {
                    return (T)(object)ipv.GetUInt8();
                }
                else if (typeof(T) == typeof(Int16)) {
                    return (T)(object)ipv.GetInt16();
                }
                else if (typeof(T) == typeof(UInt16)) {
                    return (T)(object)ipv.GetUInt16();
                }
                else if (typeof(T) == typeof(Int32)) {
                    return (T)(object)ipv.GetUInt32();
                }
                else if (typeof(T) == typeof(UInt32)) {
                    return (T)(object)ipv.GetUInt32();
                }
                else if (typeof(T) == typeof(Int64)) {
                    return (T)(object)ipv.GetInt64();
                }
                else if (typeof(T) == typeof(UInt64)) {
                    return (T)(object)ipv.GetUInt64();
                }
                else if (typeof(T) == typeof(Single)) {
                    return (T)(object)ipv.GetSingle();
                }
                else if (typeof(T) == typeof(Double)) {
                    return (T)(object)ipv.GetDouble();
                }
                else {
                    BCLDebug.Assert(false, "T in coersion function wasn't understood as a type that can be coerced - make sure that CoerceScalarValue and NumericScalarTypes are in sync");
                }
            }

            // Otherwise, this is an invalid coersion
            throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", type, typeof(T).Name), __HResults.TYPE_E_TYPEMISMATCH);
        }

        private static bool IsCoercable(PropertyType type, object data) {
            // String <--> Guid is allowed
            if (type == PropertyType.Guid || type == PropertyType.String) {
                return true;
            }

            // All numeric scalars can also be coerced
            return IsNumericScalarImpl(type, data);
        }

        private static bool IsNumericScalarImpl(PropertyType type, object data) {
            if (data.GetType().IsEnum) {
                return true;
            }

            foreach (Tuple<Type, PropertyType> numericScalar in NumericScalarTypes) {
                if (numericScalar.Item2 == type) {
                    return true;
                }
            }

            return false;
        }

        // Unbox the data stored in the property value to a structurally equivilent type
        [Pure]
        private unsafe T Unbox<T>(Type expectedBoxedType) where T : struct {
            Contract.Requires(expectedBoxedType != null);
            Contract.Requires(Marshal.SizeOf(expectedBoxedType) == Marshal.SizeOf(typeof(T)));

            if (_data.GetType() != expectedBoxedType) {
                throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", _data.GetType(), expectedBoxedType.Name), __HResults.TYPE_E_TYPEMISMATCH);
            }

            T unboxed = new T();

            fixed (byte *pData = &JitHelpers.GetPinningHelper(_data).m_data) {
                byte* pUnboxed = (byte*)JitHelpers.UnsafeCastToStackPointer(ref unboxed);
                Buffer.Memcpy(pUnboxed, pData, Marshal.SizeOf(unboxed));
            }
            
            return unboxed;
        }

        // Convert the array stored in the property value to a structurally equivilent array type
        [Pure]
        private unsafe T[] UnboxArray<T>(Type expectedArrayElementType) where T : struct {
            Contract.Requires(expectedArrayElementType != null);
            Contract.Requires(Marshal.SizeOf(expectedArrayElementType) == Marshal.SizeOf(typeof(T)));

            Array dataArray = _data as Array;
            if (dataArray == null || _data.GetType().GetElementType() != expectedArrayElementType) {
                throw new InvalidCastException(Environment.GetResourceString("InvalidCast_WinRTIPropertyValueElement", _data.GetType(), expectedArrayElementType.MakeArrayType().Name), __HResults.TYPE_E_TYPEMISMATCH);
            }

            T[] converted = new T[dataArray.Length];

            if (converted.Length > 0) {
                fixed (byte * dataPin = &JitHelpers.GetPinningHelper(dataArray).m_data) {
                    fixed (byte * convertedPin = &JitHelpers.GetPinningHelper(converted).m_data) {
                        byte *pData = (byte *)Marshal.UnsafeAddrOfPinnedArrayElement(dataArray, 0);
                        byte *pConverted = (byte *)Marshal.UnsafeAddrOfPinnedArrayElement(converted, 0);

                        Buffer.Memcpy(pConverted, pData, checked(Marshal.SizeOf(typeof(T)) * converted.Length));
                    }
                }
            }

            return converted;
        }
    }
}