-
Notifications
You must be signed in to change notification settings - Fork 3
/
PyDict.cs
104 lines (90 loc) · 2.99 KB
/
PyDict.cs
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
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Linq;
namespace eveMarshal
{
public class PyDict : PyObject
{
public Dictionary<PyObject, PyObject> Dictionary { get; private set; }
public PyDict()
: base(PyObjectType.Dict)
{
Dictionary = new Dictionary<PyObject, PyObject>();
}
public PyDict(Dictionary<PyObject, PyObject> dict)
: base(PyObjectType.Dict)
{
Dictionary = dict;
}
public PyObject Get(string key)
{
var keyObject =
Dictionary.Keys.Where(k => k.Type == PyObjectType.String && (k as PyString).Value == key).FirstOrDefault();
return keyObject == null ? null : Dictionary[keyObject];
}
public void Set(string key, PyObject value)
{
var keyObject = Dictionary.Count > 0 ? Dictionary.Keys.Where(k => k.Type == PyObjectType.String && (k as PyString).Value == key).FirstOrDefault() : null;
if (keyObject != null)
Dictionary[keyObject] = value;
else
Dictionary.Add(new PyString(key), value);
}
public bool Contains(string key)
{
return Dictionary.Keys.Any(k => k.Type == PyObjectType.String && (k as PyString).Value == key);
}
public override void Decode(Unmarshal context, MarshalOpcode op, BinaryReader source)
{
var entries = source.ReadSizeEx();
Dictionary = new Dictionary<PyObject, PyObject>((int)entries);
for (uint i = 0; i < entries; i++)
{
var value = context.ReadObject(source);
var key = context.ReadObject(source);
Dictionary.Add(key, value);
}
}
protected override void EncodeInternal(BinaryWriter output)
{
output.WriteOpcode(MarshalOpcode.Dict);
output.WriteSizeEx(Dictionary.Count);
foreach (var pair in Dictionary)
{
pair.Value.Encode(output);
pair.Key.Encode(output);
}
}
public PyObject this[PyObject key]
{
get
{
return Dictionary[key];
}
set
{
Dictionary[key] = value;
}
}
public override PyObject this[string key]
{
get
{
return Get(key);
}
set
{
Set(key, value);
}
}
public override string ToString()
{
var sb = new StringBuilder("<\n");
foreach (var pair in Dictionary)
sb.AppendLine("\t" + pair.Key + " " + pair.Value);
sb.Append(">");
return sb.ToString();
}
}
}