Welcome to mirror list, hosted at ThFree Co, Russian Federation.

stringdictionary.cs « specialized « collections « system « compmod « System « referencesource « class « mcs - github.com/mono/mono.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 44067722d00341420211a6d254e3be9812fb75e7 (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
//------------------------------------------------------------------------------
// <copyright file="StringDictionary.cs" company="Microsoft">
//     Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>                                                                
//------------------------------------------------------------------------------

/*
 */
namespace System.Collections.Specialized {
    using System.Runtime.InteropServices;
    using System.Diagnostics;
    using System;
    using System.Collections;
    using System.ComponentModel.Design.Serialization;
    using System.Globalization;
    using System.Collections.Generic;
    
    /// <devdoc>
    ///    <para>Implements a hashtable with the key strongly typed to be
    ///       a string rather than an object. </para>
    ///    <para>Consider this class obsolete - use Dictionary&lt;String, String&gt; instead
    ///       with a proper StringComparer instance.</para>
    /// </devdoc>
    [Serializable]
    [DesignerSerializer("System.Diagnostics.Design.StringDictionaryCodeDomSerializer, " + AssemblyRef.SystemDesign, "System.ComponentModel.Design.Serialization.CodeDomSerializer, " + AssemblyRef.SystemDesign)]
    // @
    public class StringDictionary : IEnumerable {

        // For compatibility, we want the Keys property to return values in lower-case.
        // That means using ToLower in each property on this type.  Also for backwards
        // compatibility, we will be converting strings to lower-case, which has a 
        // problem for some Georgian alphabets.  Can't really fix it now though...
        internal Hashtable contents = new Hashtable();

        
        /// <devdoc>
        /// <para>Initializes a new instance of the StringDictionary class.</para>
        /// <para>If you're using file names, registry keys, etc, you want to use
        /// a Dictionary&lt;String, Object&gt; and use 
        /// StringComparer.OrdinalIgnoreCase.</para>
        /// </devdoc>
        public StringDictionary() {
        }

        /// <devdoc>
        /// <para>Gets the number of key-and-value pairs in the StringDictionary.</para>
        /// </devdoc>
        public virtual int Count {
            get {
                return contents.Count;
            }
        }

        
        /// <devdoc>
        /// <para>Indicates whether access to the StringDictionary is synchronized (thread-safe). This property is 
        ///    read-only.</para>
        /// </devdoc>
        public virtual bool IsSynchronized {
            get {
                return contents.IsSynchronized;
            }
        }

        /// <devdoc>
        ///    <para>Gets or sets the value associated with the specified key.</para>
        /// </devdoc>
        public virtual string this[string key] {
            get {
                if( key == null ) {
                    throw new ArgumentNullException("key");
                }

                return (string) contents[key.ToLower(CultureInfo.InvariantCulture)];
            }
            set {
                if( key == null ) {
                    throw new ArgumentNullException("key");
                }

                contents[key.ToLower(CultureInfo.InvariantCulture)] = value;
            }
        }

        /// <devdoc>
        /// <para>Gets a collection of keys in the StringDictionary.</para>
        /// </devdoc>
        public virtual ICollection Keys {
            get {
                return contents.Keys;
            }
        }

        
        /// <devdoc>
        /// <para>Gets an object that can be used to synchronize access to the StringDictionary.</para>
        /// </devdoc>
        public virtual object SyncRoot {
            get {
                return contents.SyncRoot;
            }
        }

        /// <devdoc>
        /// <para>Gets a collection of values in the StringDictionary.</para>
        /// </devdoc>
        public virtual ICollection Values {
            get {
                return contents.Values;
            }
        }

        /// <devdoc>
        /// <para>Adds an entry with the specified key and value into the StringDictionary.</para>
        /// </devdoc>
        public virtual void Add(string key, string value) {
            if( key == null ) {
                throw new ArgumentNullException("key");
            }

            contents.Add(key.ToLower(CultureInfo.InvariantCulture), value);
        }

        /// <devdoc>
        /// <para>Removes all entries from the StringDictionary.</para>
        /// </devdoc>
        public virtual void Clear() {
            contents.Clear();
        }

        /// <devdoc>
        ///    <para>Determines if the string dictionary contains a specific key</para>
        /// </devdoc>
        public virtual bool ContainsKey(string key) {
            if( key == null ) {
                throw new ArgumentNullException("key");
            }

            return contents.ContainsKey(key.ToLower(CultureInfo.InvariantCulture));
        }

        /// <devdoc>
        /// <para>Determines if the StringDictionary contains a specific value.</para>
        /// </devdoc>
        public virtual bool ContainsValue(string value) {
            return contents.ContainsValue(value);
        }

        /// <devdoc>
        /// <para>Copies the string dictionary values to a one-dimensional <see cref='System.Array'/> instance at the 
        ///    specified index.</para>
        /// </devdoc>
        public virtual void CopyTo(Array array, int index) {
            contents.CopyTo(array, index);
        }

        /// <devdoc>
        ///    <para>Returns an enumerator that can iterate through the string dictionary.</para>
        /// </devdoc>
        public virtual IEnumerator GetEnumerator() {
            return contents.GetEnumerator();
        }

        /// <devdoc>
        ///    <para>Removes the entry with the specified key from the string dictionary.</para>
        /// </devdoc>
        public virtual void Remove(string key) {
            if( key == null ) {
                throw new ArgumentNullException("key");
            }

            contents.Remove(key.ToLower(CultureInfo.InvariantCulture));
        }

        /// <summary>
        /// Make this StringDictionary subservient to some other collection.
        /// <para>Some code was replacing the contents field with a Hashtable created elsewhere.
        /// While it may not have been incorrect, we don't want to encourage that pattern, because
        /// it will replace the IEqualityComparer in the Hashtable, and creates a possibly-undesirable
        /// link between two seemingly different collections.  Let's discourage that somewhat by
        /// making this an explicit method call instead of an internal field assignment.</para>
        /// </summary>
        /// <param name="useThisHashtableInstead">Replaces the backing store with another, possibly aliased Hashtable.</param>
        internal void ReplaceHashtable(Hashtable useThisHashtableInstead) {
            contents = useThisHashtableInstead;
        }

        internal IDictionary<string, string> AsGenericDictionary() {
            return new GenericAdapter(this);
        }

#region GenericAdapter
        //
    // This class is used to make StringDictionary implement IDictionary<string,string> indirectly. 
    // This is done to prevent StringDictionary be serialized as IDictionary<string,string> and break its serialization by DataContractSerializer due to a 
    private class GenericAdapter : IDictionary<string, string>
    {

        StringDictionary m_stringDictionary;

        internal GenericAdapter(StringDictionary stringDictionary) {
            m_stringDictionary = stringDictionary;
        }

        #region IDictionary<string, string> Members
        public void Add(string key, string value) {

            // GenericAdapter.Add has the semantics of Item property to make ProcessStartInfo.Environment deserializable by DataContractSerializer.
            // ProcessStartInfo.Environment property does not have a setter
            // and so during deserialization the serializer initializes the property by calling get_Environment and 
            // then populates it via IDictionary<,>.Add per item.
            // However since get_Environment gives the current snapshot of environment variables we might try to insert a key that already exists.
            // (For Example 'PATH') causing an exception. This implementation ensures that we overwrite values in case of duplication.

            this[key] =  value;
        }

        public bool ContainsKey(string key) {
            return m_stringDictionary.ContainsKey(key);
        }

        public void Clear() {
            m_stringDictionary.Clear();
        }

        public int Count {
            get {
                return m_stringDictionary.Count;
            }
        }

        // Items added to allow StringDictionary to provide IDictionary<string, string> support.
        ICollectionToGenericCollectionAdapter _values;
        ICollectionToGenericCollectionAdapter _keys;

        // IDictionary<string,string>.Item vs StringDictioanry.Item
        // IDictionary<string,string>.get_Item         i. KeyNotFoundException when the property is retrieved and key is not found.
        // StringBuilder.get_Item                      i. Returns null in case the key is not found.
        public string this[string key] {
            get {
                if (key == null) {
                    throw new ArgumentNullException("key");
                }

                if (!m_stringDictionary.ContainsKey(key)) throw new KeyNotFoundException();

                return m_stringDictionary[key];
            }
            set {
                if (key == null) {
                    throw new ArgumentNullException("key");
                }

                m_stringDictionary[key] = value;
            }
        }

        // This method returns a read-only view of the Keys in the StringDictinary.
        public ICollection<string> Keys {
            get {
                if( _keys == null ) {
                    _keys = new ICollectionToGenericCollectionAdapter(m_stringDictionary, KeyOrValue.Key);
                }
                return _keys;
            }
        }

        // This method returns a read-only view of the Values in the StringDictionary.
        public ICollection<string> Values {
            get {
                if( _values == null ) {
                    _values = new ICollectionToGenericCollectionAdapter(m_stringDictionary, KeyOrValue.Value);
                }
                return _values;
            }
        }

        // IDictionary<string,string>.Remove vs StringDictionary.Remove.
        // IDictionary<string,string>.Remove-  i. Returns a bool status that represents success\failure.
        //                                    ii. Returns false in case key is not found.
        // StringDictionary.Remove             i. Does not return the status and does nothing in case key is not found.
        public bool Remove(string key) {

            // Check if the key is not present and return false.
            if (!m_stringDictionary.ContainsKey(key)) return false;

            // We call the virtual StringDictionary.Remove method to ensure any subClass gets the expected behavior.
            m_stringDictionary.Remove(key);

            // If the above call has succeeded we simply return true.
            return true;
        }


        public bool TryGetValue(string key, out string value) {
            if (!m_stringDictionary.ContainsKey(key)) {
                value = null;
                return false;
            }

            value = m_stringDictionary[key];
            return true;
        }

        void ICollection<KeyValuePair<string, string>>.Add(KeyValuePair<string, string> item) {
            m_stringDictionary.Add(item.Key, item.Value);
        }

        bool ICollection<KeyValuePair<string, string>>.Contains(KeyValuePair<string, string> item) {
            string value;
            return TryGetValue(item.Key, out value) && value.Equals(item.Value);
        }

        void ICollection<KeyValuePair<string, string>>.CopyTo(KeyValuePair<string, string>[] array, int arrayIndex) {
            if( array == null )
                throw new ArgumentNullException("array", SR.GetString(SR.ArgumentNull_Array));
            if( arrayIndex < 0 )
                throw new ArgumentOutOfRangeException("arrayIndex", SR.GetString(SR.ArgumentOutOfRange_NeedNonNegNum));
            if( array.Length - arrayIndex < Count )
                throw new ArgumentException(SR.GetString(SR.Arg_ArrayPlusOffTooSmall));

            int index = arrayIndex;

            foreach (DictionaryEntry entry in m_stringDictionary) {
                array[index++] = new KeyValuePair<string, string>((string)entry.Key, (string)entry.Value);
            }
        }

        bool ICollection<KeyValuePair<string,string>>.IsReadOnly {
            get {
                return false;
            }
        }

        // ICollection<KeyValuePair<string, string>>.Remove vs StringDictionary.Remove
        // ICollection<KeyValuePair<string, string>>.Remove - i. Return status.
        //                                                   ii. Returns false in case the items is not found.
        // StringDictionary.Remove                            i. Does not return a status and does nothing in case the key is not found.
        bool ICollection<KeyValuePair<string, string>>.Remove(KeyValuePair<string, string> item) {

            // If the item is not found return false.
            ICollection<KeyValuePair<string, string>> iCollection = this;
            if( !iCollection.Contains(item) ) return false;

            // We call the virtual StringDictionary.Remove method to ensure any subClass gets the expected behavior.
            m_stringDictionary.Remove(item.Key);

            // If the above call has succeeded we simply return true.
            return true;
        }

        IEnumerator IEnumerable.GetEnumerator() {
            return this.GetEnumerator();
        }

        // The implementation asummes that this.GetEnumerator().Current can be casted to DictionaryEntry.
        // and although StringDictionary.GetEnumerator() returns IEnumerator and is a virtual method
        // it should be ok to take that assumption since it is an implicit contract.
        public IEnumerator<KeyValuePair<string, string>> GetEnumerator()
        {
            foreach (DictionaryEntry dictionaryEntry in m_stringDictionary)
                yield return new KeyValuePair<string, string>((string)dictionaryEntry.Key, (string)dictionaryEntry.Value);
        }

        internal enum KeyOrValue // Used internally for IDictionary<string, string> support 
        {
            Key,
            Value
        }

        // This Adapter converts StringDictionary.Keys and StringDictionary.Values to ICollection<string>
        // Since StringDictionary implements a virtual StringDictionary.Keys and StringDictionary.Values 
        private class ICollectionToGenericCollectionAdapter : ICollection<string> {

            StringDictionary _internal;
            KeyOrValue _keyOrValue;

            public ICollectionToGenericCollectionAdapter(StringDictionary source, KeyOrValue keyOrValue) {
                if (source == null) throw new ArgumentNullException("source");

                _internal = source;
                _keyOrValue = keyOrValue;
            }

            public void Add(string item) {
                ThrowNotSupportedException();
            }

            public void Clear() {
                ThrowNotSupportedException();
            }

            public void ThrowNotSupportedException() {
                if( _keyOrValue == KeyOrValue.Key ) {
                    throw new NotSupportedException(SR.GetString(SR.NotSupported_KeyCollectionSet)); //Same as KeyCollection/ValueCollection
                }
                throw new NotSupportedException(SR.GetString(SR.NotSupported_ValueCollectionSet)); //Same as KeyCollection/ValueCollection
            }


            public bool Contains(string item) {
                // The underlying backing store for the StringDictionary is a HashTable so we 
                // want to delegate Contains to respective ContainsKey/ContainsValue functionality 
                // depending upon whether we are using Keys or Value collections.            

                if( _keyOrValue == KeyOrValue.Key ) {
                    return _internal.ContainsKey(item);
                }
                return _internal.ContainsValue(item);
            }

            public void CopyTo(string[] array, int arrayIndex) {
                var collection = GetUnderlyingCollection();
                collection.CopyTo(array, arrayIndex);
            }

            public int Count {
                get {
                    return _internal.Count;  // hashtable count is same as key/value count.
                }
            }

            public bool IsReadOnly {
                get {
                    return true; //Same as KeyCollection/ValueCollection
                }
            }

            public bool Remove(string item) {
                ThrowNotSupportedException();
                return false;
            }

            private ICollection GetUnderlyingCollection() {
                if( _keyOrValue == KeyOrValue.Key ) {
                    return (ICollection) _internal.Keys;
                }
                return (ICollection) _internal.Values;
            }

            public IEnumerator<string> GetEnumerator() {
                ICollection collection = GetUnderlyingCollection();

                // This is doing the same as collection.Cast<string>()
                foreach (string entry in collection) {
                    yield return entry;
                }
            }

            IEnumerator IEnumerable.GetEnumerator() {
                return GetUnderlyingCollection().GetEnumerator();
            }
        }
        #endregion
    }
#endregion
    }
}