encode.go 6.3 KB

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