encode.go 6.7 KB

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