using System; using System.Collections.Generic; using System.Linq; namespace UniJSON { public static class IValueNodeObjectExtensions { public static IEnumerable, ListTreeNode>> ObjectItems(this ListTreeNode self) where T : IListTreeItem, IValue { if (!self.IsMap()) throw new DeserializationException("is not object"); var it = self.Children.GetEnumerator(); while (it.MoveNext()) { var key = it.Current; it.MoveNext(); yield return new KeyValuePair, ListTreeNode>(key, it.Current); } } public static int GetObjectCount(this ListTreeNode self) where T : IListTreeItem, IValue { if (!self.IsMap()) throw new DeserializationException("is not object"); return self.Children.Count() / 2; } public static ListTreeNode GetObjectItem(this ListTreeNode self, String key) where T : IListTreeItem, IValue { return self.GetObjectItem(Utf8String.From(key)); } public static ListTreeNode GetObjectItem(this ListTreeNode self, Utf8String key) where T : IListTreeItem, IValue { foreach (var kv in self.ObjectItems()) { if (kv.Key.GetUtf8String() == key) { return kv.Value; } } throw new KeyNotFoundException(); } public static bool ContainsKey(this ListTreeNode self, Utf8String key) where T : IListTreeItem, IValue { return self.ObjectItems().Any(x => x.Key.GetUtf8String() == key); } public static bool ContainsKey(this ListTreeNode self, String key) where T : IListTreeItem, IValue { var ukey = Utf8String.From(key); return self.ContainsKey(ukey); } public static Utf8String KeyOf(this ListTreeNode self, ListTreeNode node) where T : IListTreeItem, IValue { foreach (var kv in self.ObjectItems()) { if (node.ValueIndex == kv.Value.ValueIndex) { return kv.Key.GetUtf8String(); } } throw new KeyNotFoundException(); } } }