gen-fast-path.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. //+build ignore
  2. // Copyright (c) 2012, 2013 Ugorji Nwoke. All rights reserved.
  3. // Use of this source code is governed by a BSD-style license found in the LICENSE file.
  4. package main
  5. import (
  6. "bytes"
  7. "go/format"
  8. "os"
  9. "strings"
  10. "text/template"
  11. )
  12. const tmplstr = `
  13. // Copyright (c) 2012, 2013 Ugorji Nwoke. All rights reserved.
  14. // Use of this source code is governed by a BSD-style license found in the LICENSE file.
  15. // ************************************************************
  16. // DO NOT EDIT.
  17. // THIS FILE IS GENERATED BY RUNNING: go run gen-fast-path.go
  18. // ************************************************************
  19. package codec
  20. // Fast path functions try to create a fast path encode or decode implementation
  21. // for common maps and slices.
  22. //
  23. // We define the functions and register then in this single file
  24. // so as not to pollute the encode.go and decode.go, and create a dependency in there.
  25. // This file can be omitted without causing a build failure.
  26. //
  27. // The advantage of fast paths is:
  28. // - Many calls bypass reflection altogether
  29. //
  30. // Currently support
  31. // - slice of all builtin types,
  32. // - map of all builtin types to string or interface value
  33. // - symetrical maps of all builtin types (e.g. str-str, uint8-uint8)
  34. // This should provide adequate "typical" implementations.
  35. //
  36. // Note that fast track decode functions must handle values for which an address cannot be obtained.
  37. // For example:
  38. // m2 := map[string]int{}
  39. // p2 := []interface{}{m2}
  40. // // decoding into p2 will bomb if fast track functions do not treat like unaddressable.
  41. //
  42. import (
  43. "reflect"
  44. )
  45. func init() {
  46. if !fastpathEnabled {
  47. return // basically disable the fast path checks (since accessing empty map is basically free)
  48. }
  49. fx := func(i interface{}, fe func(*encFnInfo, reflect.Value), fd func(*decFnInfo, reflect.Value)) {
  50. xrt := reflect.TypeOf(i)
  51. xptr := reflect.ValueOf(xrt).Pointer()
  52. fastpathsTyp[xptr] = xrt
  53. fastpathsEnc[xptr] = fe
  54. fastpathsDec[xptr] = fd
  55. }
  56. {{range .Values}}{{if .Slice }}
  57. fx([]{{ .Elem }}(nil), (*encFnInfo).{{ .MethodName true }}, (*decFnInfo).{{ .MethodName false}}){{end}}{{end}}
  58. {{range .Values}}{{if not .Slice }}
  59. fx(map[{{ .MapKey }}]{{ .Elem }}(nil), (*encFnInfo).{{ .MethodName true }}, (*decFnInfo).{{ .MethodName false}}){{end}}{{end}}
  60. }
  61. // -- encode
  62. {{range .Values}}{{if .Slice }}
  63. func (f *encFnInfo) {{ .MethodName true }}(rv reflect.Value) {
  64. v := rv.Interface().([]{{ .Elem }})
  65. f.ee.encodeArrayPreamble(len(v))
  66. for _, v2 := range v {
  67. {{ encmd .Elem "v2"}}
  68. }
  69. }
  70. {{end}}{{end}}
  71. {{range .Values}}{{if not .Slice }}
  72. func (f *encFnInfo) {{ .MethodName true }}(rv reflect.Value) {
  73. v := rv.Interface().(map[{{ .MapKey }}]{{ .Elem }})
  74. f.ee.encodeMapPreamble(len(v))
  75. {{if eq .MapKey "string"}}asSymbols := f.e.h.AsSymbols&AsSymbolMapStringKeysFlag != 0{{end}}
  76. for k2, v2 := range v {
  77. {{if eq .MapKey "string"}}if asSymbols {
  78. f.ee.encodeSymbol(k2)
  79. } else {
  80. f.ee.encodeString(c_UTF8, k2)
  81. }{{else}}{{ encmd .MapKey "k2"}}{{end}}
  82. {{ encmd .Elem "v2"}}
  83. }
  84. }
  85. {{end}}{{end}}
  86. // -- decode
  87. {{range .Values}}{{if .Slice }}
  88. func (f *decFnInfo) {{ .MethodName false }}(rv reflect.Value) {
  89. xaddr := rv.CanAddr()
  90. var vp *[]{{ .Elem }}
  91. var v []{{ .Elem }}
  92. if xaddr {
  93. vp = rv.Addr().Interface().(*[]{{ .Elem }})
  94. v = *vp
  95. } else {
  96. v = rv.Interface().([]{{ .Elem }})
  97. }
  98. vtype := f.dd.currentEncodedType()
  99. if vtype == valueTypeNil {
  100. if xaddr {
  101. v = nil
  102. *vp = v
  103. } // else do nothing.
  104. return
  105. }
  106. _, containerLenS := decContLens(f.dd, vtype)
  107. if v == nil {
  108. v = make([]{{ .Elem }}, containerLenS, containerLenS)
  109. } else if containerLenS > cap(v) {
  110. if f.array {
  111. decErr(msgDecCannotExpandArr, cap(v), containerLenS)
  112. }
  113. s := make([]{{ .Elem }}, containerLenS, containerLenS)
  114. copy(s, v)
  115. v = s
  116. } else if containerLenS > len(v) {
  117. v = v[:containerLenS]
  118. }
  119. for j := 0; j < containerLenS; j++ {
  120. {{ if eq .Elem "interface{}" }}f.d.decode(&v[j])
  121. {{ else }}f.dd.initReadNext()
  122. v[j] = {{ decmd .Elem }}
  123. {{ end }}
  124. }
  125. if xaddr {
  126. *vp = v
  127. }
  128. }
  129. {{end}}{{end}}
  130. {{range .Values}}{{if not .Slice }}
  131. func (f *decFnInfo) {{ .MethodName false }}(rv reflect.Value) {
  132. xaddr := rv.CanAddr()
  133. var vp (*map[{{ .MapKey }}]{{ .Elem }})
  134. var v map[{{ .MapKey }}]{{ .Elem }}
  135. if xaddr {
  136. vp = rv.Addr().Interface().(*map[{{ .MapKey }}]{{ .Elem }})
  137. v = *vp
  138. } else {
  139. v = rv.Interface().(map[{{ .MapKey }}]{{ .Elem }})
  140. }
  141. vtype := f.dd.currentEncodedType()
  142. if vtype == valueTypeNil {
  143. if xaddr {
  144. v = nil
  145. *vp = v
  146. } // else do nothing. We never remove from a map.
  147. return
  148. }
  149. containerLen := f.dd.readMapLen()
  150. if xaddr && v == nil {
  151. v = make(map[{{ .MapKey }}]{{ .Elem }}, containerLen)
  152. *vp = v
  153. }
  154. for j := 0; j < containerLen; j++ {
  155. {{ if eq .MapKey "interface{}" }}var mk interface{}
  156. f.d.decode(&mk)
  157. // special case if a byte array.
  158. if bv, bok := mk.([]byte); bok {
  159. mk = string(bv)
  160. }
  161. {{ else }}f.dd.initReadNext()
  162. mk := {{ decmd .MapKey }}
  163. {{ end }}
  164. mv := v[mk]
  165. {{ if eq .Elem "interface{}" }}f.d.decode(&mv)
  166. {{ else }}f.dd.initReadNext()
  167. mv = {{ decmd .Elem }}
  168. {{ end }}
  169. if v != nil {
  170. v[mk] = mv
  171. }
  172. }
  173. }
  174. {{end}}{{end}}
  175. `
  176. type genInfo struct {
  177. Slice bool
  178. MapKey string
  179. Elem string
  180. }
  181. func EncCommandAsString(s string, vname string) string {
  182. switch s {
  183. case "uint", "uint8", "uint16", "uint32", "uint64":
  184. return "f.ee.encodeUint(uint64(" + vname + "))"
  185. case "int", "int8", "int16", "int32", "int64":
  186. return "f.ee.encodeInt(int64(" + vname + "))"
  187. case "string":
  188. return "f.ee.encodeString(c_UTF8, " + vname + ")"
  189. case "float32":
  190. return "f.ee.encodeFloat32(" + vname + ")"
  191. case "float64":
  192. return "f.ee.encodeFloat64(" + vname + ")"
  193. case "bool":
  194. return "f.ee.encodeBool(" + vname + ")"
  195. case "symbol":
  196. return "f.ee.encodeSymbol(" + vname + ")"
  197. default:
  198. return "f.e.encode(" + vname + ")"
  199. }
  200. }
  201. func DecCommandAsString(s string) string {
  202. switch s {
  203. case "uint":
  204. return "uint(f.dd.decodeUint(uintBitsize))"
  205. case "uint8":
  206. return "uint8(f.dd.decodeUint(8))"
  207. case "uint16":
  208. return "uint16(f.dd.decodeUint(16))"
  209. case "uint32":
  210. return "uint32(f.dd.decodeUint(32))"
  211. case "uint64":
  212. return "f.dd.decodeUint(64)"
  213. case "int":
  214. return "int(f.dd.decodeInt(intBitsize))"
  215. case "int8":
  216. return "int8(f.dd.decodeInt(8))"
  217. case "int16":
  218. return "int16(f.dd.decodeInt(16))"
  219. case "int32":
  220. return "int32(f.dd.decodeInt(32))"
  221. case "int64":
  222. return "f.dd.decodeInt(64)"
  223. case "string":
  224. return "f.dd.decodeString()"
  225. case "float32":
  226. return "float32(f.dd.decodeFloat(true))"
  227. case "float64":
  228. return "f.dd.decodeFloat(false)"
  229. case "bool":
  230. return "f.dd.decodeBool()"
  231. default:
  232. panic("unknown type for decode: " + s)
  233. }
  234. }
  235. func (x *genInfo) MethodName(encode bool) string {
  236. var name []byte
  237. name = append(name, "fast"...)
  238. if encode {
  239. name = append(name, "Enc"...)
  240. } else {
  241. name = append(name, "Dec"...)
  242. }
  243. if x.Slice {
  244. name = append(name, "Slice"...)
  245. } else {
  246. name = append(name, "Map"...)
  247. name = append(name, titleCaseName(x.MapKey)...)
  248. }
  249. name = append(name, titleCaseName(x.Elem)...)
  250. return string(name)
  251. }
  252. func titleCaseName(s string) string {
  253. switch s {
  254. case "interface{}":
  255. return "Intf"
  256. default:
  257. return strings.ToUpper(s[0:1]) + s[1:]
  258. }
  259. }
  260. type genTmpl struct {
  261. Values []genInfo
  262. }
  263. func main() {
  264. types := []string{
  265. "interface{}",
  266. "string",
  267. "float32",
  268. "float64",
  269. "uint",
  270. "uint8",
  271. "uint16",
  272. "uint32",
  273. "uint64",
  274. "int",
  275. "int8",
  276. "int16",
  277. "int32",
  278. "int64",
  279. "bool",
  280. }
  281. // keep as slice, so it is in specific iteration order.
  282. // Initial order was uint64, string, interface{}, int, int64
  283. mapvaltypes := []string{
  284. "interface{}",
  285. "string",
  286. "uint",
  287. "uint32",
  288. "uint64",
  289. "int",
  290. "int32",
  291. "int64",
  292. }
  293. mapvaltypes2 := make(map[string]bool)
  294. for _, s := range mapvaltypes {
  295. mapvaltypes2[s] = true
  296. }
  297. var gt genTmpl
  298. // For each slice or map type, there must be a (symetrical) Encode and Decode fast-path function
  299. for _, s := range types {
  300. if s != "uint8" { // do not generate fast path for slice of bytes. Treat specially already.
  301. gt.Values = append(gt.Values, genInfo{true, "", s})
  302. }
  303. if !mapvaltypes2[s] {
  304. gt.Values = append(gt.Values, genInfo{false, s, s})
  305. }
  306. for _, ms := range mapvaltypes {
  307. gt.Values = append(gt.Values, genInfo{false, s, ms})
  308. }
  309. }
  310. funcs := make(template.FuncMap)
  311. // funcs["haspfx"] = strings.HasPrefix
  312. funcs["encmd"] = EncCommandAsString
  313. funcs["decmd"] = DecCommandAsString
  314. t := template.New("")
  315. t = t.Funcs(funcs)
  316. t, err := t.Parse(tmplstr)
  317. if err != nil {
  318. panic(err)
  319. }
  320. var out bytes.Buffer
  321. err = t.Execute(&out, &gt)
  322. if err != nil {
  323. panic(err)
  324. }
  325. // os.Stdout.Write(out.Bytes())
  326. bout, err := format.Source(out.Bytes())
  327. if err != nil {
  328. panic(err)
  329. }
  330. os.Stdout.Write(bout)
  331. }