|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.Linq; |
| 4 | + |
| 5 | +namespace Python.Runtime |
| 6 | +{ |
| 7 | + static partial class InternString |
| 8 | + { |
| 9 | + private static Dictionary<string, IntPtr> _string2interns; |
| 10 | + private static Dictionary<IntPtr, string> _intern2strings; |
| 11 | + |
| 12 | + static InternString() |
| 13 | + { |
| 14 | + var identifierNames = typeof(PyIdentifier).GetFields().Select(fi => fi.Name); |
| 15 | + var validNames = new HashSet<string>(identifierNames); |
| 16 | + if (validNames.Count != _builtinNames.Length) |
| 17 | + { |
| 18 | + throw new InvalidOperationException("Identifiers args not matching"); |
| 19 | + } |
| 20 | + foreach (var name in _builtinNames) |
| 21 | + { |
| 22 | + if (!validNames.Contains(name)) |
| 23 | + { |
| 24 | + throw new InvalidOperationException($"{name} is not declared"); |
| 25 | + } |
| 26 | + } |
| 27 | + } |
| 28 | + |
| 29 | + public static void Initialize() |
| 30 | + { |
| 31 | + _string2interns = new Dictionary<string, IntPtr>(); |
| 32 | + _intern2strings = new Dictionary<IntPtr, string>(); |
| 33 | + |
| 34 | + Type type = typeof(PyIdentifier); |
| 35 | + foreach (string name in _builtinNames) |
| 36 | + { |
| 37 | + IntPtr op = Runtime.PyUnicode_InternFromString(name); |
| 38 | + SetIntern(name, op); |
| 39 | + type.GetField(name).SetValue(null, op); |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + public static void Shutdown() |
| 44 | + { |
| 45 | + foreach (var ptr in _intern2strings.Keys) |
| 46 | + { |
| 47 | + Runtime.XDecref(ptr); |
| 48 | + } |
| 49 | + _string2interns = null; |
| 50 | + _intern2strings = null; |
| 51 | + } |
| 52 | + |
| 53 | + public static string GetManagedString(IntPtr op) |
| 54 | + { |
| 55 | + string s; |
| 56 | + if (TryGetInterned(op, out s)) |
| 57 | + { |
| 58 | + return s; |
| 59 | + } |
| 60 | + return Runtime.GetManagedString(op); |
| 61 | + } |
| 62 | + |
| 63 | + public static bool TryGetInterned(IntPtr op, out string s) |
| 64 | + { |
| 65 | + return _intern2strings.TryGetValue(op, out s); |
| 66 | + } |
| 67 | + |
| 68 | + private static void SetIntern(string s, IntPtr op) |
| 69 | + { |
| 70 | + _string2interns.Add(s, op); |
| 71 | + _intern2strings.Add(op, s); |
| 72 | + } |
| 73 | + } |
| 74 | +} |
0 commit comments