1 // Licensed to the .NET Foundation under one or more agreements.
2 // The .NET Foundation licenses this file to you under the MIT license.
3 // See the LICENSE file in the project root for more information.
6 using System.Collections.Generic;
7 using System.Collections.ObjectModel;
8 using System.Diagnostics;
9 using Internal.Runtime.CompilerServices;
11 namespace System.Runtime.InteropServices.WindowsRuntime
13 // This is a set of stub methods implementing the support for the IMap`2 interface on managed
14 // objects that implement IDictionary`2. Used by the interop mashaling infrastructure.
16 // The methods on this class must be written VERY carefully to avoid introducing security holes.
17 // That's because they are invoked with special "this"! The "this" object
18 // for all of these methods are not DictionaryToMapAdapter objects. Rather, they are of type
19 // IDictionary<K, V>. No actual DictionaryToMapAdapter object is ever instantiated. Thus, you will
20 // see a lot of expressions that cast "this" to "IDictionary<K, V>".
21 internal sealed class DictionaryToMapAdapter
23 private DictionaryToMapAdapter()
25 Debug.Fail("This class is never instantiated");
29 internal V Lookup<K, V>(K key)
31 IDictionary<K, V> _this = Unsafe.As<IDictionary<K, V>>(this);
33 bool keyFound = _this.TryGetValue(key, out value);
37 Debug.Assert(key != null);
38 Exception e = new KeyNotFoundException(SR.Format(SR.Arg_KeyNotFoundWithKey, key.ToString()));
39 e.HResult = HResults.E_BOUNDS;
47 internal uint Size<K, V>()
49 IDictionary<K, V> _this = Unsafe.As<IDictionary<K, V>>(this);
50 return (uint)_this.Count;
54 internal bool HasKey<K, V>(K key)
56 IDictionary<K, V> _this = Unsafe.As<IDictionary<K, V>>(this);
57 return _this.ContainsKey(key);
60 // IMapView<K, V> GetView()
61 internal IReadOnlyDictionary<K, V> GetView<K, V>()
63 IDictionary<K, V> _this = Unsafe.As<IDictionary<K, V>>(this);
64 Debug.Assert(_this != null);
66 // Note: This dictionary is not really read-only - you could QI for a modifiable
67 // dictionary. We gain some perf by doing this. We believe this is acceptable.
68 if (!(_this is IReadOnlyDictionary<K, V> roDictionary))
70 roDictionary = new ReadOnlyDictionary<K, V>(_this);
75 // bool Insert(K key, V value)
76 internal bool Insert<K, V>(K key, V value)
78 IDictionary<K, V> _this = Unsafe.As<IDictionary<K, V>>(this);
79 bool replacing = _this.ContainsKey(key);
85 internal void Remove<K, V>(K key)
87 IDictionary<K, V> _this = Unsafe.As<IDictionary<K, V>>(this);
88 bool removed = _this.Remove(key);
92 Debug.Assert(key != null);
93 Exception e = new KeyNotFoundException(SR.Format(SR.Arg_KeyNotFoundWithKey, key.ToString()));
94 e.HResult = HResults.E_BOUNDS;
100 internal void Clear<K, V>()
102 IDictionary<K, V> _this = Unsafe.As<IDictionary<K, V>>(this);