http urls monitor.

encode.go 8.6KB

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