encode.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. package yaml
  2. import (
  3. "encoding"
  4. "fmt"
  5. "io"
  6. "reflect"
  7. "regexp"
  8. "sort"
  9. "strconv"
  10. "strings"
  11. "time"
  12. "unicode/utf8"
  13. )
  14. type encoder struct {
  15. emitter yaml_emitter_t
  16. event yaml_event_t
  17. out []byte
  18. flow bool
  19. // doneInit holds whether the initial stream_start_event has been
  20. // emitted.
  21. doneInit bool
  22. }
  23. func newEncoder() *encoder {
  24. e := &encoder{}
  25. yaml_emitter_initialize(&e.emitter)
  26. yaml_emitter_set_output_string(&e.emitter, &e.out)
  27. yaml_emitter_set_unicode(&e.emitter, true)
  28. return e
  29. }
  30. func newEncoderWithWriter(w io.Writer) *encoder {
  31. e := &encoder{}
  32. yaml_emitter_initialize(&e.emitter)
  33. yaml_emitter_set_output_writer(&e.emitter, w)
  34. yaml_emitter_set_unicode(&e.emitter, true)
  35. return e
  36. }
  37. func (e *encoder) init() {
  38. if e.doneInit {
  39. return
  40. }
  41. yaml_stream_start_event_initialize(&e.event, yaml_UTF8_ENCODING)
  42. e.emit()
  43. e.doneInit = true
  44. }
  45. func (e *encoder) finish() {
  46. e.emitter.open_ended = false
  47. yaml_stream_end_event_initialize(&e.event)
  48. e.emit()
  49. }
  50. func (e *encoder) destroy() {
  51. yaml_emitter_delete(&e.emitter)
  52. }
  53. func (e *encoder) emit() {
  54. // This will internally delete the e.event value.
  55. e.must(yaml_emitter_emit(&e.emitter, &e.event))
  56. }
  57. func (e *encoder) must(ok bool) {
  58. if !ok {
  59. msg := e.emitter.problem
  60. if msg == "" {
  61. msg = "unknown problem generating YAML content"
  62. }
  63. failf("%s", msg)
  64. }
  65. }
  66. func (e *encoder) marshalDoc(tag string, in reflect.Value) {
  67. e.init()
  68. yaml_document_start_event_initialize(&e.event, nil, nil, true)
  69. e.emit()
  70. e.marshal(tag, in)
  71. yaml_document_end_event_initialize(&e.event, true)
  72. e.emit()
  73. }
  74. func (e *encoder) marshal(tag string, in reflect.Value) {
  75. if !in.IsValid() || in.Kind() == reflect.Ptr && in.IsNil() {
  76. e.nilv()
  77. return
  78. }
  79. iface := in.Interface()
  80. switch m := iface.(type) {
  81. case Marshaler:
  82. v, err := m.MarshalYAML()
  83. if err != nil {
  84. fail(err)
  85. }
  86. if v == nil {
  87. e.nilv()
  88. return
  89. }
  90. in = reflect.ValueOf(v)
  91. case time.Time:
  92. // Although time.Time implements TextMarshaler,
  93. // we don't want to treat it as a string for YAML
  94. // purposes because YAML has special support for
  95. // timestamps.
  96. case encoding.TextMarshaler:
  97. text, err := m.MarshalText()
  98. if err != nil {
  99. fail(err)
  100. }
  101. in = reflect.ValueOf(string(text))
  102. }
  103. switch in.Kind() {
  104. case reflect.Interface:
  105. if in.IsNil() {
  106. e.nilv()
  107. } else {
  108. e.marshal(tag, in.Elem())
  109. }
  110. case reflect.Map:
  111. e.mapv(tag, in)
  112. case reflect.Ptr:
  113. if in.IsNil() {
  114. e.nilv()
  115. } else {
  116. e.marshal(tag, in.Elem())
  117. }
  118. case reflect.Struct:
  119. if in.Type() == timeType {
  120. e.timev(tag, in)
  121. } else {
  122. e.structv(tag, in)
  123. }
  124. case reflect.Slice:
  125. if in.Type().Elem() == mapItemType {
  126. e.itemsv(tag, in)
  127. } else {
  128. e.slicev(tag, in)
  129. }
  130. case reflect.String:
  131. e.stringv(tag, in)
  132. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  133. if in.Type() == durationType {
  134. e.stringv(tag, reflect.ValueOf(iface.(time.Duration).String()))
  135. } else {
  136. e.intv(tag, in)
  137. }
  138. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
  139. e.uintv(tag, in)
  140. case reflect.Float32, reflect.Float64:
  141. e.floatv(tag, in)
  142. case reflect.Bool:
  143. e.boolv(tag, in)
  144. default:
  145. panic("cannot marshal type: " + in.Type().String())
  146. }
  147. }
  148. func (e *encoder) mapv(tag string, in reflect.Value) {
  149. e.mappingv(tag, func() {
  150. keys := keyList(in.MapKeys())
  151. sort.Sort(keys)
  152. for _, k := range keys {
  153. e.marshal("", k)
  154. e.marshal("", in.MapIndex(k))
  155. }
  156. })
  157. }
  158. func (e *encoder) itemsv(tag string, in reflect.Value) {
  159. e.mappingv(tag, func() {
  160. slice := in.Convert(reflect.TypeOf([]MapItem{})).Interface().([]MapItem)
  161. for _, item := range slice {
  162. e.marshal("", reflect.ValueOf(item.Key))
  163. e.marshal("", reflect.ValueOf(item.Value))
  164. }
  165. })
  166. }
  167. func (e *encoder) structv(tag string, in reflect.Value) {
  168. sinfo, err := getStructInfo(in.Type())
  169. if err != nil {
  170. panic(err)
  171. }
  172. e.mappingv(tag, func() {
  173. for _, info := range sinfo.FieldsList {
  174. var value reflect.Value
  175. if info.Inline == nil {
  176. value = in.Field(info.Num)
  177. } else {
  178. value = in.FieldByIndex(info.Inline)
  179. }
  180. if info.OmitEmpty && isZero(value) {
  181. continue
  182. }
  183. e.marshal("", reflect.ValueOf(info.Key))
  184. e.flow = info.Flow
  185. e.marshal("", value)
  186. }
  187. if sinfo.InlineMap >= 0 {
  188. m := in.Field(sinfo.InlineMap)
  189. if m.Len() > 0 {
  190. e.flow = false
  191. keys := keyList(m.MapKeys())
  192. sort.Sort(keys)
  193. for _, k := range keys {
  194. if _, found := sinfo.FieldsMap[k.String()]; found {
  195. panic(fmt.Sprintf("Can't have key %q in inlined map; conflicts with struct field", k.String()))
  196. }
  197. e.marshal("", k)
  198. e.flow = false
  199. e.marshal("", m.MapIndex(k))
  200. }
  201. }
  202. }
  203. })
  204. }
  205. func (e *encoder) mappingv(tag string, f func()) {
  206. implicit := tag == ""
  207. style := yaml_BLOCK_MAPPING_STYLE
  208. if e.flow {
  209. e.flow = false
  210. style = yaml_FLOW_MAPPING_STYLE
  211. }
  212. yaml_mapping_start_event_initialize(&e.event, nil, []byte(tag), implicit, style)
  213. e.emit()
  214. f()
  215. yaml_mapping_end_event_initialize(&e.event)
  216. e.emit()
  217. }
  218. func (e *encoder) slicev(tag string, in reflect.Value) {
  219. implicit := tag == ""
  220. style := yaml_BLOCK_SEQUENCE_STYLE
  221. if e.flow {
  222. e.flow = false
  223. style = yaml_FLOW_SEQUENCE_STYLE
  224. }
  225. e.must(yaml_sequence_start_event_initialize(&e.event, nil, []byte(tag), implicit, style))
  226. e.emit()
  227. n := in.Len()
  228. for i := 0; i < n; i++ {
  229. e.marshal("", in.Index(i))
  230. }
  231. e.must(yaml_sequence_end_event_initialize(&e.event))
  232. e.emit()
  233. }
  234. // isBase60 returns whether s is in base 60 notation as defined in YAML 1.1.
  235. //
  236. // The base 60 float notation in YAML 1.1 is a terrible idea and is unsupported
  237. // in YAML 1.2 and by this package, but these should be marshalled quoted for
  238. // the time being for compatibility with other parsers.
  239. func isBase60Float(s string) (result bool) {
  240. // Fast path.
  241. if s == "" {
  242. return false
  243. }
  244. c := s[0]
  245. if !(c == '+' || c == '-' || c >= '0' && c <= '9') || strings.IndexByte(s, ':') < 0 {
  246. return false
  247. }
  248. // Do the full match.
  249. return base60float.MatchString(s)
  250. }
  251. // From http://yaml.org/type/float.html, except the regular expression there
  252. // is bogus. In practice parsers do not enforce the "\.[0-9_]*" suffix.
  253. var base60float = regexp.MustCompile(`^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+(?:\.[0-9_]*)?$`)
  254. func (e *encoder) stringv(tag string, in reflect.Value) {
  255. var style yaml_scalar_style_t
  256. s := in.String()
  257. canUsePlain := true
  258. switch {
  259. case !utf8.ValidString(s):
  260. if tag == yaml_BINARY_TAG {
  261. failf("explicitly tagged !!binary data must be base64-encoded")
  262. }
  263. if tag != "" {
  264. failf("cannot marshal invalid UTF-8 data as %s", shortTag(tag))
  265. }
  266. // It can't be encoded directly as YAML so use a binary tag
  267. // and encode it as base64.
  268. tag = yaml_BINARY_TAG
  269. s = encodeBase64(s)
  270. case tag == "":
  271. // Check to see if it would resolve to a specific
  272. // tag when encoded unquoted. If it doesn't,
  273. // there's no need to quote it.
  274. rtag, _ := resolve("", s)
  275. canUsePlain = rtag == yaml_STR_TAG && !isBase60Float(s)
  276. }
  277. // Note: it's possible for user code to emit invalid YAML
  278. // if they explicitly specify a tag and a string containing
  279. // text that's incompatible with that tag.
  280. switch {
  281. case strings.Contains(s, "\n"):
  282. style = yaml_LITERAL_SCALAR_STYLE
  283. case canUsePlain:
  284. style = yaml_PLAIN_SCALAR_STYLE
  285. default:
  286. style = yaml_DOUBLE_QUOTED_SCALAR_STYLE
  287. }
  288. e.emitScalar(s, "", tag, style)
  289. }
  290. func (e *encoder) boolv(tag string, in reflect.Value) {
  291. var s string
  292. if in.Bool() {
  293. s = "true"
  294. } else {
  295. s = "false"
  296. }
  297. e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE)
  298. }
  299. func (e *encoder) intv(tag string, in reflect.Value) {
  300. s := strconv.FormatInt(in.Int(), 10)
  301. e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE)
  302. }
  303. func (e *encoder) uintv(tag string, in reflect.Value) {
  304. s := strconv.FormatUint(in.Uint(), 10)
  305. e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE)
  306. }
  307. func (e *encoder) timev(tag string, in reflect.Value) {
  308. t := in.Interface().(time.Time)
  309. if tag == "" {
  310. tag = yaml_TIMESTAMP_TAG
  311. }
  312. e.emitScalar(t.Format(time.RFC3339Nano), "", tag, yaml_PLAIN_SCALAR_STYLE)
  313. }
  314. func (e *encoder) floatv(tag string, in reflect.Value) {
  315. s := strconv.FormatFloat(in.Float(), 'g', -1, 64)
  316. switch s {
  317. case "+Inf":
  318. s = ".inf"
  319. case "-Inf":
  320. s = "-.inf"
  321. case "NaN":
  322. s = ".nan"
  323. }
  324. e.emitScalar(s, "", tag, yaml_PLAIN_SCALAR_STYLE)
  325. }
  326. func (e *encoder) nilv() {
  327. e.emitScalar("null", "", "", yaml_PLAIN_SCALAR_STYLE)
  328. }
  329. func (e *encoder) emitScalar(value, anchor, tag string, style yaml_scalar_style_t) {
  330. implicit := tag == ""
  331. e.must(yaml_scalar_event_initialize(&e.event, []byte(anchor), []byte(tag), []byte(value), implicit, implicit, style))
  332. e.emit()
  333. }