ListTreeNode.cs 13.2 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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace UniJSON
{
    public struct ListTreeNode<T> : ITreeNode<ListTreeNode<T>, T>
        where T : IListTreeItem, IValue<T>
    {
        public override int GetHashCode()
        {
            return base.GetHashCode();
        }

        public override bool Equals(object obj)
        {
            if (!(obj is ListTreeNode<T>))
            {
                return false;
            }

            var rhs = (ListTreeNode<T>)obj;

            if ((Value.ValueType == ValueNodeType.Integer || Value.ValueType == ValueNodeType.Null)
                && (rhs.Value.ValueType == ValueNodeType.Integer || rhs.Value.ValueType == ValueNodeType.Number))
            {
                // ok
            }
            else if (Value.ValueType != rhs.Value.ValueType)
            {
                return false;
            }

            switch (Value.ValueType)
            {
                case ValueNodeType.Null:
                    return true;

                case ValueNodeType.Boolean:
                    return Value.GetBoolean() == rhs.GetBoolean();

                case ValueNodeType.Integer:
                case ValueNodeType.Number:
                    return Value.GetDouble() == rhs.GetDouble();

                case ValueNodeType.String:
                    return Value.GetString() == rhs.GetString();

                case ValueNodeType.Array:
                    return this.ArrayItems().SequenceEqual(rhs.ArrayItems());

                case ValueNodeType.Object:
                    {
                        //var l = ObjectItems().ToDictionary(x => x.Key, x => x.Value);
                        //var r = rhs.ObjectItems().ToDictionary(x => x.Key, x => x.Value);
                        //return l.Equals(r);
                        return this.ObjectItems().OrderBy(x => x.Key.GetUtf8String()).SequenceEqual(rhs.ObjectItems().OrderBy(x => x.Key.GetUtf8String()));
                    }
            }

            return false;
        }

        public override string ToString()
        {
            if (this.IsArray())
            {
                var sb = new StringBuilder();
                sb.Append("[");
                /*
                bool isFirst = true;
                foreach (var x in this.ArrayItems())
                {
                    if (isFirst)
                    {
                        isFirst = false;
                    }
                    else
                    {
                        sb.Append(",");
                    }
                    sb.Append(x.ToString());                    
                }
                */
                sb.Append("]");
                return sb.ToString();
            }
            else if (this.IsMap())
            {
                var sb = new StringBuilder();
                sb.Append("{");
                /*
                bool isFirst = true;
                foreach (var kv in this.ObjectItems())
                {
                    if (isFirst)
                    {
                        isFirst = false;
                    }
                    else
                    {
                        sb.Append(",");
                    }
                    sb.Append(kv.Key.ToString());
                    sb.Append(": ");
                    sb.Append(kv.Value.ToString());
                }
                */
                sb.Append("}");
                return sb.ToString();
            }
            else
            {
                return Value.ToString();
            }
        }

        IEnumerable<string> ToString(string indent, int level, bool value = false)
        {
            if (this.IsArray())
            {
                if (!value) for (int i = 0; i < level; ++i) yield return indent;
                yield return "[\n";

                var isFirst = true;
                var childLevel = level + 1;
                foreach (var x in this.ArrayItems())
                {
                    if (isFirst)
                    {
                        isFirst = false;
                    }
                    else
                    {
                        yield return ",\n";
                    }

                    foreach (var y in x.ToString(indent, childLevel))
                    {
                        yield return y;
                    }
                }
                if (!isFirst)
                {
                    yield return "\n";
                }

                for (int i = 0; i < level; ++i) yield return indent;
                yield return "]";
            }
            else if (this.IsMap())
            {
                if (!value) for (int i = 0; i < level; ++i) yield return indent;
                yield return "{\n";

                var isFirst = true;
                var childLevel = level + 1;
                foreach (var kv in this.ObjectItems())
                {
                    if (isFirst)
                    {
                        isFirst = false;
                    }
                    else
                    {
                        yield return ",\n";
                    }

                    // key
                    for (int i = 0; i < childLevel; ++i) yield return indent;
                    yield return kv.Key.ToString();
                    yield return ": ";

                    foreach (var y in kv.Value.ToString(indent, childLevel, true))
                    {
                        yield return y;
                    }
                }
                if (!isFirst)
                {
                    yield return "\n";
                }

                for (int i = 0; i < level; ++i) yield return indent;
                yield return "}";
            }
            else
            {
                if (!value) for (int i = 0; i < level; ++i) yield return indent;
                yield return Value.ToString();
            }
        }

        public string ToString(string indent)
        {
            return string.Join("", ToString(indent, 0).ToArray());
        }

        public IEnumerable<JsonDiff> Diff(ListTreeNode<T> rhs, JsonPointer path = default(JsonPointer))
        {
            switch (Value.ValueType)
            {
                case ValueNodeType.Null:
                case ValueNodeType.Boolean:
                case ValueNodeType.Number:
                case ValueNodeType.Integer:
                case ValueNodeType.String:
                    if (!Equals(rhs))
                    {
                        yield return JsonDiff.Create(this, JsonDiffType.ValueChanged, string.Format("{0} => {1}", Value, rhs.Value));
                    }
                    yield break;
            }

            if (Value.ValueType != rhs.Value.ValueType)
            {
                yield return JsonDiff.Create(this, JsonDiffType.ValueChanged, string.Format("{0} => {1}", Value.ValueType, rhs.Value));
                yield break;
            }

            if (Value.ValueType == ValueNodeType.Object)
            {

                var l = this.ObjectItems().ToDictionary(x => x.Key, x => x.Value);
                var r = rhs.ObjectItems().ToDictionary(x => x.Key, x => x.Value);

                foreach (var kv in l)
                {
                    ListTreeNode<T> x;
                    if (r.TryGetValue(kv.Key, out x))
                    {
                        r.Remove(kv.Key);
                        // Found
                        foreach (var y in kv.Value.Diff(x))
                        {
                            yield return y;
                        }
                    }
                    else
                    {
                        // Removed
                        yield return JsonDiff.Create(kv.Value, JsonDiffType.KeyRemoved, kv.Value.Value.ToString());
                    }
                }

                foreach (var kv in r)
                {
                    // Addded
                    yield return JsonDiff.Create(kv.Value, JsonDiffType.KeyAdded, kv.Value.Value.ToString());
                }
            }
            else if (Value.ValueType == ValueNodeType.Array)
            {
                var ll = this.ArrayItems().GetEnumerator();
                var rr = rhs.ArrayItems().GetEnumerator();
                while (true)
                {
                    var lll = ll.MoveNext();
                    var rrr = rr.MoveNext();
                    if (lll && rrr)
                    {
                        // found
                        foreach (var y in ll.Current.Diff(rr.Current))
                        {
                            yield return y;
                        }
                    }
                    else if (lll)
                    {
                        yield return JsonDiff.Create(ll.Current, JsonDiffType.KeyRemoved, ll.Current.Value.ToString());
                    }
                    else if (rrr)
                    {
                        yield return JsonDiff.Create(rr.Current, JsonDiffType.KeyAdded, rr.Current.Value.ToString());
                    }
                    else
                    {
                        // end
                        break;
                    }
                }
            }
            else
            {
                throw new NotImplementedException();
            }
        }

        /// <summary>
        /// Whole tree nodes
        /// </summary>
        List<T> m_Values;
        public bool IsValid
        {
            get
            {
                return m_Values != null;
            }
        }

        /// <summary>
        /// This node index
        /// </summary>
        int _valueIndex;
        public int ValueIndex
        {
            get
            {
                if (m_Values == null) return -1;
                return _valueIndex;
            }
        }

        public ListTreeNode<T> Prev
        {
            get
            {
                return new ListTreeNode<T>(m_Values, ValueIndex - 1);
            }
        }

        public T Value
        {
            get
            {
                if (m_Values == null)
                {
                    return default(T);
                }
                return m_Values[ValueIndex];
            }
        }
        public void SetValue(T value)
        {
            m_Values[ValueIndex] = value;
        }

        #region Children
        public int ChildCount
        {
            get { return Value.ChildCount; }
        }

        public IEnumerable<ListTreeNode<T>> Children
        {
            get
            {
                int count = 0;
                for (int i = ValueIndex; count < ChildCount && i < m_Values.Count; ++i)
                {
                    if (m_Values[i].ParentIndex == ValueIndex)
                    {
                        ++count;
                        yield return new ListTreeNode<T>(m_Values, i);
                    }
                }
            }
        }

        public ListTreeNode<T> this[String key]
        {
            get
            {
                return this[Utf8String.From(key)];
            }
        }

        public ListTreeNode<T> this[Utf8String key]
        {
            get
            {
                return this.GetObjectItem(key);
            }
        }

        public ListTreeNode<T> this[int index]
        {
            get
            {
                return this.GetArrrayItem(index);
            }
        }
        #endregion
        public bool HasParent
        {
            get
            {
                return Value.ParentIndex >= 0 && Value.ParentIndex < m_Values.Count;
            }
        }
        public ListTreeNode<T> Parent
        {
            get
            {
                if (Value.ParentIndex < 0)
                {
                    throw new Exception("no parent");
                }
                if (Value.ParentIndex >= m_Values.Count)
                {
                    throw new IndexOutOfRangeException();
                }
                return new ListTreeNode<T>(m_Values, Value.ParentIndex);
            }
        }

        public ListTreeNode(List<T> values, int index = 0) : this()
        {
            m_Values = values;
            _valueIndex = index;
        }

        #region JsonPointer
        public ListTreeNode<T> AddKey(Utf8String key)
        {
            return AddValue(default(T).Key(key, ValueIndex));
        }

        public ListTreeNode<T> AddValue(ArraySegment<byte> bytes, ValueNodeType valueType)
        {
            return AddValue(default(T).New(bytes, valueType, ValueIndex));
        }

        public ListTreeNode<T> AddValue(T value)
        {
            if (m_Values == null)
            {
                // initialize empty tree
                m_Values = new List<T>();
                _valueIndex = -1;
            }
            else
            {
                IncrementChildCount();
            }
            var index = m_Values.Count;
            m_Values.Add(value);
            return new ListTreeNode<T>(m_Values, index);
        }

        void IncrementChildCount()
        {
            var value = Value;
            value.SetChildCount(value.ChildCount + 1);
            SetValue(value);
        }

        public void SetValueBytesCount(int count)
        {
            var value = Value;
            value.SetBytesCount(count);
            SetValue(value);
        }
        #endregion
    }
}