fixOrder would recursively fix the ordering issue caused by addChildren, across the entire tree. fixOrder would fix the order from 5 -> 4 -> 3 -> 2 -> 1 to 1 -> 2 -> 3 -> 4 -> 5
(fj fastJsonNode)
| 394 | // 5 -> 4 -> 3 -> 2 -> 1 to |
| 395 | // 1 -> 2 -> 3 -> 4 -> 5 |
| 396 | func (enc *encoder) fixOrder(fj fastJsonNode) { |
| 397 | // If you call this again on the same fastJsonNode, then this would become wrong. Due to |
| 398 | // children being copied over, the same node can be referenced by multiple nodes. Thus, the node |
| 399 | // would be visited again, it would be fixed multiple times, causing ordering issue. |
| 400 | // To avoid this, we keep track of the node by marking it. |
| 401 | if (fj.meta & visitedBit) > 0 { |
| 402 | return |
| 403 | } |
| 404 | enc.setVisited(fj, true) |
| 405 | |
| 406 | tail := fj.child // This is node 5 in the chain mentioned above. |
| 407 | // Edge cases: Child is nil, or only child. |
| 408 | if tail == nil { |
| 409 | return |
| 410 | } |
| 411 | |
| 412 | if tail.next == nil { |
| 413 | enc.fixOrder(tail) |
| 414 | return |
| 415 | } |
| 416 | |
| 417 | left, right := tail, tail.next // Left is 5, right is 4. |
| 418 | left.next = nil // Make left the last child. |
| 419 | for right != nil { |
| 420 | next := right.next // right of ptr2 (points to 3) |
| 421 | right.next = left // ptr2 now points left to ptr1 (4 -> 5) |
| 422 | left, right = right, next // Advance both pointers (left = 4, right = 3 and so on) |
| 423 | } |
| 424 | // left is now pointing to 1. |
| 425 | fj.child = left // Child is now pointed to 1. |
| 426 | |
| 427 | // Now recurse to fix up all children. |
| 428 | child := fj.child |
| 429 | for child != nil { |
| 430 | enc.fixOrder(child) |
| 431 | child = child.next |
| 432 | } |
| 433 | } |
| 434 | |
| 435 | func (enc *encoder) getAttr(fj fastJsonNode) uint16 { |
| 436 | return uint16((fj.meta & setBytes76) >> 40) |