github.com/goshafaq/sonic@v0.0.0-20231026082336-871835fb94c6/ast/node.go (about) 1 /* 2 * Copyright 2021 ByteDance Inc. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package ast 18 19 import ( 20 "encoding/json" 21 "fmt" 22 "strconv" 23 "unsafe" 24 25 "github.com/goshafaq/sonic/internal/native/types" 26 "github.com/goshafaq/sonic/internal/rt" 27 ) 28 29 const ( 30 _V_NONE types.ValueType = 0 31 _V_NODE_BASE types.ValueType = 1 << 5 32 _V_LAZY types.ValueType = 1 << 7 33 _V_RAW types.ValueType = 1 << 8 34 _V_NUMBER = _V_NODE_BASE + 1 35 _V_ANY = _V_NODE_BASE + 2 36 _V_ARRAY_LAZY = _V_LAZY | types.V_ARRAY 37 _V_OBJECT_LAZY = _V_LAZY | types.V_OBJECT 38 _MASK_LAZY = _V_LAZY - 1 39 _MASK_RAW = _V_RAW - 1 40 ) 41 42 const ( 43 V_NONE = 0 44 V_ERROR = 1 45 V_NULL = int(types.V_NULL) 46 V_TRUE = int(types.V_TRUE) 47 V_FALSE = int(types.V_FALSE) 48 V_ARRAY = int(types.V_ARRAY) 49 V_OBJECT = int(types.V_OBJECT) 50 V_STRING = int(types.V_STRING) 51 V_NUMBER = int(_V_NUMBER) 52 V_ANY = int(_V_ANY) 53 ) 54 55 type Node struct { 56 t types.ValueType 57 l uint 58 p unsafe.Pointer 59 } 60 61 // UnmarshalJSON is just an adapter to json.Unmarshaler. 62 // If you want better performance, use Searcher.GetByPath() directly 63 func (self *Node) UnmarshalJSON(data []byte) (err error) { 64 *self = NewRaw(string(data)) 65 return self.Check() 66 } 67 68 /** Node Type Accessor **/ 69 70 // Type returns json type represented by the node 71 // It will be one of belows: 72 // 73 // V_NONE = 0 (empty node, key not exists) 74 // V_ERROR = 1 (error node) 75 // V_NULL = 2 (json value `null`, key exists) 76 // V_TRUE = 3 (json value `true`) 77 // V_FALSE = 4 (json value `false`) 78 // V_ARRAY = 5 (json value array) 79 // V_OBJECT = 6 (json value object) 80 // V_STRING = 7 (json value string) 81 // V_NUMBER = 33 (json value number ) 82 // V_ANY = 34 (golang interface{}) 83 func (self Node) Type() int { 84 return int(self.t & _MASK_LAZY & _MASK_RAW) 85 } 86 87 func (self Node) itype() types.ValueType { 88 return self.t & _MASK_LAZY & _MASK_RAW 89 } 90 91 // Exists returns false only if the self is nil or empty node V_NONE 92 func (self *Node) Exists() bool { 93 return self.Valid() && self.t != _V_NONE 94 } 95 96 // Valid reports if self is NOT V_ERROR or nil 97 func (self *Node) Valid() bool { 98 if self == nil { 99 return false 100 } 101 return self.t != V_ERROR 102 } 103 104 // Check checks if the node itself is valid, and return: 105 // - ErrNotExist If the node is nil 106 // - Its underlying error If the node is V_ERROR 107 func (self *Node) Check() error { 108 if self == nil { 109 return ErrNotExist 110 } else if self.t != V_ERROR { 111 return nil 112 } else { 113 return self 114 } 115 } 116 117 // IsRaw returns true if node's underlying value is raw json 118 func (self Node) IsRaw() bool { 119 return self.t&_V_RAW != 0 120 } 121 122 func (self *Node) isLazy() bool { 123 return self != nil && self.t&_V_LAZY != 0 124 } 125 126 func (self *Node) isAny() bool { 127 return self != nil && self.t == _V_ANY 128 } 129 130 /** Simple Value Methods **/ 131 132 // Raw returns json representation of the node, 133 func (self *Node) Raw() (string, error) { 134 if self == nil { 135 return "", ErrNotExist 136 } 137 if !self.IsRaw() { 138 buf, err := self.MarshalJSON() 139 return rt.Mem2Str(buf), err 140 } 141 return self.toString(), nil 142 } 143 144 func (self *Node) checkRaw() error { 145 if err := self.Check(); err != nil { 146 return err 147 } 148 if self.IsRaw() { 149 self.parseRaw(false) 150 } 151 return self.Check() 152 } 153 154 // Bool returns bool value represented by this node, 155 // including types.V_TRUE|V_FALSE|V_NUMBER|V_STRING|V_ANY|V_NULL, 156 // V_NONE will return error 157 func (self *Node) Bool() (bool, error) { 158 if err := self.checkRaw(); err != nil { 159 return false, err 160 } 161 switch self.t { 162 case types.V_TRUE: 163 return true, nil 164 case types.V_FALSE: 165 return false, nil 166 case types.V_NULL: 167 return false, nil 168 case _V_NUMBER: 169 if i, err := self.toInt64(); err == nil { 170 return i != 0, nil 171 } else if f, err := self.toFloat64(); err == nil { 172 return f != 0, nil 173 } else { 174 return false, err 175 } 176 case types.V_STRING: 177 return strconv.ParseBool(self.toString()) 178 case _V_ANY: 179 any := self.packAny() 180 switch v := any.(type) { 181 case bool: 182 return v, nil 183 case int: 184 return v != 0, nil 185 case int8: 186 return v != 0, nil 187 case int16: 188 return v != 0, nil 189 case int32: 190 return v != 0, nil 191 case int64: 192 return v != 0, nil 193 case uint: 194 return v != 0, nil 195 case uint8: 196 return v != 0, nil 197 case uint16: 198 return v != 0, nil 199 case uint32: 200 return v != 0, nil 201 case uint64: 202 return v != 0, nil 203 case float32: 204 return v != 0, nil 205 case float64: 206 return v != 0, nil 207 case string: 208 return strconv.ParseBool(v) 209 case json.Number: 210 if i, err := v.Int64(); err == nil { 211 return i != 0, nil 212 } else if f, err := v.Float64(); err == nil { 213 return f != 0, nil 214 } else { 215 return false, err 216 } 217 default: 218 return false, ErrUnsupportType 219 } 220 default: 221 return false, ErrUnsupportType 222 } 223 } 224 225 // Int64 casts the node to int64 value, 226 // including V_NUMBER|V_TRUE|V_FALSE|V_ANY|V_STRING 227 // V_NONE it will return error 228 func (self *Node) Int64() (int64, error) { 229 if err := self.checkRaw(); err != nil { 230 return 0, err 231 } 232 switch self.t { 233 case _V_NUMBER, types.V_STRING: 234 if i, err := self.toInt64(); err == nil { 235 return i, nil 236 } else if f, err := self.toFloat64(); err == nil { 237 return int64(f), nil 238 } else { 239 return 0, err 240 } 241 case types.V_TRUE: 242 return 1, nil 243 case types.V_FALSE: 244 return 0, nil 245 case types.V_NULL: 246 return 0, nil 247 case _V_ANY: 248 any := self.packAny() 249 switch v := any.(type) { 250 case bool: 251 if v { 252 return 1, nil 253 } else { 254 return 0, nil 255 } 256 case int: 257 return int64(v), nil 258 case int8: 259 return int64(v), nil 260 case int16: 261 return int64(v), nil 262 case int32: 263 return int64(v), nil 264 case int64: 265 return int64(v), nil 266 case uint: 267 return int64(v), nil 268 case uint8: 269 return int64(v), nil 270 case uint16: 271 return int64(v), nil 272 case uint32: 273 return int64(v), nil 274 case uint64: 275 return int64(v), nil 276 case float32: 277 return int64(v), nil 278 case float64: 279 return int64(v), nil 280 case string: 281 if i, err := strconv.ParseInt(v, 10, 64); err == nil { 282 return i, nil 283 } else if f, err := strconv.ParseFloat(v, 64); err == nil { 284 return int64(f), nil 285 } else { 286 return 0, err 287 } 288 case json.Number: 289 if i, err := v.Int64(); err == nil { 290 return i, nil 291 } else if f, err := v.Float64(); err == nil { 292 return int64(f), nil 293 } else { 294 return 0, err 295 } 296 default: 297 return 0, ErrUnsupportType 298 } 299 default: 300 return 0, ErrUnsupportType 301 } 302 } 303 304 // StrictInt64 exports underlying int64 value, including V_NUMBER, V_ANY 305 func (self *Node) StrictInt64() (int64, error) { 306 if err := self.checkRaw(); err != nil { 307 return 0, err 308 } 309 switch self.t { 310 case _V_NUMBER: 311 return self.toInt64() 312 case _V_ANY: 313 any := self.packAny() 314 switch v := any.(type) { 315 case int: 316 return int64(v), nil 317 case int8: 318 return int64(v), nil 319 case int16: 320 return int64(v), nil 321 case int32: 322 return int64(v), nil 323 case int64: 324 return int64(v), nil 325 case uint: 326 return int64(v), nil 327 case uint8: 328 return int64(v), nil 329 case uint16: 330 return int64(v), nil 331 case uint32: 332 return int64(v), nil 333 case uint64: 334 return int64(v), nil 335 case json.Number: 336 if i, err := v.Int64(); err == nil { 337 return i, nil 338 } else { 339 return 0, err 340 } 341 default: 342 return 0, ErrUnsupportType 343 } 344 default: 345 return 0, ErrUnsupportType 346 } 347 } 348 349 func castNumber(v bool) json.Number { 350 if v { 351 return json.Number("1") 352 } else { 353 return json.Number("0") 354 } 355 } 356 357 // Number casts node to float64, 358 // including V_NUMBER|V_TRUE|V_FALSE|V_ANY|V_STRING|V_NULL, 359 // V_NONE it will return error 360 func (self *Node) Number() (json.Number, error) { 361 if err := self.checkRaw(); err != nil { 362 return json.Number(""), err 363 } 364 switch self.t { 365 case _V_NUMBER: 366 return self.toNumber(), nil 367 case types.V_STRING: 368 if _, err := self.toInt64(); err == nil { 369 return self.toNumber(), nil 370 } else if _, err := self.toFloat64(); err == nil { 371 return self.toNumber(), nil 372 } else { 373 return json.Number(""), err 374 } 375 case types.V_TRUE: 376 return json.Number("1"), nil 377 case types.V_FALSE: 378 return json.Number("0"), nil 379 case types.V_NULL: 380 return json.Number("0"), nil 381 case _V_ANY: 382 any := self.packAny() 383 switch v := any.(type) { 384 case bool: 385 return castNumber(v), nil 386 case int: 387 return castNumber(v != 0), nil 388 case int8: 389 return castNumber(v != 0), nil 390 case int16: 391 return castNumber(v != 0), nil 392 case int32: 393 return castNumber(v != 0), nil 394 case int64: 395 return castNumber(v != 0), nil 396 case uint: 397 return castNumber(v != 0), nil 398 case uint8: 399 return castNumber(v != 0), nil 400 case uint16: 401 return castNumber(v != 0), nil 402 case uint32: 403 return castNumber(v != 0), nil 404 case uint64: 405 return castNumber(v != 0), nil 406 case float32: 407 return castNumber(v != 0), nil 408 case float64: 409 return castNumber(v != 0), nil 410 case string: 411 if _, err := strconv.ParseFloat(v, 64); err == nil { 412 return json.Number(v), nil 413 } else { 414 return json.Number(""), err 415 } 416 case json.Number: 417 return v, nil 418 default: 419 return json.Number(""), ErrUnsupportType 420 } 421 default: 422 return json.Number(""), ErrUnsupportType 423 } 424 } 425 426 // Number exports underlying float64 value, including V_NUMBER, V_ANY of json.Number 427 func (self *Node) StrictNumber() (json.Number, error) { 428 if err := self.checkRaw(); err != nil { 429 return json.Number(""), err 430 } 431 switch self.t { 432 case _V_NUMBER: 433 return self.toNumber(), nil 434 case _V_ANY: 435 if v, ok := self.packAny().(json.Number); ok { 436 return v, nil 437 } else { 438 return json.Number(""), ErrUnsupportType 439 } 440 default: 441 return json.Number(""), ErrUnsupportType 442 } 443 } 444 445 // String cast node to string, 446 // including V_NUMBER|V_TRUE|V_FALSE|V_ANY|V_STRING|V_NULL, 447 // V_NONE it will return error 448 func (self *Node) String() (string, error) { 449 if err := self.checkRaw(); err != nil { 450 return "", err 451 } 452 switch self.t { 453 case types.V_NULL: 454 return "", nil 455 case types.V_TRUE: 456 return "true", nil 457 case types.V_FALSE: 458 return "false", nil 459 case types.V_STRING, _V_NUMBER: 460 return self.toString(), nil 461 case _V_ANY: 462 any := self.packAny() 463 switch v := any.(type) { 464 case bool: 465 return strconv.FormatBool(v), nil 466 case int: 467 return strconv.Itoa(v), nil 468 case int8: 469 return strconv.Itoa(int(v)), nil 470 case int16: 471 return strconv.Itoa(int(v)), nil 472 case int32: 473 return strconv.Itoa(int(v)), nil 474 case int64: 475 return strconv.Itoa(int(v)), nil 476 case uint: 477 return strconv.Itoa(int(v)), nil 478 case uint8: 479 return strconv.Itoa(int(v)), nil 480 case uint16: 481 return strconv.Itoa(int(v)), nil 482 case uint32: 483 return strconv.Itoa(int(v)), nil 484 case uint64: 485 return strconv.Itoa(int(v)), nil 486 case float32: 487 return strconv.FormatFloat(float64(v), 'g', -1, 64), nil 488 case float64: 489 return strconv.FormatFloat(float64(v), 'g', -1, 64), nil 490 case string: 491 return v, nil 492 case json.Number: 493 return v.String(), nil 494 default: 495 return "", ErrUnsupportType 496 } 497 default: 498 return "", ErrUnsupportType 499 } 500 } 501 502 // StrictString returns string value (unescaped), includeing V_STRING, V_ANY of string. 503 // In other cases, it will return empty string. 504 func (self *Node) StrictString() (string, error) { 505 if err := self.checkRaw(); err != nil { 506 return "", err 507 } 508 switch self.t { 509 case types.V_STRING: 510 return self.toString(), nil 511 case _V_ANY: 512 if v, ok := self.packAny().(string); ok { 513 return v, nil 514 } else { 515 return "", ErrUnsupportType 516 } 517 default: 518 return "", ErrUnsupportType 519 } 520 } 521 522 // Float64 cast node to float64, 523 // including V_NUMBER|V_TRUE|V_FALSE|V_ANY|V_STRING|V_NULL, 524 // V_NONE it will return error 525 func (self *Node) Float64() (float64, error) { 526 if err := self.checkRaw(); err != nil { 527 return 0.0, err 528 } 529 switch self.t { 530 case _V_NUMBER, types.V_STRING: 531 return self.toFloat64() 532 case types.V_TRUE: 533 return 1.0, nil 534 case types.V_FALSE: 535 return 0.0, nil 536 case types.V_NULL: 537 return 0.0, nil 538 case _V_ANY: 539 any := self.packAny() 540 switch v := any.(type) { 541 case bool: 542 if v { 543 return 1.0, nil 544 } else { 545 return 0.0, nil 546 } 547 case int: 548 return float64(v), nil 549 case int8: 550 return float64(v), nil 551 case int16: 552 return float64(v), nil 553 case int32: 554 return float64(v), nil 555 case int64: 556 return float64(v), nil 557 case uint: 558 return float64(v), nil 559 case uint8: 560 return float64(v), nil 561 case uint16: 562 return float64(v), nil 563 case uint32: 564 return float64(v), nil 565 case uint64: 566 return float64(v), nil 567 case float32: 568 return float64(v), nil 569 case float64: 570 return float64(v), nil 571 case string: 572 if f, err := strconv.ParseFloat(v, 64); err == nil { 573 return float64(f), nil 574 } else { 575 return 0, err 576 } 577 case json.Number: 578 if f, err := v.Float64(); err == nil { 579 return float64(f), nil 580 } else { 581 return 0, err 582 } 583 default: 584 return 0, ErrUnsupportType 585 } 586 default: 587 return 0.0, ErrUnsupportType 588 } 589 } 590 591 // Float64 exports underlying float64 value, includeing V_NUMBER, V_ANY 592 func (self *Node) StrictFloat64() (float64, error) { 593 if err := self.checkRaw(); err != nil { 594 return 0.0, err 595 } 596 switch self.t { 597 case _V_NUMBER: 598 return self.toFloat64() 599 case _V_ANY: 600 any := self.packAny() 601 switch v := any.(type) { 602 case float32: 603 return float64(v), nil 604 case float64: 605 return float64(v), nil 606 default: 607 return 0, ErrUnsupportType 608 } 609 default: 610 return 0.0, ErrUnsupportType 611 } 612 } 613 614 /** Sequencial Value Methods **/ 615 616 // Len returns children count of a array|object|string node 617 // WARN: For partially loaded node, it also works but only counts the parsed children 618 // WARN: For ARRAY|OBJECT nodes which has been conducted `UnsetXX()`, its length WON'T change 619 func (self *Node) Len() (int, error) { 620 if err := self.checkRaw(); err != nil { 621 return 0, err 622 } 623 if self.t == types.V_ARRAY || self.t == types.V_OBJECT || self.t == _V_ARRAY_LAZY || self.t == _V_OBJECT_LAZY || self.t == types.V_STRING { 624 return int(self.l), nil 625 } else if self.t == _V_NONE || self.t == types.V_NULL { 626 return 0, nil 627 } else { 628 return 0, ErrUnsupportType 629 } 630 } 631 632 func (self Node) len() int { 633 return int(self.l) 634 } 635 636 // Cap returns malloc capacity of a array|object node for children 637 func (self *Node) Cap() (int, error) { 638 if err := self.checkRaw(); err != nil { 639 return 0, err 640 } 641 switch self.t { 642 case types.V_ARRAY: 643 return (*linkedNodes)(self.p).Cap(), nil 644 case types.V_OBJECT: 645 return (*linkedPairs)(self.p).Cap(), nil 646 case _V_ARRAY_LAZY: 647 return (*parseArrayStack)(self.p).v.Cap(), nil 648 case _V_OBJECT_LAZY: 649 return (*parseObjectStack)(self.p).v.Cap(), nil 650 case _V_NONE, types.V_NULL: 651 return 0, nil 652 default: 653 return 0, ErrUnsupportType 654 } 655 } 656 657 // Set sets the node of given key under self, and reports if the key has existed. 658 // 659 // If self is V_NONE or V_NULL, it becomes V_OBJECT and sets the node at the key. 660 func (self *Node) Set(key string, node Node) (bool, error) { 661 if err := self.Check(); err != nil { 662 return false, err 663 } 664 if err := node.Check(); err != nil { 665 return false, err 666 } 667 668 if self.t == _V_NONE || self.t == types.V_NULL { 669 *self = NewObject([]Pair{{key, node}}) 670 return false, nil 671 } 672 673 p := self.Get(key) 674 675 if !p.Exists() { 676 // self must be fully-loaded here 677 if self.len() == 0 { 678 *self = newObject(new(linkedPairs)) 679 } 680 s := (*linkedPairs)(self.p) 681 s.Add(Pair{key, node}) 682 self.l++ 683 return false, nil 684 685 } else if err := p.Check(); err != nil { 686 return false, err 687 } 688 689 *p = node 690 return true, nil 691 } 692 693 // SetAny wraps val with V_ANY node, and Set() the node. 694 func (self *Node) SetAny(key string, val interface{}) (bool, error) { 695 return self.Set(key, NewAny(val)) 696 } 697 698 // Unset RESET the node of given key under object parent, and reports if the key has existed. 699 // WARN: After conducting `UnsetXX()`, the node's length WON'T change 700 func (self *Node) Unset(key string) (bool, error) { 701 if err := self.should(types.V_OBJECT, "an object"); err != nil { 702 return false, err 703 } 704 p, i := self.skipKey(key) 705 if !p.Exists() { 706 return false, nil 707 } else if err := p.Check(); err != nil { 708 return false, err 709 } 710 711 self.removePair(i) 712 return true, nil 713 } 714 715 // SetByIndex sets the node of given index, and reports if the key has existed. 716 // 717 // The index must be within self's children. 718 func (self *Node) SetByIndex(index int, node Node) (bool, error) { 719 if err := self.Check(); err != nil { 720 return false, err 721 } 722 if err := node.Check(); err != nil { 723 return false, err 724 } 725 726 if index == 0 && (self.t == _V_NONE || self.t == types.V_NULL) { 727 *self = NewArray([]Node{node}) 728 return false, nil 729 } 730 731 p := self.Index(index) 732 if !p.Exists() { 733 return false, ErrNotExist 734 } else if err := p.Check(); err != nil { 735 return false, err 736 } 737 738 *p = node 739 return true, nil 740 } 741 742 // SetAny wraps val with V_ANY node, and SetByIndex() the node. 743 func (self *Node) SetAnyByIndex(index int, val interface{}) (bool, error) { 744 return self.SetByIndex(index, NewAny(val)) 745 } 746 747 // UnsetByIndex remove the node of given index 748 // WARN: After conducting `UnsetXX()`, the node's length WON'T change 749 func (self *Node) UnsetByIndex(index int) (bool, error) { 750 if err := self.Check(); err != nil { 751 return false, err 752 } 753 754 var p *Node 755 it := self.itype() 756 if it == types.V_ARRAY { 757 p = self.Index(index) 758 } else if it == types.V_OBJECT { 759 if err := self.checkRaw(); err != nil { 760 return false, err 761 } 762 pr := self.skipIndexPair(index) 763 if pr == nil { 764 return false, ErrNotExist 765 } 766 p = &pr.Value 767 } else { 768 return false, ErrUnsupportType 769 } 770 771 if !p.Exists() { 772 return false, ErrNotExist 773 } 774 775 if it == types.V_ARRAY { 776 self.removeNode(index) 777 } else if it == types.V_OBJECT { 778 self.removePair(index) 779 } 780 return true, nil 781 } 782 783 // Add appends the given node under self. 784 // 785 // If self is V_NONE or V_NULL, it becomes V_ARRAY and sets the node at index 0. 786 func (self *Node) Add(node Node) error { 787 if err := self.Check(); err != nil { 788 return err 789 } 790 791 if self != nil && (self.t == _V_NONE || self.t == types.V_NULL) { 792 *self = NewArray([]Node{node}) 793 return nil 794 } 795 if err := self.should(types.V_ARRAY, "an array"); err != nil { 796 return err 797 } 798 s, err := self.unsafeArray() 799 if err != nil { 800 return err 801 } 802 803 s.Add(node) 804 self.l++ 805 return nil 806 } 807 808 // SetAny wraps val with V_ANY node, and Add() the node. 809 func (self *Node) AddAny(val interface{}) error { 810 return self.Add(NewAny(val)) 811 } 812 813 // GetByPath load given path on demands, 814 // which only ensure nodes before this path got parsed. 815 // 816 // Note, the api expects the json is well-formed at least, 817 // otherwise it may return unexpected result. 818 func (self *Node) GetByPath(path ...interface{}) *Node { 819 if !self.Valid() { 820 return self 821 } 822 var s = self 823 for _, p := range path { 824 switch p := p.(type) { 825 case int: 826 s = s.Index(p) 827 if !s.Valid() { 828 return s 829 } 830 case string: 831 s = s.Get(p) 832 if !s.Valid() { 833 return s 834 } 835 default: 836 panic("path must be either int or string") 837 } 838 } 839 return s 840 } 841 842 // Get loads given key of an object node on demands 843 func (self *Node) Get(key string) *Node { 844 if err := self.should(types.V_OBJECT, "an object"); err != nil { 845 return unwrapError(err) 846 } 847 n, _ := self.skipKey(key) 848 return n 849 } 850 851 // Index indexies node at given idx, 852 // node type CAN be either V_OBJECT or V_ARRAY 853 // WARN: After conducting `UnsetXX()`, the node's length WON'T change, 854 // thus its children's indexing WON'T change too 855 func (self *Node) Index(idx int) *Node { 856 if err := self.checkRaw(); err != nil { 857 return unwrapError(err) 858 } 859 860 it := self.itype() 861 if it == types.V_ARRAY { 862 return self.skipIndex(idx) 863 864 } else if it == types.V_OBJECT { 865 pr := self.skipIndexPair(idx) 866 if pr == nil { 867 return newError(_ERR_NOT_FOUND, "value not exists") 868 } 869 return &pr.Value 870 871 } else { 872 return newError(_ERR_UNSUPPORT_TYPE, fmt.Sprintf("unsupported type: %v", self.itype())) 873 } 874 } 875 876 // IndexPair indexies pair at given idx, 877 // node type MUST be either V_OBJECT 878 // WARN: After conducting `UnsetXX()`, the node's length WON'T change, 879 // thus its children's indexing WON'T change too 880 func (self *Node) IndexPair(idx int) *Pair { 881 if err := self.should(types.V_OBJECT, "an object"); err != nil { 882 return nil 883 } 884 return self.skipIndexPair(idx) 885 } 886 887 // IndexOrGet firstly use idx to index a value and check if its key matches 888 // If not, then use the key to search value 889 func (self *Node) IndexOrGet(idx int, key string) *Node { 890 if err := self.should(types.V_OBJECT, "an object"); err != nil { 891 return unwrapError(err) 892 } 893 894 pr := self.skipIndexPair(idx) 895 if pr != nil && pr.Key == key { 896 return &pr.Value 897 } 898 n, _ := self.skipKey(key) 899 return n 900 } 901 902 /** Generic Value Converters **/ 903 904 // Map loads all keys of an object node 905 func (self *Node) Map() (map[string]interface{}, error) { 906 if self.isAny() { 907 any := self.packAny() 908 if v, ok := any.(map[string]interface{}); ok { 909 return v, nil 910 } else { 911 return nil, ErrUnsupportType 912 } 913 } 914 if err := self.should(types.V_OBJECT, "an object"); err != nil { 915 return nil, err 916 } 917 if err := self.loadAllKey(); err != nil { 918 return nil, err 919 } 920 return self.toGenericObject() 921 } 922 923 // MapUseNumber loads all keys of an object node, with numeric nodes casted to json.Number 924 func (self *Node) MapUseNumber() (map[string]interface{}, error) { 925 if self.isAny() { 926 any := self.packAny() 927 if v, ok := any.(map[string]interface{}); ok { 928 return v, nil 929 } else { 930 return nil, ErrUnsupportType 931 } 932 } 933 if err := self.should(types.V_OBJECT, "an object"); err != nil { 934 return nil, err 935 } 936 if err := self.loadAllKey(); err != nil { 937 return nil, err 938 } 939 return self.toGenericObjectUseNumber() 940 } 941 942 // MapUseNode scans both parsed and non-parsed chidren nodes, 943 // and map them by their keys 944 func (self *Node) MapUseNode() (map[string]Node, error) { 945 if self.isAny() { 946 any := self.packAny() 947 if v, ok := any.(map[string]Node); ok { 948 return v, nil 949 } else { 950 return nil, ErrUnsupportType 951 } 952 } 953 if err := self.should(types.V_OBJECT, "an object"); err != nil { 954 return nil, err 955 } 956 if err := self.skipAllKey(); err != nil { 957 return nil, err 958 } 959 return self.toGenericObjectUseNode() 960 } 961 962 // MapUnsafe exports the underlying pointer to its children map 963 // WARN: don't use it unless you know what you are doing 964 // 965 // Deprecated: this API now returns copied nodes instead of directly reference, 966 // func (self *Node) UnsafeMap() ([]Pair, error) { 967 // if err := self.should(types.V_OBJECT, "an object"); err != nil { 968 // return nil, err 969 // } 970 // if err := self.skipAllKey(); err != nil { 971 // return nil, err 972 // } 973 // return self.toGenericObjectUsePair() 974 // } 975 976 //go:nocheckptr 977 func (self *Node) unsafeMap() (*linkedPairs, error) { 978 if err := self.skipAllKey(); err != nil { 979 return nil, err 980 } 981 if self.p == nil { 982 *self = newObject(new(linkedPairs)) 983 } 984 return (*linkedPairs)(self.p), nil 985 } 986 987 // SortKeys sorts children of a V_OBJECT node in ascending key-order. 988 // If recurse is true, it recursively sorts children's children as long as a V_OBJECT node is found. 989 func (self *Node) SortKeys(recurse bool) error { 990 // check raw node first 991 if err := self.checkRaw(); err != nil { 992 return err 993 } 994 if self.itype() == types.V_OBJECT { 995 return self.sortKeys(recurse) 996 } else { 997 var err error 998 err2 := self.ForEach(func(path Sequence, node *Node) bool { 999 it := node.itype() 1000 if it == types.V_ARRAY || it == types.V_OBJECT { 1001 err = node.SortKeys(recurse) 1002 if err != nil { 1003 return false 1004 } 1005 } 1006 return true 1007 }) 1008 if err != nil { 1009 return err 1010 } 1011 return err2 1012 } 1013 } 1014 1015 func (self *Node) sortKeys(recurse bool) (err error) { 1016 ps, err := self.unsafeMap() 1017 if err != nil { 1018 return err 1019 } 1020 ps.Sort() 1021 if recurse { 1022 var sc Scanner 1023 sc = func(path Sequence, node *Node) bool { 1024 if node.itype() == types.V_OBJECT { 1025 if err := node.sortKeys(recurse); err != nil { 1026 return false 1027 } 1028 } 1029 if node.itype() == types.V_ARRAY { 1030 if err := node.ForEach(sc); err != nil { 1031 return false 1032 } 1033 } 1034 return true 1035 } 1036 if err := self.ForEach(sc); err != nil { 1037 return err 1038 } 1039 } 1040 return nil 1041 } 1042 1043 // Array loads all indexes of an array node 1044 func (self *Node) Array() ([]interface{}, error) { 1045 if self.isAny() { 1046 any := self.packAny() 1047 if v, ok := any.([]interface{}); ok { 1048 return v, nil 1049 } else { 1050 return nil, ErrUnsupportType 1051 } 1052 } 1053 if err := self.should(types.V_ARRAY, "an array"); err != nil { 1054 return nil, err 1055 } 1056 if err := self.loadAllIndex(); err != nil { 1057 return nil, err 1058 } 1059 return self.toGenericArray() 1060 } 1061 1062 // ArrayUseNumber loads all indexes of an array node, with numeric nodes casted to json.Number 1063 func (self *Node) ArrayUseNumber() ([]interface{}, error) { 1064 if self.isAny() { 1065 any := self.packAny() 1066 if v, ok := any.([]interface{}); ok { 1067 return v, nil 1068 } else { 1069 return nil, ErrUnsupportType 1070 } 1071 } 1072 if err := self.should(types.V_ARRAY, "an array"); err != nil { 1073 return nil, err 1074 } 1075 if err := self.loadAllIndex(); err != nil { 1076 return nil, err 1077 } 1078 return self.toGenericArrayUseNumber() 1079 } 1080 1081 // ArrayUseNode copys both parsed and non-parsed chidren nodes, 1082 // and indexes them by original order 1083 func (self *Node) ArrayUseNode() ([]Node, error) { 1084 if self.isAny() { 1085 any := self.packAny() 1086 if v, ok := any.([]Node); ok { 1087 return v, nil 1088 } else { 1089 return nil, ErrUnsupportType 1090 } 1091 } 1092 if err := self.should(types.V_ARRAY, "an array"); err != nil { 1093 return nil, err 1094 } 1095 if err := self.skipAllIndex(); err != nil { 1096 return nil, err 1097 } 1098 return self.toGenericArrayUseNode() 1099 } 1100 1101 // ArrayUnsafe exports the underlying pointer to its children array 1102 // WARN: don't use it unless you know what you are doing 1103 // 1104 // Deprecated: this API now returns copied nodes instead of directly reference, 1105 // which has no difference with ArrayUseNode 1106 // func (self *Node) UnsafeArray() ([]Node, error) { 1107 // if err := self.should(types.V_ARRAY, "an array"); err != nil { 1108 // return nil, err 1109 // } 1110 // if err := self.skipAllIndex(); err != nil { 1111 // return nil, err 1112 // } 1113 // return self.toGenericArrayUseNode() 1114 // } 1115 1116 func (self *Node) unsafeArray() (*linkedNodes, error) { 1117 if err := self.skipAllIndex(); err != nil { 1118 return nil, err 1119 } 1120 if self.p == nil { 1121 *self = newArray(new(linkedNodes)) 1122 } 1123 return (*linkedNodes)(self.p), nil 1124 } 1125 1126 // Interface loads all children under all pathes from this node, 1127 // and converts itself as generic type. 1128 // WARN: all numberic nodes are casted to float64 1129 func (self *Node) Interface() (interface{}, error) { 1130 if err := self.checkRaw(); err != nil { 1131 return nil, err 1132 } 1133 switch self.t { 1134 case V_ERROR: 1135 return nil, self.Check() 1136 case types.V_NULL: 1137 return nil, nil 1138 case types.V_TRUE: 1139 return true, nil 1140 case types.V_FALSE: 1141 return false, nil 1142 case types.V_ARRAY: 1143 return self.toGenericArray() 1144 case types.V_OBJECT: 1145 return self.toGenericObject() 1146 case types.V_STRING: 1147 return self.toString(), nil 1148 case _V_NUMBER: 1149 v, err := self.toFloat64() 1150 if err != nil { 1151 return nil, err 1152 } 1153 return v, nil 1154 case _V_ARRAY_LAZY: 1155 if err := self.loadAllIndex(); err != nil { 1156 return nil, err 1157 } 1158 return self.toGenericArray() 1159 case _V_OBJECT_LAZY: 1160 if err := self.loadAllKey(); err != nil { 1161 return nil, err 1162 } 1163 return self.toGenericObject() 1164 case _V_ANY: 1165 switch v := self.packAny().(type) { 1166 case Node: 1167 return v.Interface() 1168 case *Node: 1169 return v.Interface() 1170 default: 1171 return v, nil 1172 } 1173 default: 1174 return nil, ErrUnsupportType 1175 } 1176 } 1177 1178 func (self *Node) packAny() interface{} { 1179 return *(*interface{})(self.p) 1180 } 1181 1182 // InterfaceUseNumber works same with Interface() 1183 // except numberic nodes are casted to json.Number 1184 func (self *Node) InterfaceUseNumber() (interface{}, error) { 1185 if err := self.checkRaw(); err != nil { 1186 return nil, err 1187 } 1188 switch self.t { 1189 case V_ERROR: 1190 return nil, self.Check() 1191 case types.V_NULL: 1192 return nil, nil 1193 case types.V_TRUE: 1194 return true, nil 1195 case types.V_FALSE: 1196 return false, nil 1197 case types.V_ARRAY: 1198 return self.toGenericArrayUseNumber() 1199 case types.V_OBJECT: 1200 return self.toGenericObjectUseNumber() 1201 case types.V_STRING: 1202 return self.toString(), nil 1203 case _V_NUMBER: 1204 return self.toNumber(), nil 1205 case _V_ARRAY_LAZY: 1206 if err := self.loadAllIndex(); err != nil { 1207 return nil, err 1208 } 1209 return self.toGenericArrayUseNumber() 1210 case _V_OBJECT_LAZY: 1211 if err := self.loadAllKey(); err != nil { 1212 return nil, err 1213 } 1214 return self.toGenericObjectUseNumber() 1215 case _V_ANY: 1216 return self.packAny(), nil 1217 default: 1218 return nil, ErrUnsupportType 1219 } 1220 } 1221 1222 // InterfaceUseNode clone itself as a new node, 1223 // or its children as map[string]Node (or []Node) 1224 func (self *Node) InterfaceUseNode() (interface{}, error) { 1225 if err := self.checkRaw(); err != nil { 1226 return nil, err 1227 } 1228 switch self.t { 1229 case types.V_ARRAY: 1230 return self.toGenericArrayUseNode() 1231 case types.V_OBJECT: 1232 return self.toGenericObjectUseNode() 1233 case _V_ARRAY_LAZY: 1234 if err := self.skipAllIndex(); err != nil { 1235 return nil, err 1236 } 1237 return self.toGenericArrayUseNode() 1238 case _V_OBJECT_LAZY: 1239 if err := self.skipAllKey(); err != nil { 1240 return nil, err 1241 } 1242 return self.toGenericObjectUseNode() 1243 default: 1244 return *self, self.Check() 1245 } 1246 } 1247 1248 // LoadAll loads all the node's children and children's children as parsed. 1249 // After calling it, the node can be safely used on concurrency 1250 func (self *Node) LoadAll() error { 1251 if self.IsRaw() { 1252 self.parseRaw(true) 1253 return self.Check() 1254 } 1255 1256 switch self.itype() { 1257 case types.V_ARRAY: 1258 e := self.len() 1259 if err := self.loadAllIndex(); err != nil { 1260 return err 1261 } 1262 for i := 0; i < e; i++ { 1263 n := self.nodeAt(i) 1264 if n.IsRaw() { 1265 n.parseRaw(true) 1266 } 1267 if err := n.Check(); err != nil { 1268 return err 1269 } 1270 } 1271 return nil 1272 case types.V_OBJECT: 1273 e := self.len() 1274 if err := self.loadAllKey(); err != nil { 1275 return err 1276 } 1277 for i := 0; i < e; i++ { 1278 n := self.pairAt(i) 1279 if n.Value.IsRaw() { 1280 n.Value.parseRaw(true) 1281 } 1282 if err := n.Value.Check(); err != nil { 1283 return err 1284 } 1285 } 1286 return nil 1287 default: 1288 return self.Check() 1289 } 1290 } 1291 1292 // Load loads the node's children as parsed. 1293 // After calling it, only the node itself can be used on concurrency (not include its children) 1294 func (self *Node) Load() error { 1295 if err := self.checkRaw(); err != nil { 1296 return err 1297 } 1298 1299 switch self.t { 1300 case _V_ARRAY_LAZY: 1301 return self.skipAllIndex() 1302 case _V_OBJECT_LAZY: 1303 return self.skipAllKey() 1304 default: 1305 return self.Check() 1306 } 1307 } 1308 1309 /**---------------------------------- Internal Helper Methods ----------------------------------**/ 1310 1311 func (self *Node) should(t types.ValueType, s string) error { 1312 if err := self.checkRaw(); err != nil { 1313 return err 1314 } 1315 if self.itype() != t { 1316 return ErrUnsupportType 1317 } 1318 return nil 1319 } 1320 1321 func (self *Node) nodeAt(i int) *Node { 1322 var p *linkedNodes 1323 if self.isLazy() { 1324 _, stack := self.getParserAndArrayStack() 1325 p = &stack.v 1326 } else { 1327 p = (*linkedNodes)(self.p) 1328 } 1329 return p.At(i) 1330 } 1331 1332 func (self *Node) pairAt(i int) *Pair { 1333 var p *linkedPairs 1334 if self.isLazy() { 1335 _, stack := self.getParserAndObjectStack() 1336 p = &stack.v 1337 } else { 1338 p = (*linkedPairs)(self.p) 1339 } 1340 return p.At(i) 1341 } 1342 1343 func (self *Node) skipAllIndex() error { 1344 if !self.isLazy() { 1345 return nil 1346 } 1347 var err types.ParsingError 1348 parser, stack := self.getParserAndArrayStack() 1349 parser.skipValue = true 1350 parser.noLazy = true 1351 *self, err = parser.decodeArray(&stack.v) 1352 if err != 0 { 1353 return parser.ExportError(err) 1354 } 1355 return nil 1356 } 1357 1358 func (self *Node) skipAllKey() error { 1359 if !self.isLazy() { 1360 return nil 1361 } 1362 var err types.ParsingError 1363 parser, stack := self.getParserAndObjectStack() 1364 parser.skipValue = true 1365 parser.noLazy = true 1366 *self, err = parser.decodeObject(&stack.v) 1367 if err != 0 { 1368 return parser.ExportError(err) 1369 } 1370 return nil 1371 } 1372 1373 func (self *Node) skipKey(key string) (*Node, int) { 1374 nb := self.len() 1375 lazy := self.isLazy() 1376 1377 if nb > 0 { 1378 /* linear search */ 1379 var p *Pair 1380 var i int 1381 if lazy { 1382 s := (*parseObjectStack)(self.p) 1383 p, i = s.v.Get(key) 1384 } else { 1385 p, i = (*linkedPairs)(self.p).Get(key) 1386 } 1387 1388 if p != nil { 1389 return &p.Value, i 1390 } 1391 } 1392 1393 /* not found */ 1394 if !lazy { 1395 return nil, -1 1396 } 1397 1398 // lazy load 1399 for last, i := self.skipNextPair(), nb; last != nil; last, i = self.skipNextPair(), i+1 { 1400 if last.Value.Check() != nil { 1401 return &last.Value, -1 1402 } 1403 if last.Key == key { 1404 return &last.Value, i 1405 } 1406 } 1407 1408 return nil, -1 1409 } 1410 1411 func (self *Node) skipIndex(index int) *Node { 1412 nb := self.len() 1413 if nb > index { 1414 v := self.nodeAt(index) 1415 return v 1416 } 1417 if !self.isLazy() { 1418 return nil 1419 } 1420 1421 // lazy load 1422 for last := self.skipNextNode(); last != nil; last = self.skipNextNode() { 1423 if last.Check() != nil { 1424 return last 1425 } 1426 if self.len() > index { 1427 return last 1428 } 1429 } 1430 1431 return nil 1432 } 1433 1434 func (self *Node) skipIndexPair(index int) *Pair { 1435 nb := self.len() 1436 if nb > index { 1437 return self.pairAt(index) 1438 } 1439 if !self.isLazy() { 1440 return nil 1441 } 1442 1443 // lazy load 1444 for last := self.skipNextPair(); last != nil; last = self.skipNextPair() { 1445 if last.Value.Check() != nil { 1446 return last 1447 } 1448 if self.len() > index { 1449 return last 1450 } 1451 } 1452 1453 return nil 1454 } 1455 1456 func (self *Node) loadAllIndex() error { 1457 if !self.isLazy() { 1458 return nil 1459 } 1460 var err types.ParsingError 1461 parser, stack := self.getParserAndArrayStack() 1462 parser.noLazy = true 1463 *self, err = parser.decodeArray(&stack.v) 1464 if err != 0 { 1465 return parser.ExportError(err) 1466 } 1467 return nil 1468 } 1469 1470 func (self *Node) loadAllKey() error { 1471 if !self.isLazy() { 1472 return nil 1473 } 1474 var err types.ParsingError 1475 parser, stack := self.getParserAndObjectStack() 1476 parser.noLazy = true 1477 *self, err = parser.decodeObject(&stack.v) 1478 if err != 0 { 1479 return parser.ExportError(err) 1480 } 1481 return nil 1482 } 1483 1484 func (self *Node) removeNode(i int) { 1485 node := self.nodeAt(i) 1486 if node == nil { 1487 return 1488 } 1489 *node = Node{} 1490 // NOTICE: for consistency with linkedNodes, we DOSEN'T reduce size here 1491 // self.l-- 1492 } 1493 1494 func (self *Node) removePair(i int) { 1495 last := self.pairAt(i) 1496 if last == nil { 1497 return 1498 } 1499 *last = Pair{} 1500 // NOTICE: for consistency with linkedNodes, we DOSEN'T reduce size here 1501 // self.l-- 1502 } 1503 1504 func (self *Node) toGenericArray() ([]interface{}, error) { 1505 nb := self.len() 1506 if nb == 0 { 1507 return []interface{}{}, nil 1508 } 1509 ret := make([]interface{}, nb) 1510 1511 /* convert each item */ 1512 var s = (*linkedNodes)(self.p) 1513 for i := 0; i < nb; i++ { 1514 p := s.At(i) 1515 x, err := p.Interface() 1516 if err != nil { 1517 return nil, err 1518 } 1519 ret[i] = x 1520 } 1521 1522 /* all done */ 1523 return ret, nil 1524 } 1525 1526 func (self *Node) toGenericArrayUseNumber() ([]interface{}, error) { 1527 nb := self.len() 1528 if nb == 0 { 1529 return []interface{}{}, nil 1530 } 1531 ret := make([]interface{}, nb) 1532 1533 /* convert each item */ 1534 var s = (*linkedNodes)(self.p) 1535 for i := 0; i < nb; i++ { 1536 p := s.At(i) 1537 x, err := p.InterfaceUseNumber() 1538 if err != nil { 1539 return nil, err 1540 } 1541 ret[i] = x 1542 } 1543 1544 /* all done */ 1545 return ret, nil 1546 } 1547 1548 func (self *Node) toGenericArrayUseNode() ([]Node, error) { 1549 var nb = self.len() 1550 if nb == 0 { 1551 return []Node{}, nil 1552 } 1553 1554 var s = (*linkedNodes)(self.p) 1555 var out = make([]Node, nb) 1556 s.ToSlice(out) 1557 1558 return out, nil 1559 } 1560 1561 func (self *Node) toGenericObject() (map[string]interface{}, error) { 1562 nb := self.len() 1563 if nb == 0 { 1564 return map[string]interface{}{}, nil 1565 } 1566 ret := make(map[string]interface{}, nb) 1567 1568 /* convert each item */ 1569 var s = (*linkedPairs)(self.p) 1570 for i := 0; i < nb; i++ { 1571 p := s.At(i) 1572 x, err := p.Value.Interface() 1573 if err != nil { 1574 return nil, err 1575 } 1576 ret[p.Key] = x 1577 } 1578 1579 /* all done */ 1580 return ret, nil 1581 } 1582 1583 func (self *Node) toGenericObjectUseNumber() (map[string]interface{}, error) { 1584 nb := self.len() 1585 if nb == 0 { 1586 return map[string]interface{}{}, nil 1587 } 1588 ret := make(map[string]interface{}, nb) 1589 1590 /* convert each item */ 1591 var s = (*linkedPairs)(self.p) 1592 for i := 0; i < nb; i++ { 1593 p := s.At(i) 1594 x, err := p.Value.InterfaceUseNumber() 1595 if err != nil { 1596 return nil, err 1597 } 1598 ret[p.Key] = x 1599 } 1600 1601 /* all done */ 1602 return ret, nil 1603 } 1604 1605 func (self *Node) toGenericObjectUseNode() (map[string]Node, error) { 1606 var nb = self.len() 1607 if nb == 0 { 1608 return map[string]Node{}, nil 1609 } 1610 1611 var s = (*linkedPairs)(self.p) 1612 var out = make(map[string]Node, nb) 1613 s.ToMap(out) 1614 1615 /* all done */ 1616 return out, nil 1617 } 1618 1619 /**------------------------------------ Factory Methods ------------------------------------**/ 1620 1621 var ( 1622 nullNode = Node{t: types.V_NULL} 1623 trueNode = Node{t: types.V_TRUE} 1624 falseNode = Node{t: types.V_FALSE} 1625 ) 1626 1627 // NewRaw creates a node of raw json. 1628 // If the input json is invalid, NewRaw returns a error Node. 1629 func NewRaw(json string) Node { 1630 parser := NewParserObj(json) 1631 start, err := parser.skip() 1632 if err != 0 { 1633 return *newError(err, err.Message()) 1634 } 1635 it := switchRawType(parser.s[start]) 1636 if it == _V_NONE { 1637 return Node{} 1638 } 1639 return newRawNode(parser.s[start:parser.p], it) 1640 } 1641 1642 // NewAny creates a node of type V_ANY if any's type isn't Node or *Node, 1643 // which stores interface{} and can be only used for `.Interface()`\`.MarshalJSON()`. 1644 func NewAny(any interface{}) Node { 1645 switch n := any.(type) { 1646 case Node: 1647 return n 1648 case *Node: 1649 return *n 1650 default: 1651 return Node{ 1652 t: _V_ANY, 1653 p: unsafe.Pointer(&any), 1654 } 1655 } 1656 } 1657 1658 // NewBytes encodes given src with Base64 (RFC 4648), and creates a node of type V_STRING. 1659 func NewBytes(src []byte) Node { 1660 if len(src) == 0 { 1661 panic("empty src bytes") 1662 } 1663 out := encodeBase64(src) 1664 return NewString(out) 1665 } 1666 1667 // NewNull creates a node of type V_NULL 1668 func NewNull() Node { 1669 return Node{ 1670 p: nil, 1671 t: types.V_NULL, 1672 } 1673 } 1674 1675 // NewBool creates a node of type bool: 1676 // 1677 // If v is true, returns V_TRUE node 1678 // If v is false, returns V_FALSE node 1679 func NewBool(v bool) Node { 1680 var t = types.V_FALSE 1681 if v { 1682 t = types.V_TRUE 1683 } 1684 return Node{ 1685 p: nil, 1686 t: t, 1687 } 1688 } 1689 1690 // NewNumber creates a json.Number node 1691 // v must be a decimal string complying with RFC8259 1692 func NewNumber(v string) Node { 1693 return Node{ 1694 l: uint(len(v)), 1695 p: rt.StrPtr(v), 1696 t: _V_NUMBER, 1697 } 1698 } 1699 1700 func (node Node) toNumber() json.Number { 1701 return json.Number(rt.StrFrom(node.p, int64(node.l))) 1702 } 1703 1704 func (self Node) toString() string { 1705 return rt.StrFrom(self.p, int64(self.l)) 1706 } 1707 1708 func (node Node) toFloat64() (float64, error) { 1709 ret, err := node.toNumber().Float64() 1710 if err != nil { 1711 return 0, err 1712 } 1713 return ret, nil 1714 } 1715 1716 func (node Node) toInt64() (int64, error) { 1717 ret, err := node.toNumber().Int64() 1718 if err != nil { 1719 return 0, err 1720 } 1721 return ret, nil 1722 } 1723 1724 func newBytes(v []byte) Node { 1725 return Node{ 1726 t: types.V_STRING, 1727 p: mem2ptr(v), 1728 l: uint(len(v)), 1729 } 1730 } 1731 1732 // NewString creates a node of type V_STRING. 1733 // v is considered to be a valid UTF-8 string, 1734 // which means it won't be validated and unescaped. 1735 // when the node is encoded to json, v will be escaped. 1736 func NewString(v string) Node { 1737 return Node{ 1738 t: types.V_STRING, 1739 p: rt.StrPtr(v), 1740 l: uint(len(v)), 1741 } 1742 } 1743 1744 // NewArray creates a node of type V_ARRAY, 1745 // using v as its underlying children 1746 func NewArray(v []Node) Node { 1747 s := new(linkedNodes) 1748 s.FromSlice(v) 1749 return newArray(s) 1750 } 1751 1752 func newArray(v *linkedNodes) Node { 1753 return Node{ 1754 t: types.V_ARRAY, 1755 l: uint(v.Len()), 1756 p: unsafe.Pointer(v), 1757 } 1758 } 1759 1760 func (self *Node) setArray(v *linkedNodes) { 1761 self.t = types.V_ARRAY 1762 self.l = uint(v.Len()) 1763 self.p = unsafe.Pointer(v) 1764 } 1765 1766 // NewObject creates a node of type V_OBJECT, 1767 // using v as its underlying children 1768 func NewObject(v []Pair) Node { 1769 s := new(linkedPairs) 1770 s.FromSlice(v) 1771 return newObject(s) 1772 } 1773 1774 func newObject(v *linkedPairs) Node { 1775 return Node{ 1776 t: types.V_OBJECT, 1777 l: uint(v.Len()), 1778 p: unsafe.Pointer(v), 1779 } 1780 } 1781 1782 func (self *Node) setObject(v *linkedPairs) { 1783 self.t = types.V_OBJECT 1784 self.l = uint(v.Len()) 1785 self.p = unsafe.Pointer(v) 1786 } 1787 1788 func newRawNode(str string, typ types.ValueType) Node { 1789 return Node{ 1790 t: _V_RAW | typ, 1791 p: rt.StrPtr(str), 1792 l: uint(len(str)), 1793 } 1794 } 1795 1796 func (self *Node) parseRaw(full bool) { 1797 raw := self.toString() 1798 parser := NewParserObj(raw) 1799 if full { 1800 parser.noLazy = true 1801 parser.skipValue = false 1802 } 1803 var e types.ParsingError 1804 *self, e = parser.Parse() 1805 if e != 0 { 1806 *self = *newSyntaxError(parser.syntaxError(e)) 1807 } 1808 } 1809 1810 var typeJumpTable = [256]types.ValueType{ 1811 '"': types.V_STRING, 1812 '-': _V_NUMBER, 1813 '0': _V_NUMBER, 1814 '1': _V_NUMBER, 1815 '2': _V_NUMBER, 1816 '3': _V_NUMBER, 1817 '4': _V_NUMBER, 1818 '5': _V_NUMBER, 1819 '6': _V_NUMBER, 1820 '7': _V_NUMBER, 1821 '8': _V_NUMBER, 1822 '9': _V_NUMBER, 1823 '[': types.V_ARRAY, 1824 'f': types.V_FALSE, 1825 'n': types.V_NULL, 1826 't': types.V_TRUE, 1827 '{': types.V_OBJECT, 1828 } 1829 1830 func switchRawType(c byte) types.ValueType { 1831 return typeJumpTable[c] 1832 }