encode.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. package yaml
  2. import (
  3. "reflect"
  4. "regexp"
  5. "sort"
  6. "strconv"
  7. "strings"
  8. "time"
  9. )
  10. type encoder struct {
  11. emitter yaml_emitter_t
  12. event yaml_event_t
  13. out []byte
  14. flow bool
  15. }
  16. func newEncoder() (e *encoder) {
  17. e = &encoder{}
  18. e.must(yaml_emitter_initialize(&e.emitter))
  19. yaml_emitter_set_output_string(&e.emitter, &e.out)
  20. e.must(yaml_stream_start_event_initialize(&e.event, yaml_UTF8_ENCODING))
  21. e.emit()
  22. e.must(yaml_document_start_event_initialize(&e.event, nil, nil, true))
  23. e.emit()
  24. return e
  25. }
  26. func (e *encoder) finish() {
  27. e.must(yaml_document_end_event_initialize(&e.event, true))
  28. e.emit()
  29. e.emitter.open_ended = false
  30. e.must(yaml_stream_end_event_initialize(&e.event))
  31. e.emit()
  32. }
  33. func (e *encoder) destroy() {
  34. yaml_emitter_delete(&e.emitter)
  35. }
  36. func (e *encoder) emit() {
  37. // This will internally delete the e.event value.
  38. if !yaml_emitter_emit(&e.emitter, &e.event) && e.event.typ != yaml_DOCUMENT_END_EVENT && e.event.typ != yaml_STREAM_END_EVENT {
  39. e.must(false)
  40. }
  41. }
  42. func (e *encoder) must(ok bool) {
  43. if !ok {
  44. msg := e.emitter.problem
  45. if msg == "" {
  46. msg = "Unknown problem generating YAML content"
  47. }
  48. fail(msg)
  49. }
  50. }
  51. func (e *encoder) marshal(tag string, in reflect.Value) {
  52. var value interface{}
  53. if getter, ok := in.Interface().(Getter); ok {
  54. tag, value = getter.GetYAML()
  55. tag = longTag(tag)
  56. if value == nil {
  57. e.nilv()
  58. return
  59. }
  60. in = reflect.ValueOf(value)
  61. }
  62. switch in.Kind() {
  63. case reflect.Interface:
  64. if in.IsNil() {
  65. e.nilv()
  66. } else {
  67. e.marshal(tag, in.Elem())
  68. }
  69. case reflect.Map:
  70. e.mapv(tag, in)
  71. case reflect.Ptr:
  72. if in.IsNil() {
  73. e.nilv()
  74. } else {
  75. e.marshal(tag, in.Elem())
  76. }
  77. case reflect.Struct:
  78. e.structv(tag, in)
  79. case reflect.Slice:
  80. e.slicev(tag, in)
  81. case reflect.String:
  82. e.stringv(tag, in)
  83. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  84. if in.Type() == durationType {
  85. e.stringv(tag, reflect.ValueOf(in.Interface().(time.Duration).String()))
  86. } else {
  87. e.intv(tag, in)
  88. }
  89. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
  90. e.uintv(tag, in)
  91. case reflect.Float32, reflect.Float64:
  92. e.floatv(tag, in)
  93. case reflect.Bool:
  94. e.boolv(tag, in)
  95. default:
  96. panic("Can't marshal type: " + in.Type().String())
  97. }
  98. }
  99. func (e *encoder) mapv(tag string, in reflect.Value) {
  100. e.mappingv(tag, func() {
  101. keys := keyList(in.MapKeys())
  102. sort.Sort(keys)
  103. for _, k := range keys {
  104. e.marshal("", k)
  105. e.marshal("", in.MapIndex(k))
  106. }
  107. })
  108. }
  109. func (e *encoder) structv(tag string, in reflect.Value) {
  110. sinfo, err := getStructInfo(in.Type())
  111. if err != nil {
  112. panic(err)
  113. }
  114. e.mappingv(tag, func() {
  115. for _, info := range sinfo.FieldsList {
  116. var value reflect.Value
  117. if info.Inline == nil {
  118. value = in.Field(info.Num)
  119. } else {
  120. value = in.FieldByIndex(info.Inline)
  121. }
  122. if info.OmitEmpty && isZero(value) {
  123. continue
  124. }
  125. e.marshal("", reflect.ValueOf(info.Key))
  126. e.flow = info.Flow
  127. e.marshal("", value)
  128. }
  129. })
  130. }
  131. func (e *encoder) mappingv(tag string, f func()) {
  132. implicit := tag == ""
  133. style := yaml_BLOCK_MAPPING_STYLE
  134. if e.flow {
  135. e.flow = false
  136. style = yaml_FLOW_MAPPING_STYLE
  137. }
  138. e.must(yaml_mapping_start_event_initialize(&e.event, nil, []byte(tag), implicit, style))
  139. e.emit()
  140. f()
  141. e.must(yaml_mapping_end_event_initialize(&e.event))
  142. e.emit()
  143. }
  144. func (e *encoder) slicev(tag string, in reflect.Value) {
  145. implicit := tag == ""
  146. style := yaml_BLOCK_SEQUENCE_STYLE
  147. if e.flow {
  148. e.flow = false
  149. style = yaml_FLOW_SEQUENCE_STYLE
  150. }
  151. e.must(yaml_sequence_start_event_initialize(&e.event, nil, []byte(tag), implicit, style))
  152. e.emit()
  153. n := in.Len()
  154. for i := 0; i < n; i++ {
  155. e.marshal("", in.Index(i))
  156. }
  157. e.must(yaml_sequence_end_event_initialize(&e.event))
  158. e.emit()
  159. }
  160. // isBase60 returns whether s is in base 60 notation as defined in YAML 1.1.
  161. //
  162. // The base 60 float notation in YAML 1.1 is a terrible idea and is unsupported
  163. // in YAML 1.2 and by this package, but these should be marshalled quoted for
  164. // the time being for compatibility with other parsers.
  165. func isBase60Float(s string) (result bool) {
  166. // Fast path.
  167. if s == "" {
  168. return false
  169. }
  170. c := s[0]
  171. if !(c == '+' || c == '-' || c >= '0' && c <= '9') || strings.IndexByte(s, ':') < 0 {
  172. return false
  173. }
  174. // Do the full match.
  175. return base60float.MatchString(s)
  176. }
  177. // From http://yaml.org/type/float.html, except the regular expression there
  178. // is bogus. In practice parsers do not enforce the "\.[0-9_]*" suffix.
  179. var base60float = regexp.MustCompile(`^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+(?:\.[0-9_]*)?$`)
  180. func (e *encoder) stringv(tag string, in reflect.Value) {
  181. var style yaml_scalar_style_t
  182. s := in.String()
  183. rtag, rs := resolve("", s)
  184. if rtag == yaml_BINARY_TAG {
  185. if tag == "" || tag == yaml_STR_TAG {
  186. tag = rtag
  187. s = rs.(string)
  188. } else if tag == yaml_BINARY_TAG {
  189. fail("explicitly tagged !!binary data must be base64-encoded")
  190. } else {
  191. fail("cannot marshal invalid UTF-8 data as " + shortTag(tag))
  192. }
  193. }
  194. if tag == "" && (rtag != yaml_STR_TAG || isBase60Float(s)) {
  195. style = yaml_DOUBLE_QUOTED_SCALAR_STYLE
  196. } else if strings.Contains(s, "\n") {
  197. style = yaml_LITERAL_SCALAR_STYLE
  198. } else {
  199. style = yaml_PLAIN_SCALAR_STYLE
  200. }
  201. e.emitScalar(s, "", tag, style)
  202. }
  203. func (e *encoder) boolv(tag string, in reflect.Value) {
  204. var s string
  205. if in.Bool() {
  206. s = "true"
  207. } else {
  208. s = "false"
  209. }
  210. e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE)
  211. }
  212. func (e *encoder) intv(tag string, in reflect.Value) {
  213. s := strconv.FormatInt(in.Int(), 10)
  214. e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE)
  215. }
  216. func (e *encoder) uintv(tag string, in reflect.Value) {
  217. s := strconv.FormatUint(in.Uint(), 10)
  218. e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE)
  219. }
  220. func (e *encoder) floatv(tag string, in reflect.Value) {
  221. // FIXME: Handle 64 bits here.
  222. s := strconv.FormatFloat(float64(in.Float()), 'g', -1, 32)
  223. switch s {
  224. case "+Inf":
  225. s = ".inf"
  226. case "-Inf":
  227. s = "-.inf"
  228. case "NaN":
  229. s = ".nan"
  230. }
  231. e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE)
  232. }
  233. func (e *encoder) nilv() {
  234. e.emitScalar("null", "", "", yaml_PLAIN_SCALAR_STYLE)
  235. }
  236. func (e *encoder) emitScalar(value, anchor, tag string, style yaml_scalar_style_t) {
  237. implicit := tag == ""
  238. e.must(yaml_scalar_event_initialize(&e.event, []byte(anchor), []byte(tag), []byte(value), implicit, implicit, style))
  239. e.emit()
  240. }