encode.go 5.9 KB

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