unmarshal_session.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. // Copyright 2019 Yunion
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package jsonutils
  15. import (
  16. "reflect"
  17. )
  18. type sJsonNodeValues struct {
  19. nodeValue reflect.Value
  20. nodeValueSet bool
  21. targetValues []reflect.Value
  22. }
  23. type sJsonUnmarshalSession struct {
  24. objectMap map[int]*sJsonNodeValues
  25. }
  26. func newJsonUnmarshalSession() *sJsonUnmarshalSession {
  27. return &sJsonUnmarshalSession{
  28. objectMap: make(map[int]*sJsonNodeValues),
  29. }
  30. }
  31. func (s *sJsonUnmarshalSession) saveNodeValue(nodeId int, val reflect.Value) {
  32. if nv, ok := s.objectMap[nodeId]; !ok {
  33. s.objectMap[nodeId] = &sJsonNodeValues{
  34. nodeValue: val,
  35. nodeValueSet: true,
  36. }
  37. } else {
  38. nv.nodeValue = val
  39. nv.nodeValueSet = true
  40. for i := range nv.targetValues {
  41. nv.targetValues[i].Set(val)
  42. }
  43. nv.targetValues = nil
  44. }
  45. }
  46. func (s *sJsonUnmarshalSession) setPointerValue(nodeId int, val reflect.Value) error {
  47. if nv, ok := s.objectMap[nodeId]; ok && nv.nodeValueSet {
  48. val.Set(nv.nodeValue)
  49. } else if ok && !nv.nodeValueSet {
  50. nv.targetValues = append(nv.targetValues, val)
  51. } else {
  52. s.objectMap[nodeId] = &sJsonNodeValues{
  53. nodeValueSet: false,
  54. targetValues: []reflect.Value{
  55. val,
  56. },
  57. }
  58. }
  59. return nil
  60. }