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. func newJsonContext(head string, tail *jsonContext) *jsonContext {
  31. return &jsonContext{head, tail}
  32. }
  33. // String displays the context in reverse.
  34. // This plays well with the data structure's persistent nature with
  35. // Cons and a json document's tree structure.
  36. func (c *jsonContext) String(del ...string) string {
  37. byteArr := make([]byte, 0, c.stringLen())
  38. buf := bytes.NewBuffer(byteArr)
  39. c.writeStringToBuffer(buf, del)
  40. return buf.String()
  41. }
  42. func (c *jsonContext) stringLen() int {
  43. length := 0
  44. if c.tail != nil {
  45. length = c.tail.stringLen() + 1 // add 1 for "."
  46. }
  47. length += len(c.head)
  48. return length
  49. }
  50. func (c *jsonContext) writeStringToBuffer(buf *bytes.Buffer, del []string) {
  51. if c.tail != nil {
  52. c.tail.writeStringToBuffer(buf, del)
  53. if len(del) > 0 {
  54. buf.WriteString(del[0])
  55. } else {
  56. buf.WriteString(".")
  57. }
  58. }
  59. buf.WriteString(c.head)
  60. }