encode.go 6.6 KB

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