encode.go 6.8 KB

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