jsonContext.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // Copyright 2013 MongoDB, Inc.
  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. // author tolsen
  15. // author-github https://github.com/tolsen
  16. //
  17. // repository-name gojsonschema
  18. // repository-desc An implementation of JSON Schema, based on IETF's draft v4 - Go language.
  19. //
  20. // description Implements a persistent (immutable w/ shared structure) singly-linked list of strings for the purpose of storing a json context
  21. //
  22. // created 04-09-2013
  23. package gojsonschema
  24. import "bytes"
  25. // JsonContext implements a persistent linked-list of strings
  26. type JsonContext struct {
  27. head string
  28. tail *JsonContext
  29. }
  30. // NewJsonContext creates a new JsonContext
  31. func NewJsonContext(head string, tail *JsonContext) *JsonContext {
  32. return &JsonContext{head, tail}
  33. }
  34. // String displays the context in reverse.
  35. // This plays well with the data structure's persistent nature with
  36. // Cons and a json document's tree structure.
  37. func (c *JsonContext) String(del ...string) string {
  38. byteArr := make([]byte, 0, c.stringLen())
  39. buf := bytes.NewBuffer(byteArr)
  40. c.writeStringToBuffer(buf, del)
  41. return buf.String()
  42. }
  43. func (c *JsonContext) stringLen() int {
  44. length := 0
  45. if c.tail != nil {
  46. length = c.tail.stringLen() + 1 // add 1 for "."
  47. }
  48. length += len(c.head)
  49. return length
  50. }
  51. func (c *JsonContext) writeStringToBuffer(buf *bytes.Buffer, del []string) {
  52. if c.tail != nil {
  53. c.tail.writeStringToBuffer(buf, del)
  54. if len(del) > 0 {
  55. buf.WriteString(del[0])
  56. } else {
  57. buf.WriteString(".")
  58. }
  59. }
  60. buf.WriteString(c.head)
  61. }