3 // Copyright (c) Microsoft Corporation. All rights reserved.
7 // <OWNER>GPaperin</OWNER>
8 // <OWNER>Microsoft</OWNER>
11 using System.Security;
12 using System.Reflection;
13 using System.Collections;
14 using System.Collections.Generic;
15 using System.Collections.ObjectModel;
16 using System.Diagnostics.Contracts;
17 using System.Runtime.InteropServices;
18 using System.Runtime.CompilerServices;
20 namespace System.Runtime.InteropServices.WindowsRuntime
22 // This is a set of stub methods implementing the support for the IMap`2 interface on managed
23 // objects that implement IDictionary`2. Used by the interop mashaling infrastructure.
25 // The methods on this class must be written VERY carefully to avoid introducing security holes.
26 // That's because they are invoked with special "this"! The "this" object
27 // for all of these methods are not DictionaryToMapAdapter objects. Rather, they are of type
28 // IDictionary<K, V>. No actual DictionaryToMapAdapter object is ever instantiated. Thus, you will
29 // see a lot of expressions that cast "this" to "IDictionary<K, V>".
30 internal sealed class DictionaryToMapAdapter
32 private DictionaryToMapAdapter()
34 Contract.Assert(false, "This class is never instantiated");
39 internal V Lookup<K, V>(K key)
41 IDictionary<K, V> _this = JitHelpers.UnsafeCast<IDictionary<K, V>>(this);
43 bool keyFound = _this.TryGetValue(key, out value);
47 Exception e = new KeyNotFoundException(Environment.GetResourceString("Arg_KeyNotFound"));
48 e.SetErrorCode(__HResults.E_BOUNDS);
57 internal uint Size<K, V>()
59 IDictionary<K, V> _this = JitHelpers.UnsafeCast<IDictionary<K, V>>(this);
60 return (uint)_this.Count;
65 internal bool HasKey<K, V>(K key)
67 IDictionary<K, V> _this = JitHelpers.UnsafeCast<IDictionary<K, V>>(this);
68 return _this.ContainsKey(key);
71 // IMapView<K, V> GetView()
73 internal IReadOnlyDictionary<K, V> GetView<K, V>()
75 IDictionary<K, V> _this = JitHelpers.UnsafeCast<IDictionary<K, V>>(this);
76 Contract.Assert(_this != null);
78 // Note: This dictionary is not really read-only - you could QI for a modifiable
79 // dictionary. We gain some perf by doing this. We believe this is acceptable.
80 IReadOnlyDictionary<K, V> roDictionary = _this as IReadOnlyDictionary<K, V>;
81 if (roDictionary == null)
83 roDictionary = new ReadOnlyDictionary<K, V>(_this);
88 // bool Insert(K key, V value)
90 internal bool Insert<K, V>(K key, V value)
92 IDictionary<K, V> _this = JitHelpers.UnsafeCast<IDictionary<K, V>>(this);
93 bool replacing = _this.ContainsKey(key);
100 internal void Remove<K, V>(K key)
102 IDictionary<K, V> _this = JitHelpers.UnsafeCast<IDictionary<K, V>>(this);
103 bool removed = _this.Remove(key);
107 Exception e = new KeyNotFoundException(Environment.GetResourceString("Arg_KeyNotFound"));
108 e.SetErrorCode(__HResults.E_BOUNDS);
115 internal void Clear<K, V>()
117 IDictionary<K, V> _this = JitHelpers.UnsafeCast<IDictionary<K, V>>(this);