-
Notifications
You must be signed in to change notification settings - Fork 310
Expand file tree
/
Copy pathPythonDictionary.cs
More file actions
1837 lines (1457 loc) · 62.5 KB
/
PythonDictionary.cs
File metadata and controls
1837 lines (1457 loc) · 62.5 KB
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
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Security;
using System.Text;
using Microsoft.Scripting;
using Microsoft.Scripting.Runtime;
using IronPython.Runtime.Operations;
using IronPython.Runtime.Types;
namespace IronPython.Runtime {
[PythonType("dict"), Serializable, DebuggerTypeProxy(typeof(DebugProxy)), DebuggerDisplay("Count = {Count}")]
public class PythonDictionary : IDictionary<object, object>, IDictionary,
ICodeFormattable, IStructuralEquatable {
internal DictionaryStorage _storage;
internal static object MakeDict(CodeContext/*!*/ context, PythonType cls) {
if (cls == TypeCache.Dict) {
return new PythonDictionary();
}
return PythonCalls.Call(context, cls);
}
#region Constructors
public PythonDictionary() {
_storage = EmptyDictionaryStorage.Instance;
}
internal PythonDictionary(DictionaryStorage storage) {
_storage = storage;
}
internal PythonDictionary(IDictionary dict) {
var storage = new CommonDictionaryStorage();
foreach (DictionaryEntry de in dict) {
storage.AddNoLock(de.Key, de.Value);
}
_storage = storage;
}
internal PythonDictionary(IDictionary<object, object> dict) {
var storage = new CommonDictionaryStorage();
foreach (var pair in dict) {
storage.AddNoLock(pair.Key, pair.Value);
}
_storage = storage;
}
internal PythonDictionary(PythonDictionary dict) {
_storage = dict._storage.Clone();
}
internal PythonDictionary(CodeContext/*!*/ context, object o)
: this() {
update(context, o);
}
internal PythonDictionary(int size) {
_storage = size == 0 ? (DictionaryStorage)EmptyDictionaryStorage.Instance : new CommonDictionaryStorage(size);
}
internal static PythonDictionary FromIAC(CodeContext context, PythonDictionary iac) {
return iac.GetType() == typeof(PythonDictionary) ? iac : MakeDictFromIAC(context, iac);
}
internal static PythonDictionary MakeDictFromIAC(CodeContext context, object iac) {
return new PythonDictionary(new ObjectAttributesAdapter(context, iac));
}
internal static PythonDictionary MakeSymbolDictionary() {
return new PythonDictionary(new StringDictionaryStorage());
}
internal static PythonDictionary MakeSymbolDictionary(int count) {
return new PythonDictionary(new StringDictionaryStorage(count));
}
public void __init__(CodeContext/*!*/ context, object o\u00F8, [ParamDictionary] IDictionary<object, object> kwArgs) {
update(context, o\u00F8);
update(context, kwArgs);
}
public void __init__(CodeContext/*!*/ context, [ParamDictionary] IDictionary<object, object> kwArgs) {
update(context, kwArgs);
}
public void __init__(CodeContext/*!*/ context, object o\u00F8) {
update(context, o\u00F8);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")]
public void __init__() {
}
#endregion
#region IDictionary<object,object> Members
[PythonHidden]
public void Add(object key, object value) {
_storage.Add(ref _storage, key, value);
}
[PythonHidden]
public bool ContainsKey(object key) {
return _storage.Contains(key);
}
[PythonHidden]
public ICollection<object> Keys {
// Convert to an array since keys() is slow to iterate over in most of the cases where we use this
get { return _storage.GetKeys().ToArray(); }
}
[PythonHidden]
public bool Remove(object key) {
try {
__delitem__(key);
return true;
} catch (KeyNotFoundException) {
return false;
}
}
[PythonHidden]
public bool RemoveDirect(object key) {
// Directly remove the value, without calling __delitem__
// This is used to implement pop() in a manner consistent with CPython, which does
// not call __delitem__ on pop().
return _storage.Remove(ref _storage, key);
}
[PythonHidden]
public bool TryGetValue(object key, out object value) {
if (_storage.TryGetValue(key, out value)) {
return true;
}
// we need to manually look up a slot to get the correct behavior when
// the __missing__ function is declared on a sub-type which is an old-class
if (GetType() != typeof(PythonDictionary) &&
PythonTypeOps.TryInvokeBinaryOperator(DefaultContext.Default, this, key, "__missing__", out value)) {
return true;
}
return false;
}
internal bool TryGetValueNoMissing(object key, out object value) {
return _storage.TryGetValue(key, out value);
}
public ICollection<object> Values {
[PythonHidden]
get { return values(); }
}
#endregion
#region ICollection<KeyValuePair<object,object>> Members
[PythonHidden]
public void Add(KeyValuePair<object, object> item) {
_storage.Add(ref _storage, item.Key, item.Value);
}
[PythonHidden]
public void Clear() {
_storage.Clear(ref _storage);
}
[PythonHidden]
public bool Contains(KeyValuePair<object, object> item) {
object result;
return _storage.TryGetValue(item.Key, out result) && PythonOps.IsOrEqualsRetBool(result, item.Value);
}
[PythonHidden]
public void CopyTo(KeyValuePair<object, object>[] array, int arrayIndex) {
_storage.GetItems().CopyTo(array, arrayIndex);
}
public int Count {
[PythonHidden]
get { return _storage.Count; }
}
bool ICollection<KeyValuePair<object, object>>.IsReadOnly {
get { return false; }
}
[PythonHidden]
public bool Remove(KeyValuePair<object, object> item) {
return _storage.Remove(ref _storage, item.Key);
}
#endregion
#region IEnumerable<KeyValuePair<object,object>> Members
[PythonHidden]
public IEnumerator<KeyValuePair<object, object>> GetEnumerator() {
foreach (KeyValuePair<object, object> kvp in _storage.GetItems()) {
yield return kvp;
}
}
#endregion
#region IEnumerable Members
IEnumerator IEnumerable.GetEnumerator() {
return Converter.ConvertToIEnumerator(__iter__());
}
public virtual object __iter__() {
return new DictionaryKeyEnumerator(_storage);
}
#endregion
#region IMapping Members
public object get(object key) {
return DictionaryOps.get(this, key);
}
public object get(object key, object defaultValue) {
return DictionaryOps.get(this, key, defaultValue);
}
public virtual object this[params object[] key] {
get {
if (key == null) {
return GetItem(null);
}
if (key.Length == 0) {
throw PythonOps.TypeError("__getitem__() takes exactly one argument (0 given)");
}
return this[PythonTuple.MakeTuple(key)];
}
set {
if (key == null) {
SetItem(null, value);
return;
}
if (key.Length == 0) {
throw PythonOps.TypeError("__setitem__() takes exactly two argument (1 given)");
}
this[PythonTuple.MakeTuple(key)] = value;
}
}
public virtual object this[object key] {
get {
return GetItem(key);
}
set {
SetItem(key, value);
}
}
internal void SetItem(object key, object value) {
_storage.Add(ref _storage, key, value);
}
private object GetItem(object key) {
object ret;
if (TryGetValue(key, out ret)) {
return ret;
}
throw PythonOps.KeyError(key);
}
public virtual void __delitem__(object key) {
if (!RemoveDirect(key)) {
throw PythonOps.KeyError(key);
}
}
public virtual void __delitem__(params object[] key) {
if (key == null) {
__delitem__((object)null);
} else if (key.Length > 0) {
__delitem__(PythonTuple.MakeTuple(key));
} else {
throw PythonOps.TypeError("__delitem__() takes exactly one argument (0 given)");
}
}
#endregion
#region IPythonContainer Members
public virtual int __len__() {
return Count;
}
#endregion
#region Python dict implementation
public void clear() {
_storage.Clear(ref _storage);
}
public object pop(object key) {
return DictionaryOps.pop(this, key);
}
public object pop(object key, object defaultValue) {
return DictionaryOps.pop(this, key, defaultValue);
}
public PythonTuple popitem() {
return DictionaryOps.popitem(this);
}
public object setdefault(object key) {
return DictionaryOps.setdefault(this, key);
}
public object setdefault(object key, object defaultValue) {
return DictionaryOps.setdefault(this, key, defaultValue);
}
public DictionaryItemView items() => new DictionaryItemView(this);
public DictionaryKeyView keys() => new DictionaryKeyView(this);
public DictionaryValueView values() => new DictionaryValueView(this);
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")]
public void update() { }
public void update(CodeContext/*!*/ context, [ParamDictionary] IDictionary<object, object> other\u00F8) {
DictionaryOps.update(context, this, other\u00F8);
}
public void update(CodeContext/*!*/ context, object other\u00F8) {
DictionaryOps.update(context, this, other\u00F8);
}
public void update(CodeContext/*!*/ context, object other\u00F8, [ParamDictionary] IDictionary<object, object> otherArgs\u00F8) {
DictionaryOps.update(context, this, other\u00F8);
DictionaryOps.update(context, this, otherArgs\u00F8);
}
private static object fromkeysAny(CodeContext/*!*/ context, PythonType cls, object o, object value) {
PythonDictionary pyDict;
object dict;
if (cls == TypeCache.Dict) {
string str;
// creating our own dict, try and get the ideal size and add w/o locks
if (o is ICollection ic) {
pyDict = new PythonDictionary(new CommonDictionaryStorage(ic.Count));
} else if ((str = o as string) != null) {
pyDict = new PythonDictionary(str.Length);
} else {
pyDict = new PythonDictionary();
}
IEnumerator i = PythonOps.GetEnumerator(o);
while (i.MoveNext()) {
pyDict._storage.AddNoLock(ref pyDict._storage, i.Current, value);
}
return pyDict;
} else {
// call the user type constructor
dict = MakeDict(context, cls);
pyDict = dict as PythonDictionary;
}
if (pyDict != null) {
// then store all the keys with their associated value
IEnumerator i = PythonOps.GetEnumerator(o);
while (i.MoveNext()) {
pyDict[i.Current] = value;
}
} else {
// slow path, cls.__new__ returned a user defined dictionary instead of a PythonDictionary.
PythonContext pc = context.LanguageContext;
IEnumerator i = PythonOps.GetEnumerator(o);
while (i.MoveNext()) {
pc.SetIndex(dict, i.Current, value);
}
}
return dict;
}
[ClassMethod]
public static object fromkeys(CodeContext context, PythonType cls, object seq) {
return fromkeys(context, cls, seq, null);
}
[ClassMethod]
public static object fromkeys(CodeContext context, PythonType cls, object seq, object value) {
if (seq is PythonRange xr) {
int n = xr.__len__();
object ret = context.LanguageContext.CallSplat(cls);
if (ret.GetType() == typeof(PythonDictionary)) {
PythonDictionary dr = ret as PythonDictionary;
for (int i = 0; i < n; i++) {
dr[xr[i]] = value;
}
} else {
// slow path, user defined dict
PythonContext pc = context.LanguageContext;
for (int i = 0; i < n; i++) {
pc.SetIndex(ret, xr[i], value);
}
}
return ret;
}
return fromkeysAny(context, cls, seq, value);
}
public virtual PythonDictionary copy(CodeContext/*!*/ context) {
return new PythonDictionary(_storage.Clone());
}
public virtual bool __contains__(object key) {
return _storage.Contains(key);
}
// Dictionary has an odd not-implemented check to support custom dictionaries and therefore
// needs a custom __eq__ / __ne__ implementation.
[return: MaybeNotImplemented]
public object __eq__(CodeContext/*!*/ context, object other) {
if (!(other is PythonDictionary || other is IDictionary<object, object>))
return NotImplementedType.Value;
return ScriptingRuntimeHelpers.BooleanToObject(
((IStructuralEquatable)this).Equals(other, context.LanguageContext.EqualityComparerNonGeneric)
);
}
[return: MaybeNotImplemented]
public object __ne__(CodeContext/*!*/ context, object other) {
if (!(other is PythonDictionary || other is IDictionary<object, object>))
return NotImplementedType.Value;
return ScriptingRuntimeHelpers.BooleanToObject(
!((IStructuralEquatable)this).Equals(other, context.LanguageContext.EqualityComparerNonGeneric)
);
}
[return: MaybeNotImplemented]
public NotImplementedType __gt__(CodeContext context, object other) => NotImplementedType.Value;
[return: MaybeNotImplemented]
public NotImplementedType __lt__(CodeContext context, object other) => NotImplementedType.Value;
[return: MaybeNotImplemented]
public NotImplementedType __ge__(CodeContext context, object other) => NotImplementedType.Value;
[return: MaybeNotImplemented]
public NotImplementedType __le__(CodeContext context, object other) => NotImplementedType.Value;
#endregion
#region IStructuralEquatable Members
public const object __hash__ = null;
int IStructuralEquatable.GetHashCode(IEqualityComparer comparer) {
if (CompareUtil.Check(this)) {
return 0;
}
int res;
SetStorage pairs = new SetStorage();
foreach (KeyValuePair<object, object> kvp in _storage.GetItems()) {
pairs.AddNoLock(PythonTuple.MakeTuple(kvp.Key, kvp.Value));
}
CompareUtil.Push(this);
try {
IStructuralEquatable eq = FrozenSetCollection.Make(pairs);
res = eq.GetHashCode(comparer);
} finally {
CompareUtil.Pop(this);
}
return res;
}
bool IStructuralEquatable.Equals(object other, IEqualityComparer comparer) {
return EqualsWorker(other, comparer);
}
private bool EqualsWorker(object other, IEqualityComparer comparer) {
if (Object.ReferenceEquals(this, other)) return true;
if (!(other is IDictionary<object, object> oth)) return false;
if (oth.Count != Count) return false;
if (other is PythonDictionary pd) {
return ValueEqualsPythonDict(pd, comparer);
}
// we cannot call Compare here and compare against zero because Python defines
// value equality even if the keys/values are unordered.
foreach (object o in keys()) {
object res;
if (!oth.TryGetValue(o, out res)) return false;
CompareUtil.Push(res);
try {
var val = this[o];
if (comparer == null) {
if (!PythonOps.IsOrEqualsRetBool(res, val)) return false;
} else {
if (!ReferenceEquals(res, val) && !comparer.Equals(res, val)) return false;
}
} finally {
CompareUtil.Pop(res);
}
}
return true;
}
private bool ValueEqualsPythonDict(PythonDictionary pd, IEqualityComparer comparer) {
foreach (object o in keys()) {
object res;
if (!pd.TryGetValueNoMissing(o, out res)) return false;
CompareUtil.Push(res);
try {
var val = this[o];
if (comparer == null) {
if (!PythonOps.IsOrEqualsRetBool(res, val)) return false;
} else {
if (!ReferenceEquals(res, val) && !comparer.Equals(res, val)) return false;
}
} finally {
CompareUtil.Pop(res);
}
}
return true;
}
#endregion
#region IDictionary Members
[PythonHidden]
public bool Contains(object key) {
return __contains__(key);
}
internal class DictEnumerator : IDictionaryEnumerator {
private readonly IEnumerator<KeyValuePair<object, object>> _enumerator;
private bool _moved;
public DictEnumerator(IEnumerator<KeyValuePair<object, object>> enumerator) {
_enumerator = enumerator;
}
#region IDictionaryEnumerator Members
public DictionaryEntry Entry {
get {
// PythonList<T> enumerator doesn't throw, so we need to.
if (!_moved) throw new InvalidOperationException();
return new DictionaryEntry(_enumerator.Current.Key, _enumerator.Current.Value);
}
}
public object Key {
get { return Entry.Key; }
}
public object Value {
get { return Entry.Value; }
}
#endregion
#region IEnumerator Members
public object Current {
get { return Entry; }
}
public bool MoveNext() {
if (_enumerator.MoveNext()) {
_moved = true;
return true;
}
_moved = false;
return false;
}
public void Reset() {
_enumerator.Reset();
_moved = false;
}
#endregion
}
IDictionaryEnumerator IDictionary.GetEnumerator() {
return new DictEnumerator(_storage.GetItems().GetEnumerator());
}
bool IDictionary.IsFixedSize {
get { return false; }
}
bool IDictionary.IsReadOnly {
get { return false; }
}
ICollection IDictionary.Keys {
get { return keys(); }
}
ICollection IDictionary.Values {
get { return values(); }
}
void IDictionary.Remove(object key) {
((IDictionary<object, object>)this).Remove(key);
}
#endregion
#region ICollection Members
void ICollection.CopyTo(Array array, int index) {
throw new NotImplementedException("The method or operation is not implemented.");
}
bool ICollection.IsSynchronized {
get { return false; }
}
object ICollection.SyncRoot {
get { return null; }
}
#endregion
#region ICodeFormattable Members
public virtual string/*!*/ __repr__(CodeContext/*!*/ context) {
return DictionaryOps.__repr__(context, this);
}
#endregion
internal bool TryRemoveValue(object key, out object value) {
return _storage.TryRemoveValue(ref _storage, key, out value);
}
/// <summary>
/// If __iter__ is overridden then we should treat the dict as a mapping.
/// </summary>
internal bool TreatAsMapping => GetType() != typeof(PythonDictionary) && ((Func<object>)__iter__).Method.DeclaringType != typeof(PythonDictionary);
#region Debugger View
internal class DebugProxy {
private readonly PythonDictionary _dict;
public DebugProxy(PythonDictionary dict) {
_dict = dict;
}
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public List<KeyValueDebugView> Members {
get {
var res = new List<KeyValueDebugView>();
foreach (var v in _dict) {
res.Add(new KeyValueDebugView(v.Key, v.Value));
}
return res;
}
}
}
[DebuggerDisplay("{Value}", Name = "{Key,nq}", Type = "{TypeInfo,nq}")]
internal class KeyValueDebugView {
public readonly object Key;
public readonly object Value;
public KeyValueDebugView(object key, object value) {
Key = key;
Value = value;
}
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
public string TypeInfo {
get {
#pragma warning disable IPY04 // Direct call to PythonTypeOps.GetName
return "Key: " + PythonTypeOps.GetName(Key) + ", " + "Value: " + PythonTypeOps.GetName(Value);
#pragma warning restore IPY04
}
}
}
#endregion
}
#if FEATURE_PROCESS
[Serializable]
internal sealed class EnvironmentDictionaryStorage : DictionaryStorage {
private readonly CommonDictionaryStorage/*!*/ _storage = new CommonDictionaryStorage();
public EnvironmentDictionaryStorage() {
AddEnvironmentVars();
}
private void AddEnvironmentVars() {
try {
foreach (DictionaryEntry de in Environment.GetEnvironmentVariables()) {
_storage.Add(de.Key, de.Value);
}
} catch (SecurityException) {
// environment isn't available under partial trust
}
}
public override void Add(ref DictionaryStorage storage, object key, object value) {
_storage.Add(key, value);
if (key is string s1 && value is string s2) {
Environment.SetEnvironmentVariable(s1, s2);
}
}
public override bool Remove(ref DictionaryStorage storage, object key) {
bool res = _storage.Remove(key);
if (key is string s) {
Environment.SetEnvironmentVariable(s, string.Empty);
}
return res;
}
/// <summary>
/// Since <see cref="EnvironmentDictionaryStorage"/> is always mutable, this is a no-op.
/// </summary>
/// <param name="storage">Ignored.</param>
/// <returns><c>this</c></returns>
public override DictionaryStorage AsMutable(ref DictionaryStorage storage) => this;
public override bool Contains(object key) {
return _storage.Contains(key);
}
public override bool TryGetValue(object key, out object value) {
return _storage.TryGetValue(key, out value);
}
public override int Count {
get { return _storage.Count; }
}
public override void Clear(ref DictionaryStorage storage) {
foreach (var x in GetItems()) {
if (x.Key is string key) {
Environment.SetEnvironmentVariable(key, string.Empty);
}
}
_storage.Clear(ref storage);
}
public override List<KeyValuePair<object, object>> GetItems() {
return _storage.GetItems();
}
}
#endif
/// <summary>
/// Note:
/// IEnumerator innerEnum = Dictionary<K,V>.KeysCollections.GetEnumerator();
/// innerEnum.MoveNext() will throw InvalidOperation even if the values get changed,
/// which is supported in python
/// </summary>
[PythonType("dict_keyiterator")]
public sealed class DictionaryKeyEnumerator : IEnumerator<object> {
private readonly int _size;
private readonly DictionaryStorage _dict;
private readonly IEnumerator<object> _keys;
private int _pos;
internal DictionaryKeyEnumerator(DictionaryStorage dict) {
_dict = dict;
_size = dict.Count;
_keys = dict.GetKeys().GetEnumerator();
_pos = -1;
}
bool IEnumerator.MoveNext() {
if (_size != _dict.Count) {
_pos = _size - 1; // make the length 0
throw PythonOps.RuntimeError("dictionary changed size during iteration");
}
if (_keys.MoveNext()) {
_pos++;
return true;
} else {
return false;
}
}
void IEnumerator.Reset() {
_keys.Reset();
_pos = -1;
}
object IEnumerator<object>.Current => _keys.Current;
object IEnumerator.Current => _keys.Current;
void IDisposable.Dispose() { }
public object __iter__() => this;
public int __length_hint__() => _size - _pos - 1;
#region Pickling
public object __reduce__(CodeContext context) {
object iter;
context.TryLookupBuiltin("iter", out iter);
return PythonTuple.MakeTuple(iter, PythonTuple.MakeTuple(PythonList.FromArrayNoCopy(_dict.GetKeys().Skip(_pos + 1).ToArray())));
}
#endregion
}
/// <summary>
/// Note:
/// IEnumerator innerEnum = Dictionary<K,V>.KeysCollections.GetEnumerator();
/// innerEnum.MoveNext() will throw InvalidOperation even if the values get changed,
/// which is supported in python
/// </summary>
[PythonType("dict_valueiterator")]
public sealed class DictionaryValueEnumerator : IEnumerator<object> {
private readonly int _size;
private readonly DictionaryStorage _dict;
private readonly object[] _values;
private int _pos;
internal DictionaryValueEnumerator(DictionaryStorage dict) {
_dict = dict;
_size = dict.Count;
_values = new object[_size];
int i = 0;
foreach (KeyValuePair<object, object> kvp in dict.GetItems()) {
_values[i++] = kvp.Value;
}
_pos = -1;
}
bool IEnumerator.MoveNext() {
if (_size != _dict.Count) {
_pos = _size - 1; // make the length 0
throw PythonOps.RuntimeError("dictionary changed size during iteration");
}
if (_pos + 1 < _size) {
_pos++;
return true;
} else {
return false;
}
}
void IEnumerator.Reset() {
_pos = -1;
}
object IEnumerator<object>.Current => _values[_pos];
object IEnumerator.Current => _values[_pos];
void IDisposable.Dispose() { }
public object __iter__() => this;
public int __len__() => _size - _pos - 1;
#region Pickling
public object __reduce__(CodeContext context) {
object iter;
context.TryLookupBuiltin("iter", out iter);
return PythonTuple.MakeTuple(iter, PythonTuple.MakeTuple(PythonList.FromArrayNoCopy(_dict.GetItems().Skip(_pos + 1).Select(x => x.Value).ToArray())));
}
#endregion
}
/// <summary>
/// Note:
/// IEnumerator innerEnum = Dictionary<K,V>.KeysCollections.GetEnumerator();
/// innerEnum.MoveNext() will throw InvalidOperation even if the values get changed,
/// which is supported in python
/// </summary>
[PythonType("dict_itemiterator")]
public sealed class DictionaryItemEnumerator : IEnumerator<object> {
private readonly int _size;
private readonly DictionaryStorage _dict;
private readonly List<object> _keys;
private readonly List<object> _values;
private int _pos;
internal DictionaryItemEnumerator(DictionaryStorage dict) {
_dict = dict;
_keys = new List<object>(dict.Count);
_values = new List<object>(dict.Count);
foreach (KeyValuePair<object, object> kvp in dict.GetItems()) {
_keys.Add(kvp.Key);
_values.Add(kvp.Value);
}
_size = _values.Count;
_pos = -1;
}
bool IEnumerator.MoveNext() {
if (_size != _dict.Count) {
_pos = _size - 1; // make the length 0
throw PythonOps.RuntimeError("dictionary changed size during iteration");
}
if (_pos + 1 < _size) {
_pos++;
return true;
} else {
return false;
}
}
void IEnumerator.Reset() {
_pos = -1;
}
object IEnumerator<object>.Current => PythonTuple.MakeTuple(_keys[_pos], _values[_pos]);
object IEnumerator.Current => PythonTuple.MakeTuple(_keys[_pos], _values[_pos]);
void IDisposable.Dispose() { }
public object __iter__() => this;
public int __len__() => _size - _pos - 1;
#region Pickling
public object __reduce__(CodeContext context) {
object iter;
context.TryLookupBuiltin("iter", out iter);
return PythonTuple.MakeTuple(iter, PythonTuple.MakeTuple(PythonList.FromArrayNoCopy(_dict.GetItems().Skip(_pos + 1).Select(x => x.Value).ToArray())));
}
#endregion
}
[PythonType("dict_values")]
public sealed class DictionaryValueView : ICollection<object>, ICollection, ICodeFormattable {
private readonly PythonDictionary _dict;
internal DictionaryValueView(PythonDictionary/*!*/ dict) {
Debug.Assert(dict != null);
_dict = dict;
}
IEnumerator<object> IEnumerable<object>.GetEnumerator() => new DictionaryValueEnumerator(_dict._storage);
IEnumerator IEnumerable.GetEnumerator() => new DictionaryValueEnumerator(_dict._storage);