Browse Source

update dependencies

Ask Bjørn Hansen 7 years ago
parent
commit
0f45b612a7
100 changed files with 10812 additions and 6094 deletions
  1. 103 53
      Gopkg.lock
  2. 2 6
      Gopkg.toml
  3. 20 0
      vendor/github.com/beorn7/perks/LICENSE
  4. 316 0
      vendor/github.com/beorn7/perks/quantile/stream.go
  5. 0 0
      vendor/github.com/fsnotify/fsnotify/AUTHORS
  6. 0 0
      vendor/github.com/fsnotify/fsnotify/LICENSE
  7. 0 0
      vendor/github.com/fsnotify/fsnotify/fen.go
  8. 0 0
      vendor/github.com/fsnotify/fsnotify/fsnotify.go
  9. 0 0
      vendor/github.com/fsnotify/fsnotify/inotify.go
  10. 0 0
      vendor/github.com/fsnotify/fsnotify/inotify_poller.go
  11. 0 0
      vendor/github.com/fsnotify/fsnotify/kqueue.go
  12. 0 0
      vendor/github.com/fsnotify/fsnotify/open_mode_bsd.go
  13. 0 0
      vendor/github.com/fsnotify/fsnotify/open_mode_darwin.go
  14. 0 0
      vendor/github.com/fsnotify/fsnotify/windows.go
  15. 4 3
      vendor/github.com/golang/geo/r3/vector.go
  16. 4 3
      vendor/github.com/golang/geo/s1/chordangle.go
  17. 108 5
      vendor/github.com/golang/geo/s2/cell.go
  18. 63 3
      vendor/github.com/golang/geo/s2/edge_distances.go
  19. 78 1
      vendor/github.com/golang/geo/s2/polygon.go
  20. 164 9
      vendor/github.com/golang/geo/s2/predicates.go
  21. 203 0
      vendor/github.com/golang/geo/s2/projections.go
  22. 3 0
      vendor/github.com/golang/protobuf/AUTHORS
  23. 3 0
      vendor/github.com/golang/protobuf/CONTRIBUTORS
  24. 31 0
      vendor/github.com/golang/protobuf/LICENSE
  25. 229 0
      vendor/github.com/golang/protobuf/proto/clone.go
  26. 970 0
      vendor/github.com/golang/protobuf/proto/decode.go
  27. 151 0
      vendor/github.com/golang/protobuf/proto/discard.go
  28. 1362 0
      vendor/github.com/golang/protobuf/proto/encode.go
  29. 300 0
      vendor/github.com/golang/protobuf/proto/equal.go
  30. 587 0
      vendor/github.com/golang/protobuf/proto/extensions.go
  31. 897 0
      vendor/github.com/golang/protobuf/proto/lib.go
  32. 311 0
      vendor/github.com/golang/protobuf/proto/message_set.go
  33. 484 0
      vendor/github.com/golang/protobuf/proto/pointer_reflect.go
  34. 270 0
      vendor/github.com/golang/protobuf/proto/pointer_unsafe.go
  35. 872 0
      vendor/github.com/golang/protobuf/proto/properties.go
  36. 854 0
      vendor/github.com/golang/protobuf/proto/text.go
  37. 895 0
      vendor/github.com/golang/protobuf/proto/text_parser.go
  38. 0 21
      vendor/github.com/hpcloud/tail/LICENSE.txt
  39. 0 7
      vendor/github.com/hpcloud/tail/ratelimiter/Licence
  40. 0 97
      vendor/github.com/hpcloud/tail/ratelimiter/leakybucket.go
  41. 0 60
      vendor/github.com/hpcloud/tail/ratelimiter/memory.go
  42. 0 6
      vendor/github.com/hpcloud/tail/ratelimiter/storage.go
  43. 0 437
      vendor/github.com/hpcloud/tail/tail.go
  44. 0 11
      vendor/github.com/hpcloud/tail/tail_posix.go
  45. 0 12
      vendor/github.com/hpcloud/tail/tail_windows.go
  46. 0 48
      vendor/github.com/hpcloud/tail/util/util.go
  47. 0 36
      vendor/github.com/hpcloud/tail/watch/filechanges.go
  48. 0 135
      vendor/github.com/hpcloud/tail/watch/inotify.go
  49. 0 248
      vendor/github.com/hpcloud/tail/watch/inotify_tracker.go
  50. 0 118
      vendor/github.com/hpcloud/tail/watch/polling.go
  51. 0 20
      vendor/github.com/hpcloud/tail/watch/watch.go
  52. 0 92
      vendor/github.com/hpcloud/tail/winfile/winfile.go
  53. 0 20
      vendor/github.com/influxdata/influxdb/LICENSE
  54. 0 62
      vendor/github.com/influxdata/influxdb/LICENSE_OF_DEPENDENCIES.md
  55. 0 638
      vendor/github.com/influxdata/influxdb/client/v2/client.go
  56. 0 112
      vendor/github.com/influxdata/influxdb/client/v2/udp.go
  57. 0 48
      vendor/github.com/influxdata/influxdb/models/consistency.go
  58. 0 32
      vendor/github.com/influxdata/influxdb/models/inline_fnv.go
  59. 0 44
      vendor/github.com/influxdata/influxdb/models/inline_strconv_parse.go
  60. 0 2328
      vendor/github.com/influxdata/influxdb/models/points.go
  61. 0 62
      vendor/github.com/influxdata/influxdb/models/rows.go
  62. 0 42
      vendor/github.com/influxdata/influxdb/models/statistic.go
  63. 0 74
      vendor/github.com/influxdata/influxdb/models/time.go
  64. 0 7
      vendor/github.com/influxdata/influxdb/models/uint_support.go
  65. 0 115
      vendor/github.com/influxdata/influxdb/pkg/escape/bytes.go
  66. 0 21
      vendor/github.com/influxdata/influxdb/pkg/escape/strings.go
  67. 0 21
      vendor/github.com/kr/pretty/License
  68. 0 265
      vendor/github.com/kr/pretty/diff.go
  69. 0 328
      vendor/github.com/kr/pretty/formatter.go
  70. 0 108
      vendor/github.com/kr/pretty/pretty.go
  71. 0 41
      vendor/github.com/kr/pretty/zero.go
  72. 0 19
      vendor/github.com/kr/text/License
  73. 0 3
      vendor/github.com/kr/text/doc.go
  74. 0 74
      vendor/github.com/kr/text/indent.go
  75. 0 86
      vendor/github.com/kr/text/wrap.go
  76. 201 0
      vendor/github.com/matttproud/golang_protobuf_extensions/LICENSE
  77. 1 0
      vendor/github.com/matttproud/golang_protobuf_extensions/NOTICE
  78. 75 0
      vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/decode.go
  79. 16 0
      vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/doc.go
  80. 46 0
      vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/encode.go
  81. 4 7
      vendor/github.com/miekg/dns/client.go
  82. 1 1
      vendor/github.com/miekg/dns/clientconfig.go
  83. 2 2
      vendor/github.com/miekg/dns/doc.go
  84. 45 22
      vendor/github.com/miekg/dns/msg.go
  85. 65 60
      vendor/github.com/miekg/dns/server.go
  86. 23 10
      vendor/github.com/miekg/dns/udp.go
  87. 1 1
      vendor/github.com/miekg/dns/version.go
  88. 1 3
      vendor/github.com/oschwald/maxminddb-golang/mmap_unix.go
  89. 14 1
      vendor/github.com/oschwald/maxminddb-golang/reader.go
  90. 3 1
      vendor/github.com/oschwald/maxminddb-golang/reader_appengine.go
  91. 7 5
      vendor/github.com/oschwald/maxminddb-golang/reader_other.go
  92. 18 0
      vendor/github.com/prometheus/client_golang/AUTHORS.md
  93. 201 0
      vendor/github.com/prometheus/client_golang/LICENSE
  94. 23 0
      vendor/github.com/prometheus/client_golang/NOTICE
  95. 75 0
      vendor/github.com/prometheus/client_golang/prometheus/collector.go
  96. 172 0
      vendor/github.com/prometheus/client_golang/prometheus/counter.go
  97. 205 0
      vendor/github.com/prometheus/client_golang/prometheus/desc.go
  98. 181 0
      vendor/github.com/prometheus/client_golang/prometheus/doc.go
  99. 119 0
      vendor/github.com/prometheus/client_golang/prometheus/expvar_collector.go
  100. 29 0
      vendor/github.com/prometheus/client_golang/prometheus/fnv.go

+ 103 - 53
Gopkg.lock

@@ -7,6 +7,12 @@
   packages = ["."]
   revision = "f9bd360d00b902548fbb80837aef90dca2c8285e"
 
+[[projects]]
+  branch = "master"
+  name = "github.com/beorn7/perks"
+  packages = ["quantile"]
+  revision = "3a771d992973f24aa725d07868b467d1ddfceafb"
+
 [[projects]]
   name = "github.com/davecgh/go-spew"
   packages = ["spew"]
@@ -14,52 +20,52 @@
   version = "v1.1.0"
 
 [[projects]]
-  branch = "master"
-  name = "github.com/golang/geo"
-  packages = ["r1","r2","r3","s1","s2"]
-  revision = "a8523298cefedcf7b70bbbf4eeef24cbb3258376"
-
-[[projects]]
-  branch = "master"
-  name = "github.com/hpcloud/tail"
-  packages = [".","ratelimiter","util","watch","winfile"]
-  revision = "37f4271387456dd1bf82ab1ad9229f060cc45386"
+  name = "github.com/fsnotify/fsnotify"
+  packages = ["."]
+  revision = "c2828203cd70a50dcccfb2761f8b1f8ceef9a8e9"
+  version = "v1.4.7"
 
 [[projects]]
   branch = "master"
-  name = "github.com/influxdata/influxdb"
-  packages = ["client/v2","models","pkg/escape"]
-  revision = "b228fc5f0d0aa523be7c39f0ee28187084a1e271"
+  name = "github.com/golang/geo"
+  packages = [
+    "r1",
+    "r2",
+    "r3",
+    "s1",
+    "s2"
+  ]
+  revision = "fb250ae94fbe10f86b4f1a9b70a19925da3410b9"
+
+[[projects]]
+  name = "github.com/golang/protobuf"
+  packages = ["proto"]
+  revision = "925541529c1fa6821df4e44ce2723319eb2be768"
+  version = "v1.0.0"
 
 [[projects]]
-  branch = "master"
-  name = "github.com/kr/pretty"
-  packages = ["."]
-  revision = "cfb55aafdaf3ec08f0db22699ab822c50091b1c4"
+  name = "github.com/matttproud/golang_protobuf_extensions"
+  packages = ["pbutil"]
+  revision = "3247c84500bff8d9fb6d579d800f20b3e091582c"
+  version = "v1.0.0"
 
 [[projects]]
   branch = "master"
-  name = "github.com/kr/text"
-  packages = ["."]
-  revision = "7cafcd837844e784b526369c9bce262804aebc60"
-
-[[projects]]
   name = "github.com/miekg/dns"
   packages = ["."]
-  revision = "5364553f1ee9cddc7ac8b62dce148309c386695b"
-  version = "v1.0.4"
+  revision = "01d59357d468872339068bcd5d55a00e2463051f"
 
 [[projects]]
   name = "github.com/oschwald/geoip2-golang"
   packages = ["."]
-  revision = "b1581f42de7092eb285fa413a1310f90c4f328fb"
-  version = "v1.2.0"
+  revision = "7118115686e16b77967cdbf55d1b944fe14ad312"
+  version = "v1.2.1"
 
 [[projects]]
   name = "github.com/oschwald/maxminddb-golang"
   packages = ["."]
-  revision = "8727e98aa1b91610eb184ed1ab615943b8d9deb0"
-  version = "v1.2.1"
+  revision = "c5bec84d1963260297932a1b7a1753c8420717a7"
+  version = "v1.3.0"
 
 [[projects]]
   name = "github.com/pborman/uuid"
@@ -73,47 +79,97 @@
   revision = "792786c7400a136282c1664665ae0a8db921c6c2"
   version = "v1.0.0"
 
+[[projects]]
+  name = "github.com/prometheus/client_golang"
+  packages = [
+    "prometheus",
+    "prometheus/promhttp"
+  ]
+  revision = "c5b7fccd204277076155f10851dad72b76a49317"
+  version = "v0.8.0"
+
+[[projects]]
+  branch = "master"
+  name = "github.com/prometheus/client_model"
+  packages = ["go"]
+  revision = "99fa1f4be8e564e8a6b613da7fa6f46c9edafc6c"
+
+[[projects]]
+  branch = "master"
+  name = "github.com/prometheus/common"
+  packages = [
+    "expfmt",
+    "internal/bitbucket.org/ww/goautoneg",
+    "model"
+  ]
+  revision = "d811d2e9bf898806ecfb6ef6296774b13ffc314c"
+
+[[projects]]
+  branch = "master"
+  name = "github.com/prometheus/procfs"
+  packages = [
+    ".",
+    "internal/util",
+    "nfs",
+    "xfs"
+  ]
+  revision = "8b1c2da0d56deffdbb9e48d4414b4e674bd8083e"
+
 [[projects]]
   branch = "master"
   name = "github.com/rcrowley/go-metrics"
   packages = ["."]
-  revision = "8732c616f52954686704c8645fe1a9d59e9df7c1"
+  revision = "d932a24a8ccb8fcadc993e5c6c58f93dac168294"
 
 [[projects]]
   branch = "master"
   name = "github.com/stretchr/testify"
-  packages = ["assert","require"]
-  revision = "be8372ae8ec5c6daaed3cc28ebf73c54b737c240"
+  packages = [
+    "assert",
+    "require"
+  ]
+  revision = "c679ae2cc0cb27ec3293fea7e254e47386f05d69"
 
 [[projects]]
   branch = "master"
   name = "golang.org/x/crypto"
-  packages = ["ed25519","ed25519/internal/edwards25519"]
-  revision = "432090b8f568c018896cd8a0fb0345872bbac6ce"
+  packages = [
+    "ed25519",
+    "ed25519/internal/edwards25519"
+  ]
+  revision = "b49d69b5da943f7ef3c9cf91c8777c1f78a0cc3c"
 
 [[projects]]
   branch = "master"
   name = "golang.org/x/net"
-  packages = ["bpf","internal/iana","internal/socket","ipv4","ipv6","websocket"]
-  revision = "cbe0f9307d0156177f9dd5dc85da1a31abc5f2fb"
+  packages = [
+    "bpf",
+    "internal/iana",
+    "internal/socket",
+    "ipv4",
+    "ipv6"
+  ]
+  revision = "5f9ae10d9af5b1c89ae6904293b14b064d4ada23"
 
 [[projects]]
   branch = "master"
   name = "golang.org/x/sys"
-  packages = ["unix","windows"]
-  revision = "37707fdb30a5b38865cfb95e5aab41707daec7fd"
-
-[[projects]]
-  name = "gopkg.in/fsnotify.v1"
-  packages = ["."]
-  revision = "c2828203cd70a50dcccfb2761f8b1f8ceef9a8e9"
-  version = "v1.4.7"
+  packages = [
+    "unix",
+    "windows"
+  ]
+  revision = "bb9c189858d91f42db229b04d45a4c3d23a7662a"
 
 [[projects]]
   name = "gopkg.in/gcfg.v1"
-  packages = [".","scanner","token","types"]
-  revision = "298b7a6a3838f79debfaee8bd3bfb2b8d779e756"
-  version = "v1.2.1"
+  packages = [
+    ".",
+    "scanner",
+    "token",
+    "types"
+  ]
+  revision = "f02745ab41b9d54a9d495f3356e76f7396da404c"
+  version = "v1.2.2"
 
 [[projects]]
   branch = "v2.0"
@@ -121,12 +177,6 @@
   packages = ["."]
   revision = "aee4629129445bbdfb69aa565537dcfa16544311"
 
-[[projects]]
-  branch = "v1"
-  name = "gopkg.in/tomb.v1"
-  packages = ["."]
-  revision = "dd632973f1e7218eb1089048e0798ec9ae7dceb8"
-
 [[projects]]
   name = "gopkg.in/warnings.v0"
   packages = ["."]
@@ -136,6 +186,6 @@
 [solve-meta]
   analyzer-name = "dep"
   analyzer-version = 1
-  inputs-digest = "f0c6f2e8ea3e595a7d2b5733fcff121dda3c3022a45d5dee81b2b30b54e5b260"
+  inputs-digest = "7190fccfeab013147857f68f6b40036db654c4e57e5f830c5601d873fa9d299c"
   solver-name = "gps-cdcl"
   solver-version = 1

+ 2 - 6
Gopkg.toml

@@ -32,12 +32,8 @@
   name = "github.com/stretchr/testify"
 
 [[constraint]]
-  branch = "master"
-  name = "golang.org/x/net"
-
-[[constraint]]
-  version = "v1.4.7"
-  name = "gopkg.in/fsnotify.v1"
+  version = "^v1.4.7"
+  name = "github.com/fsnotify/fsnotify"
 
 [[constraint]]
   version = "v1.2.1"

+ 20 - 0
vendor/github.com/beorn7/perks/LICENSE

@@ -0,0 +1,20 @@
+Copyright (C) 2013 Blake Mizerany
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

+ 316 - 0
vendor/github.com/beorn7/perks/quantile/stream.go

@@ -0,0 +1,316 @@
+// Package quantile computes approximate quantiles over an unbounded data
+// stream within low memory and CPU bounds.
+//
+// A small amount of accuracy is traded to achieve the above properties.
+//
+// Multiple streams can be merged before calling Query to generate a single set
+// of results. This is meaningful when the streams represent the same type of
+// data. See Merge and Samples.
+//
+// For more detailed information about the algorithm used, see:
+//
+// Effective Computation of Biased Quantiles over Data Streams
+//
+// http://www.cs.rutgers.edu/~muthu/bquant.pdf
+package quantile
+
+import (
+	"math"
+	"sort"
+)
+
+// Sample holds an observed value and meta information for compression. JSON
+// tags have been added for convenience.
+type Sample struct {
+	Value float64 `json:",string"`
+	Width float64 `json:",string"`
+	Delta float64 `json:",string"`
+}
+
+// Samples represents a slice of samples. It implements sort.Interface.
+type Samples []Sample
+
+func (a Samples) Len() int           { return len(a) }
+func (a Samples) Less(i, j int) bool { return a[i].Value < a[j].Value }
+func (a Samples) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
+
+type invariant func(s *stream, r float64) float64
+
+// NewLowBiased returns an initialized Stream for low-biased quantiles
+// (e.g. 0.01, 0.1, 0.5) where the needed quantiles are not known a priori, but
+// error guarantees can still be given even for the lower ranks of the data
+// distribution.
+//
+// The provided epsilon is a relative error, i.e. the true quantile of a value
+// returned by a query is guaranteed to be within (1±Epsilon)*Quantile.
+//
+// See http://www.cs.rutgers.edu/~muthu/bquant.pdf for time, space, and error
+// properties.
+func NewLowBiased(epsilon float64) *Stream {
+	ƒ := func(s *stream, r float64) float64 {
+		return 2 * epsilon * r
+	}
+	return newStream(ƒ)
+}
+
+// NewHighBiased returns an initialized Stream for high-biased quantiles
+// (e.g. 0.01, 0.1, 0.5) where the needed quantiles are not known a priori, but
+// error guarantees can still be given even for the higher ranks of the data
+// distribution.
+//
+// The provided epsilon is a relative error, i.e. the true quantile of a value
+// returned by a query is guaranteed to be within 1-(1±Epsilon)*(1-Quantile).
+//
+// See http://www.cs.rutgers.edu/~muthu/bquant.pdf for time, space, and error
+// properties.
+func NewHighBiased(epsilon float64) *Stream {
+	ƒ := func(s *stream, r float64) float64 {
+		return 2 * epsilon * (s.n - r)
+	}
+	return newStream(ƒ)
+}
+
+// NewTargeted returns an initialized Stream concerned with a particular set of
+// quantile values that are supplied a priori. Knowing these a priori reduces
+// space and computation time. The targets map maps the desired quantiles to
+// their absolute errors, i.e. the true quantile of a value returned by a query
+// is guaranteed to be within (Quantile±Epsilon).
+//
+// See http://www.cs.rutgers.edu/~muthu/bquant.pdf for time, space, and error properties.
+func NewTargeted(targetMap map[float64]float64) *Stream {
+	// Convert map to slice to avoid slow iterations on a map.
+	// ƒ is called on the hot path, so converting the map to a slice
+	// beforehand results in significant CPU savings.
+	targets := targetMapToSlice(targetMap)
+
+	ƒ := func(s *stream, r float64) float64 {
+		var m = math.MaxFloat64
+		var f float64
+		for _, t := range targets {
+			if t.quantile*s.n <= r {
+				f = (2 * t.epsilon * r) / t.quantile
+			} else {
+				f = (2 * t.epsilon * (s.n - r)) / (1 - t.quantile)
+			}
+			if f < m {
+				m = f
+			}
+		}
+		return m
+	}
+	return newStream(ƒ)
+}
+
+type target struct {
+	quantile float64
+	epsilon  float64
+}
+
+func targetMapToSlice(targetMap map[float64]float64) []target {
+	targets := make([]target, 0, len(targetMap))
+
+	for quantile, epsilon := range targetMap {
+		t := target{
+			quantile: quantile,
+			epsilon:  epsilon,
+		}
+		targets = append(targets, t)
+	}
+
+	return targets
+}
+
+// Stream computes quantiles for a stream of float64s. It is not thread-safe by
+// design. Take care when using across multiple goroutines.
+type Stream struct {
+	*stream
+	b      Samples
+	sorted bool
+}
+
+func newStream(ƒ invariant) *Stream {
+	x := &stream{ƒ: ƒ}
+	return &Stream{x, make(Samples, 0, 500), true}
+}
+
+// Insert inserts v into the stream.
+func (s *Stream) Insert(v float64) {
+	s.insert(Sample{Value: v, Width: 1})
+}
+
+func (s *Stream) insert(sample Sample) {
+	s.b = append(s.b, sample)
+	s.sorted = false
+	if len(s.b) == cap(s.b) {
+		s.flush()
+	}
+}
+
+// Query returns the computed qth percentiles value. If s was created with
+// NewTargeted, and q is not in the set of quantiles provided a priori, Query
+// will return an unspecified result.
+func (s *Stream) Query(q float64) float64 {
+	if !s.flushed() {
+		// Fast path when there hasn't been enough data for a flush;
+		// this also yields better accuracy for small sets of data.
+		l := len(s.b)
+		if l == 0 {
+			return 0
+		}
+		i := int(math.Ceil(float64(l) * q))
+		if i > 0 {
+			i -= 1
+		}
+		s.maybeSort()
+		return s.b[i].Value
+	}
+	s.flush()
+	return s.stream.query(q)
+}
+
+// Merge merges samples into the underlying streams samples. This is handy when
+// merging multiple streams from separate threads, database shards, etc.
+//
+// ATTENTION: This method is broken and does not yield correct results. The
+// underlying algorithm is not capable of merging streams correctly.
+func (s *Stream) Merge(samples Samples) {
+	sort.Sort(samples)
+	s.stream.merge(samples)
+}
+
+// Reset reinitializes and clears the list reusing the samples buffer memory.
+func (s *Stream) Reset() {
+	s.stream.reset()
+	s.b = s.b[:0]
+}
+
+// Samples returns stream samples held by s.
+func (s *Stream) Samples() Samples {
+	if !s.flushed() {
+		return s.b
+	}
+	s.flush()
+	return s.stream.samples()
+}
+
+// Count returns the total number of samples observed in the stream
+// since initialization.
+func (s *Stream) Count() int {
+	return len(s.b) + s.stream.count()
+}
+
+func (s *Stream) flush() {
+	s.maybeSort()
+	s.stream.merge(s.b)
+	s.b = s.b[:0]
+}
+
+func (s *Stream) maybeSort() {
+	if !s.sorted {
+		s.sorted = true
+		sort.Sort(s.b)
+	}
+}
+
+func (s *Stream) flushed() bool {
+	return len(s.stream.l) > 0
+}
+
+type stream struct {
+	n float64
+	l []Sample
+	ƒ invariant
+}
+
+func (s *stream) reset() {
+	s.l = s.l[:0]
+	s.n = 0
+}
+
+func (s *stream) insert(v float64) {
+	s.merge(Samples{{v, 1, 0}})
+}
+
+func (s *stream) merge(samples Samples) {
+	// TODO(beorn7): This tries to merge not only individual samples, but
+	// whole summaries. The paper doesn't mention merging summaries at
+	// all. Unittests show that the merging is inaccurate. Find out how to
+	// do merges properly.
+	var r float64
+	i := 0
+	for _, sample := range samples {
+		for ; i < len(s.l); i++ {
+			c := s.l[i]
+			if c.Value > sample.Value {
+				// Insert at position i.
+				s.l = append(s.l, Sample{})
+				copy(s.l[i+1:], s.l[i:])
+				s.l[i] = Sample{
+					sample.Value,
+					sample.Width,
+					math.Max(sample.Delta, math.Floor(s.ƒ(s, r))-1),
+					// TODO(beorn7): How to calculate delta correctly?
+				}
+				i++
+				goto inserted
+			}
+			r += c.Width
+		}
+		s.l = append(s.l, Sample{sample.Value, sample.Width, 0})
+		i++
+	inserted:
+		s.n += sample.Width
+		r += sample.Width
+	}
+	s.compress()
+}
+
+func (s *stream) count() int {
+	return int(s.n)
+}
+
+func (s *stream) query(q float64) float64 {
+	t := math.Ceil(q * s.n)
+	t += math.Ceil(s.ƒ(s, t) / 2)
+	p := s.l[0]
+	var r float64
+	for _, c := range s.l[1:] {
+		r += p.Width
+		if r+c.Width+c.Delta > t {
+			return p.Value
+		}
+		p = c
+	}
+	return p.Value
+}
+
+func (s *stream) compress() {
+	if len(s.l) < 2 {
+		return
+	}
+	x := s.l[len(s.l)-1]
+	xi := len(s.l) - 1
+	r := s.n - 1 - x.Width
+
+	for i := len(s.l) - 2; i >= 0; i-- {
+		c := s.l[i]
+		if c.Width+x.Width+x.Delta <= s.ƒ(s, r) {
+			x.Width += c.Width
+			s.l[xi] = x
+			// Remove element at i.
+			copy(s.l[i:], s.l[i+1:])
+			s.l = s.l[:len(s.l)-1]
+			xi -= 1
+		} else {
+			x = c
+			xi = i
+		}
+		r -= c.Width
+	}
+}
+
+func (s *stream) samples() Samples {
+	samples := make(Samples, len(s.l))
+	copy(samples, s.l)
+	return samples
+}

+ 0 - 0
vendor/gopkg.in/fsnotify.v1/AUTHORS → vendor/github.com/fsnotify/fsnotify/AUTHORS


+ 0 - 0
vendor/gopkg.in/fsnotify.v1/LICENSE → vendor/github.com/fsnotify/fsnotify/LICENSE


+ 0 - 0
vendor/gopkg.in/fsnotify.v1/fen.go → vendor/github.com/fsnotify/fsnotify/fen.go


+ 0 - 0
vendor/gopkg.in/fsnotify.v1/fsnotify.go → vendor/github.com/fsnotify/fsnotify/fsnotify.go


+ 0 - 0
vendor/gopkg.in/fsnotify.v1/inotify.go → vendor/github.com/fsnotify/fsnotify/inotify.go


+ 0 - 0
vendor/gopkg.in/fsnotify.v1/inotify_poller.go → vendor/github.com/fsnotify/fsnotify/inotify_poller.go


+ 0 - 0
vendor/gopkg.in/fsnotify.v1/kqueue.go → vendor/github.com/fsnotify/fsnotify/kqueue.go


+ 0 - 0
vendor/gopkg.in/fsnotify.v1/open_mode_bsd.go → vendor/github.com/fsnotify/fsnotify/open_mode_bsd.go


+ 0 - 0
vendor/gopkg.in/fsnotify.v1/open_mode_darwin.go → vendor/github.com/fsnotify/fsnotify/open_mode_darwin.go


+ 0 - 0
vendor/gopkg.in/fsnotify.v1/windows.go → vendor/github.com/fsnotify/fsnotify/windows.go


+ 4 - 3
vendor/github.com/golang/geo/r3/vector.go

@@ -42,10 +42,11 @@ func (v Vector) Norm2() float64 { return v.Dot(v) }
 
 // Normalize returns a unit vector in the same direction as v.
 func (v Vector) Normalize() Vector {
-	if v == (Vector{0, 0, 0}) {
-		return v
+	n2 := v.Norm2()
+	if n2 == 0 {
+		return Vector{0, 0, 0}
 	}
-	return v.Mul(1 / v.Norm())
+	return v.Mul(1 / math.Sqrt(n2))
 }
 
 // IsUnit returns whether this vector is of approximately unit length.

+ 4 - 3
vendor/github.com/golang/geo/s1/chordangle.go

@@ -161,9 +161,10 @@ func (c ChordAngle) Predecessor() ChordAngle {
 // the true distance after the points are projected to lie exactly on the sphere.
 func (c ChordAngle) MaxPointError() float64 {
 	// There is a relative error of (2.5*dblEpsilon) when computing the squared
-	// distance, plus an absolute error of (16 * dblEpsilon**2) because the
-	// lengths of the input points may differ from 1 by up to (2*dblEpsilon) each.
-	return 2.5*dblEpsilon*float64(c) + 16*dblEpsilon*dblEpsilon
+	// distance, plus a relative error of 2 * dblEpsilon, plus an absolute error
+	// of (16 * dblEpsilon**2) because the lengths of the input points may differ
+	// from 1 by up to (2*dblEpsilon) each. (This is the maximum error in Normalize).
+	return 4.5*dblEpsilon*float64(c) + 16*dblEpsilon*dblEpsilon
 }
 
 // MaxAngleError returns the maximum error for a ChordAngle constructed

+ 108 - 5
vendor/github.com/golang/geo/s2/cell.go

@@ -62,6 +62,11 @@ func (c Cell) Face() int {
 	return int(c.face)
 }
 
+// oppositeFace returns the face opposite the given face.
+func oppositeFace(face int) int {
+	return (face + 3) % 6
+}
+
 // Level returns the level of this cell.
 func (c Cell) Level() int {
 	return int(c.level)
@@ -415,7 +420,7 @@ func (c *Cell) decode(d *decoder) {
 
 // vertexChordDist2 returns the squared chord distance from point P to the
 // given corner vertex specified by the Hi or Lo values of each.
-func (c Cell) vertexChordDist2(p Point, xHi, yHi bool) float64 {
+func (c Cell) vertexChordDist2(p Point, xHi, yHi bool) s1.ChordAngle {
 	x := c.uv.X.Lo
 	y := c.uv.Y.Lo
 	if xHi {
@@ -425,7 +430,7 @@ func (c Cell) vertexChordDist2(p Point, xHi, yHi bool) float64 {
 		y = c.uv.Y.Hi
 	}
 
-	return p.Sub(PointFromCoords(x, y, 1).Vector).Norm2()
+	return ChordAngleBetweenPoints(p, PointFromCoords(x, y, 1))
 }
 
 // uEdgeIsClosest reports whether a point P is closer to the interior of the specified
@@ -535,11 +540,10 @@ func (c Cell) distanceInternal(targetXYZ Point, toInterior bool) s1.ChordAngle {
 	// tests above, because (1) the edges don't meet at right angles and (2)
 	// there are points on the far side of the sphere that are both above *and*
 	// below the cell, etc.
-	chordDist2 := minFloat64(c.vertexChordDist2(target, false, false),
+	return minChordAngle(c.vertexChordDist2(target, false, false),
 		c.vertexChordDist2(target, true, false),
 		c.vertexChordDist2(target, false, true),
 		c.vertexChordDist2(target, true, true))
-	return s1.ChordAngleFromSquaredLength(chordDist2)
 }
 
 // Distance reports the distance from the cell to the given point. Returns zero if
@@ -548,6 +552,26 @@ func (c Cell) Distance(target Point) s1.ChordAngle {
 	return c.distanceInternal(target, true)
 }
 
+// MaxDistance reports the maximum distance from the cell (including its interior) to the
+// given point.
+func (c Cell) MaxDistance(target Point) s1.ChordAngle {
+	// First check the 4 cell vertices.  If all are within the hemisphere
+	// centered around target, the max distance will be to one of these vertices.
+	targetUVW := faceXYZtoUVW(int(c.face), target)
+	maxDist := maxChordAngle(c.vertexChordDist2(targetUVW, false, false),
+		c.vertexChordDist2(targetUVW, true, false),
+		c.vertexChordDist2(targetUVW, false, true),
+		c.vertexChordDist2(targetUVW, true, true))
+
+	if maxDist <= s1.RightChordAngle {
+		return maxDist
+	}
+
+	// Otherwise, find the minimum distance dMin to the antipodal point and the
+	// maximum distance will be pi - dMin.
+	return s1.StraightChordAngle - c.BoundaryDistance(Point{target.Mul(-1)})
+}
+
 // BoundaryDistance reports the distance from the cell boundary to the given point.
 func (c Cell) BoundaryDistance(target Point) s1.ChordAngle {
 	return c.distanceInternal(target, false)
@@ -576,7 +600,7 @@ func (c Cell) DistanceToEdge(a, b Point) s1.ChordAngle {
 	// Otherwise, check whether the edge crosses the cell boundary.
 	crosser := NewChainEdgeCrosser(a, b, c.Vertex(3))
 	for i := 0; i < 4; i++ {
-		if crosser.ChainCrossingSign(c.Vertex(i)) >= 0 {
+		if crosser.ChainCrossingSign(c.Vertex(i)) != DoNotCross {
 			return 0
 		}
 	}
@@ -593,3 +617,82 @@ func (c Cell) DistanceToEdge(a, b Point) s1.ChordAngle {
 	}
 	return minDist
 }
+
+// MaxDistanceToEdge returns the maximum distance from the cell (including its interior)
+// to the given edge AB.
+func (c Cell) MaxDistanceToEdge(a, b Point) s1.ChordAngle {
+	// If the maximum distance from both endpoints to the cell is less than π/2
+	// then the maximum distance from the edge to the cell is the maximum of the
+	// two endpoint distances.
+	maxDist := maxChordAngle(c.MaxDistance(a), c.MaxDistance(b))
+	if maxDist <= s1.RightChordAngle {
+		return maxDist
+	}
+
+	return s1.StraightChordAngle - c.DistanceToEdge(Point{a.Mul(-1)}, Point{b.Mul(-1)})
+}
+
+// DistanceToCell returns the minimum distance from this cell to the given cell.
+// It returns zero if one cell contains the other.
+func (c Cell) DistanceToCell(target Cell) s1.ChordAngle {
+	// If the cells intersect, the distance is zero.  We use the (u,v) ranges
+	// rather than CellID intersects so that cells that share a partial edge or
+	// corner are considered to intersect.
+	if c.face == target.face && c.uv.Intersects(target.uv) {
+		return 0
+	}
+
+	// Otherwise, the minimum distance always occurs between a vertex of one
+	// cell and an edge of the other cell (including the edge endpoints).  This
+	// represents a total of 32 possible (vertex, edge) pairs.
+	//
+	// TODO(roberts): This could be optimized to be at least 5x faster by pruning
+	// the set of possible closest vertex/edge pairs using the faces and (u,v)
+	// ranges of both cells.
+	var va, vb [4]Point
+	for i := 0; i < 4; i++ {
+		va[i] = c.Vertex(i)
+		vb[i] = target.Vertex(i)
+	}
+	minDist := s1.InfChordAngle()
+	for i := 0; i < 4; i++ {
+		for j := 0; j < 4; j++ {
+			minDist, _ = UpdateMinDistance(va[i], vb[j], vb[(j+1)&3], minDist)
+			minDist, _ = UpdateMinDistance(vb[i], va[j], va[(j+1)&3], minDist)
+		}
+	}
+	return minDist
+}
+
+// MaxDistanceToCell returns the maximum distance from the cell (including its
+// interior) to the given target cell.
+func (c Cell) MaxDistanceToCell(target Cell) s1.ChordAngle {
+	// Need to check the antipodal target for intersection with the cell. If it
+	// intersects, the distance is the straight ChordAngle.
+	// antipodalUV is the transpose of the original UV, interpreted within the opposite face.
+	antipodalUV := r2.Rect{target.uv.Y, target.uv.X}
+	if int(c.face) == oppositeFace(int(target.face)) && c.uv.Intersects(antipodalUV) {
+		return s1.StraightChordAngle
+	}
+
+	// Otherwise, the maximum distance always occurs between a vertex of one
+	// cell and an edge of the other cell (including the edge endpoints).  This
+	// represents a total of 32 possible (vertex, edge) pairs.
+	//
+	// TODO(roberts): When the maximum distance is at most π/2, the maximum is
+	// always attained between a pair of vertices, and this could be made much
+	// faster by testing each vertex pair once rather than the current 4 times.
+	var va, vb [4]Point
+	for i := 0; i < 4; i++ {
+		va[i] = c.Vertex(i)
+		vb[i] = target.Vertex(i)
+	}
+	maxDist := s1.NegativeChordAngle
+	for i := 0; i < 4; i++ {
+		for j := 0; j < 4; j++ {
+			maxDist, _ = UpdateMaxDistance(va[i], vb[j], vb[(j+1)&3], maxDist)
+			maxDist, _ = UpdateMaxDistance(vb[i], va[j], va[(j+1)&3], maxDist)
+		}
+	}
+	return maxDist
+}

+ 63 - 3
vendor/github.com/golang/geo/s2/edge_distances.go

@@ -43,7 +43,7 @@ func IsDistanceLess(x, a, b Point, limit s1.ChordAngle) bool {
 }
 
 // UpdateMinDistance checks if the distance from X to the edge AB is less
-// then minDist, and if so, returns the updated value and true.
+// than minDist, and if so, returns the updated value and true.
 // The case A == B is handled correctly.
 //
 // Use this method when you want to compute many distances and keep track of
@@ -55,6 +55,22 @@ func UpdateMinDistance(x, a, b Point, minDist s1.ChordAngle) (s1.ChordAngle, boo
 	return updateMinDistance(x, a, b, minDist, false)
 }
 
+// UpdateMaxDistance checks if the distance from X to the edge AB is greater
+// than maxDist, and if so, returns the updated value and true.
+// Otherwise it returns false. The case A == B is handled correctly.
+func UpdateMaxDistance(x, a, b Point, maxDist s1.ChordAngle) (s1.ChordAngle, bool) {
+	dist := maxChordAngle(ChordAngleBetweenPoints(x, a), ChordAngleBetweenPoints(x, b))
+	if dist > s1.RightChordAngle {
+		dist, _ = updateMinDistance(Point{x.Mul(-1)}, a, b, dist, true)
+		dist = s1.StraightChordAngle - dist
+	}
+	if maxDist < dist {
+		return dist, true
+	}
+
+	return maxDist, false
+}
+
 // IsInteriorDistanceLess reports whether the minimum distance from X to the
 // edge AB is attained at an interior point of AB (i.e., not an endpoint), and
 // that distance is less than limit.
@@ -155,12 +171,30 @@ func minUpdateDistanceMaxError(dist s1.ChordAngle) float64 {
 // UpdateMinInteriorDistance, assuming that all input points are normalized
 // to within the bounds guaranteed by Point's Normalize. The error can be added
 // or subtracted from an s1.ChordAngle using its Expanded method.
+//
+// Note that accuracy goes down as the distance approaches 0 degrees or 180
+// degrees (for different reasons). Near 0 degrees the error is acceptable
+// for all practical purposes (about 1.2e-15 radians ~= 8 nanometers).  For
+// exactly antipodal points the maximum error is quite high (0.5 meters),
+// but this error drops rapidly as the points move away from antipodality
+// (approximately 1 millimeter for points that are 50 meters from antipodal,
+// and 1 micrometer for points that are 50km from antipodal).
+//
+// TODO(roberts): Currently the error bound does not hold for edges whose endpoints
+// are antipodal to within about 1e-15 radians (less than 1 micron). This could
+// be fixed by extending PointCross to use higher precision when necessary.
 func minUpdateInteriorDistanceMaxError(dist s1.ChordAngle) float64 {
+	// If a point is more than 90 degrees from an edge, then the minimum
+	// distance is always to one of the endpoints, not to the edge interior.
+	if dist >= s1.RightChordAngle {
+		return 0.0
+	}
+
 	// This bound includes all source of error, assuming that the input points
 	// are normalized. a and b are components of chord length that are
 	// perpendicular and parallel to a plane containing the edge respectively.
-	b := 0.5 * float64(dist) * float64(dist)
-	a := float64(dist) * math.Sqrt(1-0.5*b)
+	b := math.Min(1.0, 0.5*float64(dist)*float64(dist))
+	a := math.Sqrt(b * (2 - b))
 	return ((2.5+2*math.Sqrt(3)+8.5*a)*a +
 		(2+2*math.Sqrt(3)/3+6.5*(1-b))*b +
 		(23+16/math.Sqrt(3))*dblEpsilon) * dblEpsilon
@@ -256,6 +290,9 @@ func interiorDist(x, a, b Point, minDist s1.ChordAngle, alwaysUpdate bool) (s1.C
 	return dist, true
 }
 
+// updateEdgePairMinDistance computes the minimum distance between the given
+// pair of edges. If the two edges cross, the distance is zero. The cases
+// a0 == a1 and b0 == b1 are handled correctly.
 func updateEdgePairMinDistance(a0, a1, b0, b1 Point, minDist s1.ChordAngle) (s1.ChordAngle, bool) {
 	if minDist == 0 {
 		return 0, false
@@ -278,6 +315,29 @@ func updateEdgePairMinDistance(a0, a1, b0, b1 Point, minDist s1.ChordAngle) (s1.
 	return minDist, ok1 || ok2 || ok3 || ok4
 }
 
+// updateEdgePairMaxDistance reports the minimum distance between the given pair of edges.
+// If one edge crosses the antipodal reflection of the other, the distance is pi.
+func updateEdgePairMaxDistance(a0, a1, b0, b1 Point, maxDist s1.ChordAngle) (s1.ChordAngle, bool) {
+	if maxDist == s1.StraightChordAngle {
+		return s1.StraightChordAngle, false
+	}
+	if CrossingSign(a0, a1, Point{b0.Mul(-1)}, Point{b1.Mul(-1)}) == Cross {
+		return s1.StraightChordAngle, true
+	}
+
+	// Otherwise, the maximum distance is achieved at an endpoint of at least
+	// one of the two edges. We ensure that all four possibilities are always checked.
+	//
+	// The calculation below computes each of the six vertex-vertex distances
+	// twice (this could be optimized).
+	var ok1, ok2, ok3, ok4 bool
+	maxDist, ok1 = UpdateMaxDistance(a0, b0, b1, maxDist)
+	maxDist, ok2 = UpdateMaxDistance(a1, b0, b1, maxDist)
+	maxDist, ok3 = UpdateMaxDistance(b0, a0, a1, maxDist)
+	maxDist, ok4 = UpdateMaxDistance(b1, a0, a1, maxDist)
+	return maxDist, ok1 || ok2 || ok3 || ok4
+}
+
 // EdgePairClosestPoints returns the pair of points (a, b) that achieves the
 // minimum distance between edges a0a1 and b0b1, where a is a point on a0a1 and
 // b is a point on b0b1. If the two edges intersect, a and b are both equal to

+ 78 - 1
vendor/github.com/golang/geo/s2/polygon.go

@@ -330,6 +330,84 @@ func FullPolygon() *Polygon {
 	return ret
 }
 
+// IsValid reports whether this is a valid polygon (including checking whether all
+// the loops are themselves valid).
+func (p *Polygon) IsValid() bool {
+	// TODO(roberts): If we want to expose the error, add a Validate() error method.
+	return p.validate() == nil
+}
+
+// validate reports any error if this is not a valid polygon.
+//
+// Note that in the returned error messages, loops that represent holes have their
+// edges numbered in reverse order, starting from the last vertex of the loop.
+func (p *Polygon) validate() error {
+	for i, l := range p.loops {
+		// Check for loop errors that don't require building a ShapeIndex.
+		if err := l.findValidationErrorNoIndex(); err != nil {
+			return fmt.Errorf("loop %d: %v", i, err)
+		}
+		// Check that no loop is empty, and that the full loop only appears in the
+		// full polygon.
+		if l.IsEmpty() {
+			return fmt.Errorf("loop %d: empty loops are not allowed", i)
+		}
+		if l.IsFull() && len(p.loops) > 1 {
+			return fmt.Errorf("loop %d: full loop appears in non-full polygon", i)
+		}
+	}
+
+	// TODO(roberts): Uncomment the remaining checks when they are completed.
+
+	// Check for loop self-intersections and loop pairs that cross
+	// (including duplicate edges and vertices).
+	// if findSelfIntersection(p.index) {
+	//	return fmt.Errorf("polygon has loop pairs that cross")
+	// }
+
+	// Check whether initOriented detected inconsistent loop orientations.
+	// if p.hasInconsistentLoopOrientations {
+	// 	return fmt.Errorf("inconsistent loop orientations detected")
+	// }
+
+	// Finally, verify the loop nesting hierarchy.
+	return p.findLoopNestingError()
+}
+
+// findLoopNestingError reports if there is an error in the loop nesting hierarchy.
+func (p *Polygon) findLoopNestingError() error {
+	// First check that the loop depths make sense.
+	lastDepth := -1
+	for i, l := range p.loops {
+		depth := l.depth
+		if depth < 0 || depth > lastDepth+1 {
+			return fmt.Errorf("loop %d: invalid loop depth (%d)", i, depth)
+		}
+		lastDepth = depth
+	}
+	// Then check that they correspond to the actual loop nesting.  This test
+	// is quadratic in the number of loops but the cost per iteration is small.
+	for i, l := range p.loops {
+		last := p.LastDescendant(i)
+		for j, l2 := range p.loops {
+			if i == j {
+				continue
+			}
+			nested := (j >= i+1) && (j <= last)
+			const reverseB = false
+
+			if l.containsNonCrossingBoundary(l2, reverseB) != nested {
+				nestedStr := ""
+				if !nested {
+					nestedStr = "not "
+				}
+				return fmt.Errorf("invalid nesting: loop %d should %scontain loop %d", i, nestedStr, j)
+			}
+		}
+	}
+	return nil
+}
+
 // IsEmpty reports whether this is the special "empty" polygon (consisting of no loops).
 func (p *Polygon) IsEmpty() bool {
 	return len(p.loops) == 0
@@ -1009,7 +1087,6 @@ func (p *Polygon) decodeCompressed(d *decoder) {
 }
 
 // TODO(roberts): Differences from C++
-// IsValid
 // Area
 // Centroid
 // SnapLevel

+ 164 - 9
vendor/github.com/golang/geo/s2/predicates.go

@@ -407,20 +407,175 @@ func symbolicallyPerturbedSign(a, b, c, bCrossC r3.PreciseVector) Direction {
 	return CounterClockwise // dc.Z * db.Y * da.X
 }
 
+// CompareDistances returns -1, 0, or +1 according to whether AX < BX, A == B,
+// or AX > BX respectively. Distances are measured with respect to the positions
+// of X, A, and B as though they were reprojected to lie exactly on the surface of
+// the unit sphere. Furthermore, this method uses symbolic perturbations to
+// ensure that the result is non-zero whenever A != B, even when AX == BX
+// exactly, or even when A and B project to the same point on the sphere.
+// Such results are guaranteed to be self-consistent, i.e. if AB < BC and
+// BC < AC, then AB < AC.
+func CompareDistances(x, a, b Point) int {
+	// We start by comparing distances using dot products (i.e., cosine of the
+	// angle), because (1) this is the cheapest technique, and (2) it is valid
+	// over the entire range of possible angles. (We can only use the sin^2
+	// technique if both angles are less than 90 degrees or both angles are
+	// greater than 90 degrees.)
+	sign := triageCompareCosDistances(x, a, b)
+	if sign != 0 {
+		return sign
+	}
+
+	// Optimization for (a == b) to avoid falling back to exact arithmetic.
+	if a == b {
+		return 0
+	}
+
+	// It is much better numerically to compare distances using cos(angle) if
+	// the distances are near 90 degrees and sin^2(angle) if the distances are
+	// near 0 or 180 degrees. We only need to check one of the two angles when
+	// making this decision because the fact that the test above failed means
+	// that angles "a" and "b" are very close together.
+	cosAX := a.Dot(x.Vector)
+	if cosAX > 1/math.Sqrt2 {
+		// Angles < 45 degrees.
+		sign = triageCompareSin2Distances(x, a, b)
+	} else if cosAX < -1/math.Sqrt2 {
+		// Angles > 135 degrees. sin^2(angle) is decreasing in this range.
+		sign = -triageCompareSin2Distances(x, a, b)
+	}
+	// C++ adds an additional check here using 80-bit floats.
+	// This is skipped in Go because we only have 32 and 64 bit floats.
+
+	if sign != 0 {
+		return sign
+	}
+
+	sign = exactCompareDistances(r3.PreciseVectorFromVector(x.Vector), r3.PreciseVectorFromVector(a.Vector), r3.PreciseVectorFromVector(b.Vector))
+	if sign != 0 {
+		return sign
+	}
+	return symbolicCompareDistances(x, a, b)
+}
+
+// cosDistance returns cos(XY) where XY is the angle between X and Y, and the
+// maximum error amount in the result. This requires X and Y be normalized.
+func cosDistance(x, y Point) (cos, err float64) {
+	cos = x.Dot(y.Vector)
+	return cos, 9.5*dblEpsilon*math.Abs(cos) + 1.5*dblEpsilon
+}
+
+// sin2Distance returns sin**2(XY), where XY is the angle between X and Y,
+// and the maximum error amount in the result. This requires X and Y be normalized.
+func sin2Distance(x, y Point) (sin2, err float64) {
+	// The (x-y).Cross(x+y) trick eliminates almost all of error due to x
+	// and y being not quite unit length. This method is extremely accurate
+	// for small distances; the *relative* error in the result is O(dblEpsilon) for
+	// distances as small as dblEpsilon.
+	n := x.Sub(y.Vector).Cross(x.Add(y.Vector))
+	sin2 = 0.25 * n.Norm2()
+	err = ((21+4*math.Sqrt(3))*dblEpsilon*sin2 +
+		32*math.Sqrt(3)*dblEpsilon*dblEpsilon*math.Sqrt(sin2) +
+		768*dblEpsilon*dblEpsilon*dblEpsilon*dblEpsilon)
+	return sin2, err
+}
+
+// triageCompareCosDistances returns -1, 0, or +1 according to whether AX < BX,
+// A == B, or AX > BX by comparing the distances between them using cosDistance.
+func triageCompareCosDistances(x, a, b Point) int {
+	cosAX, cosAXerror := cosDistance(a, x)
+	cosBX, cosBXerror := cosDistance(b, x)
+	diff := cosAX - cosBX
+	err := cosAXerror + cosBXerror
+	if diff > err {
+		return -1
+	}
+	if diff < -err {
+		return 1
+	}
+	return 0
+}
+
+// triageCompareSin2Distances returns -1, 0, or +1 according to whether AX < BX,
+// A == B, or AX > BX by comparing the distances between them using sin2Distance.
+func triageCompareSin2Distances(x, a, b Point) int {
+	sin2AX, sin2AXerror := sin2Distance(a, x)
+	sin2BX, sin2BXerror := sin2Distance(b, x)
+	diff := sin2AX - sin2BX
+	err := sin2AXerror + sin2BXerror
+	if diff > err {
+		return 1
+	}
+	if diff < -err {
+		return -1
+	}
+	return 0
+}
+
+// exactCompareDistances returns -1, 0, or 1 after comparing using the values as
+// PreciseVectors.
+func exactCompareDistances(x, a, b r3.PreciseVector) int {
+	// This code produces the same result as though all points were reprojected
+	// to lie exactly on the surface of the unit sphere. It is based on testing
+	// whether x.Dot(a.Normalize()) < x.Dot(b.Normalize()), reformulated
+	// so that it can be evaluated using exact arithmetic.
+	cosAX := x.Dot(a)
+	cosBX := x.Dot(b)
+
+	// If the two values have different signs, we need to handle that case now
+	// before squaring them below.
+	aSign := cosAX.Sign()
+	bSign := cosBX.Sign()
+	if aSign != bSign {
+		// If cos(AX) > cos(BX), then AX < BX.
+		if aSign > bSign {
+			return -1
+		}
+		return 1
+	}
+	cosAX2 := new(big.Float).Mul(cosAX, cosAX)
+	cosBX2 := new(big.Float).Mul(cosBX, cosBX)
+	cmp := new(big.Float).Sub(cosBX2.Mul(cosBX2, a.Norm2()), cosAX2.Mul(cosAX2, b.Norm2()))
+	return aSign * cmp.Sign()
+}
+
+// symbolicCompareDistances returns -1, 0, or +1 given three points such that AX == BX
+// (exactly) according to whether AX < BX, AX == BX, or AX > BX after symbolic
+// perturbations are taken into account.
+func symbolicCompareDistances(x, a, b Point) int {
+	// Our symbolic perturbation strategy is based on the following model.
+	// Similar to "simulation of simplicity", we assign a perturbation to every
+	// point such that if A < B, then the symbolic perturbation for A is much,
+	// much larger than the symbolic perturbation for B. We imagine that
+	// rather than projecting every point to lie exactly on the unit sphere,
+	// instead each point is positioned on its own tiny pedestal that raises it
+	// just off the surface of the unit sphere. This means that the distance AX
+	// is actually the true distance AX plus the (symbolic) heights of the
+	// pedestals for A and X. The pedestals are infinitesmally thin, so they do
+	// not affect distance measurements except at the two endpoints. If several
+	// points project to exactly the same point on the unit sphere, we imagine
+	// that they are placed on separate pedestals placed close together, where
+	// the distance between pedestals is much, much less than the height of any
+	// pedestal. (There are a finite number of Points, and therefore a finite
+	// number of pedestals, so this is possible.)
+	//
+	// If A < B, then A is on a higher pedestal than B, and therefore AX > BX.
+	switch a.Cmp(b.Vector) {
+	case -1:
+		return 1
+	case 1:
+		return -1
+	default:
+		return 0
+	}
+}
+
 // TODO(roberts): Differences from C++
-// CompareDistance(s)
+// CompareDistance
 // CompareEdgeDistance
 // CompareEdgeDirections
 // EdgeCircumcenterSign
 // GetVoronoiSiteExclusion
-// GetCosDistance
-// GetSinDistance
-// GetSin2Distance
-// TriageCompareCosDistances
-// ExactCompareDistances
-// SymbolicCompareDistances
-// CompareSin2Distances
-// TriageCompareSin2Distance
 // GetClosestVertex
 // TriageCompareLineSin2Distance
 // TriageCompareLineCos2Distance

+ 203 - 0
vendor/github.com/golang/geo/s2/projections.go

@@ -0,0 +1,203 @@
+// Copyright 2018 Google Inc. All rights reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package s2
+
+import (
+	"math"
+
+	"github.com/golang/geo/r2"
+	"github.com/golang/geo/s1"
+)
+
+// Projection defines an interface for different ways of mapping between s2 and r2 Points.
+// It can also define the coordinate wrapping behavior along each axis.
+type Projection interface {
+	// Project converts a point on the sphere to a projected 2D point.
+	Project(p Point) r2.Point
+
+	// Unproject converts a projected 2D point to a point on the sphere.
+	//
+	// If wrapping is defined for a given axis (see below), then this method
+	// should accept any real number for the corresponding coordinate.
+	Unproject(p r2.Point) Point
+
+	// FromLatLng is a convenience function equivalent to Project(LatLngToPoint(ll)),
+	// but the implementation is more efficient.
+	FromLatLng(ll LatLng) r2.Point
+
+	// ToLatLng is a convenience function equivalent to LatLngFromPoint(Unproject(p)),
+	// but the implementation is more efficient.
+	ToLatLng(p r2.Point) LatLng
+
+	// Interpolate returns the point obtained by interpolating the given
+	// fraction of the distance along the line from A to B.
+	// Fractions < 0 or > 1 result in extrapolation instead.
+	Interpolate(f float64, a, b r2.Point) r2.Point
+
+	// WrapDistance reports the coordinate wrapping distance along each axis.
+	// If this value is non-zero for a given axis, the coordinates are assumed
+	// to "wrap" with the given period. For example, if WrapDistance.Y == 360
+	// then (x, y) and (x, y + 360) should map to the same Point.
+	//
+	// This information is used to ensure that edges takes the shortest path
+	// between two given points. For example, if coordinates represent
+	// (latitude, longitude) pairs in degrees and WrapDistance().Y == 360,
+	// then the edge (5:179, 5:-179) would be interpreted as spanning 2 degrees
+	// of longitude rather than 358 degrees.
+	//
+	// If a given axis does not wrap, its WrapDistance should be set to zero.
+	WrapDistance() r2.Point
+}
+
+// PlateCarreeProjection defines the "plate carree" (square plate) projection,
+// which converts points on the sphere to (longitude, latitude) pairs.
+// Coordinates can be scaled so that they represent radians, degrees, etc, but
+// the projection is always centered around (latitude=0, longitude=0).
+//
+// Note that (x, y) coordinates are backwards compared to the usual (latitude,
+// longitude) ordering, in order to match the usual convention for graphs in
+// which "x" is horizontal and "y" is vertical.
+type PlateCarreeProjection struct {
+	xWrap       float64
+	toRadians   float64 // Multiplier to convert coordinates to radians.
+	fromRadians float64 // Multiplier to convert coordinates from radians.
+}
+
+// NewPlateCarreeProjection constructs a plate carree projection where the
+// x-coordinates (lng) span [-xScale, xScale] and the y coordinates (lat)
+// span [-xScale/2, xScale/2]. For example if xScale==180 then the x
+// range is [-180, 180] and the y range is [-90, 90].
+//
+// By default coordinates are expressed in radians, i.e. the x range is
+// [-Pi, Pi] and the y range is [-Pi/2, Pi/2].
+func NewPlateCarreeProjection(xScale float64) Projection {
+	return &PlateCarreeProjection{
+		xWrap:       2 * xScale,
+		toRadians:   math.Pi / xScale,
+		fromRadians: xScale / math.Pi,
+	}
+}
+
+// Project converts a point on the sphere to a projected 2D point.
+func (p *PlateCarreeProjection) Project(pt Point) r2.Point {
+	return p.FromLatLng(LatLngFromPoint(pt))
+}
+
+// Unproject converts a projected 2D point to a point on the sphere.
+func (p *PlateCarreeProjection) Unproject(pt r2.Point) Point {
+	return PointFromLatLng(p.ToLatLng(pt))
+}
+
+// FromLatLng returns the LatLng projected into an R2 Point.
+func (p *PlateCarreeProjection) FromLatLng(ll LatLng) r2.Point {
+	return r2.Point{
+		X: p.fromRadians * ll.Lng.Radians(),
+		Y: p.fromRadians * ll.Lat.Radians(),
+	}
+}
+
+// ToLatLng returns the LatLng projected from the given R2 Point.
+func (p *PlateCarreeProjection) ToLatLng(pt r2.Point) LatLng {
+	return LatLng{
+		Lat: s1.Angle(p.fromRadians * pt.Y),
+		Lng: s1.Angle(p.fromRadians * math.Remainder(pt.X, p.xWrap)),
+	}
+}
+
+// Interpolate returns the point obtained by interpolating the given
+// fraction of the distance along the line from A to B.
+func (p *PlateCarreeProjection) Interpolate(f float64, a, b r2.Point) r2.Point {
+	return a.Mul(1 - f).Add(b.Mul(f))
+}
+
+// WrapDistance reports the coordinate wrapping distance along each axis.
+func (p *PlateCarreeProjection) WrapDistance() r2.Point {
+	return r2.Point{p.xWrap, 0}
+}
+
+// MercatorProjection defines the spherical Mercator projection. Google Maps
+// uses this projection together with WGS84 coordinates, in which case it is
+// known as the "Web Mercator" projection (see Wikipedia). This class makes
+// no assumptions regarding the coordinate system of its input points, but
+// simply applies the spherical Mercator projection to them.
+//
+// The Mercator projection is finite in width (x) but infinite in height (y).
+// "x" corresponds to longitude, and spans a finite range such as [-180, 180]
+// (with coordinate wrapping), while "y" is a function of latitude and spans
+// an infinite range. (As "y" coordinates get larger, points get closer to
+// the north pole but never quite reach it.) The north and south poles have
+// infinite "y" values. (Note that this will cause problems if you tessellate
+// a Mercator edge where one endpoint is a pole. If you need to do this, clip
+// the edge first so that the "y" coordinate is no more than about 5 * maxX.)
+type MercatorProjection struct {
+	xWrap       float64
+	toRadians   float64 // Multiplier to convert coordinates to radians.
+	fromRadians float64 // Multiplier to convert coordinates from radians.
+}
+
+// NewMercatorProjection constructs a Mercator projection with the given maximum
+// longitude axis value corresponding to a range of [-maxLng, maxLng].
+// The horizontal and vertical axes are scaled equally.
+func NewMercatorProjection(maxLng float64) Projection {
+	return &MercatorProjection{
+		xWrap:       2 * maxLng,
+		toRadians:   math.Pi / maxLng,
+		fromRadians: maxLng / math.Pi,
+	}
+}
+
+// Project converts a point on the sphere to a projected 2D point.
+func (p *MercatorProjection) Project(pt Point) r2.Point {
+	return p.FromLatLng(LatLngFromPoint(pt))
+}
+
+// Unproject converts a projected 2D point to a point on the sphere.
+func (p *MercatorProjection) Unproject(pt r2.Point) Point {
+	return PointFromLatLng(p.ToLatLng(pt))
+}
+
+// FromLatLng returns the LatLng projected into an R2 Point.
+func (p *MercatorProjection) FromLatLng(ll LatLng) r2.Point {
+	// This formula is more accurate near zero than the log(tan()) version.
+	// Note that latitudes of +/- 90 degrees yield "y" values of +/- infinity.
+	sinPhi := math.Sin(float64(ll.Lat))
+	y := 0.5 * math.Log((1+sinPhi)/(1-sinPhi))
+	return r2.Point{p.fromRadians * float64(ll.Lng), p.fromRadians * y}
+}
+
+// ToLatLng returns the LatLng projected from the given R2 Point.
+func (p *MercatorProjection) ToLatLng(pt r2.Point) LatLng {
+	// This formula is more accurate near zero than the atan(exp()) version.
+	x := p.toRadians * math.Remainder(pt.X, p.xWrap)
+	k := math.Exp(2 * p.toRadians * pt.Y)
+	var y float64
+	if math.IsInf(k, 0) {
+		y = math.Pi / 2
+	} else {
+		y = math.Asin((k - 1) / (k + 1))
+	}
+	return LatLng{s1.Angle(y), s1.Angle(x)}
+}
+
+// Interpolate returns the point obtained by interpolating the given
+// fraction of the distance along the line from A to B.
+func (p *MercatorProjection) Interpolate(f float64, a, b r2.Point) r2.Point {
+	return a.Mul(1 - f).Add(b.Mul(f))
+}
+
+// WrapDistance reports the coordinate wrapping distance along each axis.
+func (p *MercatorProjection) WrapDistance() r2.Point {
+	return r2.Point{p.xWrap, 0}
+}

+ 3 - 0
vendor/github.com/golang/protobuf/AUTHORS

@@ -0,0 +1,3 @@
+# This source code refers to The Go Authors for copyright purposes.
+# The master list of authors is in the main Go distribution,
+# visible at http://tip.golang.org/AUTHORS.

+ 3 - 0
vendor/github.com/golang/protobuf/CONTRIBUTORS

@@ -0,0 +1,3 @@
+# This source code was written by the Go contributors.
+# The master list of contributors is in the main Go distribution,
+# visible at http://tip.golang.org/CONTRIBUTORS.

+ 31 - 0
vendor/github.com/golang/protobuf/LICENSE

@@ -0,0 +1,31 @@
+Go support for Protocol Buffers - Google's data interchange format
+
+Copyright 2010 The Go Authors.  All rights reserved.
+https://github.com/golang/protobuf
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are
+met:
+
+    * Redistributions of source code must retain the above copyright
+notice, this list of conditions and the following disclaimer.
+    * Redistributions in binary form must reproduce the above
+copyright notice, this list of conditions and the following disclaimer
+in the documentation and/or other materials provided with the
+distribution.
+    * Neither the name of Google Inc. nor the names of its
+contributors may be used to endorse or promote products derived from
+this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+

+ 229 - 0
vendor/github.com/golang/protobuf/proto/clone.go

@@ -0,0 +1,229 @@
+// Go support for Protocol Buffers - Google's data interchange format
+//
+// Copyright 2011 The Go Authors.  All rights reserved.
+// https://github.com/golang/protobuf
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+//     * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+//     * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+//     * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+// Protocol buffer deep copy and merge.
+// TODO: RawMessage.
+
+package proto
+
+import (
+	"log"
+	"reflect"
+	"strings"
+)
+
+// Clone returns a deep copy of a protocol buffer.
+func Clone(pb Message) Message {
+	in := reflect.ValueOf(pb)
+	if in.IsNil() {
+		return pb
+	}
+
+	out := reflect.New(in.Type().Elem())
+	// out is empty so a merge is a deep copy.
+	mergeStruct(out.Elem(), in.Elem())
+	return out.Interface().(Message)
+}
+
+// Merge merges src into dst.
+// Required and optional fields that are set in src will be set to that value in dst.
+// Elements of repeated fields will be appended.
+// Merge panics if src and dst are not the same type, or if dst is nil.
+func Merge(dst, src Message) {
+	in := reflect.ValueOf(src)
+	out := reflect.ValueOf(dst)
+	if out.IsNil() {
+		panic("proto: nil destination")
+	}
+	if in.Type() != out.Type() {
+		// Explicit test prior to mergeStruct so that mistyped nils will fail
+		panic("proto: type mismatch")
+	}
+	if in.IsNil() {
+		// Merging nil into non-nil is a quiet no-op
+		return
+	}
+	mergeStruct(out.Elem(), in.Elem())
+}
+
+func mergeStruct(out, in reflect.Value) {
+	sprop := GetProperties(in.Type())
+	for i := 0; i < in.NumField(); i++ {
+		f := in.Type().Field(i)
+		if strings.HasPrefix(f.Name, "XXX_") {
+			continue
+		}
+		mergeAny(out.Field(i), in.Field(i), false, sprop.Prop[i])
+	}
+
+	if emIn, ok := extendable(in.Addr().Interface()); ok {
+		emOut, _ := extendable(out.Addr().Interface())
+		mIn, muIn := emIn.extensionsRead()
+		if mIn != nil {
+			mOut := emOut.extensionsWrite()
+			muIn.Lock()
+			mergeExtension(mOut, mIn)
+			muIn.Unlock()
+		}
+	}
+
+	uf := in.FieldByName("XXX_unrecognized")
+	if !uf.IsValid() {
+		return
+	}
+	uin := uf.Bytes()
+	if len(uin) > 0 {
+		out.FieldByName("XXX_unrecognized").SetBytes(append([]byte(nil), uin...))
+	}
+}
+
+// mergeAny performs a merge between two values of the same type.
+// viaPtr indicates whether the values were indirected through a pointer (implying proto2).
+// prop is set if this is a struct field (it may be nil).
+func mergeAny(out, in reflect.Value, viaPtr bool, prop *Properties) {
+	if in.Type() == protoMessageType {
+		if !in.IsNil() {
+			if out.IsNil() {
+				out.Set(reflect.ValueOf(Clone(in.Interface().(Message))))
+			} else {
+				Merge(out.Interface().(Message), in.Interface().(Message))
+			}
+		}
+		return
+	}
+	switch in.Kind() {
+	case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int32, reflect.Int64,
+		reflect.String, reflect.Uint32, reflect.Uint64:
+		if !viaPtr && isProto3Zero(in) {
+			return
+		}
+		out.Set(in)
+	case reflect.Interface:
+		// Probably a oneof field; copy non-nil values.
+		if in.IsNil() {
+			return
+		}
+		// Allocate destination if it is not set, or set to a different type.
+		// Otherwise we will merge as normal.
+		if out.IsNil() || out.Elem().Type() != in.Elem().Type() {
+			out.Set(reflect.New(in.Elem().Elem().Type())) // interface -> *T -> T -> new(T)
+		}
+		mergeAny(out.Elem(), in.Elem(), false, nil)
+	case reflect.Map:
+		if in.Len() == 0 {
+			return
+		}
+		if out.IsNil() {
+			out.Set(reflect.MakeMap(in.Type()))
+		}
+		// For maps with value types of *T or []byte we need to deep copy each value.
+		elemKind := in.Type().Elem().Kind()
+		for _, key := range in.MapKeys() {
+			var val reflect.Value
+			switch elemKind {
+			case reflect.Ptr:
+				val = reflect.New(in.Type().Elem().Elem())
+				mergeAny(val, in.MapIndex(key), false, nil)
+			case reflect.Slice:
+				val = in.MapIndex(key)
+				val = reflect.ValueOf(append([]byte{}, val.Bytes()...))
+			default:
+				val = in.MapIndex(key)
+			}
+			out.SetMapIndex(key, val)
+		}
+	case reflect.Ptr:
+		if in.IsNil() {
+			return
+		}
+		if out.IsNil() {
+			out.Set(reflect.New(in.Elem().Type()))
+		}
+		mergeAny(out.Elem(), in.Elem(), true, nil)
+	case reflect.Slice:
+		if in.IsNil() {
+			return
+		}
+		if in.Type().Elem().Kind() == reflect.Uint8 {
+			// []byte is a scalar bytes field, not a repeated field.
+
+			// Edge case: if this is in a proto3 message, a zero length
+			// bytes field is considered the zero value, and should not
+			// be merged.
+			if prop != nil && prop.proto3 && in.Len() == 0 {
+				return
+			}
+
+			// Make a deep copy.
+			// Append to []byte{} instead of []byte(nil) so that we never end up
+			// with a nil result.
+			out.SetBytes(append([]byte{}, in.Bytes()...))
+			return
+		}
+		n := in.Len()
+		if out.IsNil() {
+			out.Set(reflect.MakeSlice(in.Type(), 0, n))
+		}
+		switch in.Type().Elem().Kind() {
+		case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int32, reflect.Int64,
+			reflect.String, reflect.Uint32, reflect.Uint64:
+			out.Set(reflect.AppendSlice(out, in))
+		default:
+			for i := 0; i < n; i++ {
+				x := reflect.Indirect(reflect.New(in.Type().Elem()))
+				mergeAny(x, in.Index(i), false, nil)
+				out.Set(reflect.Append(out, x))
+			}
+		}
+	case reflect.Struct:
+		mergeStruct(out, in)
+	default:
+		// unknown type, so not a protocol buffer
+		log.Printf("proto: don't know how to copy %v", in)
+	}
+}
+
+func mergeExtension(out, in map[int32]Extension) {
+	for extNum, eIn := range in {
+		eOut := Extension{desc: eIn.desc}
+		if eIn.value != nil {
+			v := reflect.New(reflect.TypeOf(eIn.value)).Elem()
+			mergeAny(v, reflect.ValueOf(eIn.value), false, nil)
+			eOut.value = v.Interface()
+		}
+		if eIn.enc != nil {
+			eOut.enc = make([]byte, len(eIn.enc))
+			copy(eOut.enc, eIn.enc)
+		}
+
+		out[extNum] = eOut
+	}
+}

+ 970 - 0
vendor/github.com/golang/protobuf/proto/decode.go

@@ -0,0 +1,970 @@
+// Go support for Protocol Buffers - Google's data interchange format
+//
+// Copyright 2010 The Go Authors.  All rights reserved.
+// https://github.com/golang/protobuf
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+//     * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+//     * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+//     * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+package proto
+
+/*
+ * Routines for decoding protocol buffer data to construct in-memory representations.
+ */
+
+import (
+	"errors"
+	"fmt"
+	"io"
+	"os"
+	"reflect"
+)
+
+// errOverflow is returned when an integer is too large to be represented.
+var errOverflow = errors.New("proto: integer overflow")
+
+// ErrInternalBadWireType is returned by generated code when an incorrect
+// wire type is encountered. It does not get returned to user code.
+var ErrInternalBadWireType = errors.New("proto: internal error: bad wiretype for oneof")
+
+// The fundamental decoders that interpret bytes on the wire.
+// Those that take integer types all return uint64 and are
+// therefore of type valueDecoder.
+
+// DecodeVarint reads a varint-encoded integer from the slice.
+// It returns the integer and the number of bytes consumed, or
+// zero if there is not enough.
+// This is the format for the
+// int32, int64, uint32, uint64, bool, and enum
+// protocol buffer types.
+func DecodeVarint(buf []byte) (x uint64, n int) {
+	for shift := uint(0); shift < 64; shift += 7 {
+		if n >= len(buf) {
+			return 0, 0
+		}
+		b := uint64(buf[n])
+		n++
+		x |= (b & 0x7F) << shift
+		if (b & 0x80) == 0 {
+			return x, n
+		}
+	}
+
+	// The number is too large to represent in a 64-bit value.
+	return 0, 0
+}
+
+func (p *Buffer) decodeVarintSlow() (x uint64, err error) {
+	i := p.index
+	l := len(p.buf)
+
+	for shift := uint(0); shift < 64; shift += 7 {
+		if i >= l {
+			err = io.ErrUnexpectedEOF
+			return
+		}
+		b := p.buf[i]
+		i++
+		x |= (uint64(b) & 0x7F) << shift
+		if b < 0x80 {
+			p.index = i
+			return
+		}
+	}
+
+	// The number is too large to represent in a 64-bit value.
+	err = errOverflow
+	return
+}
+
+// DecodeVarint reads a varint-encoded integer from the Buffer.
+// This is the format for the
+// int32, int64, uint32, uint64, bool, and enum
+// protocol buffer types.
+func (p *Buffer) DecodeVarint() (x uint64, err error) {
+	i := p.index
+	buf := p.buf
+
+	if i >= len(buf) {
+		return 0, io.ErrUnexpectedEOF
+	} else if buf[i] < 0x80 {
+		p.index++
+		return uint64(buf[i]), nil
+	} else if len(buf)-i < 10 {
+		return p.decodeVarintSlow()
+	}
+
+	var b uint64
+	// we already checked the first byte
+	x = uint64(buf[i]) - 0x80
+	i++
+
+	b = uint64(buf[i])
+	i++
+	x += b << 7
+	if b&0x80 == 0 {
+		goto done
+	}
+	x -= 0x80 << 7
+
+	b = uint64(buf[i])
+	i++
+	x += b << 14
+	if b&0x80 == 0 {
+		goto done
+	}
+	x -= 0x80 << 14
+
+	b = uint64(buf[i])
+	i++
+	x += b << 21
+	if b&0x80 == 0 {
+		goto done
+	}
+	x -= 0x80 << 21
+
+	b = uint64(buf[i])
+	i++
+	x += b << 28
+	if b&0x80 == 0 {
+		goto done
+	}
+	x -= 0x80 << 28
+
+	b = uint64(buf[i])
+	i++
+	x += b << 35
+	if b&0x80 == 0 {
+		goto done
+	}
+	x -= 0x80 << 35
+
+	b = uint64(buf[i])
+	i++
+	x += b << 42
+	if b&0x80 == 0 {
+		goto done
+	}
+	x -= 0x80 << 42
+
+	b = uint64(buf[i])
+	i++
+	x += b << 49
+	if b&0x80 == 0 {
+		goto done
+	}
+	x -= 0x80 << 49
+
+	b = uint64(buf[i])
+	i++
+	x += b << 56
+	if b&0x80 == 0 {
+		goto done
+	}
+	x -= 0x80 << 56
+
+	b = uint64(buf[i])
+	i++
+	x += b << 63
+	if b&0x80 == 0 {
+		goto done
+	}
+	// x -= 0x80 << 63 // Always zero.
+
+	return 0, errOverflow
+
+done:
+	p.index = i
+	return x, nil
+}
+
+// DecodeFixed64 reads a 64-bit integer from the Buffer.
+// This is the format for the
+// fixed64, sfixed64, and double protocol buffer types.
+func (p *Buffer) DecodeFixed64() (x uint64, err error) {
+	// x, err already 0
+	i := p.index + 8
+	if i < 0 || i > len(p.buf) {
+		err = io.ErrUnexpectedEOF
+		return
+	}
+	p.index = i
+
+	x = uint64(p.buf[i-8])
+	x |= uint64(p.buf[i-7]) << 8
+	x |= uint64(p.buf[i-6]) << 16
+	x |= uint64(p.buf[i-5]) << 24
+	x |= uint64(p.buf[i-4]) << 32
+	x |= uint64(p.buf[i-3]) << 40
+	x |= uint64(p.buf[i-2]) << 48
+	x |= uint64(p.buf[i-1]) << 56
+	return
+}
+
+// DecodeFixed32 reads a 32-bit integer from the Buffer.
+// This is the format for the
+// fixed32, sfixed32, and float protocol buffer types.
+func (p *Buffer) DecodeFixed32() (x uint64, err error) {
+	// x, err already 0
+	i := p.index + 4
+	if i < 0 || i > len(p.buf) {
+		err = io.ErrUnexpectedEOF
+		return
+	}
+	p.index = i
+
+	x = uint64(p.buf[i-4])
+	x |= uint64(p.buf[i-3]) << 8
+	x |= uint64(p.buf[i-2]) << 16
+	x |= uint64(p.buf[i-1]) << 24
+	return
+}
+
+// DecodeZigzag64 reads a zigzag-encoded 64-bit integer
+// from the Buffer.
+// This is the format used for the sint64 protocol buffer type.
+func (p *Buffer) DecodeZigzag64() (x uint64, err error) {
+	x, err = p.DecodeVarint()
+	if err != nil {
+		return
+	}
+	x = (x >> 1) ^ uint64((int64(x&1)<<63)>>63)
+	return
+}
+
+// DecodeZigzag32 reads a zigzag-encoded 32-bit integer
+// from  the Buffer.
+// This is the format used for the sint32 protocol buffer type.
+func (p *Buffer) DecodeZigzag32() (x uint64, err error) {
+	x, err = p.DecodeVarint()
+	if err != nil {
+		return
+	}
+	x = uint64((uint32(x) >> 1) ^ uint32((int32(x&1)<<31)>>31))
+	return
+}
+
+// These are not ValueDecoders: they produce an array of bytes or a string.
+// bytes, embedded messages
+
+// DecodeRawBytes reads a count-delimited byte buffer from the Buffer.
+// This is the format used for the bytes protocol buffer
+// type and for embedded messages.
+func (p *Buffer) DecodeRawBytes(alloc bool) (buf []byte, err error) {
+	n, err := p.DecodeVarint()
+	if err != nil {
+		return nil, err
+	}
+
+	nb := int(n)
+	if nb < 0 {
+		return nil, fmt.Errorf("proto: bad byte length %d", nb)
+	}
+	end := p.index + nb
+	if end < p.index || end > len(p.buf) {
+		return nil, io.ErrUnexpectedEOF
+	}
+
+	if !alloc {
+		// todo: check if can get more uses of alloc=false
+		buf = p.buf[p.index:end]
+		p.index += nb
+		return
+	}
+
+	buf = make([]byte, nb)
+	copy(buf, p.buf[p.index:])
+	p.index += nb
+	return
+}
+
+// DecodeStringBytes reads an encoded string from the Buffer.
+// This is the format used for the proto2 string type.
+func (p *Buffer) DecodeStringBytes() (s string, err error) {
+	buf, err := p.DecodeRawBytes(false)
+	if err != nil {
+		return
+	}
+	return string(buf), nil
+}
+
+// Skip the next item in the buffer. Its wire type is decoded and presented as an argument.
+// If the protocol buffer has extensions, and the field matches, add it as an extension.
+// Otherwise, if the XXX_unrecognized field exists, append the skipped data there.
+func (o *Buffer) skipAndSave(t reflect.Type, tag, wire int, base structPointer, unrecField field) error {
+	oi := o.index
+
+	err := o.skip(t, tag, wire)
+	if err != nil {
+		return err
+	}
+
+	if !unrecField.IsValid() {
+		return nil
+	}
+
+	ptr := structPointer_Bytes(base, unrecField)
+
+	// Add the skipped field to struct field
+	obuf := o.buf
+
+	o.buf = *ptr
+	o.EncodeVarint(uint64(tag<<3 | wire))
+	*ptr = append(o.buf, obuf[oi:o.index]...)
+
+	o.buf = obuf
+
+	return nil
+}
+
+// Skip the next item in the buffer. Its wire type is decoded and presented as an argument.
+func (o *Buffer) skip(t reflect.Type, tag, wire int) error {
+
+	var u uint64
+	var err error
+
+	switch wire {
+	case WireVarint:
+		_, err = o.DecodeVarint()
+	case WireFixed64:
+		_, err = o.DecodeFixed64()
+	case WireBytes:
+		_, err = o.DecodeRawBytes(false)
+	case WireFixed32:
+		_, err = o.DecodeFixed32()
+	case WireStartGroup:
+		for {
+			u, err = o.DecodeVarint()
+			if err != nil {
+				break
+			}
+			fwire := int(u & 0x7)
+			if fwire == WireEndGroup {
+				break
+			}
+			ftag := int(u >> 3)
+			err = o.skip(t, ftag, fwire)
+			if err != nil {
+				break
+			}
+		}
+	default:
+		err = fmt.Errorf("proto: can't skip unknown wire type %d for %s", wire, t)
+	}
+	return err
+}
+
+// Unmarshaler is the interface representing objects that can
+// unmarshal themselves.  The method should reset the receiver before
+// decoding starts.  The argument points to data that may be
+// overwritten, so implementations should not keep references to the
+// buffer.
+type Unmarshaler interface {
+	Unmarshal([]byte) error
+}
+
+// Unmarshal parses the protocol buffer representation in buf and places the
+// decoded result in pb.  If the struct underlying pb does not match
+// the data in buf, the results can be unpredictable.
+//
+// Unmarshal resets pb before starting to unmarshal, so any
+// existing data in pb is always removed. Use UnmarshalMerge
+// to preserve and append to existing data.
+func Unmarshal(buf []byte, pb Message) error {
+	pb.Reset()
+	return UnmarshalMerge(buf, pb)
+}
+
+// UnmarshalMerge parses the protocol buffer representation in buf and
+// writes the decoded result to pb.  If the struct underlying pb does not match
+// the data in buf, the results can be unpredictable.
+//
+// UnmarshalMerge merges into existing data in pb.
+// Most code should use Unmarshal instead.
+func UnmarshalMerge(buf []byte, pb Message) error {
+	// If the object can unmarshal itself, let it.
+	if u, ok := pb.(Unmarshaler); ok {
+		return u.Unmarshal(buf)
+	}
+	return NewBuffer(buf).Unmarshal(pb)
+}
+
+// DecodeMessage reads a count-delimited message from the Buffer.
+func (p *Buffer) DecodeMessage(pb Message) error {
+	enc, err := p.DecodeRawBytes(false)
+	if err != nil {
+		return err
+	}
+	return NewBuffer(enc).Unmarshal(pb)
+}
+
+// DecodeGroup reads a tag-delimited group from the Buffer.
+func (p *Buffer) DecodeGroup(pb Message) error {
+	typ, base, err := getbase(pb)
+	if err != nil {
+		return err
+	}
+	return p.unmarshalType(typ.Elem(), GetProperties(typ.Elem()), true, base)
+}
+
+// Unmarshal parses the protocol buffer representation in the
+// Buffer and places the decoded result in pb.  If the struct
+// underlying pb does not match the data in the buffer, the results can be
+// unpredictable.
+//
+// Unlike proto.Unmarshal, this does not reset pb before starting to unmarshal.
+func (p *Buffer) Unmarshal(pb Message) error {
+	// If the object can unmarshal itself, let it.
+	if u, ok := pb.(Unmarshaler); ok {
+		err := u.Unmarshal(p.buf[p.index:])
+		p.index = len(p.buf)
+		return err
+	}
+
+	typ, base, err := getbase(pb)
+	if err != nil {
+		return err
+	}
+
+	err = p.unmarshalType(typ.Elem(), GetProperties(typ.Elem()), false, base)
+
+	if collectStats {
+		stats.Decode++
+	}
+
+	return err
+}
+
+// unmarshalType does the work of unmarshaling a structure.
+func (o *Buffer) unmarshalType(st reflect.Type, prop *StructProperties, is_group bool, base structPointer) error {
+	var state errorState
+	required, reqFields := prop.reqCount, uint64(0)
+
+	var err error
+	for err == nil && o.index < len(o.buf) {
+		oi := o.index
+		var u uint64
+		u, err = o.DecodeVarint()
+		if err != nil {
+			break
+		}
+		wire := int(u & 0x7)
+		if wire == WireEndGroup {
+			if is_group {
+				if required > 0 {
+					// Not enough information to determine the exact field.
+					// (See below.)
+					return &RequiredNotSetError{"{Unknown}"}
+				}
+				return nil // input is satisfied
+			}
+			return fmt.Errorf("proto: %s: wiretype end group for non-group", st)
+		}
+		tag := int(u >> 3)
+		if tag <= 0 {
+			return fmt.Errorf("proto: %s: illegal tag %d (wire type %d)", st, tag, wire)
+		}
+		fieldnum, ok := prop.decoderTags.get(tag)
+		if !ok {
+			// Maybe it's an extension?
+			if prop.extendable {
+				if e, _ := extendable(structPointer_Interface(base, st)); isExtensionField(e, int32(tag)) {
+					if err = o.skip(st, tag, wire); err == nil {
+						extmap := e.extensionsWrite()
+						ext := extmap[int32(tag)] // may be missing
+						ext.enc = append(ext.enc, o.buf[oi:o.index]...)
+						extmap[int32(tag)] = ext
+					}
+					continue
+				}
+			}
+			// Maybe it's a oneof?
+			if prop.oneofUnmarshaler != nil {
+				m := structPointer_Interface(base, st).(Message)
+				// First return value indicates whether tag is a oneof field.
+				ok, err = prop.oneofUnmarshaler(m, tag, wire, o)
+				if err == ErrInternalBadWireType {
+					// Map the error to something more descriptive.
+					// Do the formatting here to save generated code space.
+					err = fmt.Errorf("bad wiretype for oneof field in %T", m)
+				}
+				if ok {
+					continue
+				}
+			}
+			err = o.skipAndSave(st, tag, wire, base, prop.unrecField)
+			continue
+		}
+		p := prop.Prop[fieldnum]
+
+		if p.dec == nil {
+			fmt.Fprintf(os.Stderr, "proto: no protobuf decoder for %s.%s\n", st, st.Field(fieldnum).Name)
+			continue
+		}
+		dec := p.dec
+		if wire != WireStartGroup && wire != p.WireType {
+			if wire == WireBytes && p.packedDec != nil {
+				// a packable field
+				dec = p.packedDec
+			} else {
+				err = fmt.Errorf("proto: bad wiretype for field %s.%s: got wiretype %d, want %d", st, st.Field(fieldnum).Name, wire, p.WireType)
+				continue
+			}
+		}
+		decErr := dec(o, p, base)
+		if decErr != nil && !state.shouldContinue(decErr, p) {
+			err = decErr
+		}
+		if err == nil && p.Required {
+			// Successfully decoded a required field.
+			if tag <= 64 {
+				// use bitmap for fields 1-64 to catch field reuse.
+				var mask uint64 = 1 << uint64(tag-1)
+				if reqFields&mask == 0 {
+					// new required field
+					reqFields |= mask
+					required--
+				}
+			} else {
+				// This is imprecise. It can be fooled by a required field
+				// with a tag > 64 that is encoded twice; that's very rare.
+				// A fully correct implementation would require allocating
+				// a data structure, which we would like to avoid.
+				required--
+			}
+		}
+	}
+	if err == nil {
+		if is_group {
+			return io.ErrUnexpectedEOF
+		}
+		if state.err != nil {
+			return state.err
+		}
+		if required > 0 {
+			// Not enough information to determine the exact field. If we use extra
+			// CPU, we could determine the field only if the missing required field
+			// has a tag <= 64 and we check reqFields.
+			return &RequiredNotSetError{"{Unknown}"}
+		}
+	}
+	return err
+}
+
+// Individual type decoders
+// For each,
+//	u is the decoded value,
+//	v is a pointer to the field (pointer) in the struct
+
+// Sizes of the pools to allocate inside the Buffer.
+// The goal is modest amortization and allocation
+// on at least 16-byte boundaries.
+const (
+	boolPoolSize   = 16
+	uint32PoolSize = 8
+	uint64PoolSize = 4
+)
+
+// Decode a bool.
+func (o *Buffer) dec_bool(p *Properties, base structPointer) error {
+	u, err := p.valDec(o)
+	if err != nil {
+		return err
+	}
+	if len(o.bools) == 0 {
+		o.bools = make([]bool, boolPoolSize)
+	}
+	o.bools[0] = u != 0
+	*structPointer_Bool(base, p.field) = &o.bools[0]
+	o.bools = o.bools[1:]
+	return nil
+}
+
+func (o *Buffer) dec_proto3_bool(p *Properties, base structPointer) error {
+	u, err := p.valDec(o)
+	if err != nil {
+		return err
+	}
+	*structPointer_BoolVal(base, p.field) = u != 0
+	return nil
+}
+
+// Decode an int32.
+func (o *Buffer) dec_int32(p *Properties, base structPointer) error {
+	u, err := p.valDec(o)
+	if err != nil {
+		return err
+	}
+	word32_Set(structPointer_Word32(base, p.field), o, uint32(u))
+	return nil
+}
+
+func (o *Buffer) dec_proto3_int32(p *Properties, base structPointer) error {
+	u, err := p.valDec(o)
+	if err != nil {
+		return err
+	}
+	word32Val_Set(structPointer_Word32Val(base, p.field), uint32(u))
+	return nil
+}
+
+// Decode an int64.
+func (o *Buffer) dec_int64(p *Properties, base structPointer) error {
+	u, err := p.valDec(o)
+	if err != nil {
+		return err
+	}
+	word64_Set(structPointer_Word64(base, p.field), o, u)
+	return nil
+}
+
+func (o *Buffer) dec_proto3_int64(p *Properties, base structPointer) error {
+	u, err := p.valDec(o)
+	if err != nil {
+		return err
+	}
+	word64Val_Set(structPointer_Word64Val(base, p.field), o, u)
+	return nil
+}
+
+// Decode a string.
+func (o *Buffer) dec_string(p *Properties, base structPointer) error {
+	s, err := o.DecodeStringBytes()
+	if err != nil {
+		return err
+	}
+	*structPointer_String(base, p.field) = &s
+	return nil
+}
+
+func (o *Buffer) dec_proto3_string(p *Properties, base structPointer) error {
+	s, err := o.DecodeStringBytes()
+	if err != nil {
+		return err
+	}
+	*structPointer_StringVal(base, p.field) = s
+	return nil
+}
+
+// Decode a slice of bytes ([]byte).
+func (o *Buffer) dec_slice_byte(p *Properties, base structPointer) error {
+	b, err := o.DecodeRawBytes(true)
+	if err != nil {
+		return err
+	}
+	*structPointer_Bytes(base, p.field) = b
+	return nil
+}
+
+// Decode a slice of bools ([]bool).
+func (o *Buffer) dec_slice_bool(p *Properties, base structPointer) error {
+	u, err := p.valDec(o)
+	if err != nil {
+		return err
+	}
+	v := structPointer_BoolSlice(base, p.field)
+	*v = append(*v, u != 0)
+	return nil
+}
+
+// Decode a slice of bools ([]bool) in packed format.
+func (o *Buffer) dec_slice_packed_bool(p *Properties, base structPointer) error {
+	v := structPointer_BoolSlice(base, p.field)
+
+	nn, err := o.DecodeVarint()
+	if err != nil {
+		return err
+	}
+	nb := int(nn) // number of bytes of encoded bools
+	fin := o.index + nb
+	if fin < o.index {
+		return errOverflow
+	}
+
+	y := *v
+	for o.index < fin {
+		u, err := p.valDec(o)
+		if err != nil {
+			return err
+		}
+		y = append(y, u != 0)
+	}
+
+	*v = y
+	return nil
+}
+
+// Decode a slice of int32s ([]int32).
+func (o *Buffer) dec_slice_int32(p *Properties, base structPointer) error {
+	u, err := p.valDec(o)
+	if err != nil {
+		return err
+	}
+	structPointer_Word32Slice(base, p.field).Append(uint32(u))
+	return nil
+}
+
+// Decode a slice of int32s ([]int32) in packed format.
+func (o *Buffer) dec_slice_packed_int32(p *Properties, base structPointer) error {
+	v := structPointer_Word32Slice(base, p.field)
+
+	nn, err := o.DecodeVarint()
+	if err != nil {
+		return err
+	}
+	nb := int(nn) // number of bytes of encoded int32s
+
+	fin := o.index + nb
+	if fin < o.index {
+		return errOverflow
+	}
+	for o.index < fin {
+		u, err := p.valDec(o)
+		if err != nil {
+			return err
+		}
+		v.Append(uint32(u))
+	}
+	return nil
+}
+
+// Decode a slice of int64s ([]int64).
+func (o *Buffer) dec_slice_int64(p *Properties, base structPointer) error {
+	u, err := p.valDec(o)
+	if err != nil {
+		return err
+	}
+
+	structPointer_Word64Slice(base, p.field).Append(u)
+	return nil
+}
+
+// Decode a slice of int64s ([]int64) in packed format.
+func (o *Buffer) dec_slice_packed_int64(p *Properties, base structPointer) error {
+	v := structPointer_Word64Slice(base, p.field)
+
+	nn, err := o.DecodeVarint()
+	if err != nil {
+		return err
+	}
+	nb := int(nn) // number of bytes of encoded int64s
+
+	fin := o.index + nb
+	if fin < o.index {
+		return errOverflow
+	}
+	for o.index < fin {
+		u, err := p.valDec(o)
+		if err != nil {
+			return err
+		}
+		v.Append(u)
+	}
+	return nil
+}
+
+// Decode a slice of strings ([]string).
+func (o *Buffer) dec_slice_string(p *Properties, base structPointer) error {
+	s, err := o.DecodeStringBytes()
+	if err != nil {
+		return err
+	}
+	v := structPointer_StringSlice(base, p.field)
+	*v = append(*v, s)
+	return nil
+}
+
+// Decode a slice of slice of bytes ([][]byte).
+func (o *Buffer) dec_slice_slice_byte(p *Properties, base structPointer) error {
+	b, err := o.DecodeRawBytes(true)
+	if err != nil {
+		return err
+	}
+	v := structPointer_BytesSlice(base, p.field)
+	*v = append(*v, b)
+	return nil
+}
+
+// Decode a map field.
+func (o *Buffer) dec_new_map(p *Properties, base structPointer) error {
+	raw, err := o.DecodeRawBytes(false)
+	if err != nil {
+		return err
+	}
+	oi := o.index       // index at the end of this map entry
+	o.index -= len(raw) // move buffer back to start of map entry
+
+	mptr := structPointer_NewAt(base, p.field, p.mtype) // *map[K]V
+	if mptr.Elem().IsNil() {
+		mptr.Elem().Set(reflect.MakeMap(mptr.Type().Elem()))
+	}
+	v := mptr.Elem() // map[K]V
+
+	// Prepare addressable doubly-indirect placeholders for the key and value types.
+	// See enc_new_map for why.
+	keyptr := reflect.New(reflect.PtrTo(p.mtype.Key())).Elem() // addressable *K
+	keybase := toStructPointer(keyptr.Addr())                  // **K
+
+	var valbase structPointer
+	var valptr reflect.Value
+	switch p.mtype.Elem().Kind() {
+	case reflect.Slice:
+		// []byte
+		var dummy []byte
+		valptr = reflect.ValueOf(&dummy)  // *[]byte
+		valbase = toStructPointer(valptr) // *[]byte
+	case reflect.Ptr:
+		// message; valptr is **Msg; need to allocate the intermediate pointer
+		valptr = reflect.New(reflect.PtrTo(p.mtype.Elem())).Elem() // addressable *V
+		valptr.Set(reflect.New(valptr.Type().Elem()))
+		valbase = toStructPointer(valptr)
+	default:
+		// everything else
+		valptr = reflect.New(reflect.PtrTo(p.mtype.Elem())).Elem() // addressable *V
+		valbase = toStructPointer(valptr.Addr())                   // **V
+	}
+
+	// Decode.
+	// This parses a restricted wire format, namely the encoding of a message
+	// with two fields. See enc_new_map for the format.
+	for o.index < oi {
+		// tagcode for key and value properties are always a single byte
+		// because they have tags 1 and 2.
+		tagcode := o.buf[o.index]
+		o.index++
+		switch tagcode {
+		case p.mkeyprop.tagcode[0]:
+			if err := p.mkeyprop.dec(o, p.mkeyprop, keybase); err != nil {
+				return err
+			}
+		case p.mvalprop.tagcode[0]:
+			if err := p.mvalprop.dec(o, p.mvalprop, valbase); err != nil {
+				return err
+			}
+		default:
+			// TODO: Should we silently skip this instead?
+			return fmt.Errorf("proto: bad map data tag %d", raw[0])
+		}
+	}
+	keyelem, valelem := keyptr.Elem(), valptr.Elem()
+	if !keyelem.IsValid() {
+		keyelem = reflect.Zero(p.mtype.Key())
+	}
+	if !valelem.IsValid() {
+		valelem = reflect.Zero(p.mtype.Elem())
+	}
+
+	v.SetMapIndex(keyelem, valelem)
+	return nil
+}
+
+// Decode a group.
+func (o *Buffer) dec_struct_group(p *Properties, base structPointer) error {
+	bas := structPointer_GetStructPointer(base, p.field)
+	if structPointer_IsNil(bas) {
+		// allocate new nested message
+		bas = toStructPointer(reflect.New(p.stype))
+		structPointer_SetStructPointer(base, p.field, bas)
+	}
+	return o.unmarshalType(p.stype, p.sprop, true, bas)
+}
+
+// Decode an embedded message.
+func (o *Buffer) dec_struct_message(p *Properties, base structPointer) (err error) {
+	raw, e := o.DecodeRawBytes(false)
+	if e != nil {
+		return e
+	}
+
+	bas := structPointer_GetStructPointer(base, p.field)
+	if structPointer_IsNil(bas) {
+		// allocate new nested message
+		bas = toStructPointer(reflect.New(p.stype))
+		structPointer_SetStructPointer(base, p.field, bas)
+	}
+
+	// If the object can unmarshal itself, let it.
+	if p.isUnmarshaler {
+		iv := structPointer_Interface(bas, p.stype)
+		return iv.(Unmarshaler).Unmarshal(raw)
+	}
+
+	obuf := o.buf
+	oi := o.index
+	o.buf = raw
+	o.index = 0
+
+	err = o.unmarshalType(p.stype, p.sprop, false, bas)
+	o.buf = obuf
+	o.index = oi
+
+	return err
+}
+
+// Decode a slice of embedded messages.
+func (o *Buffer) dec_slice_struct_message(p *Properties, base structPointer) error {
+	return o.dec_slice_struct(p, false, base)
+}
+
+// Decode a slice of embedded groups.
+func (o *Buffer) dec_slice_struct_group(p *Properties, base structPointer) error {
+	return o.dec_slice_struct(p, true, base)
+}
+
+// Decode a slice of structs ([]*struct).
+func (o *Buffer) dec_slice_struct(p *Properties, is_group bool, base structPointer) error {
+	v := reflect.New(p.stype)
+	bas := toStructPointer(v)
+	structPointer_StructPointerSlice(base, p.field).Append(bas)
+
+	if is_group {
+		err := o.unmarshalType(p.stype, p.sprop, is_group, bas)
+		return err
+	}
+
+	raw, err := o.DecodeRawBytes(false)
+	if err != nil {
+		return err
+	}
+
+	// If the object can unmarshal itself, let it.
+	if p.isUnmarshaler {
+		iv := v.Interface()
+		return iv.(Unmarshaler).Unmarshal(raw)
+	}
+
+	obuf := o.buf
+	oi := o.index
+	o.buf = raw
+	o.index = 0
+
+	err = o.unmarshalType(p.stype, p.sprop, is_group, bas)
+
+	o.buf = obuf
+	o.index = oi
+
+	return err
+}

+ 151 - 0
vendor/github.com/golang/protobuf/proto/discard.go

@@ -0,0 +1,151 @@
+// Go support for Protocol Buffers - Google's data interchange format
+//
+// Copyright 2017 The Go Authors.  All rights reserved.
+// https://github.com/golang/protobuf
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+//     * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+//     * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+//     * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+package proto
+
+import (
+	"fmt"
+	"reflect"
+	"strings"
+)
+
+// DiscardUnknown recursively discards all unknown fields from this message
+// and all embedded messages.
+//
+// When unmarshaling a message with unrecognized fields, the tags and values
+// of such fields are preserved in the Message. This allows a later call to
+// marshal to be able to produce a message that continues to have those
+// unrecognized fields. To avoid this, DiscardUnknown is used to
+// explicitly clear the unknown fields after unmarshaling.
+//
+// For proto2 messages, the unknown fields of message extensions are only
+// discarded from messages that have been accessed via GetExtension.
+func DiscardUnknown(m Message) {
+	discardLegacy(m)
+}
+
+func discardLegacy(m Message) {
+	v := reflect.ValueOf(m)
+	if v.Kind() != reflect.Ptr || v.IsNil() {
+		return
+	}
+	v = v.Elem()
+	if v.Kind() != reflect.Struct {
+		return
+	}
+	t := v.Type()
+
+	for i := 0; i < v.NumField(); i++ {
+		f := t.Field(i)
+		if strings.HasPrefix(f.Name, "XXX_") {
+			continue
+		}
+		vf := v.Field(i)
+		tf := f.Type
+
+		// Unwrap tf to get its most basic type.
+		var isPointer, isSlice bool
+		if tf.Kind() == reflect.Slice && tf.Elem().Kind() != reflect.Uint8 {
+			isSlice = true
+			tf = tf.Elem()
+		}
+		if tf.Kind() == reflect.Ptr {
+			isPointer = true
+			tf = tf.Elem()
+		}
+		if isPointer && isSlice && tf.Kind() != reflect.Struct {
+			panic(fmt.Sprintf("%T.%s cannot be a slice of pointers to primitive types", m, f.Name))
+		}
+
+		switch tf.Kind() {
+		case reflect.Struct:
+			switch {
+			case !isPointer:
+				panic(fmt.Sprintf("%T.%s cannot be a direct struct value", m, f.Name))
+			case isSlice: // E.g., []*pb.T
+				for j := 0; j < vf.Len(); j++ {
+					discardLegacy(vf.Index(j).Interface().(Message))
+				}
+			default: // E.g., *pb.T
+				discardLegacy(vf.Interface().(Message))
+			}
+		case reflect.Map:
+			switch {
+			case isPointer || isSlice:
+				panic(fmt.Sprintf("%T.%s cannot be a pointer to a map or a slice of map values", m, f.Name))
+			default: // E.g., map[K]V
+				tv := vf.Type().Elem()
+				if tv.Kind() == reflect.Ptr && tv.Implements(protoMessageType) { // Proto struct (e.g., *T)
+					for _, key := range vf.MapKeys() {
+						val := vf.MapIndex(key)
+						discardLegacy(val.Interface().(Message))
+					}
+				}
+			}
+		case reflect.Interface:
+			// Must be oneof field.
+			switch {
+			case isPointer || isSlice:
+				panic(fmt.Sprintf("%T.%s cannot be a pointer to a interface or a slice of interface values", m, f.Name))
+			default: // E.g., test_proto.isCommunique_Union interface
+				if !vf.IsNil() && f.Tag.Get("protobuf_oneof") != "" {
+					vf = vf.Elem() // E.g., *test_proto.Communique_Msg
+					if !vf.IsNil() {
+						vf = vf.Elem()   // E.g., test_proto.Communique_Msg
+						vf = vf.Field(0) // E.g., Proto struct (e.g., *T) or primitive value
+						if vf.Kind() == reflect.Ptr {
+							discardLegacy(vf.Interface().(Message))
+						}
+					}
+				}
+			}
+		}
+	}
+
+	if vf := v.FieldByName("XXX_unrecognized"); vf.IsValid() {
+		if vf.Type() != reflect.TypeOf([]byte{}) {
+			panic("expected XXX_unrecognized to be of type []byte")
+		}
+		vf.Set(reflect.ValueOf([]byte(nil)))
+	}
+
+	// For proto2 messages, only discard unknown fields in message extensions
+	// that have been accessed via GetExtension.
+	if em, ok := extendable(m); ok {
+		// Ignore lock since discardLegacy is not concurrency safe.
+		emm, _ := em.extensionsRead()
+		for _, mx := range emm {
+			if m, ok := mx.value.(Message); ok {
+				discardLegacy(m)
+			}
+		}
+	}
+}

+ 1362 - 0
vendor/github.com/golang/protobuf/proto/encode.go

@@ -0,0 +1,1362 @@
+// Go support for Protocol Buffers - Google's data interchange format
+//
+// Copyright 2010 The Go Authors.  All rights reserved.
+// https://github.com/golang/protobuf
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+//     * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+//     * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+//     * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+package proto
+
+/*
+ * Routines for encoding data into the wire format for protocol buffers.
+ */
+
+import (
+	"errors"
+	"fmt"
+	"reflect"
+	"sort"
+)
+
+// RequiredNotSetError is the error returned if Marshal is called with
+// a protocol buffer struct whose required fields have not
+// all been initialized. It is also the error returned if Unmarshal is
+// called with an encoded protocol buffer that does not include all the
+// required fields.
+//
+// When printed, RequiredNotSetError reports the first unset required field in a
+// message. If the field cannot be precisely determined, it is reported as
+// "{Unknown}".
+type RequiredNotSetError struct {
+	field string
+}
+
+func (e *RequiredNotSetError) Error() string {
+	return fmt.Sprintf("proto: required field %q not set", e.field)
+}
+
+var (
+	// errRepeatedHasNil is the error returned if Marshal is called with
+	// a struct with a repeated field containing a nil element.
+	errRepeatedHasNil = errors.New("proto: repeated field has nil element")
+
+	// errOneofHasNil is the error returned if Marshal is called with
+	// a struct with a oneof field containing a nil element.
+	errOneofHasNil = errors.New("proto: oneof field has nil value")
+
+	// ErrNil is the error returned if Marshal is called with nil.
+	ErrNil = errors.New("proto: Marshal called with nil")
+
+	// ErrTooLarge is the error returned if Marshal is called with a
+	// message that encodes to >2GB.
+	ErrTooLarge = errors.New("proto: message encodes to over 2 GB")
+)
+
+// The fundamental encoders that put bytes on the wire.
+// Those that take integer types all accept uint64 and are
+// therefore of type valueEncoder.
+
+const maxVarintBytes = 10 // maximum length of a varint
+
+// maxMarshalSize is the largest allowed size of an encoded protobuf,
+// since C++ and Java use signed int32s for the size.
+const maxMarshalSize = 1<<31 - 1
+
+// EncodeVarint returns the varint encoding of x.
+// This is the format for the
+// int32, int64, uint32, uint64, bool, and enum
+// protocol buffer types.
+// Not used by the package itself, but helpful to clients
+// wishing to use the same encoding.
+func EncodeVarint(x uint64) []byte {
+	var buf [maxVarintBytes]byte
+	var n int
+	for n = 0; x > 127; n++ {
+		buf[n] = 0x80 | uint8(x&0x7F)
+		x >>= 7
+	}
+	buf[n] = uint8(x)
+	n++
+	return buf[0:n]
+}
+
+// EncodeVarint writes a varint-encoded integer to the Buffer.
+// This is the format for the
+// int32, int64, uint32, uint64, bool, and enum
+// protocol buffer types.
+func (p *Buffer) EncodeVarint(x uint64) error {
+	for x >= 1<<7 {
+		p.buf = append(p.buf, uint8(x&0x7f|0x80))
+		x >>= 7
+	}
+	p.buf = append(p.buf, uint8(x))
+	return nil
+}
+
+// SizeVarint returns the varint encoding size of an integer.
+func SizeVarint(x uint64) int {
+	return sizeVarint(x)
+}
+
+func sizeVarint(x uint64) (n int) {
+	for {
+		n++
+		x >>= 7
+		if x == 0 {
+			break
+		}
+	}
+	return n
+}
+
+// EncodeFixed64 writes a 64-bit integer to the Buffer.
+// This is the format for the
+// fixed64, sfixed64, and double protocol buffer types.
+func (p *Buffer) EncodeFixed64(x uint64) error {
+	p.buf = append(p.buf,
+		uint8(x),
+		uint8(x>>8),
+		uint8(x>>16),
+		uint8(x>>24),
+		uint8(x>>32),
+		uint8(x>>40),
+		uint8(x>>48),
+		uint8(x>>56))
+	return nil
+}
+
+func sizeFixed64(x uint64) int {
+	return 8
+}
+
+// EncodeFixed32 writes a 32-bit integer to the Buffer.
+// This is the format for the
+// fixed32, sfixed32, and float protocol buffer types.
+func (p *Buffer) EncodeFixed32(x uint64) error {
+	p.buf = append(p.buf,
+		uint8(x),
+		uint8(x>>8),
+		uint8(x>>16),
+		uint8(x>>24))
+	return nil
+}
+
+func sizeFixed32(x uint64) int {
+	return 4
+}
+
+// EncodeZigzag64 writes a zigzag-encoded 64-bit integer
+// to the Buffer.
+// This is the format used for the sint64 protocol buffer type.
+func (p *Buffer) EncodeZigzag64(x uint64) error {
+	// use signed number to get arithmetic right shift.
+	return p.EncodeVarint((x << 1) ^ uint64((int64(x) >> 63)))
+}
+
+func sizeZigzag64(x uint64) int {
+	return sizeVarint((x << 1) ^ uint64((int64(x) >> 63)))
+}
+
+// EncodeZigzag32 writes a zigzag-encoded 32-bit integer
+// to the Buffer.
+// This is the format used for the sint32 protocol buffer type.
+func (p *Buffer) EncodeZigzag32(x uint64) error {
+	// use signed number to get arithmetic right shift.
+	return p.EncodeVarint(uint64((uint32(x) << 1) ^ uint32((int32(x) >> 31))))
+}
+
+func sizeZigzag32(x uint64) int {
+	return sizeVarint(uint64((uint32(x) << 1) ^ uint32((int32(x) >> 31))))
+}
+
+// EncodeRawBytes writes a count-delimited byte buffer to the Buffer.
+// This is the format used for the bytes protocol buffer
+// type and for embedded messages.
+func (p *Buffer) EncodeRawBytes(b []byte) error {
+	p.EncodeVarint(uint64(len(b)))
+	p.buf = append(p.buf, b...)
+	return nil
+}
+
+func sizeRawBytes(b []byte) int {
+	return sizeVarint(uint64(len(b))) +
+		len(b)
+}
+
+// EncodeStringBytes writes an encoded string to the Buffer.
+// This is the format used for the proto2 string type.
+func (p *Buffer) EncodeStringBytes(s string) error {
+	p.EncodeVarint(uint64(len(s)))
+	p.buf = append(p.buf, s...)
+	return nil
+}
+
+func sizeStringBytes(s string) int {
+	return sizeVarint(uint64(len(s))) +
+		len(s)
+}
+
+// Marshaler is the interface representing objects that can marshal themselves.
+type Marshaler interface {
+	Marshal() ([]byte, error)
+}
+
+// Marshal takes the protocol buffer
+// and encodes it into the wire format, returning the data.
+func Marshal(pb Message) ([]byte, error) {
+	// Can the object marshal itself?
+	if m, ok := pb.(Marshaler); ok {
+		return m.Marshal()
+	}
+	p := NewBuffer(nil)
+	err := p.Marshal(pb)
+	if p.buf == nil && err == nil {
+		// Return a non-nil slice on success.
+		return []byte{}, nil
+	}
+	return p.buf, err
+}
+
+// EncodeMessage writes the protocol buffer to the Buffer,
+// prefixed by a varint-encoded length.
+func (p *Buffer) EncodeMessage(pb Message) error {
+	t, base, err := getbase(pb)
+	if structPointer_IsNil(base) {
+		return ErrNil
+	}
+	if err == nil {
+		var state errorState
+		err = p.enc_len_struct(GetProperties(t.Elem()), base, &state)
+	}
+	return err
+}
+
+// Marshal takes the protocol buffer
+// and encodes it into the wire format, writing the result to the
+// Buffer.
+func (p *Buffer) Marshal(pb Message) error {
+	// Can the object marshal itself?
+	if m, ok := pb.(Marshaler); ok {
+		data, err := m.Marshal()
+		p.buf = append(p.buf, data...)
+		return err
+	}
+
+	t, base, err := getbase(pb)
+	if structPointer_IsNil(base) {
+		return ErrNil
+	}
+	if err == nil {
+		err = p.enc_struct(GetProperties(t.Elem()), base)
+	}
+
+	if collectStats {
+		(stats).Encode++ // Parens are to work around a goimports bug.
+	}
+
+	if len(p.buf) > maxMarshalSize {
+		return ErrTooLarge
+	}
+	return err
+}
+
+// Size returns the encoded size of a protocol buffer.
+func Size(pb Message) (n int) {
+	// Can the object marshal itself?  If so, Size is slow.
+	// TODO: add Size to Marshaler, or add a Sizer interface.
+	if m, ok := pb.(Marshaler); ok {
+		b, _ := m.Marshal()
+		return len(b)
+	}
+
+	t, base, err := getbase(pb)
+	if structPointer_IsNil(base) {
+		return 0
+	}
+	if err == nil {
+		n = size_struct(GetProperties(t.Elem()), base)
+	}
+
+	if collectStats {
+		(stats).Size++ // Parens are to work around a goimports bug.
+	}
+
+	return
+}
+
+// Individual type encoders.
+
+// Encode a bool.
+func (o *Buffer) enc_bool(p *Properties, base structPointer) error {
+	v := *structPointer_Bool(base, p.field)
+	if v == nil {
+		return ErrNil
+	}
+	x := 0
+	if *v {
+		x = 1
+	}
+	o.buf = append(o.buf, p.tagcode...)
+	p.valEnc(o, uint64(x))
+	return nil
+}
+
+func (o *Buffer) enc_proto3_bool(p *Properties, base structPointer) error {
+	v := *structPointer_BoolVal(base, p.field)
+	if !v {
+		return ErrNil
+	}
+	o.buf = append(o.buf, p.tagcode...)
+	p.valEnc(o, 1)
+	return nil
+}
+
+func size_bool(p *Properties, base structPointer) int {
+	v := *structPointer_Bool(base, p.field)
+	if v == nil {
+		return 0
+	}
+	return len(p.tagcode) + 1 // each bool takes exactly one byte
+}
+
+func size_proto3_bool(p *Properties, base structPointer) int {
+	v := *structPointer_BoolVal(base, p.field)
+	if !v && !p.oneof {
+		return 0
+	}
+	return len(p.tagcode) + 1 // each bool takes exactly one byte
+}
+
+// Encode an int32.
+func (o *Buffer) enc_int32(p *Properties, base structPointer) error {
+	v := structPointer_Word32(base, p.field)
+	if word32_IsNil(v) {
+		return ErrNil
+	}
+	x := int32(word32_Get(v)) // permit sign extension to use full 64-bit range
+	o.buf = append(o.buf, p.tagcode...)
+	p.valEnc(o, uint64(x))
+	return nil
+}
+
+func (o *Buffer) enc_proto3_int32(p *Properties, base structPointer) error {
+	v := structPointer_Word32Val(base, p.field)
+	x := int32(word32Val_Get(v)) // permit sign extension to use full 64-bit range
+	if x == 0 {
+		return ErrNil
+	}
+	o.buf = append(o.buf, p.tagcode...)
+	p.valEnc(o, uint64(x))
+	return nil
+}
+
+func size_int32(p *Properties, base structPointer) (n int) {
+	v := structPointer_Word32(base, p.field)
+	if word32_IsNil(v) {
+		return 0
+	}
+	x := int32(word32_Get(v)) // permit sign extension to use full 64-bit range
+	n += len(p.tagcode)
+	n += p.valSize(uint64(x))
+	return
+}
+
+func size_proto3_int32(p *Properties, base structPointer) (n int) {
+	v := structPointer_Word32Val(base, p.field)
+	x := int32(word32Val_Get(v)) // permit sign extension to use full 64-bit range
+	if x == 0 && !p.oneof {
+		return 0
+	}
+	n += len(p.tagcode)
+	n += p.valSize(uint64(x))
+	return
+}
+
+// Encode a uint32.
+// Exactly the same as int32, except for no sign extension.
+func (o *Buffer) enc_uint32(p *Properties, base structPointer) error {
+	v := structPointer_Word32(base, p.field)
+	if word32_IsNil(v) {
+		return ErrNil
+	}
+	x := word32_Get(v)
+	o.buf = append(o.buf, p.tagcode...)
+	p.valEnc(o, uint64(x))
+	return nil
+}
+
+func (o *Buffer) enc_proto3_uint32(p *Properties, base structPointer) error {
+	v := structPointer_Word32Val(base, p.field)
+	x := word32Val_Get(v)
+	if x == 0 {
+		return ErrNil
+	}
+	o.buf = append(o.buf, p.tagcode...)
+	p.valEnc(o, uint64(x))
+	return nil
+}
+
+func size_uint32(p *Properties, base structPointer) (n int) {
+	v := structPointer_Word32(base, p.field)
+	if word32_IsNil(v) {
+		return 0
+	}
+	x := word32_Get(v)
+	n += len(p.tagcode)
+	n += p.valSize(uint64(x))
+	return
+}
+
+func size_proto3_uint32(p *Properties, base structPointer) (n int) {
+	v := structPointer_Word32Val(base, p.field)
+	x := word32Val_Get(v)
+	if x == 0 && !p.oneof {
+		return 0
+	}
+	n += len(p.tagcode)
+	n += p.valSize(uint64(x))
+	return
+}
+
+// Encode an int64.
+func (o *Buffer) enc_int64(p *Properties, base structPointer) error {
+	v := structPointer_Word64(base, p.field)
+	if word64_IsNil(v) {
+		return ErrNil
+	}
+	x := word64_Get(v)
+	o.buf = append(o.buf, p.tagcode...)
+	p.valEnc(o, x)
+	return nil
+}
+
+func (o *Buffer) enc_proto3_int64(p *Properties, base structPointer) error {
+	v := structPointer_Word64Val(base, p.field)
+	x := word64Val_Get(v)
+	if x == 0 {
+		return ErrNil
+	}
+	o.buf = append(o.buf, p.tagcode...)
+	p.valEnc(o, x)
+	return nil
+}
+
+func size_int64(p *Properties, base structPointer) (n int) {
+	v := structPointer_Word64(base, p.field)
+	if word64_IsNil(v) {
+		return 0
+	}
+	x := word64_Get(v)
+	n += len(p.tagcode)
+	n += p.valSize(x)
+	return
+}
+
+func size_proto3_int64(p *Properties, base structPointer) (n int) {
+	v := structPointer_Word64Val(base, p.field)
+	x := word64Val_Get(v)
+	if x == 0 && !p.oneof {
+		return 0
+	}
+	n += len(p.tagcode)
+	n += p.valSize(x)
+	return
+}
+
+// Encode a string.
+func (o *Buffer) enc_string(p *Properties, base structPointer) error {
+	v := *structPointer_String(base, p.field)
+	if v == nil {
+		return ErrNil
+	}
+	x := *v
+	o.buf = append(o.buf, p.tagcode...)
+	o.EncodeStringBytes(x)
+	return nil
+}
+
+func (o *Buffer) enc_proto3_string(p *Properties, base structPointer) error {
+	v := *structPointer_StringVal(base, p.field)
+	if v == "" {
+		return ErrNil
+	}
+	o.buf = append(o.buf, p.tagcode...)
+	o.EncodeStringBytes(v)
+	return nil
+}
+
+func size_string(p *Properties, base structPointer) (n int) {
+	v := *structPointer_String(base, p.field)
+	if v == nil {
+		return 0
+	}
+	x := *v
+	n += len(p.tagcode)
+	n += sizeStringBytes(x)
+	return
+}
+
+func size_proto3_string(p *Properties, base structPointer) (n int) {
+	v := *structPointer_StringVal(base, p.field)
+	if v == "" && !p.oneof {
+		return 0
+	}
+	n += len(p.tagcode)
+	n += sizeStringBytes(v)
+	return
+}
+
+// All protocol buffer fields are nillable, but be careful.
+func isNil(v reflect.Value) bool {
+	switch v.Kind() {
+	case reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice:
+		return v.IsNil()
+	}
+	return false
+}
+
+// Encode a message struct.
+func (o *Buffer) enc_struct_message(p *Properties, base structPointer) error {
+	var state errorState
+	structp := structPointer_GetStructPointer(base, p.field)
+	if structPointer_IsNil(structp) {
+		return ErrNil
+	}
+
+	// Can the object marshal itself?
+	if p.isMarshaler {
+		m := structPointer_Interface(structp, p.stype).(Marshaler)
+		data, err := m.Marshal()
+		if err != nil && !state.shouldContinue(err, nil) {
+			return err
+		}
+		o.buf = append(o.buf, p.tagcode...)
+		o.EncodeRawBytes(data)
+		return state.err
+	}
+
+	o.buf = append(o.buf, p.tagcode...)
+	return o.enc_len_struct(p.sprop, structp, &state)
+}
+
+func size_struct_message(p *Properties, base structPointer) int {
+	structp := structPointer_GetStructPointer(base, p.field)
+	if structPointer_IsNil(structp) {
+		return 0
+	}
+
+	// Can the object marshal itself?
+	if p.isMarshaler {
+		m := structPointer_Interface(structp, p.stype).(Marshaler)
+		data, _ := m.Marshal()
+		n0 := len(p.tagcode)
+		n1 := sizeRawBytes(data)
+		return n0 + n1
+	}
+
+	n0 := len(p.tagcode)
+	n1 := size_struct(p.sprop, structp)
+	n2 := sizeVarint(uint64(n1)) // size of encoded length
+	return n0 + n1 + n2
+}
+
+// Encode a group struct.
+func (o *Buffer) enc_struct_group(p *Properties, base structPointer) error {
+	var state errorState
+	b := structPointer_GetStructPointer(base, p.field)
+	if structPointer_IsNil(b) {
+		return ErrNil
+	}
+
+	o.EncodeVarint(uint64((p.Tag << 3) | WireStartGroup))
+	err := o.enc_struct(p.sprop, b)
+	if err != nil && !state.shouldContinue(err, nil) {
+		return err
+	}
+	o.EncodeVarint(uint64((p.Tag << 3) | WireEndGroup))
+	return state.err
+}
+
+func size_struct_group(p *Properties, base structPointer) (n int) {
+	b := structPointer_GetStructPointer(base, p.field)
+	if structPointer_IsNil(b) {
+		return 0
+	}
+
+	n += sizeVarint(uint64((p.Tag << 3) | WireStartGroup))
+	n += size_struct(p.sprop, b)
+	n += sizeVarint(uint64((p.Tag << 3) | WireEndGroup))
+	return
+}
+
+// Encode a slice of bools ([]bool).
+func (o *Buffer) enc_slice_bool(p *Properties, base structPointer) error {
+	s := *structPointer_BoolSlice(base, p.field)
+	l := len(s)
+	if l == 0 {
+		return ErrNil
+	}
+	for _, x := range s {
+		o.buf = append(o.buf, p.tagcode...)
+		v := uint64(0)
+		if x {
+			v = 1
+		}
+		p.valEnc(o, v)
+	}
+	return nil
+}
+
+func size_slice_bool(p *Properties, base structPointer) int {
+	s := *structPointer_BoolSlice(base, p.field)
+	l := len(s)
+	if l == 0 {
+		return 0
+	}
+	return l * (len(p.tagcode) + 1) // each bool takes exactly one byte
+}
+
+// Encode a slice of bools ([]bool) in packed format.
+func (o *Buffer) enc_slice_packed_bool(p *Properties, base structPointer) error {
+	s := *structPointer_BoolSlice(base, p.field)
+	l := len(s)
+	if l == 0 {
+		return ErrNil
+	}
+	o.buf = append(o.buf, p.tagcode...)
+	o.EncodeVarint(uint64(l)) // each bool takes exactly one byte
+	for _, x := range s {
+		v := uint64(0)
+		if x {
+			v = 1
+		}
+		p.valEnc(o, v)
+	}
+	return nil
+}
+
+func size_slice_packed_bool(p *Properties, base structPointer) (n int) {
+	s := *structPointer_BoolSlice(base, p.field)
+	l := len(s)
+	if l == 0 {
+		return 0
+	}
+	n += len(p.tagcode)
+	n += sizeVarint(uint64(l))
+	n += l // each bool takes exactly one byte
+	return
+}
+
+// Encode a slice of bytes ([]byte).
+func (o *Buffer) enc_slice_byte(p *Properties, base structPointer) error {
+	s := *structPointer_Bytes(base, p.field)
+	if s == nil {
+		return ErrNil
+	}
+	o.buf = append(o.buf, p.tagcode...)
+	o.EncodeRawBytes(s)
+	return nil
+}
+
+func (o *Buffer) enc_proto3_slice_byte(p *Properties, base structPointer) error {
+	s := *structPointer_Bytes(base, p.field)
+	if len(s) == 0 {
+		return ErrNil
+	}
+	o.buf = append(o.buf, p.tagcode...)
+	o.EncodeRawBytes(s)
+	return nil
+}
+
+func size_slice_byte(p *Properties, base structPointer) (n int) {
+	s := *structPointer_Bytes(base, p.field)
+	if s == nil && !p.oneof {
+		return 0
+	}
+	n += len(p.tagcode)
+	n += sizeRawBytes(s)
+	return
+}
+
+func size_proto3_slice_byte(p *Properties, base structPointer) (n int) {
+	s := *structPointer_Bytes(base, p.field)
+	if len(s) == 0 && !p.oneof {
+		return 0
+	}
+	n += len(p.tagcode)
+	n += sizeRawBytes(s)
+	return
+}
+
+// Encode a slice of int32s ([]int32).
+func (o *Buffer) enc_slice_int32(p *Properties, base structPointer) error {
+	s := structPointer_Word32Slice(base, p.field)
+	l := s.Len()
+	if l == 0 {
+		return ErrNil
+	}
+	for i := 0; i < l; i++ {
+		o.buf = append(o.buf, p.tagcode...)
+		x := int32(s.Index(i)) // permit sign extension to use full 64-bit range
+		p.valEnc(o, uint64(x))
+	}
+	return nil
+}
+
+func size_slice_int32(p *Properties, base structPointer) (n int) {
+	s := structPointer_Word32Slice(base, p.field)
+	l := s.Len()
+	if l == 0 {
+		return 0
+	}
+	for i := 0; i < l; i++ {
+		n += len(p.tagcode)
+		x := int32(s.Index(i)) // permit sign extension to use full 64-bit range
+		n += p.valSize(uint64(x))
+	}
+	return
+}
+
+// Encode a slice of int32s ([]int32) in packed format.
+func (o *Buffer) enc_slice_packed_int32(p *Properties, base structPointer) error {
+	s := structPointer_Word32Slice(base, p.field)
+	l := s.Len()
+	if l == 0 {
+		return ErrNil
+	}
+	// TODO: Reuse a Buffer.
+	buf := NewBuffer(nil)
+	for i := 0; i < l; i++ {
+		x := int32(s.Index(i)) // permit sign extension to use full 64-bit range
+		p.valEnc(buf, uint64(x))
+	}
+
+	o.buf = append(o.buf, p.tagcode...)
+	o.EncodeVarint(uint64(len(buf.buf)))
+	o.buf = append(o.buf, buf.buf...)
+	return nil
+}
+
+func size_slice_packed_int32(p *Properties, base structPointer) (n int) {
+	s := structPointer_Word32Slice(base, p.field)
+	l := s.Len()
+	if l == 0 {
+		return 0
+	}
+	var bufSize int
+	for i := 0; i < l; i++ {
+		x := int32(s.Index(i)) // permit sign extension to use full 64-bit range
+		bufSize += p.valSize(uint64(x))
+	}
+
+	n += len(p.tagcode)
+	n += sizeVarint(uint64(bufSize))
+	n += bufSize
+	return
+}
+
+// Encode a slice of uint32s ([]uint32).
+// Exactly the same as int32, except for no sign extension.
+func (o *Buffer) enc_slice_uint32(p *Properties, base structPointer) error {
+	s := structPointer_Word32Slice(base, p.field)
+	l := s.Len()
+	if l == 0 {
+		return ErrNil
+	}
+	for i := 0; i < l; i++ {
+		o.buf = append(o.buf, p.tagcode...)
+		x := s.Index(i)
+		p.valEnc(o, uint64(x))
+	}
+	return nil
+}
+
+func size_slice_uint32(p *Properties, base structPointer) (n int) {
+	s := structPointer_Word32Slice(base, p.field)
+	l := s.Len()
+	if l == 0 {
+		return 0
+	}
+	for i := 0; i < l; i++ {
+		n += len(p.tagcode)
+		x := s.Index(i)
+		n += p.valSize(uint64(x))
+	}
+	return
+}
+
+// Encode a slice of uint32s ([]uint32) in packed format.
+// Exactly the same as int32, except for no sign extension.
+func (o *Buffer) enc_slice_packed_uint32(p *Properties, base structPointer) error {
+	s := structPointer_Word32Slice(base, p.field)
+	l := s.Len()
+	if l == 0 {
+		return ErrNil
+	}
+	// TODO: Reuse a Buffer.
+	buf := NewBuffer(nil)
+	for i := 0; i < l; i++ {
+		p.valEnc(buf, uint64(s.Index(i)))
+	}
+
+	o.buf = append(o.buf, p.tagcode...)
+	o.EncodeVarint(uint64(len(buf.buf)))
+	o.buf = append(o.buf, buf.buf...)
+	return nil
+}
+
+func size_slice_packed_uint32(p *Properties, base structPointer) (n int) {
+	s := structPointer_Word32Slice(base, p.field)
+	l := s.Len()
+	if l == 0 {
+		return 0
+	}
+	var bufSize int
+	for i := 0; i < l; i++ {
+		bufSize += p.valSize(uint64(s.Index(i)))
+	}
+
+	n += len(p.tagcode)
+	n += sizeVarint(uint64(bufSize))
+	n += bufSize
+	return
+}
+
+// Encode a slice of int64s ([]int64).
+func (o *Buffer) enc_slice_int64(p *Properties, base structPointer) error {
+	s := structPointer_Word64Slice(base, p.field)
+	l := s.Len()
+	if l == 0 {
+		return ErrNil
+	}
+	for i := 0; i < l; i++ {
+		o.buf = append(o.buf, p.tagcode...)
+		p.valEnc(o, s.Index(i))
+	}
+	return nil
+}
+
+func size_slice_int64(p *Properties, base structPointer) (n int) {
+	s := structPointer_Word64Slice(base, p.field)
+	l := s.Len()
+	if l == 0 {
+		return 0
+	}
+	for i := 0; i < l; i++ {
+		n += len(p.tagcode)
+		n += p.valSize(s.Index(i))
+	}
+	return
+}
+
+// Encode a slice of int64s ([]int64) in packed format.
+func (o *Buffer) enc_slice_packed_int64(p *Properties, base structPointer) error {
+	s := structPointer_Word64Slice(base, p.field)
+	l := s.Len()
+	if l == 0 {
+		return ErrNil
+	}
+	// TODO: Reuse a Buffer.
+	buf := NewBuffer(nil)
+	for i := 0; i < l; i++ {
+		p.valEnc(buf, s.Index(i))
+	}
+
+	o.buf = append(o.buf, p.tagcode...)
+	o.EncodeVarint(uint64(len(buf.buf)))
+	o.buf = append(o.buf, buf.buf...)
+	return nil
+}
+
+func size_slice_packed_int64(p *Properties, base structPointer) (n int) {
+	s := structPointer_Word64Slice(base, p.field)
+	l := s.Len()
+	if l == 0 {
+		return 0
+	}
+	var bufSize int
+	for i := 0; i < l; i++ {
+		bufSize += p.valSize(s.Index(i))
+	}
+
+	n += len(p.tagcode)
+	n += sizeVarint(uint64(bufSize))
+	n += bufSize
+	return
+}
+
+// Encode a slice of slice of bytes ([][]byte).
+func (o *Buffer) enc_slice_slice_byte(p *Properties, base structPointer) error {
+	ss := *structPointer_BytesSlice(base, p.field)
+	l := len(ss)
+	if l == 0 {
+		return ErrNil
+	}
+	for i := 0; i < l; i++ {
+		o.buf = append(o.buf, p.tagcode...)
+		o.EncodeRawBytes(ss[i])
+	}
+	return nil
+}
+
+func size_slice_slice_byte(p *Properties, base structPointer) (n int) {
+	ss := *structPointer_BytesSlice(base, p.field)
+	l := len(ss)
+	if l == 0 {
+		return 0
+	}
+	n += l * len(p.tagcode)
+	for i := 0; i < l; i++ {
+		n += sizeRawBytes(ss[i])
+	}
+	return
+}
+
+// Encode a slice of strings ([]string).
+func (o *Buffer) enc_slice_string(p *Properties, base structPointer) error {
+	ss := *structPointer_StringSlice(base, p.field)
+	l := len(ss)
+	for i := 0; i < l; i++ {
+		o.buf = append(o.buf, p.tagcode...)
+		o.EncodeStringBytes(ss[i])
+	}
+	return nil
+}
+
+func size_slice_string(p *Properties, base structPointer) (n int) {
+	ss := *structPointer_StringSlice(base, p.field)
+	l := len(ss)
+	n += l * len(p.tagcode)
+	for i := 0; i < l; i++ {
+		n += sizeStringBytes(ss[i])
+	}
+	return
+}
+
+// Encode a slice of message structs ([]*struct).
+func (o *Buffer) enc_slice_struct_message(p *Properties, base structPointer) error {
+	var state errorState
+	s := structPointer_StructPointerSlice(base, p.field)
+	l := s.Len()
+
+	for i := 0; i < l; i++ {
+		structp := s.Index(i)
+		if structPointer_IsNil(structp) {
+			return errRepeatedHasNil
+		}
+
+		// Can the object marshal itself?
+		if p.isMarshaler {
+			m := structPointer_Interface(structp, p.stype).(Marshaler)
+			data, err := m.Marshal()
+			if err != nil && !state.shouldContinue(err, nil) {
+				return err
+			}
+			o.buf = append(o.buf, p.tagcode...)
+			o.EncodeRawBytes(data)
+			continue
+		}
+
+		o.buf = append(o.buf, p.tagcode...)
+		err := o.enc_len_struct(p.sprop, structp, &state)
+		if err != nil && !state.shouldContinue(err, nil) {
+			if err == ErrNil {
+				return errRepeatedHasNil
+			}
+			return err
+		}
+	}
+	return state.err
+}
+
+func size_slice_struct_message(p *Properties, base structPointer) (n int) {
+	s := structPointer_StructPointerSlice(base, p.field)
+	l := s.Len()
+	n += l * len(p.tagcode)
+	for i := 0; i < l; i++ {
+		structp := s.Index(i)
+		if structPointer_IsNil(structp) {
+			return // return the size up to this point
+		}
+
+		// Can the object marshal itself?
+		if p.isMarshaler {
+			m := structPointer_Interface(structp, p.stype).(Marshaler)
+			data, _ := m.Marshal()
+			n += sizeRawBytes(data)
+			continue
+		}
+
+		n0 := size_struct(p.sprop, structp)
+		n1 := sizeVarint(uint64(n0)) // size of encoded length
+		n += n0 + n1
+	}
+	return
+}
+
+// Encode a slice of group structs ([]*struct).
+func (o *Buffer) enc_slice_struct_group(p *Properties, base structPointer) error {
+	var state errorState
+	s := structPointer_StructPointerSlice(base, p.field)
+	l := s.Len()
+
+	for i := 0; i < l; i++ {
+		b := s.Index(i)
+		if structPointer_IsNil(b) {
+			return errRepeatedHasNil
+		}
+
+		o.EncodeVarint(uint64((p.Tag << 3) | WireStartGroup))
+
+		err := o.enc_struct(p.sprop, b)
+
+		if err != nil && !state.shouldContinue(err, nil) {
+			if err == ErrNil {
+				return errRepeatedHasNil
+			}
+			return err
+		}
+
+		o.EncodeVarint(uint64((p.Tag << 3) | WireEndGroup))
+	}
+	return state.err
+}
+
+func size_slice_struct_group(p *Properties, base structPointer) (n int) {
+	s := structPointer_StructPointerSlice(base, p.field)
+	l := s.Len()
+
+	n += l * sizeVarint(uint64((p.Tag<<3)|WireStartGroup))
+	n += l * sizeVarint(uint64((p.Tag<<3)|WireEndGroup))
+	for i := 0; i < l; i++ {
+		b := s.Index(i)
+		if structPointer_IsNil(b) {
+			return // return size up to this point
+		}
+
+		n += size_struct(p.sprop, b)
+	}
+	return
+}
+
+// Encode an extension map.
+func (o *Buffer) enc_map(p *Properties, base structPointer) error {
+	exts := structPointer_ExtMap(base, p.field)
+	if err := encodeExtensionsMap(*exts); err != nil {
+		return err
+	}
+
+	return o.enc_map_body(*exts)
+}
+
+func (o *Buffer) enc_exts(p *Properties, base structPointer) error {
+	exts := structPointer_Extensions(base, p.field)
+
+	v, mu := exts.extensionsRead()
+	if v == nil {
+		return nil
+	}
+
+	mu.Lock()
+	defer mu.Unlock()
+	if err := encodeExtensionsMap(v); err != nil {
+		return err
+	}
+
+	return o.enc_map_body(v)
+}
+
+func (o *Buffer) enc_map_body(v map[int32]Extension) error {
+	// Fast-path for common cases: zero or one extensions.
+	if len(v) <= 1 {
+		for _, e := range v {
+			o.buf = append(o.buf, e.enc...)
+		}
+		return nil
+	}
+
+	// Sort keys to provide a deterministic encoding.
+	keys := make([]int, 0, len(v))
+	for k := range v {
+		keys = append(keys, int(k))
+	}
+	sort.Ints(keys)
+
+	for _, k := range keys {
+		o.buf = append(o.buf, v[int32(k)].enc...)
+	}
+	return nil
+}
+
+func size_map(p *Properties, base structPointer) int {
+	v := structPointer_ExtMap(base, p.field)
+	return extensionsMapSize(*v)
+}
+
+func size_exts(p *Properties, base structPointer) int {
+	v := structPointer_Extensions(base, p.field)
+	return extensionsSize(v)
+}
+
+// Encode a map field.
+func (o *Buffer) enc_new_map(p *Properties, base structPointer) error {
+	var state errorState // XXX: or do we need to plumb this through?
+
+	/*
+		A map defined as
+			map<key_type, value_type> map_field = N;
+		is encoded in the same way as
+			message MapFieldEntry {
+				key_type key = 1;
+				value_type value = 2;
+			}
+			repeated MapFieldEntry map_field = N;
+	*/
+
+	v := structPointer_NewAt(base, p.field, p.mtype).Elem() // map[K]V
+	if v.Len() == 0 {
+		return nil
+	}
+
+	keycopy, valcopy, keybase, valbase := mapEncodeScratch(p.mtype)
+
+	enc := func() error {
+		if err := p.mkeyprop.enc(o, p.mkeyprop, keybase); err != nil {
+			return err
+		}
+		if err := p.mvalprop.enc(o, p.mvalprop, valbase); err != nil && err != ErrNil {
+			return err
+		}
+		return nil
+	}
+
+	// Don't sort map keys. It is not required by the spec, and C++ doesn't do it.
+	for _, key := range v.MapKeys() {
+		val := v.MapIndex(key)
+
+		keycopy.Set(key)
+		valcopy.Set(val)
+
+		o.buf = append(o.buf, p.tagcode...)
+		if err := o.enc_len_thing(enc, &state); err != nil {
+			return err
+		}
+	}
+	return nil
+}
+
+func size_new_map(p *Properties, base structPointer) int {
+	v := structPointer_NewAt(base, p.field, p.mtype).Elem() // map[K]V
+
+	keycopy, valcopy, keybase, valbase := mapEncodeScratch(p.mtype)
+
+	n := 0
+	for _, key := range v.MapKeys() {
+		val := v.MapIndex(key)
+		keycopy.Set(key)
+		valcopy.Set(val)
+
+		// Tag codes for key and val are the responsibility of the sub-sizer.
+		keysize := p.mkeyprop.size(p.mkeyprop, keybase)
+		valsize := p.mvalprop.size(p.mvalprop, valbase)
+		entry := keysize + valsize
+		// Add on tag code and length of map entry itself.
+		n += len(p.tagcode) + sizeVarint(uint64(entry)) + entry
+	}
+	return n
+}
+
+// mapEncodeScratch returns a new reflect.Value matching the map's value type,
+// and a structPointer suitable for passing to an encoder or sizer.
+func mapEncodeScratch(mapType reflect.Type) (keycopy, valcopy reflect.Value, keybase, valbase structPointer) {
+	// Prepare addressable doubly-indirect placeholders for the key and value types.
+	// This is needed because the element-type encoders expect **T, but the map iteration produces T.
+
+	keycopy = reflect.New(mapType.Key()).Elem()                 // addressable K
+	keyptr := reflect.New(reflect.PtrTo(keycopy.Type())).Elem() // addressable *K
+	keyptr.Set(keycopy.Addr())                                  //
+	keybase = toStructPointer(keyptr.Addr())                    // **K
+
+	// Value types are more varied and require special handling.
+	switch mapType.Elem().Kind() {
+	case reflect.Slice:
+		// []byte
+		var dummy []byte
+		valcopy = reflect.ValueOf(&dummy).Elem() // addressable []byte
+		valbase = toStructPointer(valcopy.Addr())
+	case reflect.Ptr:
+		// message; the generated field type is map[K]*Msg (so V is *Msg),
+		// so we only need one level of indirection.
+		valcopy = reflect.New(mapType.Elem()).Elem() // addressable V
+		valbase = toStructPointer(valcopy.Addr())
+	default:
+		// everything else
+		valcopy = reflect.New(mapType.Elem()).Elem()                // addressable V
+		valptr := reflect.New(reflect.PtrTo(valcopy.Type())).Elem() // addressable *V
+		valptr.Set(valcopy.Addr())                                  //
+		valbase = toStructPointer(valptr.Addr())                    // **V
+	}
+	return
+}
+
+// Encode a struct.
+func (o *Buffer) enc_struct(prop *StructProperties, base structPointer) error {
+	var state errorState
+	// Encode fields in tag order so that decoders may use optimizations
+	// that depend on the ordering.
+	// https://developers.google.com/protocol-buffers/docs/encoding#order
+	for _, i := range prop.order {
+		p := prop.Prop[i]
+		if p.enc != nil {
+			err := p.enc(o, p, base)
+			if err != nil {
+				if err == ErrNil {
+					if p.Required && state.err == nil {
+						state.err = &RequiredNotSetError{p.Name}
+					}
+				} else if err == errRepeatedHasNil {
+					// Give more context to nil values in repeated fields.
+					return errors.New("repeated field " + p.OrigName + " has nil element")
+				} else if !state.shouldContinue(err, p) {
+					return err
+				}
+			}
+			if len(o.buf) > maxMarshalSize {
+				return ErrTooLarge
+			}
+		}
+	}
+
+	// Do oneof fields.
+	if prop.oneofMarshaler != nil {
+		m := structPointer_Interface(base, prop.stype).(Message)
+		if err := prop.oneofMarshaler(m, o); err == ErrNil {
+			return errOneofHasNil
+		} else if err != nil {
+			return err
+		}
+	}
+
+	// Add unrecognized fields at the end.
+	if prop.unrecField.IsValid() {
+		v := *structPointer_Bytes(base, prop.unrecField)
+		if len(o.buf)+len(v) > maxMarshalSize {
+			return ErrTooLarge
+		}
+		if len(v) > 0 {
+			o.buf = append(o.buf, v...)
+		}
+	}
+
+	return state.err
+}
+
+func size_struct(prop *StructProperties, base structPointer) (n int) {
+	for _, i := range prop.order {
+		p := prop.Prop[i]
+		if p.size != nil {
+			n += p.size(p, base)
+		}
+	}
+
+	// Add unrecognized fields at the end.
+	if prop.unrecField.IsValid() {
+		v := *structPointer_Bytes(base, prop.unrecField)
+		n += len(v)
+	}
+
+	// Factor in any oneof fields.
+	if prop.oneofSizer != nil {
+		m := structPointer_Interface(base, prop.stype).(Message)
+		n += prop.oneofSizer(m)
+	}
+
+	return
+}
+
+var zeroes [20]byte // longer than any conceivable sizeVarint
+
+// Encode a struct, preceded by its encoded length (as a varint).
+func (o *Buffer) enc_len_struct(prop *StructProperties, base structPointer, state *errorState) error {
+	return o.enc_len_thing(func() error { return o.enc_struct(prop, base) }, state)
+}
+
+// Encode something, preceded by its encoded length (as a varint).
+func (o *Buffer) enc_len_thing(enc func() error, state *errorState) error {
+	iLen := len(o.buf)
+	o.buf = append(o.buf, 0, 0, 0, 0) // reserve four bytes for length
+	iMsg := len(o.buf)
+	err := enc()
+	if err != nil && !state.shouldContinue(err, nil) {
+		return err
+	}
+	lMsg := len(o.buf) - iMsg
+	lLen := sizeVarint(uint64(lMsg))
+	switch x := lLen - (iMsg - iLen); {
+	case x > 0: // actual length is x bytes larger than the space we reserved
+		// Move msg x bytes right.
+		o.buf = append(o.buf, zeroes[:x]...)
+		copy(o.buf[iMsg+x:], o.buf[iMsg:iMsg+lMsg])
+	case x < 0: // actual length is x bytes smaller than the space we reserved
+		// Move msg x bytes left.
+		copy(o.buf[iMsg+x:], o.buf[iMsg:iMsg+lMsg])
+		o.buf = o.buf[:len(o.buf)+x] // x is negative
+	}
+	// Encode the length in the reserved space.
+	o.buf = o.buf[:iLen]
+	o.EncodeVarint(uint64(lMsg))
+	o.buf = o.buf[:len(o.buf)+lMsg]
+	return state.err
+}
+
+// errorState maintains the first error that occurs and updates that error
+// with additional context.
+type errorState struct {
+	err error
+}
+
+// shouldContinue reports whether encoding should continue upon encountering the
+// given error. If the error is RequiredNotSetError, shouldContinue returns true
+// and, if this is the first appearance of that error, remembers it for future
+// reporting.
+//
+// If prop is not nil, it may update any error with additional context about the
+// field with the error.
+func (s *errorState) shouldContinue(err error, prop *Properties) bool {
+	// Ignore unset required fields.
+	reqNotSet, ok := err.(*RequiredNotSetError)
+	if !ok {
+		return false
+	}
+	if s.err == nil {
+		if prop != nil {
+			err = &RequiredNotSetError{prop.Name + "." + reqNotSet.field}
+		}
+		s.err = err
+	}
+	return true
+}

+ 300 - 0
vendor/github.com/golang/protobuf/proto/equal.go

@@ -0,0 +1,300 @@
+// Go support for Protocol Buffers - Google's data interchange format
+//
+// Copyright 2011 The Go Authors.  All rights reserved.
+// https://github.com/golang/protobuf
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+//     * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+//     * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+//     * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+// Protocol buffer comparison.
+
+package proto
+
+import (
+	"bytes"
+	"log"
+	"reflect"
+	"strings"
+)
+
+/*
+Equal returns true iff protocol buffers a and b are equal.
+The arguments must both be pointers to protocol buffer structs.
+
+Equality is defined in this way:
+  - Two messages are equal iff they are the same type,
+    corresponding fields are equal, unknown field sets
+    are equal, and extensions sets are equal.
+  - Two set scalar fields are equal iff their values are equal.
+    If the fields are of a floating-point type, remember that
+    NaN != x for all x, including NaN. If the message is defined
+    in a proto3 .proto file, fields are not "set"; specifically,
+    zero length proto3 "bytes" fields are equal (nil == {}).
+  - Two repeated fields are equal iff their lengths are the same,
+    and their corresponding elements are equal. Note a "bytes" field,
+    although represented by []byte, is not a repeated field and the
+    rule for the scalar fields described above applies.
+  - Two unset fields are equal.
+  - Two unknown field sets are equal if their current
+    encoded state is equal.
+  - Two extension sets are equal iff they have corresponding
+    elements that are pairwise equal.
+  - Two map fields are equal iff their lengths are the same,
+    and they contain the same set of elements. Zero-length map
+    fields are equal.
+  - Every other combination of things are not equal.
+
+The return value is undefined if a and b are not protocol buffers.
+*/
+func Equal(a, b Message) bool {
+	if a == nil || b == nil {
+		return a == b
+	}
+	v1, v2 := reflect.ValueOf(a), reflect.ValueOf(b)
+	if v1.Type() != v2.Type() {
+		return false
+	}
+	if v1.Kind() == reflect.Ptr {
+		if v1.IsNil() {
+			return v2.IsNil()
+		}
+		if v2.IsNil() {
+			return false
+		}
+		v1, v2 = v1.Elem(), v2.Elem()
+	}
+	if v1.Kind() != reflect.Struct {
+		return false
+	}
+	return equalStruct(v1, v2)
+}
+
+// v1 and v2 are known to have the same type.
+func equalStruct(v1, v2 reflect.Value) bool {
+	sprop := GetProperties(v1.Type())
+	for i := 0; i < v1.NumField(); i++ {
+		f := v1.Type().Field(i)
+		if strings.HasPrefix(f.Name, "XXX_") {
+			continue
+		}
+		f1, f2 := v1.Field(i), v2.Field(i)
+		if f.Type.Kind() == reflect.Ptr {
+			if n1, n2 := f1.IsNil(), f2.IsNil(); n1 && n2 {
+				// both unset
+				continue
+			} else if n1 != n2 {
+				// set/unset mismatch
+				return false
+			}
+			b1, ok := f1.Interface().(raw)
+			if ok {
+				b2 := f2.Interface().(raw)
+				// RawMessage
+				if !bytes.Equal(b1.Bytes(), b2.Bytes()) {
+					return false
+				}
+				continue
+			}
+			f1, f2 = f1.Elem(), f2.Elem()
+		}
+		if !equalAny(f1, f2, sprop.Prop[i]) {
+			return false
+		}
+	}
+
+	if em1 := v1.FieldByName("XXX_InternalExtensions"); em1.IsValid() {
+		em2 := v2.FieldByName("XXX_InternalExtensions")
+		if !equalExtensions(v1.Type(), em1.Interface().(XXX_InternalExtensions), em2.Interface().(XXX_InternalExtensions)) {
+			return false
+		}
+	}
+
+	if em1 := v1.FieldByName("XXX_extensions"); em1.IsValid() {
+		em2 := v2.FieldByName("XXX_extensions")
+		if !equalExtMap(v1.Type(), em1.Interface().(map[int32]Extension), em2.Interface().(map[int32]Extension)) {
+			return false
+		}
+	}
+
+	uf := v1.FieldByName("XXX_unrecognized")
+	if !uf.IsValid() {
+		return true
+	}
+
+	u1 := uf.Bytes()
+	u2 := v2.FieldByName("XXX_unrecognized").Bytes()
+	if !bytes.Equal(u1, u2) {
+		return false
+	}
+
+	return true
+}
+
+// v1 and v2 are known to have the same type.
+// prop may be nil.
+func equalAny(v1, v2 reflect.Value, prop *Properties) bool {
+	if v1.Type() == protoMessageType {
+		m1, _ := v1.Interface().(Message)
+		m2, _ := v2.Interface().(Message)
+		return Equal(m1, m2)
+	}
+	switch v1.Kind() {
+	case reflect.Bool:
+		return v1.Bool() == v2.Bool()
+	case reflect.Float32, reflect.Float64:
+		return v1.Float() == v2.Float()
+	case reflect.Int32, reflect.Int64:
+		return v1.Int() == v2.Int()
+	case reflect.Interface:
+		// Probably a oneof field; compare the inner values.
+		n1, n2 := v1.IsNil(), v2.IsNil()
+		if n1 || n2 {
+			return n1 == n2
+		}
+		e1, e2 := v1.Elem(), v2.Elem()
+		if e1.Type() != e2.Type() {
+			return false
+		}
+		return equalAny(e1, e2, nil)
+	case reflect.Map:
+		if v1.Len() != v2.Len() {
+			return false
+		}
+		for _, key := range v1.MapKeys() {
+			val2 := v2.MapIndex(key)
+			if !val2.IsValid() {
+				// This key was not found in the second map.
+				return false
+			}
+			if !equalAny(v1.MapIndex(key), val2, nil) {
+				return false
+			}
+		}
+		return true
+	case reflect.Ptr:
+		// Maps may have nil values in them, so check for nil.
+		if v1.IsNil() && v2.IsNil() {
+			return true
+		}
+		if v1.IsNil() != v2.IsNil() {
+			return false
+		}
+		return equalAny(v1.Elem(), v2.Elem(), prop)
+	case reflect.Slice:
+		if v1.Type().Elem().Kind() == reflect.Uint8 {
+			// short circuit: []byte
+
+			// Edge case: if this is in a proto3 message, a zero length
+			// bytes field is considered the zero value.
+			if prop != nil && prop.proto3 && v1.Len() == 0 && v2.Len() == 0 {
+				return true
+			}
+			if v1.IsNil() != v2.IsNil() {
+				return false
+			}
+			return bytes.Equal(v1.Interface().([]byte), v2.Interface().([]byte))
+		}
+
+		if v1.Len() != v2.Len() {
+			return false
+		}
+		for i := 0; i < v1.Len(); i++ {
+			if !equalAny(v1.Index(i), v2.Index(i), prop) {
+				return false
+			}
+		}
+		return true
+	case reflect.String:
+		return v1.Interface().(string) == v2.Interface().(string)
+	case reflect.Struct:
+		return equalStruct(v1, v2)
+	case reflect.Uint32, reflect.Uint64:
+		return v1.Uint() == v2.Uint()
+	}
+
+	// unknown type, so not a protocol buffer
+	log.Printf("proto: don't know how to compare %v", v1)
+	return false
+}
+
+// base is the struct type that the extensions are based on.
+// x1 and x2 are InternalExtensions.
+func equalExtensions(base reflect.Type, x1, x2 XXX_InternalExtensions) bool {
+	em1, _ := x1.extensionsRead()
+	em2, _ := x2.extensionsRead()
+	return equalExtMap(base, em1, em2)
+}
+
+func equalExtMap(base reflect.Type, em1, em2 map[int32]Extension) bool {
+	if len(em1) != len(em2) {
+		return false
+	}
+
+	for extNum, e1 := range em1 {
+		e2, ok := em2[extNum]
+		if !ok {
+			return false
+		}
+
+		m1, m2 := e1.value, e2.value
+
+		if m1 != nil && m2 != nil {
+			// Both are unencoded.
+			if !equalAny(reflect.ValueOf(m1), reflect.ValueOf(m2), nil) {
+				return false
+			}
+			continue
+		}
+
+		// At least one is encoded. To do a semantically correct comparison
+		// we need to unmarshal them first.
+		var desc *ExtensionDesc
+		if m := extensionMaps[base]; m != nil {
+			desc = m[extNum]
+		}
+		if desc == nil {
+			log.Printf("proto: don't know how to compare extension %d of %v", extNum, base)
+			continue
+		}
+		var err error
+		if m1 == nil {
+			m1, err = decodeExtension(e1.enc, desc)
+		}
+		if m2 == nil && err == nil {
+			m2, err = decodeExtension(e2.enc, desc)
+		}
+		if err != nil {
+			// The encoded form is invalid.
+			log.Printf("proto: badly encoded extension %d of %v: %v", extNum, base, err)
+			return false
+		}
+		if !equalAny(reflect.ValueOf(m1), reflect.ValueOf(m2), nil) {
+			return false
+		}
+	}
+
+	return true
+}

+ 587 - 0
vendor/github.com/golang/protobuf/proto/extensions.go

@@ -0,0 +1,587 @@
+// Go support for Protocol Buffers - Google's data interchange format
+//
+// Copyright 2010 The Go Authors.  All rights reserved.
+// https://github.com/golang/protobuf
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+//     * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+//     * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+//     * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+package proto
+
+/*
+ * Types and routines for supporting protocol buffer extensions.
+ */
+
+import (
+	"errors"
+	"fmt"
+	"reflect"
+	"strconv"
+	"sync"
+)
+
+// ErrMissingExtension is the error returned by GetExtension if the named extension is not in the message.
+var ErrMissingExtension = errors.New("proto: missing extension")
+
+// ExtensionRange represents a range of message extensions for a protocol buffer.
+// Used in code generated by the protocol compiler.
+type ExtensionRange struct {
+	Start, End int32 // both inclusive
+}
+
+// extendableProto is an interface implemented by any protocol buffer generated by the current
+// proto compiler that may be extended.
+type extendableProto interface {
+	Message
+	ExtensionRangeArray() []ExtensionRange
+	extensionsWrite() map[int32]Extension
+	extensionsRead() (map[int32]Extension, sync.Locker)
+}
+
+// extendableProtoV1 is an interface implemented by a protocol buffer generated by the previous
+// version of the proto compiler that may be extended.
+type extendableProtoV1 interface {
+	Message
+	ExtensionRangeArray() []ExtensionRange
+	ExtensionMap() map[int32]Extension
+}
+
+// extensionAdapter is a wrapper around extendableProtoV1 that implements extendableProto.
+type extensionAdapter struct {
+	extendableProtoV1
+}
+
+func (e extensionAdapter) extensionsWrite() map[int32]Extension {
+	return e.ExtensionMap()
+}
+
+func (e extensionAdapter) extensionsRead() (map[int32]Extension, sync.Locker) {
+	return e.ExtensionMap(), notLocker{}
+}
+
+// notLocker is a sync.Locker whose Lock and Unlock methods are nops.
+type notLocker struct{}
+
+func (n notLocker) Lock()   {}
+func (n notLocker) Unlock() {}
+
+// extendable returns the extendableProto interface for the given generated proto message.
+// If the proto message has the old extension format, it returns a wrapper that implements
+// the extendableProto interface.
+func extendable(p interface{}) (extendableProto, bool) {
+	if ep, ok := p.(extendableProto); ok {
+		return ep, ok
+	}
+	if ep, ok := p.(extendableProtoV1); ok {
+		return extensionAdapter{ep}, ok
+	}
+	return nil, false
+}
+
+// XXX_InternalExtensions is an internal representation of proto extensions.
+//
+// Each generated message struct type embeds an anonymous XXX_InternalExtensions field,
+// thus gaining the unexported 'extensions' method, which can be called only from the proto package.
+//
+// The methods of XXX_InternalExtensions are not concurrency safe in general,
+// but calls to logically read-only methods such as has and get may be executed concurrently.
+type XXX_InternalExtensions struct {
+	// The struct must be indirect so that if a user inadvertently copies a
+	// generated message and its embedded XXX_InternalExtensions, they
+	// avoid the mayhem of a copied mutex.
+	//
+	// The mutex serializes all logically read-only operations to p.extensionMap.
+	// It is up to the client to ensure that write operations to p.extensionMap are
+	// mutually exclusive with other accesses.
+	p *struct {
+		mu           sync.Mutex
+		extensionMap map[int32]Extension
+	}
+}
+
+// extensionsWrite returns the extension map, creating it on first use.
+func (e *XXX_InternalExtensions) extensionsWrite() map[int32]Extension {
+	if e.p == nil {
+		e.p = new(struct {
+			mu           sync.Mutex
+			extensionMap map[int32]Extension
+		})
+		e.p.extensionMap = make(map[int32]Extension)
+	}
+	return e.p.extensionMap
+}
+
+// extensionsRead returns the extensions map for read-only use.  It may be nil.
+// The caller must hold the returned mutex's lock when accessing Elements within the map.
+func (e *XXX_InternalExtensions) extensionsRead() (map[int32]Extension, sync.Locker) {
+	if e.p == nil {
+		return nil, nil
+	}
+	return e.p.extensionMap, &e.p.mu
+}
+
+var extendableProtoType = reflect.TypeOf((*extendableProto)(nil)).Elem()
+var extendableProtoV1Type = reflect.TypeOf((*extendableProtoV1)(nil)).Elem()
+
+// ExtensionDesc represents an extension specification.
+// Used in generated code from the protocol compiler.
+type ExtensionDesc struct {
+	ExtendedType  Message     // nil pointer to the type that is being extended
+	ExtensionType interface{} // nil pointer to the extension type
+	Field         int32       // field number
+	Name          string      // fully-qualified name of extension, for text formatting
+	Tag           string      // protobuf tag style
+	Filename      string      // name of the file in which the extension is defined
+}
+
+func (ed *ExtensionDesc) repeated() bool {
+	t := reflect.TypeOf(ed.ExtensionType)
+	return t.Kind() == reflect.Slice && t.Elem().Kind() != reflect.Uint8
+}
+
+// Extension represents an extension in a message.
+type Extension struct {
+	// When an extension is stored in a message using SetExtension
+	// only desc and value are set. When the message is marshaled
+	// enc will be set to the encoded form of the message.
+	//
+	// When a message is unmarshaled and contains extensions, each
+	// extension will have only enc set. When such an extension is
+	// accessed using GetExtension (or GetExtensions) desc and value
+	// will be set.
+	desc  *ExtensionDesc
+	value interface{}
+	enc   []byte
+}
+
+// SetRawExtension is for testing only.
+func SetRawExtension(base Message, id int32, b []byte) {
+	epb, ok := extendable(base)
+	if !ok {
+		return
+	}
+	extmap := epb.extensionsWrite()
+	extmap[id] = Extension{enc: b}
+}
+
+// isExtensionField returns true iff the given field number is in an extension range.
+func isExtensionField(pb extendableProto, field int32) bool {
+	for _, er := range pb.ExtensionRangeArray() {
+		if er.Start <= field && field <= er.End {
+			return true
+		}
+	}
+	return false
+}
+
+// checkExtensionTypes checks that the given extension is valid for pb.
+func checkExtensionTypes(pb extendableProto, extension *ExtensionDesc) error {
+	var pbi interface{} = pb
+	// Check the extended type.
+	if ea, ok := pbi.(extensionAdapter); ok {
+		pbi = ea.extendableProtoV1
+	}
+	if a, b := reflect.TypeOf(pbi), reflect.TypeOf(extension.ExtendedType); a != b {
+		return errors.New("proto: bad extended type; " + b.String() + " does not extend " + a.String())
+	}
+	// Check the range.
+	if !isExtensionField(pb, extension.Field) {
+		return errors.New("proto: bad extension number; not in declared ranges")
+	}
+	return nil
+}
+
+// extPropKey is sufficient to uniquely identify an extension.
+type extPropKey struct {
+	base  reflect.Type
+	field int32
+}
+
+var extProp = struct {
+	sync.RWMutex
+	m map[extPropKey]*Properties
+}{
+	m: make(map[extPropKey]*Properties),
+}
+
+func extensionProperties(ed *ExtensionDesc) *Properties {
+	key := extPropKey{base: reflect.TypeOf(ed.ExtendedType), field: ed.Field}
+
+	extProp.RLock()
+	if prop, ok := extProp.m[key]; ok {
+		extProp.RUnlock()
+		return prop
+	}
+	extProp.RUnlock()
+
+	extProp.Lock()
+	defer extProp.Unlock()
+	// Check again.
+	if prop, ok := extProp.m[key]; ok {
+		return prop
+	}
+
+	prop := new(Properties)
+	prop.Init(reflect.TypeOf(ed.ExtensionType), "unknown_name", ed.Tag, nil)
+	extProp.m[key] = prop
+	return prop
+}
+
+// encode encodes any unmarshaled (unencoded) extensions in e.
+func encodeExtensions(e *XXX_InternalExtensions) error {
+	m, mu := e.extensionsRead()
+	if m == nil {
+		return nil // fast path
+	}
+	mu.Lock()
+	defer mu.Unlock()
+	return encodeExtensionsMap(m)
+}
+
+// encode encodes any unmarshaled (unencoded) extensions in e.
+func encodeExtensionsMap(m map[int32]Extension) error {
+	for k, e := range m {
+		if e.value == nil || e.desc == nil {
+			// Extension is only in its encoded form.
+			continue
+		}
+
+		// We don't skip extensions that have an encoded form set,
+		// because the extension value may have been mutated after
+		// the last time this function was called.
+
+		et := reflect.TypeOf(e.desc.ExtensionType)
+		props := extensionProperties(e.desc)
+
+		p := NewBuffer(nil)
+		// If e.value has type T, the encoder expects a *struct{ X T }.
+		// Pass a *T with a zero field and hope it all works out.
+		x := reflect.New(et)
+		x.Elem().Set(reflect.ValueOf(e.value))
+		if err := props.enc(p, props, toStructPointer(x)); err != nil {
+			return err
+		}
+		e.enc = p.buf
+		m[k] = e
+	}
+	return nil
+}
+
+func extensionsSize(e *XXX_InternalExtensions) (n int) {
+	m, mu := e.extensionsRead()
+	if m == nil {
+		return 0
+	}
+	mu.Lock()
+	defer mu.Unlock()
+	return extensionsMapSize(m)
+}
+
+func extensionsMapSize(m map[int32]Extension) (n int) {
+	for _, e := range m {
+		if e.value == nil || e.desc == nil {
+			// Extension is only in its encoded form.
+			n += len(e.enc)
+			continue
+		}
+
+		// We don't skip extensions that have an encoded form set,
+		// because the extension value may have been mutated after
+		// the last time this function was called.
+
+		et := reflect.TypeOf(e.desc.ExtensionType)
+		props := extensionProperties(e.desc)
+
+		// If e.value has type T, the encoder expects a *struct{ X T }.
+		// Pass a *T with a zero field and hope it all works out.
+		x := reflect.New(et)
+		x.Elem().Set(reflect.ValueOf(e.value))
+		n += props.size(props, toStructPointer(x))
+	}
+	return
+}
+
+// HasExtension returns whether the given extension is present in pb.
+func HasExtension(pb Message, extension *ExtensionDesc) bool {
+	// TODO: Check types, field numbers, etc.?
+	epb, ok := extendable(pb)
+	if !ok {
+		return false
+	}
+	extmap, mu := epb.extensionsRead()
+	if extmap == nil {
+		return false
+	}
+	mu.Lock()
+	_, ok = extmap[extension.Field]
+	mu.Unlock()
+	return ok
+}
+
+// ClearExtension removes the given extension from pb.
+func ClearExtension(pb Message, extension *ExtensionDesc) {
+	epb, ok := extendable(pb)
+	if !ok {
+		return
+	}
+	// TODO: Check types, field numbers, etc.?
+	extmap := epb.extensionsWrite()
+	delete(extmap, extension.Field)
+}
+
+// GetExtension parses and returns the given extension of pb.
+// If the extension is not present and has no default value it returns ErrMissingExtension.
+func GetExtension(pb Message, extension *ExtensionDesc) (interface{}, error) {
+	epb, ok := extendable(pb)
+	if !ok {
+		return nil, errors.New("proto: not an extendable proto")
+	}
+
+	if err := checkExtensionTypes(epb, extension); err != nil {
+		return nil, err
+	}
+
+	emap, mu := epb.extensionsRead()
+	if emap == nil {
+		return defaultExtensionValue(extension)
+	}
+	mu.Lock()
+	defer mu.Unlock()
+	e, ok := emap[extension.Field]
+	if !ok {
+		// defaultExtensionValue returns the default value or
+		// ErrMissingExtension if there is no default.
+		return defaultExtensionValue(extension)
+	}
+
+	if e.value != nil {
+		// Already decoded. Check the descriptor, though.
+		if e.desc != extension {
+			// This shouldn't happen. If it does, it means that
+			// GetExtension was called twice with two different
+			// descriptors with the same field number.
+			return nil, errors.New("proto: descriptor conflict")
+		}
+		return e.value, nil
+	}
+
+	v, err := decodeExtension(e.enc, extension)
+	if err != nil {
+		return nil, err
+	}
+
+	// Remember the decoded version and drop the encoded version.
+	// That way it is safe to mutate what we return.
+	e.value = v
+	e.desc = extension
+	e.enc = nil
+	emap[extension.Field] = e
+	return e.value, nil
+}
+
+// defaultExtensionValue returns the default value for extension.
+// If no default for an extension is defined ErrMissingExtension is returned.
+func defaultExtensionValue(extension *ExtensionDesc) (interface{}, error) {
+	t := reflect.TypeOf(extension.ExtensionType)
+	props := extensionProperties(extension)
+
+	sf, _, err := fieldDefault(t, props)
+	if err != nil {
+		return nil, err
+	}
+
+	if sf == nil || sf.value == nil {
+		// There is no default value.
+		return nil, ErrMissingExtension
+	}
+
+	if t.Kind() != reflect.Ptr {
+		// We do not need to return a Ptr, we can directly return sf.value.
+		return sf.value, nil
+	}
+
+	// We need to return an interface{} that is a pointer to sf.value.
+	value := reflect.New(t).Elem()
+	value.Set(reflect.New(value.Type().Elem()))
+	if sf.kind == reflect.Int32 {
+		// We may have an int32 or an enum, but the underlying data is int32.
+		// Since we can't set an int32 into a non int32 reflect.value directly
+		// set it as a int32.
+		value.Elem().SetInt(int64(sf.value.(int32)))
+	} else {
+		value.Elem().Set(reflect.ValueOf(sf.value))
+	}
+	return value.Interface(), nil
+}
+
+// decodeExtension decodes an extension encoded in b.
+func decodeExtension(b []byte, extension *ExtensionDesc) (interface{}, error) {
+	o := NewBuffer(b)
+
+	t := reflect.TypeOf(extension.ExtensionType)
+
+	props := extensionProperties(extension)
+
+	// t is a pointer to a struct, pointer to basic type or a slice.
+	// Allocate a "field" to store the pointer/slice itself; the
+	// pointer/slice will be stored here. We pass
+	// the address of this field to props.dec.
+	// This passes a zero field and a *t and lets props.dec
+	// interpret it as a *struct{ x t }.
+	value := reflect.New(t).Elem()
+
+	for {
+		// Discard wire type and field number varint. It isn't needed.
+		if _, err := o.DecodeVarint(); err != nil {
+			return nil, err
+		}
+
+		if err := props.dec(o, props, toStructPointer(value.Addr())); err != nil {
+			return nil, err
+		}
+
+		if o.index >= len(o.buf) {
+			break
+		}
+	}
+	return value.Interface(), nil
+}
+
+// GetExtensions returns a slice of the extensions present in pb that are also listed in es.
+// The returned slice has the same length as es; missing extensions will appear as nil elements.
+func GetExtensions(pb Message, es []*ExtensionDesc) (extensions []interface{}, err error) {
+	epb, ok := extendable(pb)
+	if !ok {
+		return nil, errors.New("proto: not an extendable proto")
+	}
+	extensions = make([]interface{}, len(es))
+	for i, e := range es {
+		extensions[i], err = GetExtension(epb, e)
+		if err == ErrMissingExtension {
+			err = nil
+		}
+		if err != nil {
+			return
+		}
+	}
+	return
+}
+
+// ExtensionDescs returns a new slice containing pb's extension descriptors, in undefined order.
+// For non-registered extensions, ExtensionDescs returns an incomplete descriptor containing
+// just the Field field, which defines the extension's field number.
+func ExtensionDescs(pb Message) ([]*ExtensionDesc, error) {
+	epb, ok := extendable(pb)
+	if !ok {
+		return nil, fmt.Errorf("proto: %T is not an extendable proto.Message", pb)
+	}
+	registeredExtensions := RegisteredExtensions(pb)
+
+	emap, mu := epb.extensionsRead()
+	if emap == nil {
+		return nil, nil
+	}
+	mu.Lock()
+	defer mu.Unlock()
+	extensions := make([]*ExtensionDesc, 0, len(emap))
+	for extid, e := range emap {
+		desc := e.desc
+		if desc == nil {
+			desc = registeredExtensions[extid]
+			if desc == nil {
+				desc = &ExtensionDesc{Field: extid}
+			}
+		}
+
+		extensions = append(extensions, desc)
+	}
+	return extensions, nil
+}
+
+// SetExtension sets the specified extension of pb to the specified value.
+func SetExtension(pb Message, extension *ExtensionDesc, value interface{}) error {
+	epb, ok := extendable(pb)
+	if !ok {
+		return errors.New("proto: not an extendable proto")
+	}
+	if err := checkExtensionTypes(epb, extension); err != nil {
+		return err
+	}
+	typ := reflect.TypeOf(extension.ExtensionType)
+	if typ != reflect.TypeOf(value) {
+		return errors.New("proto: bad extension value type")
+	}
+	// nil extension values need to be caught early, because the
+	// encoder can't distinguish an ErrNil due to a nil extension
+	// from an ErrNil due to a missing field. Extensions are
+	// always optional, so the encoder would just swallow the error
+	// and drop all the extensions from the encoded message.
+	if reflect.ValueOf(value).IsNil() {
+		return fmt.Errorf("proto: SetExtension called with nil value of type %T", value)
+	}
+
+	extmap := epb.extensionsWrite()
+	extmap[extension.Field] = Extension{desc: extension, value: value}
+	return nil
+}
+
+// ClearAllExtensions clears all extensions from pb.
+func ClearAllExtensions(pb Message) {
+	epb, ok := extendable(pb)
+	if !ok {
+		return
+	}
+	m := epb.extensionsWrite()
+	for k := range m {
+		delete(m, k)
+	}
+}
+
+// A global registry of extensions.
+// The generated code will register the generated descriptors by calling RegisterExtension.
+
+var extensionMaps = make(map[reflect.Type]map[int32]*ExtensionDesc)
+
+// RegisterExtension is called from the generated code.
+func RegisterExtension(desc *ExtensionDesc) {
+	st := reflect.TypeOf(desc.ExtendedType).Elem()
+	m := extensionMaps[st]
+	if m == nil {
+		m = make(map[int32]*ExtensionDesc)
+		extensionMaps[st] = m
+	}
+	if _, ok := m[desc.Field]; ok {
+		panic("proto: duplicate extension registered: " + st.String() + " " + strconv.Itoa(int(desc.Field)))
+	}
+	m[desc.Field] = desc
+}
+
+// RegisteredExtensions returns a map of the registered extensions of a
+// protocol buffer struct, indexed by the extension number.
+// The argument pb should be a nil pointer to the struct type.
+func RegisteredExtensions(pb Message) map[int32]*ExtensionDesc {
+	return extensionMaps[reflect.TypeOf(pb).Elem()]
+}

+ 897 - 0
vendor/github.com/golang/protobuf/proto/lib.go

@@ -0,0 +1,897 @@
+// Go support for Protocol Buffers - Google's data interchange format
+//
+// Copyright 2010 The Go Authors.  All rights reserved.
+// https://github.com/golang/protobuf
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+//     * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+//     * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+//     * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+/*
+Package proto converts data structures to and from the wire format of
+protocol buffers.  It works in concert with the Go source code generated
+for .proto files by the protocol compiler.
+
+A summary of the properties of the protocol buffer interface
+for a protocol buffer variable v:
+
+  - Names are turned from camel_case to CamelCase for export.
+  - There are no methods on v to set fields; just treat
+	them as structure fields.
+  - There are getters that return a field's value if set,
+	and return the field's default value if unset.
+	The getters work even if the receiver is a nil message.
+  - The zero value for a struct is its correct initialization state.
+	All desired fields must be set before marshaling.
+  - A Reset() method will restore a protobuf struct to its zero state.
+  - Non-repeated fields are pointers to the values; nil means unset.
+	That is, optional or required field int32 f becomes F *int32.
+  - Repeated fields are slices.
+  - Helper functions are available to aid the setting of fields.
+	msg.Foo = proto.String("hello") // set field
+  - Constants are defined to hold the default values of all fields that
+	have them.  They have the form Default_StructName_FieldName.
+	Because the getter methods handle defaulted values,
+	direct use of these constants should be rare.
+  - Enums are given type names and maps from names to values.
+	Enum values are prefixed by the enclosing message's name, or by the
+	enum's type name if it is a top-level enum. Enum types have a String
+	method, and a Enum method to assist in message construction.
+  - Nested messages, groups and enums have type names prefixed with the name of
+	the surrounding message type.
+  - Extensions are given descriptor names that start with E_,
+	followed by an underscore-delimited list of the nested messages
+	that contain it (if any) followed by the CamelCased name of the
+	extension field itself.  HasExtension, ClearExtension, GetExtension
+	and SetExtension are functions for manipulating extensions.
+  - Oneof field sets are given a single field in their message,
+	with distinguished wrapper types for each possible field value.
+  - Marshal and Unmarshal are functions to encode and decode the wire format.
+
+When the .proto file specifies `syntax="proto3"`, there are some differences:
+
+  - Non-repeated fields of non-message type are values instead of pointers.
+  - Enum types do not get an Enum method.
+
+The simplest way to describe this is to see an example.
+Given file test.proto, containing
+
+	package example;
+
+	enum FOO { X = 17; }
+
+	message Test {
+	  required string label = 1;
+	  optional int32 type = 2 [default=77];
+	  repeated int64 reps = 3;
+	  optional group OptionalGroup = 4 {
+	    required string RequiredField = 5;
+	  }
+	  oneof union {
+	    int32 number = 6;
+	    string name = 7;
+	  }
+	}
+
+The resulting file, test.pb.go, is:
+
+	package example
+
+	import proto "github.com/golang/protobuf/proto"
+	import math "math"
+
+	type FOO int32
+	const (
+		FOO_X FOO = 17
+	)
+	var FOO_name = map[int32]string{
+		17: "X",
+	}
+	var FOO_value = map[string]int32{
+		"X": 17,
+	}
+
+	func (x FOO) Enum() *FOO {
+		p := new(FOO)
+		*p = x
+		return p
+	}
+	func (x FOO) String() string {
+		return proto.EnumName(FOO_name, int32(x))
+	}
+	func (x *FOO) UnmarshalJSON(data []byte) error {
+		value, err := proto.UnmarshalJSONEnum(FOO_value, data)
+		if err != nil {
+			return err
+		}
+		*x = FOO(value)
+		return nil
+	}
+
+	type Test struct {
+		Label         *string             `protobuf:"bytes,1,req,name=label" json:"label,omitempty"`
+		Type          *int32              `protobuf:"varint,2,opt,name=type,def=77" json:"type,omitempty"`
+		Reps          []int64             `protobuf:"varint,3,rep,name=reps" json:"reps,omitempty"`
+		Optionalgroup *Test_OptionalGroup `protobuf:"group,4,opt,name=OptionalGroup" json:"optionalgroup,omitempty"`
+		// Types that are valid to be assigned to Union:
+		//	*Test_Number
+		//	*Test_Name
+		Union            isTest_Union `protobuf_oneof:"union"`
+		XXX_unrecognized []byte       `json:"-"`
+	}
+	func (m *Test) Reset()         { *m = Test{} }
+	func (m *Test) String() string { return proto.CompactTextString(m) }
+	func (*Test) ProtoMessage() {}
+
+	type isTest_Union interface {
+		isTest_Union()
+	}
+
+	type Test_Number struct {
+		Number int32 `protobuf:"varint,6,opt,name=number"`
+	}
+	type Test_Name struct {
+		Name string `protobuf:"bytes,7,opt,name=name"`
+	}
+
+	func (*Test_Number) isTest_Union() {}
+	func (*Test_Name) isTest_Union()   {}
+
+	func (m *Test) GetUnion() isTest_Union {
+		if m != nil {
+			return m.Union
+		}
+		return nil
+	}
+	const Default_Test_Type int32 = 77
+
+	func (m *Test) GetLabel() string {
+		if m != nil && m.Label != nil {
+			return *m.Label
+		}
+		return ""
+	}
+
+	func (m *Test) GetType() int32 {
+		if m != nil && m.Type != nil {
+			return *m.Type
+		}
+		return Default_Test_Type
+	}
+
+	func (m *Test) GetOptionalgroup() *Test_OptionalGroup {
+		if m != nil {
+			return m.Optionalgroup
+		}
+		return nil
+	}
+
+	type Test_OptionalGroup struct {
+		RequiredField *string `protobuf:"bytes,5,req" json:"RequiredField,omitempty"`
+	}
+	func (m *Test_OptionalGroup) Reset()         { *m = Test_OptionalGroup{} }
+	func (m *Test_OptionalGroup) String() string { return proto.CompactTextString(m) }
+
+	func (m *Test_OptionalGroup) GetRequiredField() string {
+		if m != nil && m.RequiredField != nil {
+			return *m.RequiredField
+		}
+		return ""
+	}
+
+	func (m *Test) GetNumber() int32 {
+		if x, ok := m.GetUnion().(*Test_Number); ok {
+			return x.Number
+		}
+		return 0
+	}
+
+	func (m *Test) GetName() string {
+		if x, ok := m.GetUnion().(*Test_Name); ok {
+			return x.Name
+		}
+		return ""
+	}
+
+	func init() {
+		proto.RegisterEnum("example.FOO", FOO_name, FOO_value)
+	}
+
+To create and play with a Test object:
+
+	package main
+
+	import (
+		"log"
+
+		"github.com/golang/protobuf/proto"
+		pb "./example.pb"
+	)
+
+	func main() {
+		test := &pb.Test{
+			Label: proto.String("hello"),
+			Type:  proto.Int32(17),
+			Reps:  []int64{1, 2, 3},
+			Optionalgroup: &pb.Test_OptionalGroup{
+				RequiredField: proto.String("good bye"),
+			},
+			Union: &pb.Test_Name{"fred"},
+		}
+		data, err := proto.Marshal(test)
+		if err != nil {
+			log.Fatal("marshaling error: ", err)
+		}
+		newTest := &pb.Test{}
+		err = proto.Unmarshal(data, newTest)
+		if err != nil {
+			log.Fatal("unmarshaling error: ", err)
+		}
+		// Now test and newTest contain the same data.
+		if test.GetLabel() != newTest.GetLabel() {
+			log.Fatalf("data mismatch %q != %q", test.GetLabel(), newTest.GetLabel())
+		}
+		// Use a type switch to determine which oneof was set.
+		switch u := test.Union.(type) {
+		case *pb.Test_Number: // u.Number contains the number.
+		case *pb.Test_Name: // u.Name contains the string.
+		}
+		// etc.
+	}
+*/
+package proto
+
+import (
+	"encoding/json"
+	"fmt"
+	"log"
+	"reflect"
+	"sort"
+	"strconv"
+	"sync"
+)
+
+// Message is implemented by generated protocol buffer messages.
+type Message interface {
+	Reset()
+	String() string
+	ProtoMessage()
+}
+
+// Stats records allocation details about the protocol buffer encoders
+// and decoders.  Useful for tuning the library itself.
+type Stats struct {
+	Emalloc uint64 // mallocs in encode
+	Dmalloc uint64 // mallocs in decode
+	Encode  uint64 // number of encodes
+	Decode  uint64 // number of decodes
+	Chit    uint64 // number of cache hits
+	Cmiss   uint64 // number of cache misses
+	Size    uint64 // number of sizes
+}
+
+// Set to true to enable stats collection.
+const collectStats = false
+
+var stats Stats
+
+// GetStats returns a copy of the global Stats structure.
+func GetStats() Stats { return stats }
+
+// A Buffer is a buffer manager for marshaling and unmarshaling
+// protocol buffers.  It may be reused between invocations to
+// reduce memory usage.  It is not necessary to use a Buffer;
+// the global functions Marshal and Unmarshal create a
+// temporary Buffer and are fine for most applications.
+type Buffer struct {
+	buf   []byte // encode/decode byte stream
+	index int    // read point
+
+	// pools of basic types to amortize allocation.
+	bools   []bool
+	uint32s []uint32
+	uint64s []uint64
+
+	// extra pools, only used with pointer_reflect.go
+	int32s   []int32
+	int64s   []int64
+	float32s []float32
+	float64s []float64
+}
+
+// NewBuffer allocates a new Buffer and initializes its internal data to
+// the contents of the argument slice.
+func NewBuffer(e []byte) *Buffer {
+	return &Buffer{buf: e}
+}
+
+// Reset resets the Buffer, ready for marshaling a new protocol buffer.
+func (p *Buffer) Reset() {
+	p.buf = p.buf[0:0] // for reading/writing
+	p.index = 0        // for reading
+}
+
+// SetBuf replaces the internal buffer with the slice,
+// ready for unmarshaling the contents of the slice.
+func (p *Buffer) SetBuf(s []byte) {
+	p.buf = s
+	p.index = 0
+}
+
+// Bytes returns the contents of the Buffer.
+func (p *Buffer) Bytes() []byte { return p.buf }
+
+/*
+ * Helper routines for simplifying the creation of optional fields of basic type.
+ */
+
+// Bool is a helper routine that allocates a new bool value
+// to store v and returns a pointer to it.
+func Bool(v bool) *bool {
+	return &v
+}
+
+// Int32 is a helper routine that allocates a new int32 value
+// to store v and returns a pointer to it.
+func Int32(v int32) *int32 {
+	return &v
+}
+
+// Int is a helper routine that allocates a new int32 value
+// to store v and returns a pointer to it, but unlike Int32
+// its argument value is an int.
+func Int(v int) *int32 {
+	p := new(int32)
+	*p = int32(v)
+	return p
+}
+
+// Int64 is a helper routine that allocates a new int64 value
+// to store v and returns a pointer to it.
+func Int64(v int64) *int64 {
+	return &v
+}
+
+// Float32 is a helper routine that allocates a new float32 value
+// to store v and returns a pointer to it.
+func Float32(v float32) *float32 {
+	return &v
+}
+
+// Float64 is a helper routine that allocates a new float64 value
+// to store v and returns a pointer to it.
+func Float64(v float64) *float64 {
+	return &v
+}
+
+// Uint32 is a helper routine that allocates a new uint32 value
+// to store v and returns a pointer to it.
+func Uint32(v uint32) *uint32 {
+	return &v
+}
+
+// Uint64 is a helper routine that allocates a new uint64 value
+// to store v and returns a pointer to it.
+func Uint64(v uint64) *uint64 {
+	return &v
+}
+
+// String is a helper routine that allocates a new string value
+// to store v and returns a pointer to it.
+func String(v string) *string {
+	return &v
+}
+
+// EnumName is a helper function to simplify printing protocol buffer enums
+// by name.  Given an enum map and a value, it returns a useful string.
+func EnumName(m map[int32]string, v int32) string {
+	s, ok := m[v]
+	if ok {
+		return s
+	}
+	return strconv.Itoa(int(v))
+}
+
+// UnmarshalJSONEnum is a helper function to simplify recovering enum int values
+// from their JSON-encoded representation. Given a map from the enum's symbolic
+// names to its int values, and a byte buffer containing the JSON-encoded
+// value, it returns an int32 that can be cast to the enum type by the caller.
+//
+// The function can deal with both JSON representations, numeric and symbolic.
+func UnmarshalJSONEnum(m map[string]int32, data []byte, enumName string) (int32, error) {
+	if data[0] == '"' {
+		// New style: enums are strings.
+		var repr string
+		if err := json.Unmarshal(data, &repr); err != nil {
+			return -1, err
+		}
+		val, ok := m[repr]
+		if !ok {
+			return 0, fmt.Errorf("unrecognized enum %s value %q", enumName, repr)
+		}
+		return val, nil
+	}
+	// Old style: enums are ints.
+	var val int32
+	if err := json.Unmarshal(data, &val); err != nil {
+		return 0, fmt.Errorf("cannot unmarshal %#q into enum %s", data, enumName)
+	}
+	return val, nil
+}
+
+// DebugPrint dumps the encoded data in b in a debugging format with a header
+// including the string s. Used in testing but made available for general debugging.
+func (p *Buffer) DebugPrint(s string, b []byte) {
+	var u uint64
+
+	obuf := p.buf
+	index := p.index
+	p.buf = b
+	p.index = 0
+	depth := 0
+
+	fmt.Printf("\n--- %s ---\n", s)
+
+out:
+	for {
+		for i := 0; i < depth; i++ {
+			fmt.Print("  ")
+		}
+
+		index := p.index
+		if index == len(p.buf) {
+			break
+		}
+
+		op, err := p.DecodeVarint()
+		if err != nil {
+			fmt.Printf("%3d: fetching op err %v\n", index, err)
+			break out
+		}
+		tag := op >> 3
+		wire := op & 7
+
+		switch wire {
+		default:
+			fmt.Printf("%3d: t=%3d unknown wire=%d\n",
+				index, tag, wire)
+			break out
+
+		case WireBytes:
+			var r []byte
+
+			r, err = p.DecodeRawBytes(false)
+			if err != nil {
+				break out
+			}
+			fmt.Printf("%3d: t=%3d bytes [%d]", index, tag, len(r))
+			if len(r) <= 6 {
+				for i := 0; i < len(r); i++ {
+					fmt.Printf(" %.2x", r[i])
+				}
+			} else {
+				for i := 0; i < 3; i++ {
+					fmt.Printf(" %.2x", r[i])
+				}
+				fmt.Printf(" ..")
+				for i := len(r) - 3; i < len(r); i++ {
+					fmt.Printf(" %.2x", r[i])
+				}
+			}
+			fmt.Printf("\n")
+
+		case WireFixed32:
+			u, err = p.DecodeFixed32()
+			if err != nil {
+				fmt.Printf("%3d: t=%3d fix32 err %v\n", index, tag, err)
+				break out
+			}
+			fmt.Printf("%3d: t=%3d fix32 %d\n", index, tag, u)
+
+		case WireFixed64:
+			u, err = p.DecodeFixed64()
+			if err != nil {
+				fmt.Printf("%3d: t=%3d fix64 err %v\n", index, tag, err)
+				break out
+			}
+			fmt.Printf("%3d: t=%3d fix64 %d\n", index, tag, u)
+
+		case WireVarint:
+			u, err = p.DecodeVarint()
+			if err != nil {
+				fmt.Printf("%3d: t=%3d varint err %v\n", index, tag, err)
+				break out
+			}
+			fmt.Printf("%3d: t=%3d varint %d\n", index, tag, u)
+
+		case WireStartGroup:
+			fmt.Printf("%3d: t=%3d start\n", index, tag)
+			depth++
+
+		case WireEndGroup:
+			depth--
+			fmt.Printf("%3d: t=%3d end\n", index, tag)
+		}
+	}
+
+	if depth != 0 {
+		fmt.Printf("%3d: start-end not balanced %d\n", p.index, depth)
+	}
+	fmt.Printf("\n")
+
+	p.buf = obuf
+	p.index = index
+}
+
+// SetDefaults sets unset protocol buffer fields to their default values.
+// It only modifies fields that are both unset and have defined defaults.
+// It recursively sets default values in any non-nil sub-messages.
+func SetDefaults(pb Message) {
+	setDefaults(reflect.ValueOf(pb), true, false)
+}
+
+// v is a pointer to a struct.
+func setDefaults(v reflect.Value, recur, zeros bool) {
+	v = v.Elem()
+
+	defaultMu.RLock()
+	dm, ok := defaults[v.Type()]
+	defaultMu.RUnlock()
+	if !ok {
+		dm = buildDefaultMessage(v.Type())
+		defaultMu.Lock()
+		defaults[v.Type()] = dm
+		defaultMu.Unlock()
+	}
+
+	for _, sf := range dm.scalars {
+		f := v.Field(sf.index)
+		if !f.IsNil() {
+			// field already set
+			continue
+		}
+		dv := sf.value
+		if dv == nil && !zeros {
+			// no explicit default, and don't want to set zeros
+			continue
+		}
+		fptr := f.Addr().Interface() // **T
+		// TODO: Consider batching the allocations we do here.
+		switch sf.kind {
+		case reflect.Bool:
+			b := new(bool)
+			if dv != nil {
+				*b = dv.(bool)
+			}
+			*(fptr.(**bool)) = b
+		case reflect.Float32:
+			f := new(float32)
+			if dv != nil {
+				*f = dv.(float32)
+			}
+			*(fptr.(**float32)) = f
+		case reflect.Float64:
+			f := new(float64)
+			if dv != nil {
+				*f = dv.(float64)
+			}
+			*(fptr.(**float64)) = f
+		case reflect.Int32:
+			// might be an enum
+			if ft := f.Type(); ft != int32PtrType {
+				// enum
+				f.Set(reflect.New(ft.Elem()))
+				if dv != nil {
+					f.Elem().SetInt(int64(dv.(int32)))
+				}
+			} else {
+				// int32 field
+				i := new(int32)
+				if dv != nil {
+					*i = dv.(int32)
+				}
+				*(fptr.(**int32)) = i
+			}
+		case reflect.Int64:
+			i := new(int64)
+			if dv != nil {
+				*i = dv.(int64)
+			}
+			*(fptr.(**int64)) = i
+		case reflect.String:
+			s := new(string)
+			if dv != nil {
+				*s = dv.(string)
+			}
+			*(fptr.(**string)) = s
+		case reflect.Uint8:
+			// exceptional case: []byte
+			var b []byte
+			if dv != nil {
+				db := dv.([]byte)
+				b = make([]byte, len(db))
+				copy(b, db)
+			} else {
+				b = []byte{}
+			}
+			*(fptr.(*[]byte)) = b
+		case reflect.Uint32:
+			u := new(uint32)
+			if dv != nil {
+				*u = dv.(uint32)
+			}
+			*(fptr.(**uint32)) = u
+		case reflect.Uint64:
+			u := new(uint64)
+			if dv != nil {
+				*u = dv.(uint64)
+			}
+			*(fptr.(**uint64)) = u
+		default:
+			log.Printf("proto: can't set default for field %v (sf.kind=%v)", f, sf.kind)
+		}
+	}
+
+	for _, ni := range dm.nested {
+		f := v.Field(ni)
+		// f is *T or []*T or map[T]*T
+		switch f.Kind() {
+		case reflect.Ptr:
+			if f.IsNil() {
+				continue
+			}
+			setDefaults(f, recur, zeros)
+
+		case reflect.Slice:
+			for i := 0; i < f.Len(); i++ {
+				e := f.Index(i)
+				if e.IsNil() {
+					continue
+				}
+				setDefaults(e, recur, zeros)
+			}
+
+		case reflect.Map:
+			for _, k := range f.MapKeys() {
+				e := f.MapIndex(k)
+				if e.IsNil() {
+					continue
+				}
+				setDefaults(e, recur, zeros)
+			}
+		}
+	}
+}
+
+var (
+	// defaults maps a protocol buffer struct type to a slice of the fields,
+	// with its scalar fields set to their proto-declared non-zero default values.
+	defaultMu sync.RWMutex
+	defaults  = make(map[reflect.Type]defaultMessage)
+
+	int32PtrType = reflect.TypeOf((*int32)(nil))
+)
+
+// defaultMessage represents information about the default values of a message.
+type defaultMessage struct {
+	scalars []scalarField
+	nested  []int // struct field index of nested messages
+}
+
+type scalarField struct {
+	index int          // struct field index
+	kind  reflect.Kind // element type (the T in *T or []T)
+	value interface{}  // the proto-declared default value, or nil
+}
+
+// t is a struct type.
+func buildDefaultMessage(t reflect.Type) (dm defaultMessage) {
+	sprop := GetProperties(t)
+	for _, prop := range sprop.Prop {
+		fi, ok := sprop.decoderTags.get(prop.Tag)
+		if !ok {
+			// XXX_unrecognized
+			continue
+		}
+		ft := t.Field(fi).Type
+
+		sf, nested, err := fieldDefault(ft, prop)
+		switch {
+		case err != nil:
+			log.Print(err)
+		case nested:
+			dm.nested = append(dm.nested, fi)
+		case sf != nil:
+			sf.index = fi
+			dm.scalars = append(dm.scalars, *sf)
+		}
+	}
+
+	return dm
+}
+
+// fieldDefault returns the scalarField for field type ft.
+// sf will be nil if the field can not have a default.
+// nestedMessage will be true if this is a nested message.
+// Note that sf.index is not set on return.
+func fieldDefault(ft reflect.Type, prop *Properties) (sf *scalarField, nestedMessage bool, err error) {
+	var canHaveDefault bool
+	switch ft.Kind() {
+	case reflect.Ptr:
+		if ft.Elem().Kind() == reflect.Struct {
+			nestedMessage = true
+		} else {
+			canHaveDefault = true // proto2 scalar field
+		}
+
+	case reflect.Slice:
+		switch ft.Elem().Kind() {
+		case reflect.Ptr:
+			nestedMessage = true // repeated message
+		case reflect.Uint8:
+			canHaveDefault = true // bytes field
+		}
+
+	case reflect.Map:
+		if ft.Elem().Kind() == reflect.Ptr {
+			nestedMessage = true // map with message values
+		}
+	}
+
+	if !canHaveDefault {
+		if nestedMessage {
+			return nil, true, nil
+		}
+		return nil, false, nil
+	}
+
+	// We now know that ft is a pointer or slice.
+	sf = &scalarField{kind: ft.Elem().Kind()}
+
+	// scalar fields without defaults
+	if !prop.HasDefault {
+		return sf, false, nil
+	}
+
+	// a scalar field: either *T or []byte
+	switch ft.Elem().Kind() {
+	case reflect.Bool:
+		x, err := strconv.ParseBool(prop.Default)
+		if err != nil {
+			return nil, false, fmt.Errorf("proto: bad default bool %q: %v", prop.Default, err)
+		}
+		sf.value = x
+	case reflect.Float32:
+		x, err := strconv.ParseFloat(prop.Default, 32)
+		if err != nil {
+			return nil, false, fmt.Errorf("proto: bad default float32 %q: %v", prop.Default, err)
+		}
+		sf.value = float32(x)
+	case reflect.Float64:
+		x, err := strconv.ParseFloat(prop.Default, 64)
+		if err != nil {
+			return nil, false, fmt.Errorf("proto: bad default float64 %q: %v", prop.Default, err)
+		}
+		sf.value = x
+	case reflect.Int32:
+		x, err := strconv.ParseInt(prop.Default, 10, 32)
+		if err != nil {
+			return nil, false, fmt.Errorf("proto: bad default int32 %q: %v", prop.Default, err)
+		}
+		sf.value = int32(x)
+	case reflect.Int64:
+		x, err := strconv.ParseInt(prop.Default, 10, 64)
+		if err != nil {
+			return nil, false, fmt.Errorf("proto: bad default int64 %q: %v", prop.Default, err)
+		}
+		sf.value = x
+	case reflect.String:
+		sf.value = prop.Default
+	case reflect.Uint8:
+		// []byte (not *uint8)
+		sf.value = []byte(prop.Default)
+	case reflect.Uint32:
+		x, err := strconv.ParseUint(prop.Default, 10, 32)
+		if err != nil {
+			return nil, false, fmt.Errorf("proto: bad default uint32 %q: %v", prop.Default, err)
+		}
+		sf.value = uint32(x)
+	case reflect.Uint64:
+		x, err := strconv.ParseUint(prop.Default, 10, 64)
+		if err != nil {
+			return nil, false, fmt.Errorf("proto: bad default uint64 %q: %v", prop.Default, err)
+		}
+		sf.value = x
+	default:
+		return nil, false, fmt.Errorf("proto: unhandled def kind %v", ft.Elem().Kind())
+	}
+
+	return sf, false, nil
+}
+
+// Map fields may have key types of non-float scalars, strings and enums.
+// The easiest way to sort them in some deterministic order is to use fmt.
+// If this turns out to be inefficient we can always consider other options,
+// such as doing a Schwartzian transform.
+
+func mapKeys(vs []reflect.Value) sort.Interface {
+	s := mapKeySorter{
+		vs: vs,
+		// default Less function: textual comparison
+		less: func(a, b reflect.Value) bool {
+			return fmt.Sprint(a.Interface()) < fmt.Sprint(b.Interface())
+		},
+	}
+
+	// Type specialization per https://developers.google.com/protocol-buffers/docs/proto#maps;
+	// numeric keys are sorted numerically.
+	if len(vs) == 0 {
+		return s
+	}
+	switch vs[0].Kind() {
+	case reflect.Int32, reflect.Int64:
+		s.less = func(a, b reflect.Value) bool { return a.Int() < b.Int() }
+	case reflect.Uint32, reflect.Uint64:
+		s.less = func(a, b reflect.Value) bool { return a.Uint() < b.Uint() }
+	}
+
+	return s
+}
+
+type mapKeySorter struct {
+	vs   []reflect.Value
+	less func(a, b reflect.Value) bool
+}
+
+func (s mapKeySorter) Len() int      { return len(s.vs) }
+func (s mapKeySorter) Swap(i, j int) { s.vs[i], s.vs[j] = s.vs[j], s.vs[i] }
+func (s mapKeySorter) Less(i, j int) bool {
+	return s.less(s.vs[i], s.vs[j])
+}
+
+// isProto3Zero reports whether v is a zero proto3 value.
+func isProto3Zero(v reflect.Value) bool {
+	switch v.Kind() {
+	case reflect.Bool:
+		return !v.Bool()
+	case reflect.Int32, reflect.Int64:
+		return v.Int() == 0
+	case reflect.Uint32, reflect.Uint64:
+		return v.Uint() == 0
+	case reflect.Float32, reflect.Float64:
+		return v.Float() == 0
+	case reflect.String:
+		return v.String() == ""
+	}
+	return false
+}
+
+// ProtoPackageIsVersion2 is referenced from generated protocol buffer files
+// to assert that that code is compatible with this version of the proto package.
+const ProtoPackageIsVersion2 = true
+
+// ProtoPackageIsVersion1 is referenced from generated protocol buffer files
+// to assert that that code is compatible with this version of the proto package.
+const ProtoPackageIsVersion1 = true

+ 311 - 0
vendor/github.com/golang/protobuf/proto/message_set.go

@@ -0,0 +1,311 @@
+// Go support for Protocol Buffers - Google's data interchange format
+//
+// Copyright 2010 The Go Authors.  All rights reserved.
+// https://github.com/golang/protobuf
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+//     * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+//     * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+//     * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+package proto
+
+/*
+ * Support for message sets.
+ */
+
+import (
+	"bytes"
+	"encoding/json"
+	"errors"
+	"fmt"
+	"reflect"
+	"sort"
+)
+
+// errNoMessageTypeID occurs when a protocol buffer does not have a message type ID.
+// A message type ID is required for storing a protocol buffer in a message set.
+var errNoMessageTypeID = errors.New("proto does not have a message type ID")
+
+// The first two types (_MessageSet_Item and messageSet)
+// model what the protocol compiler produces for the following protocol message:
+//   message MessageSet {
+//     repeated group Item = 1 {
+//       required int32 type_id = 2;
+//       required string message = 3;
+//     };
+//   }
+// That is the MessageSet wire format. We can't use a proto to generate these
+// because that would introduce a circular dependency between it and this package.
+
+type _MessageSet_Item struct {
+	TypeId  *int32 `protobuf:"varint,2,req,name=type_id"`
+	Message []byte `protobuf:"bytes,3,req,name=message"`
+}
+
+type messageSet struct {
+	Item             []*_MessageSet_Item `protobuf:"group,1,rep"`
+	XXX_unrecognized []byte
+	// TODO: caching?
+}
+
+// Make sure messageSet is a Message.
+var _ Message = (*messageSet)(nil)
+
+// messageTypeIder is an interface satisfied by a protocol buffer type
+// that may be stored in a MessageSet.
+type messageTypeIder interface {
+	MessageTypeId() int32
+}
+
+func (ms *messageSet) find(pb Message) *_MessageSet_Item {
+	mti, ok := pb.(messageTypeIder)
+	if !ok {
+		return nil
+	}
+	id := mti.MessageTypeId()
+	for _, item := range ms.Item {
+		if *item.TypeId == id {
+			return item
+		}
+	}
+	return nil
+}
+
+func (ms *messageSet) Has(pb Message) bool {
+	if ms.find(pb) != nil {
+		return true
+	}
+	return false
+}
+
+func (ms *messageSet) Unmarshal(pb Message) error {
+	if item := ms.find(pb); item != nil {
+		return Unmarshal(item.Message, pb)
+	}
+	if _, ok := pb.(messageTypeIder); !ok {
+		return errNoMessageTypeID
+	}
+	return nil // TODO: return error instead?
+}
+
+func (ms *messageSet) Marshal(pb Message) error {
+	msg, err := Marshal(pb)
+	if err != nil {
+		return err
+	}
+	if item := ms.find(pb); item != nil {
+		// reuse existing item
+		item.Message = msg
+		return nil
+	}
+
+	mti, ok := pb.(messageTypeIder)
+	if !ok {
+		return errNoMessageTypeID
+	}
+
+	mtid := mti.MessageTypeId()
+	ms.Item = append(ms.Item, &_MessageSet_Item{
+		TypeId:  &mtid,
+		Message: msg,
+	})
+	return nil
+}
+
+func (ms *messageSet) Reset()         { *ms = messageSet{} }
+func (ms *messageSet) String() string { return CompactTextString(ms) }
+func (*messageSet) ProtoMessage()     {}
+
+// Support for the message_set_wire_format message option.
+
+func skipVarint(buf []byte) []byte {
+	i := 0
+	for ; buf[i]&0x80 != 0; i++ {
+	}
+	return buf[i+1:]
+}
+
+// MarshalMessageSet encodes the extension map represented by m in the message set wire format.
+// It is called by generated Marshal methods on protocol buffer messages with the message_set_wire_format option.
+func MarshalMessageSet(exts interface{}) ([]byte, error) {
+	var m map[int32]Extension
+	switch exts := exts.(type) {
+	case *XXX_InternalExtensions:
+		if err := encodeExtensions(exts); err != nil {
+			return nil, err
+		}
+		m, _ = exts.extensionsRead()
+	case map[int32]Extension:
+		if err := encodeExtensionsMap(exts); err != nil {
+			return nil, err
+		}
+		m = exts
+	default:
+		return nil, errors.New("proto: not an extension map")
+	}
+
+	// Sort extension IDs to provide a deterministic encoding.
+	// See also enc_map in encode.go.
+	ids := make([]int, 0, len(m))
+	for id := range m {
+		ids = append(ids, int(id))
+	}
+	sort.Ints(ids)
+
+	ms := &messageSet{Item: make([]*_MessageSet_Item, 0, len(m))}
+	for _, id := range ids {
+		e := m[int32(id)]
+		// Remove the wire type and field number varint, as well as the length varint.
+		msg := skipVarint(skipVarint(e.enc))
+
+		ms.Item = append(ms.Item, &_MessageSet_Item{
+			TypeId:  Int32(int32(id)),
+			Message: msg,
+		})
+	}
+	return Marshal(ms)
+}
+
+// UnmarshalMessageSet decodes the extension map encoded in buf in the message set wire format.
+// It is called by generated Unmarshal methods on protocol buffer messages with the message_set_wire_format option.
+func UnmarshalMessageSet(buf []byte, exts interface{}) error {
+	var m map[int32]Extension
+	switch exts := exts.(type) {
+	case *XXX_InternalExtensions:
+		m = exts.extensionsWrite()
+	case map[int32]Extension:
+		m = exts
+	default:
+		return errors.New("proto: not an extension map")
+	}
+
+	ms := new(messageSet)
+	if err := Unmarshal(buf, ms); err != nil {
+		return err
+	}
+	for _, item := range ms.Item {
+		id := *item.TypeId
+		msg := item.Message
+
+		// Restore wire type and field number varint, plus length varint.
+		// Be careful to preserve duplicate items.
+		b := EncodeVarint(uint64(id)<<3 | WireBytes)
+		if ext, ok := m[id]; ok {
+			// Existing data; rip off the tag and length varint
+			// so we join the new data correctly.
+			// We can assume that ext.enc is set because we are unmarshaling.
+			o := ext.enc[len(b):]   // skip wire type and field number
+			_, n := DecodeVarint(o) // calculate length of length varint
+			o = o[n:]               // skip length varint
+			msg = append(o, msg...) // join old data and new data
+		}
+		b = append(b, EncodeVarint(uint64(len(msg)))...)
+		b = append(b, msg...)
+
+		m[id] = Extension{enc: b}
+	}
+	return nil
+}
+
+// MarshalMessageSetJSON encodes the extension map represented by m in JSON format.
+// It is called by generated MarshalJSON methods on protocol buffer messages with the message_set_wire_format option.
+func MarshalMessageSetJSON(exts interface{}) ([]byte, error) {
+	var m map[int32]Extension
+	switch exts := exts.(type) {
+	case *XXX_InternalExtensions:
+		m, _ = exts.extensionsRead()
+	case map[int32]Extension:
+		m = exts
+	default:
+		return nil, errors.New("proto: not an extension map")
+	}
+	var b bytes.Buffer
+	b.WriteByte('{')
+
+	// Process the map in key order for deterministic output.
+	ids := make([]int32, 0, len(m))
+	for id := range m {
+		ids = append(ids, id)
+	}
+	sort.Sort(int32Slice(ids)) // int32Slice defined in text.go
+
+	for i, id := range ids {
+		ext := m[id]
+		if i > 0 {
+			b.WriteByte(',')
+		}
+
+		msd, ok := messageSetMap[id]
+		if !ok {
+			// Unknown type; we can't render it, so skip it.
+			continue
+		}
+		fmt.Fprintf(&b, `"[%s]":`, msd.name)
+
+		x := ext.value
+		if x == nil {
+			x = reflect.New(msd.t.Elem()).Interface()
+			if err := Unmarshal(ext.enc, x.(Message)); err != nil {
+				return nil, err
+			}
+		}
+		d, err := json.Marshal(x)
+		if err != nil {
+			return nil, err
+		}
+		b.Write(d)
+	}
+	b.WriteByte('}')
+	return b.Bytes(), nil
+}
+
+// UnmarshalMessageSetJSON decodes the extension map encoded in buf in JSON format.
+// It is called by generated UnmarshalJSON methods on protocol buffer messages with the message_set_wire_format option.
+func UnmarshalMessageSetJSON(buf []byte, exts interface{}) error {
+	// Common-case fast path.
+	if len(buf) == 0 || bytes.Equal(buf, []byte("{}")) {
+		return nil
+	}
+
+	// This is fairly tricky, and it's not clear that it is needed.
+	return errors.New("TODO: UnmarshalMessageSetJSON not yet implemented")
+}
+
+// A global registry of types that can be used in a MessageSet.
+
+var messageSetMap = make(map[int32]messageSetDesc)
+
+type messageSetDesc struct {
+	t    reflect.Type // pointer to struct
+	name string
+}
+
+// RegisterMessageSetType is called from the generated code.
+func RegisterMessageSetType(m Message, fieldNum int32, name string) {
+	messageSetMap[fieldNum] = messageSetDesc{
+		t:    reflect.TypeOf(m),
+		name: name,
+	}
+}

+ 484 - 0
vendor/github.com/golang/protobuf/proto/pointer_reflect.go

@@ -0,0 +1,484 @@
+// Go support for Protocol Buffers - Google's data interchange format
+//
+// Copyright 2012 The Go Authors.  All rights reserved.
+// https://github.com/golang/protobuf
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+//     * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+//     * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+//     * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+// +build appengine js
+
+// This file contains an implementation of proto field accesses using package reflect.
+// It is slower than the code in pointer_unsafe.go but it avoids package unsafe and can
+// be used on App Engine.
+
+package proto
+
+import (
+	"math"
+	"reflect"
+)
+
+// A structPointer is a pointer to a struct.
+type structPointer struct {
+	v reflect.Value
+}
+
+// toStructPointer returns a structPointer equivalent to the given reflect value.
+// The reflect value must itself be a pointer to a struct.
+func toStructPointer(v reflect.Value) structPointer {
+	return structPointer{v}
+}
+
+// IsNil reports whether p is nil.
+func structPointer_IsNil(p structPointer) bool {
+	return p.v.IsNil()
+}
+
+// Interface returns the struct pointer as an interface value.
+func structPointer_Interface(p structPointer, _ reflect.Type) interface{} {
+	return p.v.Interface()
+}
+
+// A field identifies a field in a struct, accessible from a structPointer.
+// In this implementation, a field is identified by the sequence of field indices
+// passed to reflect's FieldByIndex.
+type field []int
+
+// toField returns a field equivalent to the given reflect field.
+func toField(f *reflect.StructField) field {
+	return f.Index
+}
+
+// invalidField is an invalid field identifier.
+var invalidField = field(nil)
+
+// IsValid reports whether the field identifier is valid.
+func (f field) IsValid() bool { return f != nil }
+
+// field returns the given field in the struct as a reflect value.
+func structPointer_field(p structPointer, f field) reflect.Value {
+	// Special case: an extension map entry with a value of type T
+	// passes a *T to the struct-handling code with a zero field,
+	// expecting that it will be treated as equivalent to *struct{ X T },
+	// which has the same memory layout. We have to handle that case
+	// specially, because reflect will panic if we call FieldByIndex on a
+	// non-struct.
+	if f == nil {
+		return p.v.Elem()
+	}
+
+	return p.v.Elem().FieldByIndex(f)
+}
+
+// ifield returns the given field in the struct as an interface value.
+func structPointer_ifield(p structPointer, f field) interface{} {
+	return structPointer_field(p, f).Addr().Interface()
+}
+
+// Bytes returns the address of a []byte field in the struct.
+func structPointer_Bytes(p structPointer, f field) *[]byte {
+	return structPointer_ifield(p, f).(*[]byte)
+}
+
+// BytesSlice returns the address of a [][]byte field in the struct.
+func structPointer_BytesSlice(p structPointer, f field) *[][]byte {
+	return structPointer_ifield(p, f).(*[][]byte)
+}
+
+// Bool returns the address of a *bool field in the struct.
+func structPointer_Bool(p structPointer, f field) **bool {
+	return structPointer_ifield(p, f).(**bool)
+}
+
+// BoolVal returns the address of a bool field in the struct.
+func structPointer_BoolVal(p structPointer, f field) *bool {
+	return structPointer_ifield(p, f).(*bool)
+}
+
+// BoolSlice returns the address of a []bool field in the struct.
+func structPointer_BoolSlice(p structPointer, f field) *[]bool {
+	return structPointer_ifield(p, f).(*[]bool)
+}
+
+// String returns the address of a *string field in the struct.
+func structPointer_String(p structPointer, f field) **string {
+	return structPointer_ifield(p, f).(**string)
+}
+
+// StringVal returns the address of a string field in the struct.
+func structPointer_StringVal(p structPointer, f field) *string {
+	return structPointer_ifield(p, f).(*string)
+}
+
+// StringSlice returns the address of a []string field in the struct.
+func structPointer_StringSlice(p structPointer, f field) *[]string {
+	return structPointer_ifield(p, f).(*[]string)
+}
+
+// Extensions returns the address of an extension map field in the struct.
+func structPointer_Extensions(p structPointer, f field) *XXX_InternalExtensions {
+	return structPointer_ifield(p, f).(*XXX_InternalExtensions)
+}
+
+// ExtMap returns the address of an extension map field in the struct.
+func structPointer_ExtMap(p structPointer, f field) *map[int32]Extension {
+	return structPointer_ifield(p, f).(*map[int32]Extension)
+}
+
+// NewAt returns the reflect.Value for a pointer to a field in the struct.
+func structPointer_NewAt(p structPointer, f field, typ reflect.Type) reflect.Value {
+	return structPointer_field(p, f).Addr()
+}
+
+// SetStructPointer writes a *struct field in the struct.
+func structPointer_SetStructPointer(p structPointer, f field, q structPointer) {
+	structPointer_field(p, f).Set(q.v)
+}
+
+// GetStructPointer reads a *struct field in the struct.
+func structPointer_GetStructPointer(p structPointer, f field) structPointer {
+	return structPointer{structPointer_field(p, f)}
+}
+
+// StructPointerSlice the address of a []*struct field in the struct.
+func structPointer_StructPointerSlice(p structPointer, f field) structPointerSlice {
+	return structPointerSlice{structPointer_field(p, f)}
+}
+
+// A structPointerSlice represents the address of a slice of pointers to structs
+// (themselves messages or groups). That is, v.Type() is *[]*struct{...}.
+type structPointerSlice struct {
+	v reflect.Value
+}
+
+func (p structPointerSlice) Len() int                  { return p.v.Len() }
+func (p structPointerSlice) Index(i int) structPointer { return structPointer{p.v.Index(i)} }
+func (p structPointerSlice) Append(q structPointer) {
+	p.v.Set(reflect.Append(p.v, q.v))
+}
+
+var (
+	int32Type   = reflect.TypeOf(int32(0))
+	uint32Type  = reflect.TypeOf(uint32(0))
+	float32Type = reflect.TypeOf(float32(0))
+	int64Type   = reflect.TypeOf(int64(0))
+	uint64Type  = reflect.TypeOf(uint64(0))
+	float64Type = reflect.TypeOf(float64(0))
+)
+
+// A word32 represents a field of type *int32, *uint32, *float32, or *enum.
+// That is, v.Type() is *int32, *uint32, *float32, or *enum and v is assignable.
+type word32 struct {
+	v reflect.Value
+}
+
+// IsNil reports whether p is nil.
+func word32_IsNil(p word32) bool {
+	return p.v.IsNil()
+}
+
+// Set sets p to point at a newly allocated word with bits set to x.
+func word32_Set(p word32, o *Buffer, x uint32) {
+	t := p.v.Type().Elem()
+	switch t {
+	case int32Type:
+		if len(o.int32s) == 0 {
+			o.int32s = make([]int32, uint32PoolSize)
+		}
+		o.int32s[0] = int32(x)
+		p.v.Set(reflect.ValueOf(&o.int32s[0]))
+		o.int32s = o.int32s[1:]
+		return
+	case uint32Type:
+		if len(o.uint32s) == 0 {
+			o.uint32s = make([]uint32, uint32PoolSize)
+		}
+		o.uint32s[0] = x
+		p.v.Set(reflect.ValueOf(&o.uint32s[0]))
+		o.uint32s = o.uint32s[1:]
+		return
+	case float32Type:
+		if len(o.float32s) == 0 {
+			o.float32s = make([]float32, uint32PoolSize)
+		}
+		o.float32s[0] = math.Float32frombits(x)
+		p.v.Set(reflect.ValueOf(&o.float32s[0]))
+		o.float32s = o.float32s[1:]
+		return
+	}
+
+	// must be enum
+	p.v.Set(reflect.New(t))
+	p.v.Elem().SetInt(int64(int32(x)))
+}
+
+// Get gets the bits pointed at by p, as a uint32.
+func word32_Get(p word32) uint32 {
+	elem := p.v.Elem()
+	switch elem.Kind() {
+	case reflect.Int32:
+		return uint32(elem.Int())
+	case reflect.Uint32:
+		return uint32(elem.Uint())
+	case reflect.Float32:
+		return math.Float32bits(float32(elem.Float()))
+	}
+	panic("unreachable")
+}
+
+// Word32 returns a reference to a *int32, *uint32, *float32, or *enum field in the struct.
+func structPointer_Word32(p structPointer, f field) word32 {
+	return word32{structPointer_field(p, f)}
+}
+
+// A word32Val represents a field of type int32, uint32, float32, or enum.
+// That is, v.Type() is int32, uint32, float32, or enum and v is assignable.
+type word32Val struct {
+	v reflect.Value
+}
+
+// Set sets *p to x.
+func word32Val_Set(p word32Val, x uint32) {
+	switch p.v.Type() {
+	case int32Type:
+		p.v.SetInt(int64(x))
+		return
+	case uint32Type:
+		p.v.SetUint(uint64(x))
+		return
+	case float32Type:
+		p.v.SetFloat(float64(math.Float32frombits(x)))
+		return
+	}
+
+	// must be enum
+	p.v.SetInt(int64(int32(x)))
+}
+
+// Get gets the bits pointed at by p, as a uint32.
+func word32Val_Get(p word32Val) uint32 {
+	elem := p.v
+	switch elem.Kind() {
+	case reflect.Int32:
+		return uint32(elem.Int())
+	case reflect.Uint32:
+		return uint32(elem.Uint())
+	case reflect.Float32:
+		return math.Float32bits(float32(elem.Float()))
+	}
+	panic("unreachable")
+}
+
+// Word32Val returns a reference to a int32, uint32, float32, or enum field in the struct.
+func structPointer_Word32Val(p structPointer, f field) word32Val {
+	return word32Val{structPointer_field(p, f)}
+}
+
+// A word32Slice is a slice of 32-bit values.
+// That is, v.Type() is []int32, []uint32, []float32, or []enum.
+type word32Slice struct {
+	v reflect.Value
+}
+
+func (p word32Slice) Append(x uint32) {
+	n, m := p.v.Len(), p.v.Cap()
+	if n < m {
+		p.v.SetLen(n + 1)
+	} else {
+		t := p.v.Type().Elem()
+		p.v.Set(reflect.Append(p.v, reflect.Zero(t)))
+	}
+	elem := p.v.Index(n)
+	switch elem.Kind() {
+	case reflect.Int32:
+		elem.SetInt(int64(int32(x)))
+	case reflect.Uint32:
+		elem.SetUint(uint64(x))
+	case reflect.Float32:
+		elem.SetFloat(float64(math.Float32frombits(x)))
+	}
+}
+
+func (p word32Slice) Len() int {
+	return p.v.Len()
+}
+
+func (p word32Slice) Index(i int) uint32 {
+	elem := p.v.Index(i)
+	switch elem.Kind() {
+	case reflect.Int32:
+		return uint32(elem.Int())
+	case reflect.Uint32:
+		return uint32(elem.Uint())
+	case reflect.Float32:
+		return math.Float32bits(float32(elem.Float()))
+	}
+	panic("unreachable")
+}
+
+// Word32Slice returns a reference to a []int32, []uint32, []float32, or []enum field in the struct.
+func structPointer_Word32Slice(p structPointer, f field) word32Slice {
+	return word32Slice{structPointer_field(p, f)}
+}
+
+// word64 is like word32 but for 64-bit values.
+type word64 struct {
+	v reflect.Value
+}
+
+func word64_Set(p word64, o *Buffer, x uint64) {
+	t := p.v.Type().Elem()
+	switch t {
+	case int64Type:
+		if len(o.int64s) == 0 {
+			o.int64s = make([]int64, uint64PoolSize)
+		}
+		o.int64s[0] = int64(x)
+		p.v.Set(reflect.ValueOf(&o.int64s[0]))
+		o.int64s = o.int64s[1:]
+		return
+	case uint64Type:
+		if len(o.uint64s) == 0 {
+			o.uint64s = make([]uint64, uint64PoolSize)
+		}
+		o.uint64s[0] = x
+		p.v.Set(reflect.ValueOf(&o.uint64s[0]))
+		o.uint64s = o.uint64s[1:]
+		return
+	case float64Type:
+		if len(o.float64s) == 0 {
+			o.float64s = make([]float64, uint64PoolSize)
+		}
+		o.float64s[0] = math.Float64frombits(x)
+		p.v.Set(reflect.ValueOf(&o.float64s[0]))
+		o.float64s = o.float64s[1:]
+		return
+	}
+	panic("unreachable")
+}
+
+func word64_IsNil(p word64) bool {
+	return p.v.IsNil()
+}
+
+func word64_Get(p word64) uint64 {
+	elem := p.v.Elem()
+	switch elem.Kind() {
+	case reflect.Int64:
+		return uint64(elem.Int())
+	case reflect.Uint64:
+		return elem.Uint()
+	case reflect.Float64:
+		return math.Float64bits(elem.Float())
+	}
+	panic("unreachable")
+}
+
+func structPointer_Word64(p structPointer, f field) word64 {
+	return word64{structPointer_field(p, f)}
+}
+
+// word64Val is like word32Val but for 64-bit values.
+type word64Val struct {
+	v reflect.Value
+}
+
+func word64Val_Set(p word64Val, o *Buffer, x uint64) {
+	switch p.v.Type() {
+	case int64Type:
+		p.v.SetInt(int64(x))
+		return
+	case uint64Type:
+		p.v.SetUint(x)
+		return
+	case float64Type:
+		p.v.SetFloat(math.Float64frombits(x))
+		return
+	}
+	panic("unreachable")
+}
+
+func word64Val_Get(p word64Val) uint64 {
+	elem := p.v
+	switch elem.Kind() {
+	case reflect.Int64:
+		return uint64(elem.Int())
+	case reflect.Uint64:
+		return elem.Uint()
+	case reflect.Float64:
+		return math.Float64bits(elem.Float())
+	}
+	panic("unreachable")
+}
+
+func structPointer_Word64Val(p structPointer, f field) word64Val {
+	return word64Val{structPointer_field(p, f)}
+}
+
+type word64Slice struct {
+	v reflect.Value
+}
+
+func (p word64Slice) Append(x uint64) {
+	n, m := p.v.Len(), p.v.Cap()
+	if n < m {
+		p.v.SetLen(n + 1)
+	} else {
+		t := p.v.Type().Elem()
+		p.v.Set(reflect.Append(p.v, reflect.Zero(t)))
+	}
+	elem := p.v.Index(n)
+	switch elem.Kind() {
+	case reflect.Int64:
+		elem.SetInt(int64(int64(x)))
+	case reflect.Uint64:
+		elem.SetUint(uint64(x))
+	case reflect.Float64:
+		elem.SetFloat(float64(math.Float64frombits(x)))
+	}
+}
+
+func (p word64Slice) Len() int {
+	return p.v.Len()
+}
+
+func (p word64Slice) Index(i int) uint64 {
+	elem := p.v.Index(i)
+	switch elem.Kind() {
+	case reflect.Int64:
+		return uint64(elem.Int())
+	case reflect.Uint64:
+		return uint64(elem.Uint())
+	case reflect.Float64:
+		return math.Float64bits(float64(elem.Float()))
+	}
+	panic("unreachable")
+}
+
+func structPointer_Word64Slice(p structPointer, f field) word64Slice {
+	return word64Slice{structPointer_field(p, f)}
+}

+ 270 - 0
vendor/github.com/golang/protobuf/proto/pointer_unsafe.go

@@ -0,0 +1,270 @@
+// Go support for Protocol Buffers - Google's data interchange format
+//
+// Copyright 2012 The Go Authors.  All rights reserved.
+// https://github.com/golang/protobuf
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+//     * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+//     * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+//     * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+// +build !appengine,!js
+
+// This file contains the implementation of the proto field accesses using package unsafe.
+
+package proto
+
+import (
+	"reflect"
+	"unsafe"
+)
+
+// NOTE: These type_Foo functions would more idiomatically be methods,
+// but Go does not allow methods on pointer types, and we must preserve
+// some pointer type for the garbage collector. We use these
+// funcs with clunky names as our poor approximation to methods.
+//
+// An alternative would be
+//	type structPointer struct { p unsafe.Pointer }
+// but that does not registerize as well.
+
+// A structPointer is a pointer to a struct.
+type structPointer unsafe.Pointer
+
+// toStructPointer returns a structPointer equivalent to the given reflect value.
+func toStructPointer(v reflect.Value) structPointer {
+	return structPointer(unsafe.Pointer(v.Pointer()))
+}
+
+// IsNil reports whether p is nil.
+func structPointer_IsNil(p structPointer) bool {
+	return p == nil
+}
+
+// Interface returns the struct pointer, assumed to have element type t,
+// as an interface value.
+func structPointer_Interface(p structPointer, t reflect.Type) interface{} {
+	return reflect.NewAt(t, unsafe.Pointer(p)).Interface()
+}
+
+// A field identifies a field in a struct, accessible from a structPointer.
+// In this implementation, a field is identified by its byte offset from the start of the struct.
+type field uintptr
+
+// toField returns a field equivalent to the given reflect field.
+func toField(f *reflect.StructField) field {
+	return field(f.Offset)
+}
+
+// invalidField is an invalid field identifier.
+const invalidField = ^field(0)
+
+// IsValid reports whether the field identifier is valid.
+func (f field) IsValid() bool {
+	return f != ^field(0)
+}
+
+// Bytes returns the address of a []byte field in the struct.
+func structPointer_Bytes(p structPointer, f field) *[]byte {
+	return (*[]byte)(unsafe.Pointer(uintptr(p) + uintptr(f)))
+}
+
+// BytesSlice returns the address of a [][]byte field in the struct.
+func structPointer_BytesSlice(p structPointer, f field) *[][]byte {
+	return (*[][]byte)(unsafe.Pointer(uintptr(p) + uintptr(f)))
+}
+
+// Bool returns the address of a *bool field in the struct.
+func structPointer_Bool(p structPointer, f field) **bool {
+	return (**bool)(unsafe.Pointer(uintptr(p) + uintptr(f)))
+}
+
+// BoolVal returns the address of a bool field in the struct.
+func structPointer_BoolVal(p structPointer, f field) *bool {
+	return (*bool)(unsafe.Pointer(uintptr(p) + uintptr(f)))
+}
+
+// BoolSlice returns the address of a []bool field in the struct.
+func structPointer_BoolSlice(p structPointer, f field) *[]bool {
+	return (*[]bool)(unsafe.Pointer(uintptr(p) + uintptr(f)))
+}
+
+// String returns the address of a *string field in the struct.
+func structPointer_String(p structPointer, f field) **string {
+	return (**string)(unsafe.Pointer(uintptr(p) + uintptr(f)))
+}
+
+// StringVal returns the address of a string field in the struct.
+func structPointer_StringVal(p structPointer, f field) *string {
+	return (*string)(unsafe.Pointer(uintptr(p) + uintptr(f)))
+}
+
+// StringSlice returns the address of a []string field in the struct.
+func structPointer_StringSlice(p structPointer, f field) *[]string {
+	return (*[]string)(unsafe.Pointer(uintptr(p) + uintptr(f)))
+}
+
+// ExtMap returns the address of an extension map field in the struct.
+func structPointer_Extensions(p structPointer, f field) *XXX_InternalExtensions {
+	return (*XXX_InternalExtensions)(unsafe.Pointer(uintptr(p) + uintptr(f)))
+}
+
+func structPointer_ExtMap(p structPointer, f field) *map[int32]Extension {
+	return (*map[int32]Extension)(unsafe.Pointer(uintptr(p) + uintptr(f)))
+}
+
+// NewAt returns the reflect.Value for a pointer to a field in the struct.
+func structPointer_NewAt(p structPointer, f field, typ reflect.Type) reflect.Value {
+	return reflect.NewAt(typ, unsafe.Pointer(uintptr(p)+uintptr(f)))
+}
+
+// SetStructPointer writes a *struct field in the struct.
+func structPointer_SetStructPointer(p structPointer, f field, q structPointer) {
+	*(*structPointer)(unsafe.Pointer(uintptr(p) + uintptr(f))) = q
+}
+
+// GetStructPointer reads a *struct field in the struct.
+func structPointer_GetStructPointer(p structPointer, f field) structPointer {
+	return *(*structPointer)(unsafe.Pointer(uintptr(p) + uintptr(f)))
+}
+
+// StructPointerSlice the address of a []*struct field in the struct.
+func structPointer_StructPointerSlice(p structPointer, f field) *structPointerSlice {
+	return (*structPointerSlice)(unsafe.Pointer(uintptr(p) + uintptr(f)))
+}
+
+// A structPointerSlice represents a slice of pointers to structs (themselves submessages or groups).
+type structPointerSlice []structPointer
+
+func (v *structPointerSlice) Len() int                  { return len(*v) }
+func (v *structPointerSlice) Index(i int) structPointer { return (*v)[i] }
+func (v *structPointerSlice) Append(p structPointer)    { *v = append(*v, p) }
+
+// A word32 is the address of a "pointer to 32-bit value" field.
+type word32 **uint32
+
+// IsNil reports whether *v is nil.
+func word32_IsNil(p word32) bool {
+	return *p == nil
+}
+
+// Set sets *v to point at a newly allocated word set to x.
+func word32_Set(p word32, o *Buffer, x uint32) {
+	if len(o.uint32s) == 0 {
+		o.uint32s = make([]uint32, uint32PoolSize)
+	}
+	o.uint32s[0] = x
+	*p = &o.uint32s[0]
+	o.uint32s = o.uint32s[1:]
+}
+
+// Get gets the value pointed at by *v.
+func word32_Get(p word32) uint32 {
+	return **p
+}
+
+// Word32 returns the address of a *int32, *uint32, *float32, or *enum field in the struct.
+func structPointer_Word32(p structPointer, f field) word32 {
+	return word32((**uint32)(unsafe.Pointer(uintptr(p) + uintptr(f))))
+}
+
+// A word32Val is the address of a 32-bit value field.
+type word32Val *uint32
+
+// Set sets *p to x.
+func word32Val_Set(p word32Val, x uint32) {
+	*p = x
+}
+
+// Get gets the value pointed at by p.
+func word32Val_Get(p word32Val) uint32 {
+	return *p
+}
+
+// Word32Val returns the address of a *int32, *uint32, *float32, or *enum field in the struct.
+func structPointer_Word32Val(p structPointer, f field) word32Val {
+	return word32Val((*uint32)(unsafe.Pointer(uintptr(p) + uintptr(f))))
+}
+
+// A word32Slice is a slice of 32-bit values.
+type word32Slice []uint32
+
+func (v *word32Slice) Append(x uint32)    { *v = append(*v, x) }
+func (v *word32Slice) Len() int           { return len(*v) }
+func (v *word32Slice) Index(i int) uint32 { return (*v)[i] }
+
+// Word32Slice returns the address of a []int32, []uint32, []float32, or []enum field in the struct.
+func structPointer_Word32Slice(p structPointer, f field) *word32Slice {
+	return (*word32Slice)(unsafe.Pointer(uintptr(p) + uintptr(f)))
+}
+
+// word64 is like word32 but for 64-bit values.
+type word64 **uint64
+
+func word64_Set(p word64, o *Buffer, x uint64) {
+	if len(o.uint64s) == 0 {
+		o.uint64s = make([]uint64, uint64PoolSize)
+	}
+	o.uint64s[0] = x
+	*p = &o.uint64s[0]
+	o.uint64s = o.uint64s[1:]
+}
+
+func word64_IsNil(p word64) bool {
+	return *p == nil
+}
+
+func word64_Get(p word64) uint64 {
+	return **p
+}
+
+func structPointer_Word64(p structPointer, f field) word64 {
+	return word64((**uint64)(unsafe.Pointer(uintptr(p) + uintptr(f))))
+}
+
+// word64Val is like word32Val but for 64-bit values.
+type word64Val *uint64
+
+func word64Val_Set(p word64Val, o *Buffer, x uint64) {
+	*p = x
+}
+
+func word64Val_Get(p word64Val) uint64 {
+	return *p
+}
+
+func structPointer_Word64Val(p structPointer, f field) word64Val {
+	return word64Val((*uint64)(unsafe.Pointer(uintptr(p) + uintptr(f))))
+}
+
+// word64Slice is like word32Slice but for 64-bit values.
+type word64Slice []uint64
+
+func (v *word64Slice) Append(x uint64)    { *v = append(*v, x) }
+func (v *word64Slice) Len() int           { return len(*v) }
+func (v *word64Slice) Index(i int) uint64 { return (*v)[i] }
+
+func structPointer_Word64Slice(p structPointer, f field) *word64Slice {
+	return (*word64Slice)(unsafe.Pointer(uintptr(p) + uintptr(f)))
+}

+ 872 - 0
vendor/github.com/golang/protobuf/proto/properties.go

@@ -0,0 +1,872 @@
+// Go support for Protocol Buffers - Google's data interchange format
+//
+// Copyright 2010 The Go Authors.  All rights reserved.
+// https://github.com/golang/protobuf
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+//     * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+//     * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+//     * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+package proto
+
+/*
+ * Routines for encoding data into the wire format for protocol buffers.
+ */
+
+import (
+	"fmt"
+	"log"
+	"os"
+	"reflect"
+	"sort"
+	"strconv"
+	"strings"
+	"sync"
+)
+
+const debug bool = false
+
+// Constants that identify the encoding of a value on the wire.
+const (
+	WireVarint     = 0
+	WireFixed64    = 1
+	WireBytes      = 2
+	WireStartGroup = 3
+	WireEndGroup   = 4
+	WireFixed32    = 5
+)
+
+const startSize = 10 // initial slice/string sizes
+
+// Encoders are defined in encode.go
+// An encoder outputs the full representation of a field, including its
+// tag and encoder type.
+type encoder func(p *Buffer, prop *Properties, base structPointer) error
+
+// A valueEncoder encodes a single integer in a particular encoding.
+type valueEncoder func(o *Buffer, x uint64) error
+
+// Sizers are defined in encode.go
+// A sizer returns the encoded size of a field, including its tag and encoder
+// type.
+type sizer func(prop *Properties, base structPointer) int
+
+// A valueSizer returns the encoded size of a single integer in a particular
+// encoding.
+type valueSizer func(x uint64) int
+
+// Decoders are defined in decode.go
+// A decoder creates a value from its wire representation.
+// Unrecognized subelements are saved in unrec.
+type decoder func(p *Buffer, prop *Properties, base structPointer) error
+
+// A valueDecoder decodes a single integer in a particular encoding.
+type valueDecoder func(o *Buffer) (x uint64, err error)
+
+// A oneofMarshaler does the marshaling for all oneof fields in a message.
+type oneofMarshaler func(Message, *Buffer) error
+
+// A oneofUnmarshaler does the unmarshaling for a oneof field in a message.
+type oneofUnmarshaler func(Message, int, int, *Buffer) (bool, error)
+
+// A oneofSizer does the sizing for all oneof fields in a message.
+type oneofSizer func(Message) int
+
+// tagMap is an optimization over map[int]int for typical protocol buffer
+// use-cases. Encoded protocol buffers are often in tag order with small tag
+// numbers.
+type tagMap struct {
+	fastTags []int
+	slowTags map[int]int
+}
+
+// tagMapFastLimit is the upper bound on the tag number that will be stored in
+// the tagMap slice rather than its map.
+const tagMapFastLimit = 1024
+
+func (p *tagMap) get(t int) (int, bool) {
+	if t > 0 && t < tagMapFastLimit {
+		if t >= len(p.fastTags) {
+			return 0, false
+		}
+		fi := p.fastTags[t]
+		return fi, fi >= 0
+	}
+	fi, ok := p.slowTags[t]
+	return fi, ok
+}
+
+func (p *tagMap) put(t int, fi int) {
+	if t > 0 && t < tagMapFastLimit {
+		for len(p.fastTags) < t+1 {
+			p.fastTags = append(p.fastTags, -1)
+		}
+		p.fastTags[t] = fi
+		return
+	}
+	if p.slowTags == nil {
+		p.slowTags = make(map[int]int)
+	}
+	p.slowTags[t] = fi
+}
+
+// StructProperties represents properties for all the fields of a struct.
+// decoderTags and decoderOrigNames should only be used by the decoder.
+type StructProperties struct {
+	Prop             []*Properties  // properties for each field
+	reqCount         int            // required count
+	decoderTags      tagMap         // map from proto tag to struct field number
+	decoderOrigNames map[string]int // map from original name to struct field number
+	order            []int          // list of struct field numbers in tag order
+	unrecField       field          // field id of the XXX_unrecognized []byte field
+	extendable       bool           // is this an extendable proto
+
+	oneofMarshaler   oneofMarshaler
+	oneofUnmarshaler oneofUnmarshaler
+	oneofSizer       oneofSizer
+	stype            reflect.Type
+
+	// OneofTypes contains information about the oneof fields in this message.
+	// It is keyed by the original name of a field.
+	OneofTypes map[string]*OneofProperties
+}
+
+// OneofProperties represents information about a specific field in a oneof.
+type OneofProperties struct {
+	Type  reflect.Type // pointer to generated struct type for this oneof field
+	Field int          // struct field number of the containing oneof in the message
+	Prop  *Properties
+}
+
+// Implement the sorting interface so we can sort the fields in tag order, as recommended by the spec.
+// See encode.go, (*Buffer).enc_struct.
+
+func (sp *StructProperties) Len() int { return len(sp.order) }
+func (sp *StructProperties) Less(i, j int) bool {
+	return sp.Prop[sp.order[i]].Tag < sp.Prop[sp.order[j]].Tag
+}
+func (sp *StructProperties) Swap(i, j int) { sp.order[i], sp.order[j] = sp.order[j], sp.order[i] }
+
+// Properties represents the protocol-specific behavior of a single struct field.
+type Properties struct {
+	Name     string // name of the field, for error messages
+	OrigName string // original name before protocol compiler (always set)
+	JSONName string // name to use for JSON; determined by protoc
+	Wire     string
+	WireType int
+	Tag      int
+	Required bool
+	Optional bool
+	Repeated bool
+	Packed   bool   // relevant for repeated primitives only
+	Enum     string // set for enum types only
+	proto3   bool   // whether this is known to be a proto3 field; set for []byte only
+	oneof    bool   // whether this is a oneof field
+
+	Default    string // default value
+	HasDefault bool   // whether an explicit default was provided
+	def_uint64 uint64
+
+	enc           encoder
+	valEnc        valueEncoder // set for bool and numeric types only
+	field         field
+	tagcode       []byte // encoding of EncodeVarint((Tag<<3)|WireType)
+	tagbuf        [8]byte
+	stype         reflect.Type      // set for struct types only
+	sprop         *StructProperties // set for struct types only
+	isMarshaler   bool
+	isUnmarshaler bool
+
+	mtype    reflect.Type // set for map types only
+	mkeyprop *Properties  // set for map types only
+	mvalprop *Properties  // set for map types only
+
+	size    sizer
+	valSize valueSizer // set for bool and numeric types only
+
+	dec    decoder
+	valDec valueDecoder // set for bool and numeric types only
+
+	// If this is a packable field, this will be the decoder for the packed version of the field.
+	packedDec decoder
+}
+
+// String formats the properties in the protobuf struct field tag style.
+func (p *Properties) String() string {
+	s := p.Wire
+	s = ","
+	s += strconv.Itoa(p.Tag)
+	if p.Required {
+		s += ",req"
+	}
+	if p.Optional {
+		s += ",opt"
+	}
+	if p.Repeated {
+		s += ",rep"
+	}
+	if p.Packed {
+		s += ",packed"
+	}
+	s += ",name=" + p.OrigName
+	if p.JSONName != p.OrigName {
+		s += ",json=" + p.JSONName
+	}
+	if p.proto3 {
+		s += ",proto3"
+	}
+	if p.oneof {
+		s += ",oneof"
+	}
+	if len(p.Enum) > 0 {
+		s += ",enum=" + p.Enum
+	}
+	if p.HasDefault {
+		s += ",def=" + p.Default
+	}
+	return s
+}
+
+// Parse populates p by parsing a string in the protobuf struct field tag style.
+func (p *Properties) Parse(s string) {
+	// "bytes,49,opt,name=foo,def=hello!"
+	fields := strings.Split(s, ",") // breaks def=, but handled below.
+	if len(fields) < 2 {
+		fmt.Fprintf(os.Stderr, "proto: tag has too few fields: %q\n", s)
+		return
+	}
+
+	p.Wire = fields[0]
+	switch p.Wire {
+	case "varint":
+		p.WireType = WireVarint
+		p.valEnc = (*Buffer).EncodeVarint
+		p.valDec = (*Buffer).DecodeVarint
+		p.valSize = sizeVarint
+	case "fixed32":
+		p.WireType = WireFixed32
+		p.valEnc = (*Buffer).EncodeFixed32
+		p.valDec = (*Buffer).DecodeFixed32
+		p.valSize = sizeFixed32
+	case "fixed64":
+		p.WireType = WireFixed64
+		p.valEnc = (*Buffer).EncodeFixed64
+		p.valDec = (*Buffer).DecodeFixed64
+		p.valSize = sizeFixed64
+	case "zigzag32":
+		p.WireType = WireVarint
+		p.valEnc = (*Buffer).EncodeZigzag32
+		p.valDec = (*Buffer).DecodeZigzag32
+		p.valSize = sizeZigzag32
+	case "zigzag64":
+		p.WireType = WireVarint
+		p.valEnc = (*Buffer).EncodeZigzag64
+		p.valDec = (*Buffer).DecodeZigzag64
+		p.valSize = sizeZigzag64
+	case "bytes", "group":
+		p.WireType = WireBytes
+		// no numeric converter for non-numeric types
+	default:
+		fmt.Fprintf(os.Stderr, "proto: tag has unknown wire type: %q\n", s)
+		return
+	}
+
+	var err error
+	p.Tag, err = strconv.Atoi(fields[1])
+	if err != nil {
+		return
+	}
+
+	for i := 2; i < len(fields); i++ {
+		f := fields[i]
+		switch {
+		case f == "req":
+			p.Required = true
+		case f == "opt":
+			p.Optional = true
+		case f == "rep":
+			p.Repeated = true
+		case f == "packed":
+			p.Packed = true
+		case strings.HasPrefix(f, "name="):
+			p.OrigName = f[5:]
+		case strings.HasPrefix(f, "json="):
+			p.JSONName = f[5:]
+		case strings.HasPrefix(f, "enum="):
+			p.Enum = f[5:]
+		case f == "proto3":
+			p.proto3 = true
+		case f == "oneof":
+			p.oneof = true
+		case strings.HasPrefix(f, "def="):
+			p.HasDefault = true
+			p.Default = f[4:] // rest of string
+			if i+1 < len(fields) {
+				// Commas aren't escaped, and def is always last.
+				p.Default += "," + strings.Join(fields[i+1:], ",")
+				break
+			}
+		}
+	}
+}
+
+func logNoSliceEnc(t1, t2 reflect.Type) {
+	fmt.Fprintf(os.Stderr, "proto: no slice oenc for %T = []%T\n", t1, t2)
+}
+
+var protoMessageType = reflect.TypeOf((*Message)(nil)).Elem()
+
+// Initialize the fields for encoding and decoding.
+func (p *Properties) setEncAndDec(typ reflect.Type, f *reflect.StructField, lockGetProp bool) {
+	p.enc = nil
+	p.dec = nil
+	p.size = nil
+
+	switch t1 := typ; t1.Kind() {
+	default:
+		fmt.Fprintf(os.Stderr, "proto: no coders for %v\n", t1)
+
+	// proto3 scalar types
+
+	case reflect.Bool:
+		p.enc = (*Buffer).enc_proto3_bool
+		p.dec = (*Buffer).dec_proto3_bool
+		p.size = size_proto3_bool
+	case reflect.Int32:
+		p.enc = (*Buffer).enc_proto3_int32
+		p.dec = (*Buffer).dec_proto3_int32
+		p.size = size_proto3_int32
+	case reflect.Uint32:
+		p.enc = (*Buffer).enc_proto3_uint32
+		p.dec = (*Buffer).dec_proto3_int32 // can reuse
+		p.size = size_proto3_uint32
+	case reflect.Int64, reflect.Uint64:
+		p.enc = (*Buffer).enc_proto3_int64
+		p.dec = (*Buffer).dec_proto3_int64
+		p.size = size_proto3_int64
+	case reflect.Float32:
+		p.enc = (*Buffer).enc_proto3_uint32 // can just treat them as bits
+		p.dec = (*Buffer).dec_proto3_int32
+		p.size = size_proto3_uint32
+	case reflect.Float64:
+		p.enc = (*Buffer).enc_proto3_int64 // can just treat them as bits
+		p.dec = (*Buffer).dec_proto3_int64
+		p.size = size_proto3_int64
+	case reflect.String:
+		p.enc = (*Buffer).enc_proto3_string
+		p.dec = (*Buffer).dec_proto3_string
+		p.size = size_proto3_string
+
+	case reflect.Ptr:
+		switch t2 := t1.Elem(); t2.Kind() {
+		default:
+			fmt.Fprintf(os.Stderr, "proto: no encoder function for %v -> %v\n", t1, t2)
+			break
+		case reflect.Bool:
+			p.enc = (*Buffer).enc_bool
+			p.dec = (*Buffer).dec_bool
+			p.size = size_bool
+		case reflect.Int32:
+			p.enc = (*Buffer).enc_int32
+			p.dec = (*Buffer).dec_int32
+			p.size = size_int32
+		case reflect.Uint32:
+			p.enc = (*Buffer).enc_uint32
+			p.dec = (*Buffer).dec_int32 // can reuse
+			p.size = size_uint32
+		case reflect.Int64, reflect.Uint64:
+			p.enc = (*Buffer).enc_int64
+			p.dec = (*Buffer).dec_int64
+			p.size = size_int64
+		case reflect.Float32:
+			p.enc = (*Buffer).enc_uint32 // can just treat them as bits
+			p.dec = (*Buffer).dec_int32
+			p.size = size_uint32
+		case reflect.Float64:
+			p.enc = (*Buffer).enc_int64 // can just treat them as bits
+			p.dec = (*Buffer).dec_int64
+			p.size = size_int64
+		case reflect.String:
+			p.enc = (*Buffer).enc_string
+			p.dec = (*Buffer).dec_string
+			p.size = size_string
+		case reflect.Struct:
+			p.stype = t1.Elem()
+			p.isMarshaler = isMarshaler(t1)
+			p.isUnmarshaler = isUnmarshaler(t1)
+			if p.Wire == "bytes" {
+				p.enc = (*Buffer).enc_struct_message
+				p.dec = (*Buffer).dec_struct_message
+				p.size = size_struct_message
+			} else {
+				p.enc = (*Buffer).enc_struct_group
+				p.dec = (*Buffer).dec_struct_group
+				p.size = size_struct_group
+			}
+		}
+
+	case reflect.Slice:
+		switch t2 := t1.Elem(); t2.Kind() {
+		default:
+			logNoSliceEnc(t1, t2)
+			break
+		case reflect.Bool:
+			if p.Packed {
+				p.enc = (*Buffer).enc_slice_packed_bool
+				p.size = size_slice_packed_bool
+			} else {
+				p.enc = (*Buffer).enc_slice_bool
+				p.size = size_slice_bool
+			}
+			p.dec = (*Buffer).dec_slice_bool
+			p.packedDec = (*Buffer).dec_slice_packed_bool
+		case reflect.Int32:
+			if p.Packed {
+				p.enc = (*Buffer).enc_slice_packed_int32
+				p.size = size_slice_packed_int32
+			} else {
+				p.enc = (*Buffer).enc_slice_int32
+				p.size = size_slice_int32
+			}
+			p.dec = (*Buffer).dec_slice_int32
+			p.packedDec = (*Buffer).dec_slice_packed_int32
+		case reflect.Uint32:
+			if p.Packed {
+				p.enc = (*Buffer).enc_slice_packed_uint32
+				p.size = size_slice_packed_uint32
+			} else {
+				p.enc = (*Buffer).enc_slice_uint32
+				p.size = size_slice_uint32
+			}
+			p.dec = (*Buffer).dec_slice_int32
+			p.packedDec = (*Buffer).dec_slice_packed_int32
+		case reflect.Int64, reflect.Uint64:
+			if p.Packed {
+				p.enc = (*Buffer).enc_slice_packed_int64
+				p.size = size_slice_packed_int64
+			} else {
+				p.enc = (*Buffer).enc_slice_int64
+				p.size = size_slice_int64
+			}
+			p.dec = (*Buffer).dec_slice_int64
+			p.packedDec = (*Buffer).dec_slice_packed_int64
+		case reflect.Uint8:
+			p.dec = (*Buffer).dec_slice_byte
+			if p.proto3 {
+				p.enc = (*Buffer).enc_proto3_slice_byte
+				p.size = size_proto3_slice_byte
+			} else {
+				p.enc = (*Buffer).enc_slice_byte
+				p.size = size_slice_byte
+			}
+		case reflect.Float32, reflect.Float64:
+			switch t2.Bits() {
+			case 32:
+				// can just treat them as bits
+				if p.Packed {
+					p.enc = (*Buffer).enc_slice_packed_uint32
+					p.size = size_slice_packed_uint32
+				} else {
+					p.enc = (*Buffer).enc_slice_uint32
+					p.size = size_slice_uint32
+				}
+				p.dec = (*Buffer).dec_slice_int32
+				p.packedDec = (*Buffer).dec_slice_packed_int32
+			case 64:
+				// can just treat them as bits
+				if p.Packed {
+					p.enc = (*Buffer).enc_slice_packed_int64
+					p.size = size_slice_packed_int64
+				} else {
+					p.enc = (*Buffer).enc_slice_int64
+					p.size = size_slice_int64
+				}
+				p.dec = (*Buffer).dec_slice_int64
+				p.packedDec = (*Buffer).dec_slice_packed_int64
+			default:
+				logNoSliceEnc(t1, t2)
+				break
+			}
+		case reflect.String:
+			p.enc = (*Buffer).enc_slice_string
+			p.dec = (*Buffer).dec_slice_string
+			p.size = size_slice_string
+		case reflect.Ptr:
+			switch t3 := t2.Elem(); t3.Kind() {
+			default:
+				fmt.Fprintf(os.Stderr, "proto: no ptr oenc for %T -> %T -> %T\n", t1, t2, t3)
+				break
+			case reflect.Struct:
+				p.stype = t2.Elem()
+				p.isMarshaler = isMarshaler(t2)
+				p.isUnmarshaler = isUnmarshaler(t2)
+				if p.Wire == "bytes" {
+					p.enc = (*Buffer).enc_slice_struct_message
+					p.dec = (*Buffer).dec_slice_struct_message
+					p.size = size_slice_struct_message
+				} else {
+					p.enc = (*Buffer).enc_slice_struct_group
+					p.dec = (*Buffer).dec_slice_struct_group
+					p.size = size_slice_struct_group
+				}
+			}
+		case reflect.Slice:
+			switch t2.Elem().Kind() {
+			default:
+				fmt.Fprintf(os.Stderr, "proto: no slice elem oenc for %T -> %T -> %T\n", t1, t2, t2.Elem())
+				break
+			case reflect.Uint8:
+				p.enc = (*Buffer).enc_slice_slice_byte
+				p.dec = (*Buffer).dec_slice_slice_byte
+				p.size = size_slice_slice_byte
+			}
+		}
+
+	case reflect.Map:
+		p.enc = (*Buffer).enc_new_map
+		p.dec = (*Buffer).dec_new_map
+		p.size = size_new_map
+
+		p.mtype = t1
+		p.mkeyprop = &Properties{}
+		p.mkeyprop.init(reflect.PtrTo(p.mtype.Key()), "Key", f.Tag.Get("protobuf_key"), nil, lockGetProp)
+		p.mvalprop = &Properties{}
+		vtype := p.mtype.Elem()
+		if vtype.Kind() != reflect.Ptr && vtype.Kind() != reflect.Slice {
+			// The value type is not a message (*T) or bytes ([]byte),
+			// so we need encoders for the pointer to this type.
+			vtype = reflect.PtrTo(vtype)
+		}
+		p.mvalprop.init(vtype, "Value", f.Tag.Get("protobuf_val"), nil, lockGetProp)
+	}
+
+	// precalculate tag code
+	wire := p.WireType
+	if p.Packed {
+		wire = WireBytes
+	}
+	x := uint32(p.Tag)<<3 | uint32(wire)
+	i := 0
+	for i = 0; x > 127; i++ {
+		p.tagbuf[i] = 0x80 | uint8(x&0x7F)
+		x >>= 7
+	}
+	p.tagbuf[i] = uint8(x)
+	p.tagcode = p.tagbuf[0 : i+1]
+
+	if p.stype != nil {
+		if lockGetProp {
+			p.sprop = GetProperties(p.stype)
+		} else {
+			p.sprop = getPropertiesLocked(p.stype)
+		}
+	}
+}
+
+var (
+	marshalerType   = reflect.TypeOf((*Marshaler)(nil)).Elem()
+	unmarshalerType = reflect.TypeOf((*Unmarshaler)(nil)).Elem()
+)
+
+// isMarshaler reports whether type t implements Marshaler.
+func isMarshaler(t reflect.Type) bool {
+	// We're checking for (likely) pointer-receiver methods
+	// so if t is not a pointer, something is very wrong.
+	// The calls above only invoke isMarshaler on pointer types.
+	if t.Kind() != reflect.Ptr {
+		panic("proto: misuse of isMarshaler")
+	}
+	return t.Implements(marshalerType)
+}
+
+// isUnmarshaler reports whether type t implements Unmarshaler.
+func isUnmarshaler(t reflect.Type) bool {
+	// We're checking for (likely) pointer-receiver methods
+	// so if t is not a pointer, something is very wrong.
+	// The calls above only invoke isUnmarshaler on pointer types.
+	if t.Kind() != reflect.Ptr {
+		panic("proto: misuse of isUnmarshaler")
+	}
+	return t.Implements(unmarshalerType)
+}
+
+// Init populates the properties from a protocol buffer struct tag.
+func (p *Properties) Init(typ reflect.Type, name, tag string, f *reflect.StructField) {
+	p.init(typ, name, tag, f, true)
+}
+
+func (p *Properties) init(typ reflect.Type, name, tag string, f *reflect.StructField, lockGetProp bool) {
+	// "bytes,49,opt,def=hello!"
+	p.Name = name
+	p.OrigName = name
+	if f != nil {
+		p.field = toField(f)
+	}
+	if tag == "" {
+		return
+	}
+	p.Parse(tag)
+	p.setEncAndDec(typ, f, lockGetProp)
+}
+
+var (
+	propertiesMu  sync.RWMutex
+	propertiesMap = make(map[reflect.Type]*StructProperties)
+)
+
+// GetProperties returns the list of properties for the type represented by t.
+// t must represent a generated struct type of a protocol message.
+func GetProperties(t reflect.Type) *StructProperties {
+	if t.Kind() != reflect.Struct {
+		panic("proto: type must have kind struct")
+	}
+
+	// Most calls to GetProperties in a long-running program will be
+	// retrieving details for types we have seen before.
+	propertiesMu.RLock()
+	sprop, ok := propertiesMap[t]
+	propertiesMu.RUnlock()
+	if ok {
+		if collectStats {
+			stats.Chit++
+		}
+		return sprop
+	}
+
+	propertiesMu.Lock()
+	sprop = getPropertiesLocked(t)
+	propertiesMu.Unlock()
+	return sprop
+}
+
+// getPropertiesLocked requires that propertiesMu is held.
+func getPropertiesLocked(t reflect.Type) *StructProperties {
+	if prop, ok := propertiesMap[t]; ok {
+		if collectStats {
+			stats.Chit++
+		}
+		return prop
+	}
+	if collectStats {
+		stats.Cmiss++
+	}
+
+	prop := new(StructProperties)
+	// in case of recursive protos, fill this in now.
+	propertiesMap[t] = prop
+
+	// build properties
+	prop.extendable = reflect.PtrTo(t).Implements(extendableProtoType) ||
+		reflect.PtrTo(t).Implements(extendableProtoV1Type)
+	prop.unrecField = invalidField
+	prop.Prop = make([]*Properties, t.NumField())
+	prop.order = make([]int, t.NumField())
+
+	for i := 0; i < t.NumField(); i++ {
+		f := t.Field(i)
+		p := new(Properties)
+		name := f.Name
+		p.init(f.Type, name, f.Tag.Get("protobuf"), &f, false)
+
+		if f.Name == "XXX_InternalExtensions" { // special case
+			p.enc = (*Buffer).enc_exts
+			p.dec = nil // not needed
+			p.size = size_exts
+		} else if f.Name == "XXX_extensions" { // special case
+			p.enc = (*Buffer).enc_map
+			p.dec = nil // not needed
+			p.size = size_map
+		} else if f.Name == "XXX_unrecognized" { // special case
+			prop.unrecField = toField(&f)
+		}
+		oneof := f.Tag.Get("protobuf_oneof") // special case
+		if oneof != "" {
+			// Oneof fields don't use the traditional protobuf tag.
+			p.OrigName = oneof
+		}
+		prop.Prop[i] = p
+		prop.order[i] = i
+		if debug {
+			print(i, " ", f.Name, " ", t.String(), " ")
+			if p.Tag > 0 {
+				print(p.String())
+			}
+			print("\n")
+		}
+		if p.enc == nil && !strings.HasPrefix(f.Name, "XXX_") && oneof == "" {
+			fmt.Fprintln(os.Stderr, "proto: no encoder for", f.Name, f.Type.String(), "[GetProperties]")
+		}
+	}
+
+	// Re-order prop.order.
+	sort.Sort(prop)
+
+	type oneofMessage interface {
+		XXX_OneofFuncs() (func(Message, *Buffer) error, func(Message, int, int, *Buffer) (bool, error), func(Message) int, []interface{})
+	}
+	if om, ok := reflect.Zero(reflect.PtrTo(t)).Interface().(oneofMessage); ok {
+		var oots []interface{}
+		prop.oneofMarshaler, prop.oneofUnmarshaler, prop.oneofSizer, oots = om.XXX_OneofFuncs()
+		prop.stype = t
+
+		// Interpret oneof metadata.
+		prop.OneofTypes = make(map[string]*OneofProperties)
+		for _, oot := range oots {
+			oop := &OneofProperties{
+				Type: reflect.ValueOf(oot).Type(), // *T
+				Prop: new(Properties),
+			}
+			sft := oop.Type.Elem().Field(0)
+			oop.Prop.Name = sft.Name
+			oop.Prop.Parse(sft.Tag.Get("protobuf"))
+			// There will be exactly one interface field that
+			// this new value is assignable to.
+			for i := 0; i < t.NumField(); i++ {
+				f := t.Field(i)
+				if f.Type.Kind() != reflect.Interface {
+					continue
+				}
+				if !oop.Type.AssignableTo(f.Type) {
+					continue
+				}
+				oop.Field = i
+				break
+			}
+			prop.OneofTypes[oop.Prop.OrigName] = oop
+		}
+	}
+
+	// build required counts
+	// build tags
+	reqCount := 0
+	prop.decoderOrigNames = make(map[string]int)
+	for i, p := range prop.Prop {
+		if strings.HasPrefix(p.Name, "XXX_") {
+			// Internal fields should not appear in tags/origNames maps.
+			// They are handled specially when encoding and decoding.
+			continue
+		}
+		if p.Required {
+			reqCount++
+		}
+		prop.decoderTags.put(p.Tag, i)
+		prop.decoderOrigNames[p.OrigName] = i
+	}
+	prop.reqCount = reqCount
+
+	return prop
+}
+
+// Return the Properties object for the x[0]'th field of the structure.
+func propByIndex(t reflect.Type, x []int) *Properties {
+	if len(x) != 1 {
+		fmt.Fprintf(os.Stderr, "proto: field index dimension %d (not 1) for type %s\n", len(x), t)
+		return nil
+	}
+	prop := GetProperties(t)
+	return prop.Prop[x[0]]
+}
+
+// Get the address and type of a pointer to a struct from an interface.
+func getbase(pb Message) (t reflect.Type, b structPointer, err error) {
+	if pb == nil {
+		err = ErrNil
+		return
+	}
+	// get the reflect type of the pointer to the struct.
+	t = reflect.TypeOf(pb)
+	// get the address of the struct.
+	value := reflect.ValueOf(pb)
+	b = toStructPointer(value)
+	return
+}
+
+// A global registry of enum types.
+// The generated code will register the generated maps by calling RegisterEnum.
+
+var enumValueMaps = make(map[string]map[string]int32)
+
+// RegisterEnum is called from the generated code to install the enum descriptor
+// maps into the global table to aid parsing text format protocol buffers.
+func RegisterEnum(typeName string, unusedNameMap map[int32]string, valueMap map[string]int32) {
+	if _, ok := enumValueMaps[typeName]; ok {
+		panic("proto: duplicate enum registered: " + typeName)
+	}
+	enumValueMaps[typeName] = valueMap
+}
+
+// EnumValueMap returns the mapping from names to integers of the
+// enum type enumType, or a nil if not found.
+func EnumValueMap(enumType string) map[string]int32 {
+	return enumValueMaps[enumType]
+}
+
+// A registry of all linked message types.
+// The string is a fully-qualified proto name ("pkg.Message").
+var (
+	protoTypes    = make(map[string]reflect.Type)
+	revProtoTypes = make(map[reflect.Type]string)
+)
+
+// RegisterType is called from generated code and maps from the fully qualified
+// proto name to the type (pointer to struct) of the protocol buffer.
+func RegisterType(x Message, name string) {
+	if _, ok := protoTypes[name]; ok {
+		// TODO: Some day, make this a panic.
+		log.Printf("proto: duplicate proto type registered: %s", name)
+		return
+	}
+	t := reflect.TypeOf(x)
+	protoTypes[name] = t
+	revProtoTypes[t] = name
+}
+
+// MessageName returns the fully-qualified proto name for the given message type.
+func MessageName(x Message) string {
+	type xname interface {
+		XXX_MessageName() string
+	}
+	if m, ok := x.(xname); ok {
+		return m.XXX_MessageName()
+	}
+	return revProtoTypes[reflect.TypeOf(x)]
+}
+
+// MessageType returns the message type (pointer to struct) for a named message.
+func MessageType(name string) reflect.Type { return protoTypes[name] }
+
+// A registry of all linked proto files.
+var (
+	protoFiles = make(map[string][]byte) // file name => fileDescriptor
+)
+
+// RegisterFile is called from generated code and maps from the
+// full file name of a .proto file to its compressed FileDescriptorProto.
+func RegisterFile(filename string, fileDescriptor []byte) {
+	protoFiles[filename] = fileDescriptor
+}
+
+// FileDescriptor returns the compressed FileDescriptorProto for a .proto file.
+func FileDescriptor(filename string) []byte { return protoFiles[filename] }

+ 854 - 0
vendor/github.com/golang/protobuf/proto/text.go

@@ -0,0 +1,854 @@
+// Go support for Protocol Buffers - Google's data interchange format
+//
+// Copyright 2010 The Go Authors.  All rights reserved.
+// https://github.com/golang/protobuf
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+//     * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+//     * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+//     * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+package proto
+
+// Functions for writing the text protocol buffer format.
+
+import (
+	"bufio"
+	"bytes"
+	"encoding"
+	"errors"
+	"fmt"
+	"io"
+	"log"
+	"math"
+	"reflect"
+	"sort"
+	"strings"
+)
+
+var (
+	newline         = []byte("\n")
+	spaces          = []byte("                                        ")
+	gtNewline       = []byte(">\n")
+	endBraceNewline = []byte("}\n")
+	backslashN      = []byte{'\\', 'n'}
+	backslashR      = []byte{'\\', 'r'}
+	backslashT      = []byte{'\\', 't'}
+	backslashDQ     = []byte{'\\', '"'}
+	backslashBS     = []byte{'\\', '\\'}
+	posInf          = []byte("inf")
+	negInf          = []byte("-inf")
+	nan             = []byte("nan")
+)
+
+type writer interface {
+	io.Writer
+	WriteByte(byte) error
+}
+
+// textWriter is an io.Writer that tracks its indentation level.
+type textWriter struct {
+	ind      int
+	complete bool // if the current position is a complete line
+	compact  bool // whether to write out as a one-liner
+	w        writer
+}
+
+func (w *textWriter) WriteString(s string) (n int, err error) {
+	if !strings.Contains(s, "\n") {
+		if !w.compact && w.complete {
+			w.writeIndent()
+		}
+		w.complete = false
+		return io.WriteString(w.w, s)
+	}
+	// WriteString is typically called without newlines, so this
+	// codepath and its copy are rare.  We copy to avoid
+	// duplicating all of Write's logic here.
+	return w.Write([]byte(s))
+}
+
+func (w *textWriter) Write(p []byte) (n int, err error) {
+	newlines := bytes.Count(p, newline)
+	if newlines == 0 {
+		if !w.compact && w.complete {
+			w.writeIndent()
+		}
+		n, err = w.w.Write(p)
+		w.complete = false
+		return n, err
+	}
+
+	frags := bytes.SplitN(p, newline, newlines+1)
+	if w.compact {
+		for i, frag := range frags {
+			if i > 0 {
+				if err := w.w.WriteByte(' '); err != nil {
+					return n, err
+				}
+				n++
+			}
+			nn, err := w.w.Write(frag)
+			n += nn
+			if err != nil {
+				return n, err
+			}
+		}
+		return n, nil
+	}
+
+	for i, frag := range frags {
+		if w.complete {
+			w.writeIndent()
+		}
+		nn, err := w.w.Write(frag)
+		n += nn
+		if err != nil {
+			return n, err
+		}
+		if i+1 < len(frags) {
+			if err := w.w.WriteByte('\n'); err != nil {
+				return n, err
+			}
+			n++
+		}
+	}
+	w.complete = len(frags[len(frags)-1]) == 0
+	return n, nil
+}
+
+func (w *textWriter) WriteByte(c byte) error {
+	if w.compact && c == '\n' {
+		c = ' '
+	}
+	if !w.compact && w.complete {
+		w.writeIndent()
+	}
+	err := w.w.WriteByte(c)
+	w.complete = c == '\n'
+	return err
+}
+
+func (w *textWriter) indent() { w.ind++ }
+
+func (w *textWriter) unindent() {
+	if w.ind == 0 {
+		log.Print("proto: textWriter unindented too far")
+		return
+	}
+	w.ind--
+}
+
+func writeName(w *textWriter, props *Properties) error {
+	if _, err := w.WriteString(props.OrigName); err != nil {
+		return err
+	}
+	if props.Wire != "group" {
+		return w.WriteByte(':')
+	}
+	return nil
+}
+
+// raw is the interface satisfied by RawMessage.
+type raw interface {
+	Bytes() []byte
+}
+
+func requiresQuotes(u string) bool {
+	// When type URL contains any characters except [0-9A-Za-z./\-]*, it must be quoted.
+	for _, ch := range u {
+		switch {
+		case ch == '.' || ch == '/' || ch == '_':
+			continue
+		case '0' <= ch && ch <= '9':
+			continue
+		case 'A' <= ch && ch <= 'Z':
+			continue
+		case 'a' <= ch && ch <= 'z':
+			continue
+		default:
+			return true
+		}
+	}
+	return false
+}
+
+// isAny reports whether sv is a google.protobuf.Any message
+func isAny(sv reflect.Value) bool {
+	type wkt interface {
+		XXX_WellKnownType() string
+	}
+	t, ok := sv.Addr().Interface().(wkt)
+	return ok && t.XXX_WellKnownType() == "Any"
+}
+
+// writeProto3Any writes an expanded google.protobuf.Any message.
+//
+// It returns (false, nil) if sv value can't be unmarshaled (e.g. because
+// required messages are not linked in).
+//
+// It returns (true, error) when sv was written in expanded format or an error
+// was encountered.
+func (tm *TextMarshaler) writeProto3Any(w *textWriter, sv reflect.Value) (bool, error) {
+	turl := sv.FieldByName("TypeUrl")
+	val := sv.FieldByName("Value")
+	if !turl.IsValid() || !val.IsValid() {
+		return true, errors.New("proto: invalid google.protobuf.Any message")
+	}
+
+	b, ok := val.Interface().([]byte)
+	if !ok {
+		return true, errors.New("proto: invalid google.protobuf.Any message")
+	}
+
+	parts := strings.Split(turl.String(), "/")
+	mt := MessageType(parts[len(parts)-1])
+	if mt == nil {
+		return false, nil
+	}
+	m := reflect.New(mt.Elem())
+	if err := Unmarshal(b, m.Interface().(Message)); err != nil {
+		return false, nil
+	}
+	w.Write([]byte("["))
+	u := turl.String()
+	if requiresQuotes(u) {
+		writeString(w, u)
+	} else {
+		w.Write([]byte(u))
+	}
+	if w.compact {
+		w.Write([]byte("]:<"))
+	} else {
+		w.Write([]byte("]: <\n"))
+		w.ind++
+	}
+	if err := tm.writeStruct(w, m.Elem()); err != nil {
+		return true, err
+	}
+	if w.compact {
+		w.Write([]byte("> "))
+	} else {
+		w.ind--
+		w.Write([]byte(">\n"))
+	}
+	return true, nil
+}
+
+func (tm *TextMarshaler) writeStruct(w *textWriter, sv reflect.Value) error {
+	if tm.ExpandAny && isAny(sv) {
+		if canExpand, err := tm.writeProto3Any(w, sv); canExpand {
+			return err
+		}
+	}
+	st := sv.Type()
+	sprops := GetProperties(st)
+	for i := 0; i < sv.NumField(); i++ {
+		fv := sv.Field(i)
+		props := sprops.Prop[i]
+		name := st.Field(i).Name
+
+		if strings.HasPrefix(name, "XXX_") {
+			// There are two XXX_ fields:
+			//   XXX_unrecognized []byte
+			//   XXX_extensions   map[int32]proto.Extension
+			// The first is handled here;
+			// the second is handled at the bottom of this function.
+			if name == "XXX_unrecognized" && !fv.IsNil() {
+				if err := writeUnknownStruct(w, fv.Interface().([]byte)); err != nil {
+					return err
+				}
+			}
+			continue
+		}
+		if fv.Kind() == reflect.Ptr && fv.IsNil() {
+			// Field not filled in. This could be an optional field or
+			// a required field that wasn't filled in. Either way, there
+			// isn't anything we can show for it.
+			continue
+		}
+		if fv.Kind() == reflect.Slice && fv.IsNil() {
+			// Repeated field that is empty, or a bytes field that is unused.
+			continue
+		}
+
+		if props.Repeated && fv.Kind() == reflect.Slice {
+			// Repeated field.
+			for j := 0; j < fv.Len(); j++ {
+				if err := writeName(w, props); err != nil {
+					return err
+				}
+				if !w.compact {
+					if err := w.WriteByte(' '); err != nil {
+						return err
+					}
+				}
+				v := fv.Index(j)
+				if v.Kind() == reflect.Ptr && v.IsNil() {
+					// A nil message in a repeated field is not valid,
+					// but we can handle that more gracefully than panicking.
+					if _, err := w.Write([]byte("<nil>\n")); err != nil {
+						return err
+					}
+					continue
+				}
+				if err := tm.writeAny(w, v, props); err != nil {
+					return err
+				}
+				if err := w.WriteByte('\n'); err != nil {
+					return err
+				}
+			}
+			continue
+		}
+		if fv.Kind() == reflect.Map {
+			// Map fields are rendered as a repeated struct with key/value fields.
+			keys := fv.MapKeys()
+			sort.Sort(mapKeys(keys))
+			for _, key := range keys {
+				val := fv.MapIndex(key)
+				if err := writeName(w, props); err != nil {
+					return err
+				}
+				if !w.compact {
+					if err := w.WriteByte(' '); err != nil {
+						return err
+					}
+				}
+				// open struct
+				if err := w.WriteByte('<'); err != nil {
+					return err
+				}
+				if !w.compact {
+					if err := w.WriteByte('\n'); err != nil {
+						return err
+					}
+				}
+				w.indent()
+				// key
+				if _, err := w.WriteString("key:"); err != nil {
+					return err
+				}
+				if !w.compact {
+					if err := w.WriteByte(' '); err != nil {
+						return err
+					}
+				}
+				if err := tm.writeAny(w, key, props.mkeyprop); err != nil {
+					return err
+				}
+				if err := w.WriteByte('\n'); err != nil {
+					return err
+				}
+				// nil values aren't legal, but we can avoid panicking because of them.
+				if val.Kind() != reflect.Ptr || !val.IsNil() {
+					// value
+					if _, err := w.WriteString("value:"); err != nil {
+						return err
+					}
+					if !w.compact {
+						if err := w.WriteByte(' '); err != nil {
+							return err
+						}
+					}
+					if err := tm.writeAny(w, val, props.mvalprop); err != nil {
+						return err
+					}
+					if err := w.WriteByte('\n'); err != nil {
+						return err
+					}
+				}
+				// close struct
+				w.unindent()
+				if err := w.WriteByte('>'); err != nil {
+					return err
+				}
+				if err := w.WriteByte('\n'); err != nil {
+					return err
+				}
+			}
+			continue
+		}
+		if props.proto3 && fv.Kind() == reflect.Slice && fv.Len() == 0 {
+			// empty bytes field
+			continue
+		}
+		if fv.Kind() != reflect.Ptr && fv.Kind() != reflect.Slice {
+			// proto3 non-repeated scalar field; skip if zero value
+			if isProto3Zero(fv) {
+				continue
+			}
+		}
+
+		if fv.Kind() == reflect.Interface {
+			// Check if it is a oneof.
+			if st.Field(i).Tag.Get("protobuf_oneof") != "" {
+				// fv is nil, or holds a pointer to generated struct.
+				// That generated struct has exactly one field,
+				// which has a protobuf struct tag.
+				if fv.IsNil() {
+					continue
+				}
+				inner := fv.Elem().Elem() // interface -> *T -> T
+				tag := inner.Type().Field(0).Tag.Get("protobuf")
+				props = new(Properties) // Overwrite the outer props var, but not its pointee.
+				props.Parse(tag)
+				// Write the value in the oneof, not the oneof itself.
+				fv = inner.Field(0)
+
+				// Special case to cope with malformed messages gracefully:
+				// If the value in the oneof is a nil pointer, don't panic
+				// in writeAny.
+				if fv.Kind() == reflect.Ptr && fv.IsNil() {
+					// Use errors.New so writeAny won't render quotes.
+					msg := errors.New("/* nil */")
+					fv = reflect.ValueOf(&msg).Elem()
+				}
+			}
+		}
+
+		if err := writeName(w, props); err != nil {
+			return err
+		}
+		if !w.compact {
+			if err := w.WriteByte(' '); err != nil {
+				return err
+			}
+		}
+		if b, ok := fv.Interface().(raw); ok {
+			if err := writeRaw(w, b.Bytes()); err != nil {
+				return err
+			}
+			continue
+		}
+
+		// Enums have a String method, so writeAny will work fine.
+		if err := tm.writeAny(w, fv, props); err != nil {
+			return err
+		}
+
+		if err := w.WriteByte('\n'); err != nil {
+			return err
+		}
+	}
+
+	// Extensions (the XXX_extensions field).
+	pv := sv.Addr()
+	if _, ok := extendable(pv.Interface()); ok {
+		if err := tm.writeExtensions(w, pv); err != nil {
+			return err
+		}
+	}
+
+	return nil
+}
+
+// writeRaw writes an uninterpreted raw message.
+func writeRaw(w *textWriter, b []byte) error {
+	if err := w.WriteByte('<'); err != nil {
+		return err
+	}
+	if !w.compact {
+		if err := w.WriteByte('\n'); err != nil {
+			return err
+		}
+	}
+	w.indent()
+	if err := writeUnknownStruct(w, b); err != nil {
+		return err
+	}
+	w.unindent()
+	if err := w.WriteByte('>'); err != nil {
+		return err
+	}
+	return nil
+}
+
+// writeAny writes an arbitrary field.
+func (tm *TextMarshaler) writeAny(w *textWriter, v reflect.Value, props *Properties) error {
+	v = reflect.Indirect(v)
+
+	// Floats have special cases.
+	if v.Kind() == reflect.Float32 || v.Kind() == reflect.Float64 {
+		x := v.Float()
+		var b []byte
+		switch {
+		case math.IsInf(x, 1):
+			b = posInf
+		case math.IsInf(x, -1):
+			b = negInf
+		case math.IsNaN(x):
+			b = nan
+		}
+		if b != nil {
+			_, err := w.Write(b)
+			return err
+		}
+		// Other values are handled below.
+	}
+
+	// We don't attempt to serialise every possible value type; only those
+	// that can occur in protocol buffers.
+	switch v.Kind() {
+	case reflect.Slice:
+		// Should only be a []byte; repeated fields are handled in writeStruct.
+		if err := writeString(w, string(v.Bytes())); err != nil {
+			return err
+		}
+	case reflect.String:
+		if err := writeString(w, v.String()); err != nil {
+			return err
+		}
+	case reflect.Struct:
+		// Required/optional group/message.
+		var bra, ket byte = '<', '>'
+		if props != nil && props.Wire == "group" {
+			bra, ket = '{', '}'
+		}
+		if err := w.WriteByte(bra); err != nil {
+			return err
+		}
+		if !w.compact {
+			if err := w.WriteByte('\n'); err != nil {
+				return err
+			}
+		}
+		w.indent()
+		if etm, ok := v.Interface().(encoding.TextMarshaler); ok {
+			text, err := etm.MarshalText()
+			if err != nil {
+				return err
+			}
+			if _, err = w.Write(text); err != nil {
+				return err
+			}
+		} else if err := tm.writeStruct(w, v); err != nil {
+			return err
+		}
+		w.unindent()
+		if err := w.WriteByte(ket); err != nil {
+			return err
+		}
+	default:
+		_, err := fmt.Fprint(w, v.Interface())
+		return err
+	}
+	return nil
+}
+
+// equivalent to C's isprint.
+func isprint(c byte) bool {
+	return c >= 0x20 && c < 0x7f
+}
+
+// writeString writes a string in the protocol buffer text format.
+// It is similar to strconv.Quote except we don't use Go escape sequences,
+// we treat the string as a byte sequence, and we use octal escapes.
+// These differences are to maintain interoperability with the other
+// languages' implementations of the text format.
+func writeString(w *textWriter, s string) error {
+	// use WriteByte here to get any needed indent
+	if err := w.WriteByte('"'); err != nil {
+		return err
+	}
+	// Loop over the bytes, not the runes.
+	for i := 0; i < len(s); i++ {
+		var err error
+		// Divergence from C++: we don't escape apostrophes.
+		// There's no need to escape them, and the C++ parser
+		// copes with a naked apostrophe.
+		switch c := s[i]; c {
+		case '\n':
+			_, err = w.w.Write(backslashN)
+		case '\r':
+			_, err = w.w.Write(backslashR)
+		case '\t':
+			_, err = w.w.Write(backslashT)
+		case '"':
+			_, err = w.w.Write(backslashDQ)
+		case '\\':
+			_, err = w.w.Write(backslashBS)
+		default:
+			if isprint(c) {
+				err = w.w.WriteByte(c)
+			} else {
+				_, err = fmt.Fprintf(w.w, "\\%03o", c)
+			}
+		}
+		if err != nil {
+			return err
+		}
+	}
+	return w.WriteByte('"')
+}
+
+func writeUnknownStruct(w *textWriter, data []byte) (err error) {
+	if !w.compact {
+		if _, err := fmt.Fprintf(w, "/* %d unknown bytes */\n", len(data)); err != nil {
+			return err
+		}
+	}
+	b := NewBuffer(data)
+	for b.index < len(b.buf) {
+		x, err := b.DecodeVarint()
+		if err != nil {
+			_, err := fmt.Fprintf(w, "/* %v */\n", err)
+			return err
+		}
+		wire, tag := x&7, x>>3
+		if wire == WireEndGroup {
+			w.unindent()
+			if _, err := w.Write(endBraceNewline); err != nil {
+				return err
+			}
+			continue
+		}
+		if _, err := fmt.Fprint(w, tag); err != nil {
+			return err
+		}
+		if wire != WireStartGroup {
+			if err := w.WriteByte(':'); err != nil {
+				return err
+			}
+		}
+		if !w.compact || wire == WireStartGroup {
+			if err := w.WriteByte(' '); err != nil {
+				return err
+			}
+		}
+		switch wire {
+		case WireBytes:
+			buf, e := b.DecodeRawBytes(false)
+			if e == nil {
+				_, err = fmt.Fprintf(w, "%q", buf)
+			} else {
+				_, err = fmt.Fprintf(w, "/* %v */", e)
+			}
+		case WireFixed32:
+			x, err = b.DecodeFixed32()
+			err = writeUnknownInt(w, x, err)
+		case WireFixed64:
+			x, err = b.DecodeFixed64()
+			err = writeUnknownInt(w, x, err)
+		case WireStartGroup:
+			err = w.WriteByte('{')
+			w.indent()
+		case WireVarint:
+			x, err = b.DecodeVarint()
+			err = writeUnknownInt(w, x, err)
+		default:
+			_, err = fmt.Fprintf(w, "/* unknown wire type %d */", wire)
+		}
+		if err != nil {
+			return err
+		}
+		if err = w.WriteByte('\n'); err != nil {
+			return err
+		}
+	}
+	return nil
+}
+
+func writeUnknownInt(w *textWriter, x uint64, err error) error {
+	if err == nil {
+		_, err = fmt.Fprint(w, x)
+	} else {
+		_, err = fmt.Fprintf(w, "/* %v */", err)
+	}
+	return err
+}
+
+type int32Slice []int32
+
+func (s int32Slice) Len() int           { return len(s) }
+func (s int32Slice) Less(i, j int) bool { return s[i] < s[j] }
+func (s int32Slice) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }
+
+// writeExtensions writes all the extensions in pv.
+// pv is assumed to be a pointer to a protocol message struct that is extendable.
+func (tm *TextMarshaler) writeExtensions(w *textWriter, pv reflect.Value) error {
+	emap := extensionMaps[pv.Type().Elem()]
+	ep, _ := extendable(pv.Interface())
+
+	// Order the extensions by ID.
+	// This isn't strictly necessary, but it will give us
+	// canonical output, which will also make testing easier.
+	m, mu := ep.extensionsRead()
+	if m == nil {
+		return nil
+	}
+	mu.Lock()
+	ids := make([]int32, 0, len(m))
+	for id := range m {
+		ids = append(ids, id)
+	}
+	sort.Sort(int32Slice(ids))
+	mu.Unlock()
+
+	for _, extNum := range ids {
+		ext := m[extNum]
+		var desc *ExtensionDesc
+		if emap != nil {
+			desc = emap[extNum]
+		}
+		if desc == nil {
+			// Unknown extension.
+			if err := writeUnknownStruct(w, ext.enc); err != nil {
+				return err
+			}
+			continue
+		}
+
+		pb, err := GetExtension(ep, desc)
+		if err != nil {
+			return fmt.Errorf("failed getting extension: %v", err)
+		}
+
+		// Repeated extensions will appear as a slice.
+		if !desc.repeated() {
+			if err := tm.writeExtension(w, desc.Name, pb); err != nil {
+				return err
+			}
+		} else {
+			v := reflect.ValueOf(pb)
+			for i := 0; i < v.Len(); i++ {
+				if err := tm.writeExtension(w, desc.Name, v.Index(i).Interface()); err != nil {
+					return err
+				}
+			}
+		}
+	}
+	return nil
+}
+
+func (tm *TextMarshaler) writeExtension(w *textWriter, name string, pb interface{}) error {
+	if _, err := fmt.Fprintf(w, "[%s]:", name); err != nil {
+		return err
+	}
+	if !w.compact {
+		if err := w.WriteByte(' '); err != nil {
+			return err
+		}
+	}
+	if err := tm.writeAny(w, reflect.ValueOf(pb), nil); err != nil {
+		return err
+	}
+	if err := w.WriteByte('\n'); err != nil {
+		return err
+	}
+	return nil
+}
+
+func (w *textWriter) writeIndent() {
+	if !w.complete {
+		return
+	}
+	remain := w.ind * 2
+	for remain > 0 {
+		n := remain
+		if n > len(spaces) {
+			n = len(spaces)
+		}
+		w.w.Write(spaces[:n])
+		remain -= n
+	}
+	w.complete = false
+}
+
+// TextMarshaler is a configurable text format marshaler.
+type TextMarshaler struct {
+	Compact   bool // use compact text format (one line).
+	ExpandAny bool // expand google.protobuf.Any messages of known types
+}
+
+// Marshal writes a given protocol buffer in text format.
+// The only errors returned are from w.
+func (tm *TextMarshaler) Marshal(w io.Writer, pb Message) error {
+	val := reflect.ValueOf(pb)
+	if pb == nil || val.IsNil() {
+		w.Write([]byte("<nil>"))
+		return nil
+	}
+	var bw *bufio.Writer
+	ww, ok := w.(writer)
+	if !ok {
+		bw = bufio.NewWriter(w)
+		ww = bw
+	}
+	aw := &textWriter{
+		w:        ww,
+		complete: true,
+		compact:  tm.Compact,
+	}
+
+	if etm, ok := pb.(encoding.TextMarshaler); ok {
+		text, err := etm.MarshalText()
+		if err != nil {
+			return err
+		}
+		if _, err = aw.Write(text); err != nil {
+			return err
+		}
+		if bw != nil {
+			return bw.Flush()
+		}
+		return nil
+	}
+	// Dereference the received pointer so we don't have outer < and >.
+	v := reflect.Indirect(val)
+	if err := tm.writeStruct(aw, v); err != nil {
+		return err
+	}
+	if bw != nil {
+		return bw.Flush()
+	}
+	return nil
+}
+
+// Text is the same as Marshal, but returns the string directly.
+func (tm *TextMarshaler) Text(pb Message) string {
+	var buf bytes.Buffer
+	tm.Marshal(&buf, pb)
+	return buf.String()
+}
+
+var (
+	defaultTextMarshaler = TextMarshaler{}
+	compactTextMarshaler = TextMarshaler{Compact: true}
+)
+
+// TODO: consider removing some of the Marshal functions below.
+
+// MarshalText writes a given protocol buffer in text format.
+// The only errors returned are from w.
+func MarshalText(w io.Writer, pb Message) error { return defaultTextMarshaler.Marshal(w, pb) }
+
+// MarshalTextString is the same as MarshalText, but returns the string directly.
+func MarshalTextString(pb Message) string { return defaultTextMarshaler.Text(pb) }
+
+// CompactText writes a given protocol buffer in compact text format (one line).
+func CompactText(w io.Writer, pb Message) error { return compactTextMarshaler.Marshal(w, pb) }
+
+// CompactTextString is the same as CompactText, but returns the string directly.
+func CompactTextString(pb Message) string { return compactTextMarshaler.Text(pb) }

+ 895 - 0
vendor/github.com/golang/protobuf/proto/text_parser.go

@@ -0,0 +1,895 @@
+// Go support for Protocol Buffers - Google's data interchange format
+//
+// Copyright 2010 The Go Authors.  All rights reserved.
+// https://github.com/golang/protobuf
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are
+// met:
+//
+//     * Redistributions of source code must retain the above copyright
+// notice, this list of conditions and the following disclaimer.
+//     * Redistributions in binary form must reproduce the above
+// copyright notice, this list of conditions and the following disclaimer
+// in the documentation and/or other materials provided with the
+// distribution.
+//     * Neither the name of Google Inc. nor the names of its
+// contributors may be used to endorse or promote products derived from
+// this software without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+package proto
+
+// Functions for parsing the Text protocol buffer format.
+// TODO: message sets.
+
+import (
+	"encoding"
+	"errors"
+	"fmt"
+	"reflect"
+	"strconv"
+	"strings"
+	"unicode/utf8"
+)
+
+// Error string emitted when deserializing Any and fields are already set
+const anyRepeatedlyUnpacked = "Any message unpacked multiple times, or %q already set"
+
+type ParseError struct {
+	Message string
+	Line    int // 1-based line number
+	Offset  int // 0-based byte offset from start of input
+}
+
+func (p *ParseError) Error() string {
+	if p.Line == 1 {
+		// show offset only for first line
+		return fmt.Sprintf("line 1.%d: %v", p.Offset, p.Message)
+	}
+	return fmt.Sprintf("line %d: %v", p.Line, p.Message)
+}
+
+type token struct {
+	value    string
+	err      *ParseError
+	line     int    // line number
+	offset   int    // byte number from start of input, not start of line
+	unquoted string // the unquoted version of value, if it was a quoted string
+}
+
+func (t *token) String() string {
+	if t.err == nil {
+		return fmt.Sprintf("%q (line=%d, offset=%d)", t.value, t.line, t.offset)
+	}
+	return fmt.Sprintf("parse error: %v", t.err)
+}
+
+type textParser struct {
+	s            string // remaining input
+	done         bool   // whether the parsing is finished (success or error)
+	backed       bool   // whether back() was called
+	offset, line int
+	cur          token
+}
+
+func newTextParser(s string) *textParser {
+	p := new(textParser)
+	p.s = s
+	p.line = 1
+	p.cur.line = 1
+	return p
+}
+
+func (p *textParser) errorf(format string, a ...interface{}) *ParseError {
+	pe := &ParseError{fmt.Sprintf(format, a...), p.cur.line, p.cur.offset}
+	p.cur.err = pe
+	p.done = true
+	return pe
+}
+
+// Numbers and identifiers are matched by [-+._A-Za-z0-9]
+func isIdentOrNumberChar(c byte) bool {
+	switch {
+	case 'A' <= c && c <= 'Z', 'a' <= c && c <= 'z':
+		return true
+	case '0' <= c && c <= '9':
+		return true
+	}
+	switch c {
+	case '-', '+', '.', '_':
+		return true
+	}
+	return false
+}
+
+func isWhitespace(c byte) bool {
+	switch c {
+	case ' ', '\t', '\n', '\r':
+		return true
+	}
+	return false
+}
+
+func isQuote(c byte) bool {
+	switch c {
+	case '"', '\'':
+		return true
+	}
+	return false
+}
+
+func (p *textParser) skipWhitespace() {
+	i := 0
+	for i < len(p.s) && (isWhitespace(p.s[i]) || p.s[i] == '#') {
+		if p.s[i] == '#' {
+			// comment; skip to end of line or input
+			for i < len(p.s) && p.s[i] != '\n' {
+				i++
+			}
+			if i == len(p.s) {
+				break
+			}
+		}
+		if p.s[i] == '\n' {
+			p.line++
+		}
+		i++
+	}
+	p.offset += i
+	p.s = p.s[i:len(p.s)]
+	if len(p.s) == 0 {
+		p.done = true
+	}
+}
+
+func (p *textParser) advance() {
+	// Skip whitespace
+	p.skipWhitespace()
+	if p.done {
+		return
+	}
+
+	// Start of non-whitespace
+	p.cur.err = nil
+	p.cur.offset, p.cur.line = p.offset, p.line
+	p.cur.unquoted = ""
+	switch p.s[0] {
+	case '<', '>', '{', '}', ':', '[', ']', ';', ',', '/':
+		// Single symbol
+		p.cur.value, p.s = p.s[0:1], p.s[1:len(p.s)]
+	case '"', '\'':
+		// Quoted string
+		i := 1
+		for i < len(p.s) && p.s[i] != p.s[0] && p.s[i] != '\n' {
+			if p.s[i] == '\\' && i+1 < len(p.s) {
+				// skip escaped char
+				i++
+			}
+			i++
+		}
+		if i >= len(p.s) || p.s[i] != p.s[0] {
+			p.errorf("unmatched quote")
+			return
+		}
+		unq, err := unquoteC(p.s[1:i], rune(p.s[0]))
+		if err != nil {
+			p.errorf("invalid quoted string %s: %v", p.s[0:i+1], err)
+			return
+		}
+		p.cur.value, p.s = p.s[0:i+1], p.s[i+1:len(p.s)]
+		p.cur.unquoted = unq
+	default:
+		i := 0
+		for i < len(p.s) && isIdentOrNumberChar(p.s[i]) {
+			i++
+		}
+		if i == 0 {
+			p.errorf("unexpected byte %#x", p.s[0])
+			return
+		}
+		p.cur.value, p.s = p.s[0:i], p.s[i:len(p.s)]
+	}
+	p.offset += len(p.cur.value)
+}
+
+var (
+	errBadUTF8 = errors.New("proto: bad UTF-8")
+	errBadHex  = errors.New("proto: bad hexadecimal")
+)
+
+func unquoteC(s string, quote rune) (string, error) {
+	// This is based on C++'s tokenizer.cc.
+	// Despite its name, this is *not* parsing C syntax.
+	// For instance, "\0" is an invalid quoted string.
+
+	// Avoid allocation in trivial cases.
+	simple := true
+	for _, r := range s {
+		if r == '\\' || r == quote {
+			simple = false
+			break
+		}
+	}
+	if simple {
+		return s, nil
+	}
+
+	buf := make([]byte, 0, 3*len(s)/2)
+	for len(s) > 0 {
+		r, n := utf8.DecodeRuneInString(s)
+		if r == utf8.RuneError && n == 1 {
+			return "", errBadUTF8
+		}
+		s = s[n:]
+		if r != '\\' {
+			if r < utf8.RuneSelf {
+				buf = append(buf, byte(r))
+			} else {
+				buf = append(buf, string(r)...)
+			}
+			continue
+		}
+
+		ch, tail, err := unescape(s)
+		if err != nil {
+			return "", err
+		}
+		buf = append(buf, ch...)
+		s = tail
+	}
+	return string(buf), nil
+}
+
+func unescape(s string) (ch string, tail string, err error) {
+	r, n := utf8.DecodeRuneInString(s)
+	if r == utf8.RuneError && n == 1 {
+		return "", "", errBadUTF8
+	}
+	s = s[n:]
+	switch r {
+	case 'a':
+		return "\a", s, nil
+	case 'b':
+		return "\b", s, nil
+	case 'f':
+		return "\f", s, nil
+	case 'n':
+		return "\n", s, nil
+	case 'r':
+		return "\r", s, nil
+	case 't':
+		return "\t", s, nil
+	case 'v':
+		return "\v", s, nil
+	case '?':
+		return "?", s, nil // trigraph workaround
+	case '\'', '"', '\\':
+		return string(r), s, nil
+	case '0', '1', '2', '3', '4', '5', '6', '7', 'x', 'X':
+		if len(s) < 2 {
+			return "", "", fmt.Errorf(`\%c requires 2 following digits`, r)
+		}
+		base := 8
+		ss := s[:2]
+		s = s[2:]
+		if r == 'x' || r == 'X' {
+			base = 16
+		} else {
+			ss = string(r) + ss
+		}
+		i, err := strconv.ParseUint(ss, base, 8)
+		if err != nil {
+			return "", "", err
+		}
+		return string([]byte{byte(i)}), s, nil
+	case 'u', 'U':
+		n := 4
+		if r == 'U' {
+			n = 8
+		}
+		if len(s) < n {
+			return "", "", fmt.Errorf(`\%c requires %d digits`, r, n)
+		}
+
+		bs := make([]byte, n/2)
+		for i := 0; i < n; i += 2 {
+			a, ok1 := unhex(s[i])
+			b, ok2 := unhex(s[i+1])
+			if !ok1 || !ok2 {
+				return "", "", errBadHex
+			}
+			bs[i/2] = a<<4 | b
+		}
+		s = s[n:]
+		return string(bs), s, nil
+	}
+	return "", "", fmt.Errorf(`unknown escape \%c`, r)
+}
+
+// Adapted from src/pkg/strconv/quote.go.
+func unhex(b byte) (v byte, ok bool) {
+	switch {
+	case '0' <= b && b <= '9':
+		return b - '0', true
+	case 'a' <= b && b <= 'f':
+		return b - 'a' + 10, true
+	case 'A' <= b && b <= 'F':
+		return b - 'A' + 10, true
+	}
+	return 0, false
+}
+
+// Back off the parser by one token. Can only be done between calls to next().
+// It makes the next advance() a no-op.
+func (p *textParser) back() { p.backed = true }
+
+// Advances the parser and returns the new current token.
+func (p *textParser) next() *token {
+	if p.backed || p.done {
+		p.backed = false
+		return &p.cur
+	}
+	p.advance()
+	if p.done {
+		p.cur.value = ""
+	} else if len(p.cur.value) > 0 && isQuote(p.cur.value[0]) {
+		// Look for multiple quoted strings separated by whitespace,
+		// and concatenate them.
+		cat := p.cur
+		for {
+			p.skipWhitespace()
+			if p.done || !isQuote(p.s[0]) {
+				break
+			}
+			p.advance()
+			if p.cur.err != nil {
+				return &p.cur
+			}
+			cat.value += " " + p.cur.value
+			cat.unquoted += p.cur.unquoted
+		}
+		p.done = false // parser may have seen EOF, but we want to return cat
+		p.cur = cat
+	}
+	return &p.cur
+}
+
+func (p *textParser) consumeToken(s string) error {
+	tok := p.next()
+	if tok.err != nil {
+		return tok.err
+	}
+	if tok.value != s {
+		p.back()
+		return p.errorf("expected %q, found %q", s, tok.value)
+	}
+	return nil
+}
+
+// Return a RequiredNotSetError indicating which required field was not set.
+func (p *textParser) missingRequiredFieldError(sv reflect.Value) *RequiredNotSetError {
+	st := sv.Type()
+	sprops := GetProperties(st)
+	for i := 0; i < st.NumField(); i++ {
+		if !isNil(sv.Field(i)) {
+			continue
+		}
+
+		props := sprops.Prop[i]
+		if props.Required {
+			return &RequiredNotSetError{fmt.Sprintf("%v.%v", st, props.OrigName)}
+		}
+	}
+	return &RequiredNotSetError{fmt.Sprintf("%v.<unknown field name>", st)} // should not happen
+}
+
+// Returns the index in the struct for the named field, as well as the parsed tag properties.
+func structFieldByName(sprops *StructProperties, name string) (int, *Properties, bool) {
+	i, ok := sprops.decoderOrigNames[name]
+	if ok {
+		return i, sprops.Prop[i], true
+	}
+	return -1, nil, false
+}
+
+// Consume a ':' from the input stream (if the next token is a colon),
+// returning an error if a colon is needed but not present.
+func (p *textParser) checkForColon(props *Properties, typ reflect.Type) *ParseError {
+	tok := p.next()
+	if tok.err != nil {
+		return tok.err
+	}
+	if tok.value != ":" {
+		// Colon is optional when the field is a group or message.
+		needColon := true
+		switch props.Wire {
+		case "group":
+			needColon = false
+		case "bytes":
+			// A "bytes" field is either a message, a string, or a repeated field;
+			// those three become *T, *string and []T respectively, so we can check for
+			// this field being a pointer to a non-string.
+			if typ.Kind() == reflect.Ptr {
+				// *T or *string
+				if typ.Elem().Kind() == reflect.String {
+					break
+				}
+			} else if typ.Kind() == reflect.Slice {
+				// []T or []*T
+				if typ.Elem().Kind() != reflect.Ptr {
+					break
+				}
+			} else if typ.Kind() == reflect.String {
+				// The proto3 exception is for a string field,
+				// which requires a colon.
+				break
+			}
+			needColon = false
+		}
+		if needColon {
+			return p.errorf("expected ':', found %q", tok.value)
+		}
+		p.back()
+	}
+	return nil
+}
+
+func (p *textParser) readStruct(sv reflect.Value, terminator string) error {
+	st := sv.Type()
+	sprops := GetProperties(st)
+	reqCount := sprops.reqCount
+	var reqFieldErr error
+	fieldSet := make(map[string]bool)
+	// A struct is a sequence of "name: value", terminated by one of
+	// '>' or '}', or the end of the input.  A name may also be
+	// "[extension]" or "[type/url]".
+	//
+	// The whole struct can also be an expanded Any message, like:
+	// [type/url] < ... struct contents ... >
+	for {
+		tok := p.next()
+		if tok.err != nil {
+			return tok.err
+		}
+		if tok.value == terminator {
+			break
+		}
+		if tok.value == "[" {
+			// Looks like an extension or an Any.
+			//
+			// TODO: Check whether we need to handle
+			// namespace rooted names (e.g. ".something.Foo").
+			extName, err := p.consumeExtName()
+			if err != nil {
+				return err
+			}
+
+			if s := strings.LastIndex(extName, "/"); s >= 0 {
+				// If it contains a slash, it's an Any type URL.
+				messageName := extName[s+1:]
+				mt := MessageType(messageName)
+				if mt == nil {
+					return p.errorf("unrecognized message %q in google.protobuf.Any", messageName)
+				}
+				tok = p.next()
+				if tok.err != nil {
+					return tok.err
+				}
+				// consume an optional colon
+				if tok.value == ":" {
+					tok = p.next()
+					if tok.err != nil {
+						return tok.err
+					}
+				}
+				var terminator string
+				switch tok.value {
+				case "<":
+					terminator = ">"
+				case "{":
+					terminator = "}"
+				default:
+					return p.errorf("expected '{' or '<', found %q", tok.value)
+				}
+				v := reflect.New(mt.Elem())
+				if pe := p.readStruct(v.Elem(), terminator); pe != nil {
+					return pe
+				}
+				b, err := Marshal(v.Interface().(Message))
+				if err != nil {
+					return p.errorf("failed to marshal message of type %q: %v", messageName, err)
+				}
+				if fieldSet["type_url"] {
+					return p.errorf(anyRepeatedlyUnpacked, "type_url")
+				}
+				if fieldSet["value"] {
+					return p.errorf(anyRepeatedlyUnpacked, "value")
+				}
+				sv.FieldByName("TypeUrl").SetString(extName)
+				sv.FieldByName("Value").SetBytes(b)
+				fieldSet["type_url"] = true
+				fieldSet["value"] = true
+				continue
+			}
+
+			var desc *ExtensionDesc
+			// This could be faster, but it's functional.
+			// TODO: Do something smarter than a linear scan.
+			for _, d := range RegisteredExtensions(reflect.New(st).Interface().(Message)) {
+				if d.Name == extName {
+					desc = d
+					break
+				}
+			}
+			if desc == nil {
+				return p.errorf("unrecognized extension %q", extName)
+			}
+
+			props := &Properties{}
+			props.Parse(desc.Tag)
+
+			typ := reflect.TypeOf(desc.ExtensionType)
+			if err := p.checkForColon(props, typ); err != nil {
+				return err
+			}
+
+			rep := desc.repeated()
+
+			// Read the extension structure, and set it in
+			// the value we're constructing.
+			var ext reflect.Value
+			if !rep {
+				ext = reflect.New(typ).Elem()
+			} else {
+				ext = reflect.New(typ.Elem()).Elem()
+			}
+			if err := p.readAny(ext, props); err != nil {
+				if _, ok := err.(*RequiredNotSetError); !ok {
+					return err
+				}
+				reqFieldErr = err
+			}
+			ep := sv.Addr().Interface().(Message)
+			if !rep {
+				SetExtension(ep, desc, ext.Interface())
+			} else {
+				old, err := GetExtension(ep, desc)
+				var sl reflect.Value
+				if err == nil {
+					sl = reflect.ValueOf(old) // existing slice
+				} else {
+					sl = reflect.MakeSlice(typ, 0, 1)
+				}
+				sl = reflect.Append(sl, ext)
+				SetExtension(ep, desc, sl.Interface())
+			}
+			if err := p.consumeOptionalSeparator(); err != nil {
+				return err
+			}
+			continue
+		}
+
+		// This is a normal, non-extension field.
+		name := tok.value
+		var dst reflect.Value
+		fi, props, ok := structFieldByName(sprops, name)
+		if ok {
+			dst = sv.Field(fi)
+		} else if oop, ok := sprops.OneofTypes[name]; ok {
+			// It is a oneof.
+			props = oop.Prop
+			nv := reflect.New(oop.Type.Elem())
+			dst = nv.Elem().Field(0)
+			field := sv.Field(oop.Field)
+			if !field.IsNil() {
+				return p.errorf("field '%s' would overwrite already parsed oneof '%s'", name, sv.Type().Field(oop.Field).Name)
+			}
+			field.Set(nv)
+		}
+		if !dst.IsValid() {
+			return p.errorf("unknown field name %q in %v", name, st)
+		}
+
+		if dst.Kind() == reflect.Map {
+			// Consume any colon.
+			if err := p.checkForColon(props, dst.Type()); err != nil {
+				return err
+			}
+
+			// Construct the map if it doesn't already exist.
+			if dst.IsNil() {
+				dst.Set(reflect.MakeMap(dst.Type()))
+			}
+			key := reflect.New(dst.Type().Key()).Elem()
+			val := reflect.New(dst.Type().Elem()).Elem()
+
+			// The map entry should be this sequence of tokens:
+			//	< key : KEY value : VALUE >
+			// However, implementations may omit key or value, and technically
+			// we should support them in any order.  See b/28924776 for a time
+			// this went wrong.
+
+			tok := p.next()
+			var terminator string
+			switch tok.value {
+			case "<":
+				terminator = ">"
+			case "{":
+				terminator = "}"
+			default:
+				return p.errorf("expected '{' or '<', found %q", tok.value)
+			}
+			for {
+				tok := p.next()
+				if tok.err != nil {
+					return tok.err
+				}
+				if tok.value == terminator {
+					break
+				}
+				switch tok.value {
+				case "key":
+					if err := p.consumeToken(":"); err != nil {
+						return err
+					}
+					if err := p.readAny(key, props.mkeyprop); err != nil {
+						return err
+					}
+					if err := p.consumeOptionalSeparator(); err != nil {
+						return err
+					}
+				case "value":
+					if err := p.checkForColon(props.mvalprop, dst.Type().Elem()); err != nil {
+						return err
+					}
+					if err := p.readAny(val, props.mvalprop); err != nil {
+						return err
+					}
+					if err := p.consumeOptionalSeparator(); err != nil {
+						return err
+					}
+				default:
+					p.back()
+					return p.errorf(`expected "key", "value", or %q, found %q`, terminator, tok.value)
+				}
+			}
+
+			dst.SetMapIndex(key, val)
+			continue
+		}
+
+		// Check that it's not already set if it's not a repeated field.
+		if !props.Repeated && fieldSet[name] {
+			return p.errorf("non-repeated field %q was repeated", name)
+		}
+
+		if err := p.checkForColon(props, dst.Type()); err != nil {
+			return err
+		}
+
+		// Parse into the field.
+		fieldSet[name] = true
+		if err := p.readAny(dst, props); err != nil {
+			if _, ok := err.(*RequiredNotSetError); !ok {
+				return err
+			}
+			reqFieldErr = err
+		}
+		if props.Required {
+			reqCount--
+		}
+
+		if err := p.consumeOptionalSeparator(); err != nil {
+			return err
+		}
+
+	}
+
+	if reqCount > 0 {
+		return p.missingRequiredFieldError(sv)
+	}
+	return reqFieldErr
+}
+
+// consumeExtName consumes extension name or expanded Any type URL and the
+// following ']'. It returns the name or URL consumed.
+func (p *textParser) consumeExtName() (string, error) {
+	tok := p.next()
+	if tok.err != nil {
+		return "", tok.err
+	}
+
+	// If extension name or type url is quoted, it's a single token.
+	if len(tok.value) > 2 && isQuote(tok.value[0]) && tok.value[len(tok.value)-1] == tok.value[0] {
+		name, err := unquoteC(tok.value[1:len(tok.value)-1], rune(tok.value[0]))
+		if err != nil {
+			return "", err
+		}
+		return name, p.consumeToken("]")
+	}
+
+	// Consume everything up to "]"
+	var parts []string
+	for tok.value != "]" {
+		parts = append(parts, tok.value)
+		tok = p.next()
+		if tok.err != nil {
+			return "", p.errorf("unrecognized type_url or extension name: %s", tok.err)
+		}
+	}
+	return strings.Join(parts, ""), nil
+}
+
+// consumeOptionalSeparator consumes an optional semicolon or comma.
+// It is used in readStruct to provide backward compatibility.
+func (p *textParser) consumeOptionalSeparator() error {
+	tok := p.next()
+	if tok.err != nil {
+		return tok.err
+	}
+	if tok.value != ";" && tok.value != "," {
+		p.back()
+	}
+	return nil
+}
+
+func (p *textParser) readAny(v reflect.Value, props *Properties) error {
+	tok := p.next()
+	if tok.err != nil {
+		return tok.err
+	}
+	if tok.value == "" {
+		return p.errorf("unexpected EOF")
+	}
+
+	switch fv := v; fv.Kind() {
+	case reflect.Slice:
+		at := v.Type()
+		if at.Elem().Kind() == reflect.Uint8 {
+			// Special case for []byte
+			if tok.value[0] != '"' && tok.value[0] != '\'' {
+				// Deliberately written out here, as the error after
+				// this switch statement would write "invalid []byte: ...",
+				// which is not as user-friendly.
+				return p.errorf("invalid string: %v", tok.value)
+			}
+			bytes := []byte(tok.unquoted)
+			fv.Set(reflect.ValueOf(bytes))
+			return nil
+		}
+		// Repeated field.
+		if tok.value == "[" {
+			// Repeated field with list notation, like [1,2,3].
+			for {
+				fv.Set(reflect.Append(fv, reflect.New(at.Elem()).Elem()))
+				err := p.readAny(fv.Index(fv.Len()-1), props)
+				if err != nil {
+					return err
+				}
+				tok := p.next()
+				if tok.err != nil {
+					return tok.err
+				}
+				if tok.value == "]" {
+					break
+				}
+				if tok.value != "," {
+					return p.errorf("Expected ']' or ',' found %q", tok.value)
+				}
+			}
+			return nil
+		}
+		// One value of the repeated field.
+		p.back()
+		fv.Set(reflect.Append(fv, reflect.New(at.Elem()).Elem()))
+		return p.readAny(fv.Index(fv.Len()-1), props)
+	case reflect.Bool:
+		// true/1/t/True or false/f/0/False.
+		switch tok.value {
+		case "true", "1", "t", "True":
+			fv.SetBool(true)
+			return nil
+		case "false", "0", "f", "False":
+			fv.SetBool(false)
+			return nil
+		}
+	case reflect.Float32, reflect.Float64:
+		v := tok.value
+		// Ignore 'f' for compatibility with output generated by C++, but don't
+		// remove 'f' when the value is "-inf" or "inf".
+		if strings.HasSuffix(v, "f") && tok.value != "-inf" && tok.value != "inf" {
+			v = v[:len(v)-1]
+		}
+		if f, err := strconv.ParseFloat(v, fv.Type().Bits()); err == nil {
+			fv.SetFloat(f)
+			return nil
+		}
+	case reflect.Int32:
+		if x, err := strconv.ParseInt(tok.value, 0, 32); err == nil {
+			fv.SetInt(x)
+			return nil
+		}
+
+		if len(props.Enum) == 0 {
+			break
+		}
+		m, ok := enumValueMaps[props.Enum]
+		if !ok {
+			break
+		}
+		x, ok := m[tok.value]
+		if !ok {
+			break
+		}
+		fv.SetInt(int64(x))
+		return nil
+	case reflect.Int64:
+		if x, err := strconv.ParseInt(tok.value, 0, 64); err == nil {
+			fv.SetInt(x)
+			return nil
+		}
+
+	case reflect.Ptr:
+		// A basic field (indirected through pointer), or a repeated message/group
+		p.back()
+		fv.Set(reflect.New(fv.Type().Elem()))
+		return p.readAny(fv.Elem(), props)
+	case reflect.String:
+		if tok.value[0] == '"' || tok.value[0] == '\'' {
+			fv.SetString(tok.unquoted)
+			return nil
+		}
+	case reflect.Struct:
+		var terminator string
+		switch tok.value {
+		case "{":
+			terminator = "}"
+		case "<":
+			terminator = ">"
+		default:
+			return p.errorf("expected '{' or '<', found %q", tok.value)
+		}
+		// TODO: Handle nested messages which implement encoding.TextUnmarshaler.
+		return p.readStruct(fv, terminator)
+	case reflect.Uint32:
+		if x, err := strconv.ParseUint(tok.value, 0, 32); err == nil {
+			fv.SetUint(x)
+			return nil
+		}
+	case reflect.Uint64:
+		if x, err := strconv.ParseUint(tok.value, 0, 64); err == nil {
+			fv.SetUint(x)
+			return nil
+		}
+	}
+	return p.errorf("invalid %v: %v", v.Type(), tok.value)
+}
+
+// UnmarshalText reads a protocol buffer in Text format. UnmarshalText resets pb
+// before starting to unmarshal, so any existing data in pb is always removed.
+// If a required field is not set and no other error occurs,
+// UnmarshalText returns *RequiredNotSetError.
+func UnmarshalText(s string, pb Message) error {
+	if um, ok := pb.(encoding.TextUnmarshaler); ok {
+		err := um.UnmarshalText([]byte(s))
+		return err
+	}
+	pb.Reset()
+	v := reflect.ValueOf(pb)
+	if pe := newTextParser(s).readStruct(v.Elem(), ""); pe != nil {
+		return pe
+	}
+	return nil
+}

+ 0 - 21
vendor/github.com/hpcloud/tail/LICENSE.txt

@@ -1,21 +0,0 @@
-# The MIT License (MIT)
-
-# © Copyright 2015 Hewlett Packard Enterprise Development LP
-Copyright (c) 2014 ActiveState
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-SOFTWARE.

+ 0 - 7
vendor/github.com/hpcloud/tail/ratelimiter/Licence

@@ -1,7 +0,0 @@
-Copyright (C) 2013 99designs
-
-Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

+ 0 - 97
vendor/github.com/hpcloud/tail/ratelimiter/leakybucket.go

@@ -1,97 +0,0 @@
-// Package ratelimiter implements the Leaky Bucket ratelimiting algorithm with memcached and in-memory backends.
-package ratelimiter
-
-import (
-	"time"
-)
-
-type LeakyBucket struct {
-	Size         uint16
-	Fill         float64
-	LeakInterval time.Duration // time.Duration for 1 unit of size to leak
-	Lastupdate   time.Time
-	Now          func() time.Time
-}
-
-func NewLeakyBucket(size uint16, leakInterval time.Duration) *LeakyBucket {
-	bucket := LeakyBucket{
-		Size:         size,
-		Fill:         0,
-		LeakInterval: leakInterval,
-		Now:          time.Now,
-		Lastupdate:   time.Now(),
-	}
-
-	return &bucket
-}
-
-func (b *LeakyBucket) updateFill() {
-	now := b.Now()
-	if b.Fill > 0 {
-		elapsed := now.Sub(b.Lastupdate)
-
-		b.Fill -= float64(elapsed) / float64(b.LeakInterval)
-		if b.Fill < 0 {
-			b.Fill = 0
-		}
-	}
-	b.Lastupdate = now
-}
-
-func (b *LeakyBucket) Pour(amount uint16) bool {
-	b.updateFill()
-
-	var newfill float64 = b.Fill + float64(amount)
-
-	if newfill > float64(b.Size) {
-		return false
-	}
-
-	b.Fill = newfill
-
-	return true
-}
-
-// The time at which this bucket will be completely drained
-func (b *LeakyBucket) DrainedAt() time.Time {
-	return b.Lastupdate.Add(time.Duration(b.Fill * float64(b.LeakInterval)))
-}
-
-// The duration until this bucket is completely drained
-func (b *LeakyBucket) TimeToDrain() time.Duration {
-	return b.DrainedAt().Sub(b.Now())
-}
-
-func (b *LeakyBucket) TimeSinceLastUpdate() time.Duration {
-	return b.Now().Sub(b.Lastupdate)
-}
-
-type LeakyBucketSer struct {
-	Size         uint16
-	Fill         float64
-	LeakInterval time.Duration // time.Duration for 1 unit of size to leak
-	Lastupdate   time.Time
-}
-
-func (b *LeakyBucket) Serialise() *LeakyBucketSer {
-	bucket := LeakyBucketSer{
-		Size:         b.Size,
-		Fill:         b.Fill,
-		LeakInterval: b.LeakInterval,
-		Lastupdate:   b.Lastupdate,
-	}
-
-	return &bucket
-}
-
-func (b *LeakyBucketSer) DeSerialise() *LeakyBucket {
-	bucket := LeakyBucket{
-		Size:         b.Size,
-		Fill:         b.Fill,
-		LeakInterval: b.LeakInterval,
-		Lastupdate:   b.Lastupdate,
-		Now:          time.Now,
-	}
-
-	return &bucket
-}

+ 0 - 60
vendor/github.com/hpcloud/tail/ratelimiter/memory.go

@@ -1,60 +0,0 @@
-package ratelimiter
-
-import (
-	"errors"
-	"time"
-)
-
-const (
-	GC_SIZE   int           = 100
-	GC_PERIOD time.Duration = 60 * time.Second
-)
-
-type Memory struct {
-	store           map[string]LeakyBucket
-	lastGCCollected time.Time
-}
-
-func NewMemory() *Memory {
-	m := new(Memory)
-	m.store = make(map[string]LeakyBucket)
-	m.lastGCCollected = time.Now()
-	return m
-}
-
-func (m *Memory) GetBucketFor(key string) (*LeakyBucket, error) {
-
-	bucket, ok := m.store[key]
-	if !ok {
-		return nil, errors.New("miss")
-	}
-
-	return &bucket, nil
-}
-
-func (m *Memory) SetBucketFor(key string, bucket LeakyBucket) error {
-
-	if len(m.store) > GC_SIZE {
-		m.GarbageCollect()
-	}
-
-	m.store[key] = bucket
-
-	return nil
-}
-
-func (m *Memory) GarbageCollect() {
-	now := time.Now()
-
-	// rate limit GC to once per minute
-	if now.Unix() >= m.lastGCCollected.Add(GC_PERIOD).Unix() {
-		for key, bucket := range m.store {
-			// if the bucket is drained, then GC
-			if bucket.DrainedAt().Unix() < now.Unix() {
-				delete(m.store, key)
-			}
-		}
-
-		m.lastGCCollected = now
-	}
-}

+ 0 - 6
vendor/github.com/hpcloud/tail/ratelimiter/storage.go

@@ -1,6 +0,0 @@
-package ratelimiter
-
-type Storage interface {
-	GetBucketFor(string) (*LeakyBucket, error)
-	SetBucketFor(string, LeakyBucket) error
-}

+ 0 - 437
vendor/github.com/hpcloud/tail/tail.go

@@ -1,437 +0,0 @@
-// Copyright (c) 2015 HPE Software Inc. All rights reserved.
-// Copyright (c) 2013 ActiveState Software Inc. All rights reserved.
-
-package tail
-
-import (
-	"bufio"
-	"errors"
-	"fmt"
-	"io"
-	"io/ioutil"
-	"log"
-	"os"
-	"strings"
-	"sync"
-	"time"
-
-	"github.com/hpcloud/tail/ratelimiter"
-	"github.com/hpcloud/tail/util"
-	"github.com/hpcloud/tail/watch"
-	"gopkg.in/tomb.v1"
-)
-
-var (
-	ErrStop = errors.New("tail should now stop")
-)
-
-type Line struct {
-	Text string
-	Time time.Time
-	Err  error // Error from tail
-}
-
-// NewLine returns a Line with present time.
-func NewLine(text string) *Line {
-	return &Line{text, time.Now(), nil}
-}
-
-// SeekInfo represents arguments to `os.Seek`
-type SeekInfo struct {
-	Offset int64
-	Whence int // os.SEEK_*
-}
-
-type logger interface {
-	Fatal(v ...interface{})
-	Fatalf(format string, v ...interface{})
-	Fatalln(v ...interface{})
-	Panic(v ...interface{})
-	Panicf(format string, v ...interface{})
-	Panicln(v ...interface{})
-	Print(v ...interface{})
-	Printf(format string, v ...interface{})
-	Println(v ...interface{})
-}
-
-// Config is used to specify how a file must be tailed.
-type Config struct {
-	// File-specifc
-	Location    *SeekInfo // Seek to this location before tailing
-	ReOpen      bool      // Reopen recreated files (tail -F)
-	MustExist   bool      // Fail early if the file does not exist
-	Poll        bool      // Poll for file changes instead of using inotify
-	Pipe        bool      // Is a named pipe (mkfifo)
-	RateLimiter *ratelimiter.LeakyBucket
-
-	// Generic IO
-	Follow      bool // Continue looking for new lines (tail -f)
-	MaxLineSize int  // If non-zero, split longer lines into multiple lines
-
-	// Logger, when nil, is set to tail.DefaultLogger
-	// To disable logging: set field to tail.DiscardingLogger
-	Logger logger
-}
-
-type Tail struct {
-	Filename string
-	Lines    chan *Line
-	Config
-
-	file   *os.File
-	reader *bufio.Reader
-
-	watcher watch.FileWatcher
-	changes *watch.FileChanges
-
-	tomb.Tomb // provides: Done, Kill, Dying
-
-	lk sync.Mutex
-}
-
-var (
-	// DefaultLogger is used when Config.Logger == nil
-	DefaultLogger = log.New(os.Stderr, "", log.LstdFlags)
-	// DiscardingLogger can be used to disable logging output
-	DiscardingLogger = log.New(ioutil.Discard, "", 0)
-)
-
-// TailFile begins tailing the file. Output stream is made available
-// via the `Tail.Lines` channel. To handle errors during tailing,
-// invoke the `Wait` or `Err` method after finishing reading from the
-// `Lines` channel.
-func TailFile(filename string, config Config) (*Tail, error) {
-	if config.ReOpen && !config.Follow {
-		util.Fatal("cannot set ReOpen without Follow.")
-	}
-
-	t := &Tail{
-		Filename: filename,
-		Lines:    make(chan *Line),
-		Config:   config,
-	}
-
-	// when Logger was not specified in config, use default logger
-	if t.Logger == nil {
-		t.Logger = log.New(os.Stderr, "", log.LstdFlags)
-	}
-
-	if t.Poll {
-		t.watcher = watch.NewPollingFileWatcher(filename)
-	} else {
-		t.watcher = watch.NewInotifyFileWatcher(filename)
-	}
-
-	if t.MustExist {
-		var err error
-		t.file, err = OpenFile(t.Filename)
-		if err != nil {
-			return nil, err
-		}
-	}
-
-	go t.tailFileSync()
-
-	return t, nil
-}
-
-// Return the file's current position, like stdio's ftell().
-// But this value is not very accurate.
-// it may readed one line in the chan(tail.Lines),
-// so it may lost one line.
-func (tail *Tail) Tell() (offset int64, err error) {
-	if tail.file == nil {
-		return
-	}
-	offset, err = tail.file.Seek(0, os.SEEK_CUR)
-	if err != nil {
-		return
-	}
-
-	tail.lk.Lock()
-	defer tail.lk.Unlock()
-	if tail.reader == nil {
-		return
-	}
-
-	offset -= int64(tail.reader.Buffered())
-	return
-}
-
-// Stop stops the tailing activity.
-func (tail *Tail) Stop() error {
-	tail.Kill(nil)
-	return tail.Wait()
-}
-
-// StopAtEOF stops tailing as soon as the end of the file is reached.
-func (tail *Tail) StopAtEOF() error {
-	tail.Kill(errStopAtEOF)
-	return tail.Wait()
-}
-
-var errStopAtEOF = errors.New("tail: stop at eof")
-
-func (tail *Tail) close() {
-	close(tail.Lines)
-	tail.closeFile()
-}
-
-func (tail *Tail) closeFile() {
-	if tail.file != nil {
-		tail.file.Close()
-		tail.file = nil
-	}
-}
-
-func (tail *Tail) reopen() error {
-	tail.closeFile()
-	for {
-		var err error
-		tail.file, err = OpenFile(tail.Filename)
-		if err != nil {
-			if os.IsNotExist(err) {
-				tail.Logger.Printf("Waiting for %s to appear...", tail.Filename)
-				if err := tail.watcher.BlockUntilExists(&tail.Tomb); err != nil {
-					if err == tomb.ErrDying {
-						return err
-					}
-					return fmt.Errorf("Failed to detect creation of %s: %s", tail.Filename, err)
-				}
-				continue
-			}
-			return fmt.Errorf("Unable to open file %s: %s", tail.Filename, err)
-		}
-		break
-	}
-	return nil
-}
-
-func (tail *Tail) readLine() (string, error) {
-	tail.lk.Lock()
-	line, err := tail.reader.ReadString('\n')
-	tail.lk.Unlock()
-	if err != nil {
-		// Note ReadString "returns the data read before the error" in
-		// case of an error, including EOF, so we return it as is. The
-		// caller is expected to process it if err is EOF.
-		return line, err
-	}
-
-	line = strings.TrimRight(line, "\n")
-
-	return line, err
-}
-
-func (tail *Tail) tailFileSync() {
-	defer tail.Done()
-	defer tail.close()
-
-	if !tail.MustExist {
-		// deferred first open.
-		err := tail.reopen()
-		if err != nil {
-			if err != tomb.ErrDying {
-				tail.Kill(err)
-			}
-			return
-		}
-	}
-
-	// Seek to requested location on first open of the file.
-	if tail.Location != nil {
-		_, err := tail.file.Seek(tail.Location.Offset, tail.Location.Whence)
-		tail.Logger.Printf("Seeked %s - %+v\n", tail.Filename, tail.Location)
-		if err != nil {
-			tail.Killf("Seek error on %s: %s", tail.Filename, err)
-			return
-		}
-	}
-
-	tail.openReader()
-
-	var offset int64
-	var err error
-
-	// Read line by line.
-	for {
-		// do not seek in named pipes
-		if !tail.Pipe {
-			// grab the position in case we need to back up in the event of a half-line
-			offset, err = tail.Tell()
-			if err != nil {
-				tail.Kill(err)
-				return
-			}
-		}
-
-		line, err := tail.readLine()
-
-		// Process `line` even if err is EOF.
-		if err == nil {
-			cooloff := !tail.sendLine(line)
-			if cooloff {
-				// Wait a second before seeking till the end of
-				// file when rate limit is reached.
-				msg := ("Too much log activity; waiting a second " +
-					"before resuming tailing")
-				tail.Lines <- &Line{msg, time.Now(), errors.New(msg)}
-				select {
-				case <-time.After(time.Second):
-				case <-tail.Dying():
-					return
-				}
-				if err := tail.seekEnd(); err != nil {
-					tail.Kill(err)
-					return
-				}
-			}
-		} else if err == io.EOF {
-			if !tail.Follow {
-				if line != "" {
-					tail.sendLine(line)
-				}
-				return
-			}
-
-			if tail.Follow && line != "" {
-				// this has the potential to never return the last line if
-				// it's not followed by a newline; seems a fair trade here
-				err := tail.seekTo(SeekInfo{Offset: offset, Whence: 0})
-				if err != nil {
-					tail.Kill(err)
-					return
-				}
-			}
-
-			// When EOF is reached, wait for more data to become
-			// available. Wait strategy is based on the `tail.watcher`
-			// implementation (inotify or polling).
-			err := tail.waitForChanges()
-			if err != nil {
-				if err != ErrStop {
-					tail.Kill(err)
-				}
-				return
-			}
-		} else {
-			// non-EOF error
-			tail.Killf("Error reading %s: %s", tail.Filename, err)
-			return
-		}
-
-		select {
-		case <-tail.Dying():
-			if tail.Err() == errStopAtEOF {
-				continue
-			}
-			return
-		default:
-		}
-	}
-}
-
-// waitForChanges waits until the file has been appended, deleted,
-// moved or truncated. When moved or deleted - the file will be
-// reopened if ReOpen is true. Truncated files are always reopened.
-func (tail *Tail) waitForChanges() error {
-	if tail.changes == nil {
-		pos, err := tail.file.Seek(0, os.SEEK_CUR)
-		if err != nil {
-			return err
-		}
-		tail.changes, err = tail.watcher.ChangeEvents(&tail.Tomb, pos)
-		if err != nil {
-			return err
-		}
-	}
-
-	select {
-	case <-tail.changes.Modified:
-		return nil
-	case <-tail.changes.Deleted:
-		tail.changes = nil
-		if tail.ReOpen {
-			// XXX: we must not log from a library.
-			tail.Logger.Printf("Re-opening moved/deleted file %s ...", tail.Filename)
-			if err := tail.reopen(); err != nil {
-				return err
-			}
-			tail.Logger.Printf("Successfully reopened %s", tail.Filename)
-			tail.openReader()
-			return nil
-		} else {
-			tail.Logger.Printf("Stopping tail as file no longer exists: %s", tail.Filename)
-			return ErrStop
-		}
-	case <-tail.changes.Truncated:
-		// Always reopen truncated files (Follow is true)
-		tail.Logger.Printf("Re-opening truncated file %s ...", tail.Filename)
-		if err := tail.reopen(); err != nil {
-			return err
-		}
-		tail.Logger.Printf("Successfully reopened truncated %s", tail.Filename)
-		tail.openReader()
-		return nil
-	case <-tail.Dying():
-		return ErrStop
-	}
-	panic("unreachable")
-}
-
-func (tail *Tail) openReader() {
-	if tail.MaxLineSize > 0 {
-		// add 2 to account for newline characters
-		tail.reader = bufio.NewReaderSize(tail.file, tail.MaxLineSize+2)
-	} else {
-		tail.reader = bufio.NewReader(tail.file)
-	}
-}
-
-func (tail *Tail) seekEnd() error {
-	return tail.seekTo(SeekInfo{Offset: 0, Whence: os.SEEK_END})
-}
-
-func (tail *Tail) seekTo(pos SeekInfo) error {
-	_, err := tail.file.Seek(pos.Offset, pos.Whence)
-	if err != nil {
-		return fmt.Errorf("Seek error on %s: %s", tail.Filename, err)
-	}
-	// Reset the read buffer whenever the file is re-seek'ed
-	tail.reader.Reset(tail.file)
-	return nil
-}
-
-// sendLine sends the line(s) to Lines channel, splitting longer lines
-// if necessary. Return false if rate limit is reached.
-func (tail *Tail) sendLine(line string) bool {
-	now := time.Now()
-	lines := []string{line}
-
-	// Split longer lines
-	if tail.MaxLineSize > 0 && len(line) > tail.MaxLineSize {
-		lines = util.PartitionString(line, tail.MaxLineSize)
-	}
-
-	for _, line := range lines {
-		tail.Lines <- &Line{line, now, nil}
-	}
-
-	if tail.Config.RateLimiter != nil {
-		ok := tail.Config.RateLimiter.Pour(uint16(len(lines)))
-		if !ok {
-			tail.Logger.Printf("Leaky bucket full (%v); entering 1s cooloff period.\n",
-				tail.Filename)
-			return false
-		}
-	}
-
-	return true
-}
-
-// Cleanup removes inotify watches added by the tail package. This function is
-// meant to be invoked from a process's exit handler. Linux kernel may not
-// automatically remove inotify watches after the process exits.
-func (tail *Tail) Cleanup() {
-	watch.Cleanup(tail.Filename)
-}

+ 0 - 11
vendor/github.com/hpcloud/tail/tail_posix.go

@@ -1,11 +0,0 @@
-// +build linux darwin freebsd netbsd openbsd
-
-package tail
-
-import (
-	"os"
-)
-
-func OpenFile(name string) (file *os.File, err error) {
-	return os.Open(name)
-}

+ 0 - 12
vendor/github.com/hpcloud/tail/tail_windows.go

@@ -1,12 +0,0 @@
-// +build windows
-
-package tail
-
-import (
-	"github.com/hpcloud/tail/winfile"
-	"os"
-)
-
-func OpenFile(name string) (file *os.File, err error) {
-	return winfile.OpenFile(name, os.O_RDONLY, 0)
-}

+ 0 - 48
vendor/github.com/hpcloud/tail/util/util.go

@@ -1,48 +0,0 @@
-// Copyright (c) 2015 HPE Software Inc. All rights reserved.
-// Copyright (c) 2013 ActiveState Software Inc. All rights reserved.
-
-package util
-
-import (
-	"fmt"
-	"log"
-	"os"
-	"runtime/debug"
-)
-
-type Logger struct {
-	*log.Logger
-}
-
-var LOGGER = &Logger{log.New(os.Stderr, "", log.LstdFlags)}
-
-// fatal is like panic except it displays only the current goroutine's stack.
-func Fatal(format string, v ...interface{}) {
-	// https://github.com/hpcloud/log/blob/master/log.go#L45
-	LOGGER.Output(2, fmt.Sprintf("FATAL -- "+format, v...)+"\n"+string(debug.Stack()))
-	os.Exit(1)
-}
-
-// partitionString partitions the string into chunks of given size,
-// with the last chunk of variable size.
-func PartitionString(s string, chunkSize int) []string {
-	if chunkSize <= 0 {
-		panic("invalid chunkSize")
-	}
-	length := len(s)
-	chunks := 1 + length/chunkSize
-	start := 0
-	end := chunkSize
-	parts := make([]string, 0, chunks)
-	for {
-		if end > length {
-			end = length
-		}
-		parts = append(parts, s[start:end])
-		if end == length {
-			break
-		}
-		start, end = end, end+chunkSize
-	}
-	return parts
-}

+ 0 - 36
vendor/github.com/hpcloud/tail/watch/filechanges.go

@@ -1,36 +0,0 @@
-package watch
-
-type FileChanges struct {
-	Modified  chan bool // Channel to get notified of modifications
-	Truncated chan bool // Channel to get notified of truncations
-	Deleted   chan bool // Channel to get notified of deletions/renames
-}
-
-func NewFileChanges() *FileChanges {
-	return &FileChanges{
-		make(chan bool, 1), make(chan bool, 1), make(chan bool, 1)}
-}
-
-func (fc *FileChanges) NotifyModified() {
-	sendOnlyIfEmpty(fc.Modified)
-}
-
-func (fc *FileChanges) NotifyTruncated() {
-	sendOnlyIfEmpty(fc.Truncated)
-}
-
-func (fc *FileChanges) NotifyDeleted() {
-	sendOnlyIfEmpty(fc.Deleted)
-}
-
-// sendOnlyIfEmpty sends on a bool channel only if the channel has no
-// backlog to be read by other goroutines. This concurrency pattern
-// can be used to notify other goroutines if and only if they are
-// looking for it (i.e., subsequent notifications can be compressed
-// into one).
-func sendOnlyIfEmpty(ch chan bool) {
-	select {
-	case ch <- true:
-	default:
-	}
-}

+ 0 - 135
vendor/github.com/hpcloud/tail/watch/inotify.go

@@ -1,135 +0,0 @@
-// Copyright (c) 2015 HPE Software Inc. All rights reserved.
-// Copyright (c) 2013 ActiveState Software Inc. All rights reserved.
-
-package watch
-
-import (
-	"fmt"
-	"os"
-	"path/filepath"
-
-	"github.com/hpcloud/tail/util"
-
-	"gopkg.in/fsnotify.v1"
-	"gopkg.in/tomb.v1"
-)
-
-// InotifyFileWatcher uses inotify to monitor file changes.
-type InotifyFileWatcher struct {
-	Filename string
-	Size     int64
-}
-
-func NewInotifyFileWatcher(filename string) *InotifyFileWatcher {
-	fw := &InotifyFileWatcher{filepath.Clean(filename), 0}
-	return fw
-}
-
-func (fw *InotifyFileWatcher) BlockUntilExists(t *tomb.Tomb) error {
-	err := WatchCreate(fw.Filename)
-	if err != nil {
-		return err
-	}
-	defer RemoveWatchCreate(fw.Filename)
-
-	// Do a real check now as the file might have been created before
-	// calling `WatchFlags` above.
-	if _, err = os.Stat(fw.Filename); !os.IsNotExist(err) {
-		// file exists, or stat returned an error.
-		return err
-	}
-
-	events := Events(fw.Filename)
-
-	for {
-		select {
-		case evt, ok := <-events:
-			if !ok {
-				return fmt.Errorf("inotify watcher has been closed")
-			}
-			evtName, err := filepath.Abs(evt.Name)
-			if err != nil {
-				return err
-			}
-			fwFilename, err := filepath.Abs(fw.Filename)
-			if err != nil {
-				return err
-			}
-			if evtName == fwFilename {
-				return nil
-			}
-		case <-t.Dying():
-			return tomb.ErrDying
-		}
-	}
-	panic("unreachable")
-}
-
-func (fw *InotifyFileWatcher) ChangeEvents(t *tomb.Tomb, pos int64) (*FileChanges, error) {
-	err := Watch(fw.Filename)
-	if err != nil {
-		return nil, err
-	}
-
-	changes := NewFileChanges()
-	fw.Size = pos
-
-	go func() {
-
-		events := Events(fw.Filename)
-
-		for {
-			prevSize := fw.Size
-
-			var evt fsnotify.Event
-			var ok bool
-
-			select {
-			case evt, ok = <-events:
-				if !ok {
-					RemoveWatch(fw.Filename)
-					return
-				}
-			case <-t.Dying():
-				RemoveWatch(fw.Filename)
-				return
-			}
-
-			switch {
-			case evt.Op&fsnotify.Remove == fsnotify.Remove:
-				fallthrough
-
-			case evt.Op&fsnotify.Rename == fsnotify.Rename:
-				RemoveWatch(fw.Filename)
-				changes.NotifyDeleted()
-				return
-
-			//With an open fd, unlink(fd) - inotify returns IN_ATTRIB (==fsnotify.Chmod)
-			case evt.Op&fsnotify.Chmod == fsnotify.Chmod:
-				fallthrough
-
-			case evt.Op&fsnotify.Write == fsnotify.Write:
-				fi, err := os.Stat(fw.Filename)
-				if err != nil {
-					if os.IsNotExist(err) {
-						RemoveWatch(fw.Filename)
-						changes.NotifyDeleted()
-						return
-					}
-					// XXX: report this error back to the user
-					util.Fatal("Failed to stat file %v: %v", fw.Filename, err)
-				}
-				fw.Size = fi.Size()
-
-				if prevSize > 0 && prevSize > fw.Size {
-					changes.NotifyTruncated()
-				} else {
-					changes.NotifyModified()
-				}
-				prevSize = fw.Size
-			}
-		}
-	}()
-
-	return changes, nil
-}

+ 0 - 248
vendor/github.com/hpcloud/tail/watch/inotify_tracker.go

@@ -1,248 +0,0 @@
-// Copyright (c) 2015 HPE Software Inc. All rights reserved.
-// Copyright (c) 2013 ActiveState Software Inc. All rights reserved.
-
-package watch
-
-import (
-	"log"
-	"os"
-	"path/filepath"
-	"sync"
-	"syscall"
-
-	"github.com/hpcloud/tail/util"
-
-	"gopkg.in/fsnotify.v1"
-)
-
-type InotifyTracker struct {
-	mux       sync.Mutex
-	watcher   *fsnotify.Watcher
-	chans     map[string]chan fsnotify.Event
-	done      map[string]chan bool
-	watchNums map[string]int
-	watch     chan *watchInfo
-	remove    chan *watchInfo
-	error     chan error
-}
-
-type watchInfo struct {
-	op    fsnotify.Op
-	fname string
-}
-
-func (this *watchInfo) isCreate() bool {
-	return this.op == fsnotify.Create
-}
-
-var (
-	// globally shared InotifyTracker; ensures only one fsnotify.Watcher is used
-	shared *InotifyTracker
-
-	// these are used to ensure the shared InotifyTracker is run exactly once
-	once  = sync.Once{}
-	goRun = func() {
-		shared = &InotifyTracker{
-			mux:       sync.Mutex{},
-			chans:     make(map[string]chan fsnotify.Event),
-			done:      make(map[string]chan bool),
-			watchNums: make(map[string]int),
-			watch:     make(chan *watchInfo),
-			remove:    make(chan *watchInfo),
-			error:     make(chan error),
-		}
-		go shared.run()
-	}
-
-	logger = log.New(os.Stderr, "", log.LstdFlags)
-)
-
-// Watch signals the run goroutine to begin watching the input filename
-func Watch(fname string) error {
-	return watch(&watchInfo{
-		fname: fname,
-	})
-}
-
-// Watch create signals the run goroutine to begin watching the input filename
-// if call the WatchCreate function, don't call the Cleanup, call the RemoveWatchCreate
-func WatchCreate(fname string) error {
-	return watch(&watchInfo{
-		op:    fsnotify.Create,
-		fname: fname,
-	})
-}
-
-func watch(winfo *watchInfo) error {
-	// start running the shared InotifyTracker if not already running
-	once.Do(goRun)
-
-	winfo.fname = filepath.Clean(winfo.fname)
-	shared.watch <- winfo
-	return <-shared.error
-}
-
-// RemoveWatch signals the run goroutine to remove the watch for the input filename
-func RemoveWatch(fname string) error {
-	return remove(&watchInfo{
-		fname: fname,
-	})
-}
-
-// RemoveWatch create signals the run goroutine to remove the watch for the input filename
-func RemoveWatchCreate(fname string) error {
-	return remove(&watchInfo{
-		op:    fsnotify.Create,
-		fname: fname,
-	})
-}
-
-func remove(winfo *watchInfo) error {
-	// start running the shared InotifyTracker if not already running
-	once.Do(goRun)
-
-	winfo.fname = filepath.Clean(winfo.fname)
-	shared.mux.Lock()
-	done := shared.done[winfo.fname]
-	if done != nil {
-		delete(shared.done, winfo.fname)
-		close(done)
-	}
-	shared.mux.Unlock()
-
-	shared.remove <- winfo
-	return <-shared.error
-}
-
-// Events returns a channel to which FileEvents corresponding to the input filename
-// will be sent. This channel will be closed when removeWatch is called on this
-// filename.
-func Events(fname string) <-chan fsnotify.Event {
-	shared.mux.Lock()
-	defer shared.mux.Unlock()
-
-	return shared.chans[fname]
-}
-
-// Cleanup removes the watch for the input filename if necessary.
-func Cleanup(fname string) error {
-	return RemoveWatch(fname)
-}
-
-// watchFlags calls fsnotify.WatchFlags for the input filename and flags, creating
-// a new Watcher if the previous Watcher was closed.
-func (shared *InotifyTracker) addWatch(winfo *watchInfo) error {
-	shared.mux.Lock()
-	defer shared.mux.Unlock()
-
-	if shared.chans[winfo.fname] == nil {
-		shared.chans[winfo.fname] = make(chan fsnotify.Event)
-	}
-	if shared.done[winfo.fname] == nil {
-		shared.done[winfo.fname] = make(chan bool)
-	}
-
-	fname := winfo.fname
-	if winfo.isCreate() {
-		// Watch for new files to be created in the parent directory.
-		fname = filepath.Dir(fname)
-	}
-
-	var err error
-	// already in inotify watch
-	if shared.watchNums[fname] == 0 {
-		err = shared.watcher.Add(fname)
-	}
-	if err == nil {
-		shared.watchNums[fname]++
-	}
-	return err
-}
-
-// removeWatch calls fsnotify.RemoveWatch for the input filename and closes the
-// corresponding events channel.
-func (shared *InotifyTracker) removeWatch(winfo *watchInfo) error {
-	shared.mux.Lock()
-
-	ch := shared.chans[winfo.fname]
-	if ch != nil {
-		delete(shared.chans, winfo.fname)
-		close(ch)
-	}
-
-	fname := winfo.fname
-	if winfo.isCreate() {
-		// Watch for new files to be created in the parent directory.
-		fname = filepath.Dir(fname)
-	}
-	shared.watchNums[fname]--
-	watchNum := shared.watchNums[fname]
-	if watchNum == 0 {
-		delete(shared.watchNums, fname)
-	}
-	shared.mux.Unlock()
-
-	var err error
-	// If we were the last ones to watch this file, unsubscribe from inotify.
-	// This needs to happen after releasing the lock because fsnotify waits
-	// synchronously for the kernel to acknowledge the removal of the watch
-	// for this file, which causes us to deadlock if we still held the lock.
-	if watchNum == 0 {
-		err = shared.watcher.Remove(fname)
-	}
-
-	return err
-}
-
-// sendEvent sends the input event to the appropriate Tail.
-func (shared *InotifyTracker) sendEvent(event fsnotify.Event) {
-	name := filepath.Clean(event.Name)
-
-	shared.mux.Lock()
-	ch := shared.chans[name]
-	done := shared.done[name]
-	shared.mux.Unlock()
-
-	if ch != nil && done != nil {
-		select {
-		case ch <- event:
-		case <-done:
-		}
-	}
-}
-
-// run starts the goroutine in which the shared struct reads events from its
-// Watcher's Event channel and sends the events to the appropriate Tail.
-func (shared *InotifyTracker) run() {
-	watcher, err := fsnotify.NewWatcher()
-	if err != nil {
-		util.Fatal("failed to create Watcher")
-	}
-	shared.watcher = watcher
-
-	for {
-		select {
-		case winfo := <-shared.watch:
-			shared.error <- shared.addWatch(winfo)
-
-		case winfo := <-shared.remove:
-			shared.error <- shared.removeWatch(winfo)
-
-		case event, open := <-shared.watcher.Events:
-			if !open {
-				return
-			}
-			shared.sendEvent(event)
-
-		case err, open := <-shared.watcher.Errors:
-			if !open {
-				return
-			} else if err != nil {
-				sysErr, ok := err.(*os.SyscallError)
-				if !ok || sysErr.Err != syscall.EINTR {
-					logger.Printf("Error in Watcher Error channel: %s", err)
-				}
-			}
-		}
-	}
-}

+ 0 - 118
vendor/github.com/hpcloud/tail/watch/polling.go

@@ -1,118 +0,0 @@
-// Copyright (c) 2015 HPE Software Inc. All rights reserved.
-// Copyright (c) 2013 ActiveState Software Inc. All rights reserved.
-
-package watch
-
-import (
-	"os"
-	"runtime"
-	"time"
-
-	"github.com/hpcloud/tail/util"
-	"gopkg.in/tomb.v1"
-)
-
-// PollingFileWatcher polls the file for changes.
-type PollingFileWatcher struct {
-	Filename string
-	Size     int64
-}
-
-func NewPollingFileWatcher(filename string) *PollingFileWatcher {
-	fw := &PollingFileWatcher{filename, 0}
-	return fw
-}
-
-var POLL_DURATION time.Duration
-
-func (fw *PollingFileWatcher) BlockUntilExists(t *tomb.Tomb) error {
-	for {
-		if _, err := os.Stat(fw.Filename); err == nil {
-			return nil
-		} else if !os.IsNotExist(err) {
-			return err
-		}
-		select {
-		case <-time.After(POLL_DURATION):
-			continue
-		case <-t.Dying():
-			return tomb.ErrDying
-		}
-	}
-	panic("unreachable")
-}
-
-func (fw *PollingFileWatcher) ChangeEvents(t *tomb.Tomb, pos int64) (*FileChanges, error) {
-	origFi, err := os.Stat(fw.Filename)
-	if err != nil {
-		return nil, err
-	}
-
-	changes := NewFileChanges()
-	var prevModTime time.Time
-
-	// XXX: use tomb.Tomb to cleanly manage these goroutines. replace
-	// the fatal (below) with tomb's Kill.
-
-	fw.Size = pos
-
-	go func() {
-		prevSize := fw.Size
-		for {
-			select {
-			case <-t.Dying():
-				return
-			default:
-			}
-
-			time.Sleep(POLL_DURATION)
-			fi, err := os.Stat(fw.Filename)
-			if err != nil {
-				// Windows cannot delete a file if a handle is still open (tail keeps one open)
-				// so it gives access denied to anything trying to read it until all handles are released.
-				if os.IsNotExist(err) || (runtime.GOOS == "windows" && os.IsPermission(err)) {
-					// File does not exist (has been deleted).
-					changes.NotifyDeleted()
-					return
-				}
-
-				// XXX: report this error back to the user
-				util.Fatal("Failed to stat file %v: %v", fw.Filename, err)
-			}
-
-			// File got moved/renamed?
-			if !os.SameFile(origFi, fi) {
-				changes.NotifyDeleted()
-				return
-			}
-
-			// File got truncated?
-			fw.Size = fi.Size()
-			if prevSize > 0 && prevSize > fw.Size {
-				changes.NotifyTruncated()
-				prevSize = fw.Size
-				continue
-			}
-			// File got bigger?
-			if prevSize > 0 && prevSize < fw.Size {
-				changes.NotifyModified()
-				prevSize = fw.Size
-				continue
-			}
-			prevSize = fw.Size
-
-			// File was appended to (changed)?
-			modTime := fi.ModTime()
-			if modTime != prevModTime {
-				prevModTime = modTime
-				changes.NotifyModified()
-			}
-		}
-	}()
-
-	return changes, nil
-}
-
-func init() {
-	POLL_DURATION = 250 * time.Millisecond
-}

+ 0 - 20
vendor/github.com/hpcloud/tail/watch/watch.go

@@ -1,20 +0,0 @@
-// Copyright (c) 2015 HPE Software Inc. All rights reserved.
-// Copyright (c) 2013 ActiveState Software Inc. All rights reserved.
-
-package watch
-
-import "gopkg.in/tomb.v1"
-
-// FileWatcher monitors file-level events.
-type FileWatcher interface {
-	// BlockUntilExists blocks until the file comes into existence.
-	BlockUntilExists(*tomb.Tomb) error
-
-	// ChangeEvents reports on changes to a file, be it modification,
-	// deletion, renames or truncations. Returned FileChanges group of
-	// channels will be closed, thus become unusable, after a deletion
-	// or truncation event.
-	// In order to properly report truncations, ChangeEvents requires
-	// the caller to pass their current offset in the file.
-	ChangeEvents(*tomb.Tomb, int64) (*FileChanges, error)
-}

+ 0 - 92
vendor/github.com/hpcloud/tail/winfile/winfile.go

@@ -1,92 +0,0 @@
-// +build windows
-
-package winfile
-
-import (
-	"os"
-	"syscall"
-	"unsafe"
-)
-
-// issue also described here
-//https://codereview.appspot.com/8203043/
-
-// https://github.com/jnwhiteh/golang/blob/master/src/pkg/syscall/syscall_windows.go#L218
-func Open(path string, mode int, perm uint32) (fd syscall.Handle, err error) {
-	if len(path) == 0 {
-		return syscall.InvalidHandle, syscall.ERROR_FILE_NOT_FOUND
-	}
-	pathp, err := syscall.UTF16PtrFromString(path)
-	if err != nil {
-		return syscall.InvalidHandle, err
-	}
-	var access uint32
-	switch mode & (syscall.O_RDONLY | syscall.O_WRONLY | syscall.O_RDWR) {
-	case syscall.O_RDONLY:
-		access = syscall.GENERIC_READ
-	case syscall.O_WRONLY:
-		access = syscall.GENERIC_WRITE
-	case syscall.O_RDWR:
-		access = syscall.GENERIC_READ | syscall.GENERIC_WRITE
-	}
-	if mode&syscall.O_CREAT != 0 {
-		access |= syscall.GENERIC_WRITE
-	}
-	if mode&syscall.O_APPEND != 0 {
-		access &^= syscall.GENERIC_WRITE
-		access |= syscall.FILE_APPEND_DATA
-	}
-	sharemode := uint32(syscall.FILE_SHARE_READ | syscall.FILE_SHARE_WRITE | syscall.FILE_SHARE_DELETE)
-	var sa *syscall.SecurityAttributes
-	if mode&syscall.O_CLOEXEC == 0 {
-		sa = makeInheritSa()
-	}
-	var createmode uint32
-	switch {
-	case mode&(syscall.O_CREAT|syscall.O_EXCL) == (syscall.O_CREAT | syscall.O_EXCL):
-		createmode = syscall.CREATE_NEW
-	case mode&(syscall.O_CREAT|syscall.O_TRUNC) == (syscall.O_CREAT | syscall.O_TRUNC):
-		createmode = syscall.CREATE_ALWAYS
-	case mode&syscall.O_CREAT == syscall.O_CREAT:
-		createmode = syscall.OPEN_ALWAYS
-	case mode&syscall.O_TRUNC == syscall.O_TRUNC:
-		createmode = syscall.TRUNCATE_EXISTING
-	default:
-		createmode = syscall.OPEN_EXISTING
-	}
-	h, e := syscall.CreateFile(pathp, access, sharemode, sa, createmode, syscall.FILE_ATTRIBUTE_NORMAL, 0)
-	return h, e
-}
-
-// https://github.com/jnwhiteh/golang/blob/master/src/pkg/syscall/syscall_windows.go#L211
-func makeInheritSa() *syscall.SecurityAttributes {
-	var sa syscall.SecurityAttributes
-	sa.Length = uint32(unsafe.Sizeof(sa))
-	sa.InheritHandle = 1
-	return &sa
-}
-
-// https://github.com/jnwhiteh/golang/blob/master/src/pkg/os/file_windows.go#L133
-func OpenFile(name string, flag int, perm os.FileMode) (file *os.File, err error) {
-	r, e := Open(name, flag|syscall.O_CLOEXEC, syscallMode(perm))
-	if e != nil {
-		return nil, e
-	}
-	return os.NewFile(uintptr(r), name), nil
-}
-
-// https://github.com/jnwhiteh/golang/blob/master/src/pkg/os/file_posix.go#L61
-func syscallMode(i os.FileMode) (o uint32) {
-	o |= uint32(i.Perm())
-	if i&os.ModeSetuid != 0 {
-		o |= syscall.S_ISUID
-	}
-	if i&os.ModeSetgid != 0 {
-		o |= syscall.S_ISGID
-	}
-	if i&os.ModeSticky != 0 {
-		o |= syscall.S_ISVTX
-	}
-	// No mapping for Go's ModeTemporary (plan9 only).
-	return
-}

+ 0 - 20
vendor/github.com/influxdata/influxdb/LICENSE

@@ -1,20 +0,0 @@
-The MIT License (MIT)
-
-Copyright (c) 2013-2016 Errplane Inc.
-
-Permission is hereby granted, free of charge, to any person obtaining a copy of
-this software and associated documentation files (the "Software"), to deal in
-the Software without restriction, including without limitation the rights to
-use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
-the Software, and to permit persons to whom the Software is furnished to do so,
-subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
-FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
-COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
-IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
-CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

+ 0 - 62
vendor/github.com/influxdata/influxdb/LICENSE_OF_DEPENDENCIES.md

@@ -1,62 +0,0 @@
-- # List
-- bootstrap 3.3.5 [MIT LICENSE](https://github.com/twbs/bootstrap/blob/master/LICENSE)
-- collectd.org [ISC LICENSE](https://github.com/collectd/go-collectd/blob/master/LICENSE)
-- github.com/BurntSushi/toml [MIT LICENSE](https://github.com/BurntSushi/toml/blob/master/COPYING)
-- github.com/RoaringBitmap/roaring [APACHE LICENSE](https://github.com/RoaringBitmap/roaring/blob/master/LICENSE)
-- github.com/beorn7/perks [MIT LICENSE](https://github.com/beorn7/perks/blob/master/LICENSE)
-- github.com/bmizerany/pat [MIT LICENSE](https://github.com/bmizerany/pat#license)
-- github.com/boltdb/bolt [MIT LICENSE](https://github.com/boltdb/bolt/blob/master/LICENSE)
-- github.com/cespare/xxhash [MIT LICENSE](https://github.com/cespare/xxhash/blob/master/LICENSE.txt)
-- github.com/clarkduvall/hyperloglog [MIT LICENSE](https://github.com/clarkduvall/hyperloglog/blob/master/LICENSE)
-- github.com/davecgh/go-spew/spew [ISC LICENSE](https://github.com/davecgh/go-spew/blob/master/LICENSE)
-- github.com/dgrijalva/jwt-go [MIT LICENSE](https://github.com/dgrijalva/jwt-go/blob/master/LICENSE)
-- github.com/dgryski/go-bits [MIT LICENSE](https://github.com/dgryski/go-bits/blob/master/LICENSE)
-- github.com/dgryski/go-bitstream [MIT LICENSE](https://github.com/dgryski/go-bitstream/blob/master/LICENSE)
-- github.com/glycerine/go-unsnap-stream [MIT LICENSE](https://github.com/glycerine/go-unsnap-stream/blob/master/LICENSE)
-- github.com/gogo/protobuf/proto [BSD LICENSE](https://github.com/gogo/protobuf/blob/master/LICENSE)
-- github.com/golang/protobuf [BSD LICENSE](https://github.com/golang/protobuf/blob/master/LICENSE)
-- github.com/golang/snappy [BSD LICENSE](https://github.com/golang/snappy/blob/master/LICENSE)
-- github.com/google/go-cmp [BSD LICENSE](https://github.com/google/go-cmp/blob/master/LICENSE)
-- github.com/influxdata/influxql [MIT LICENSE](https://github.com/influxdata/influxql/blob/master/LICENSE)
-- github.com/influxdata/usage-client [MIT LICENSE](https://github.com/influxdata/usage-client/blob/master/LICENSE.txt)
-- github.com/influxdata/yamux [MOZILLA PUBLIC LICENSE](https://github.com/influxdata/yamux/blob/master/LICENSE)
-- github.com/influxdata/yarpc [MIT LICENSE](https://github.com/influxdata/yarpc/blob/master/LICENSE)
-- github.com/jsternberg/zap-logfmt [MIT LICENSE](https://github.com/jsternberg/zap-logfmt/blob/master/LICENSE)
-- github.com/jwilder/encoding [MIT LICENSE](https://github.com/jwilder/encoding/blob/master/LICENSE)
-- github.com/mattn/go-isatty [MIT LICENSE](https://github.com/mattn/go-isatty/blob/master/LICENSE)
-- github.com/matttproud/golang_protobuf_extensions [APACHE LICENSE](https://github.com/matttproud/golang_protobuf_extensions/blob/master/LICENSE)
-- github.com/opentracing/opentracing-go [MIT LICENSE](https://github.com/opentracing/opentracing-go/blob/master/LICENSE)
-- github.com/paulbellamy/ratecounter [MIT LICENSE](https://github.com/paulbellamy/ratecounter/blob/master/LICENSE)
-- github.com/peterh/liner [MIT LICENSE](https://github.com/peterh/liner/blob/master/COPYING)
-- github.com/philhofer/fwd [MIT LICENSE](https://github.com/philhofer/fwd/blob/master/LICENSE.md)
-- github.com/prometheus/client_golang [MIT LICENSE](https://github.com/prometheus/client_golang/blob/master/LICENSE)
-- github.com/prometheus/client_model [MIT LICENSE](https://github.com/prometheus/client_model/blob/master/LICENSE)
-- github.com/prometheus/common [APACHE LICENSE](https://github.com/prometheus/common/blob/master/LICENSE)
-- github.com/prometheus/procfs [APACHE LICENSE](https://github.com/prometheus/procfs/blob/master/LICENSE)
-- github.com/rakyll/statik [APACHE LICENSE](https://github.com/rakyll/statik/blob/master/LICENSE)
-- github.com/retailnext/hllpp [BSD LICENSE](https://github.com/retailnext/hllpp/blob/master/LICENSE)
-- github.com/tinylib/msgp [MIT LICENSE](https://github.com/tinylib/msgp/blob/master/LICENSE)
-- go.uber.org/atomic [MIT LICENSE](https://github.com/uber-go/atomic/blob/master/LICENSE.txt)
-- go.uber.org/multierr [MIT LICENSE](https://github.com/uber-go/multierr/blob/master/LICENSE.txt)
-- go.uber.org/zap [MIT LICENSE](https://github.com/uber-go/zap/blob/master/LICENSE.txt)
-- golang.org/x/crypto [BSD LICENSE](https://github.com/golang/crypto/blob/master/LICENSE)
-- golang.org/x/net [BSD LICENSE](https://github.com/golang/net/blob/master/LICENSE)
-- golang.org/x/sys [BSD LICENSE](https://github.com/golang/sys/blob/master/LICENSE)
-- golang.org/x/text [BSD LICENSE](https://github.com/golang/text/blob/master/LICENSE)
-- golang.org/x/time [BSD LICENSE](https://github.com/golang/time/blob/master/LICENSE)
-- jquery 2.1.4 [MIT LICENSE](https://github.com/jquery/jquery/blob/master/LICENSE.txt)
-- github.com/xlab/treeprint [MIT LICENSE](https://github.com/xlab/treeprint/blob/master/LICENSE)
-
-
-
-
-
-
-
-
-
-
-
-
-
-

+ 0 - 638
vendor/github.com/influxdata/influxdb/client/v2/client.go

@@ -1,638 +0,0 @@
-// Package client (v2) is the current official Go client for InfluxDB.
-package client // import "github.com/influxdata/influxdb/client/v2"
-
-import (
-	"bytes"
-	"crypto/tls"
-	"encoding/json"
-	"errors"
-	"fmt"
-	"io"
-	"io/ioutil"
-	"mime"
-	"net/http"
-	"net/url"
-	"path"
-	"strconv"
-	"strings"
-	"time"
-
-	"github.com/influxdata/influxdb/models"
-)
-
-// HTTPConfig is the config data needed to create an HTTP Client.
-type HTTPConfig struct {
-	// Addr should be of the form "http://host:port"
-	// or "http://[ipv6-host%zone]:port".
-	Addr string
-
-	// Username is the influxdb username, optional.
-	Username string
-
-	// Password is the influxdb password, optional.
-	Password string
-
-	// UserAgent is the http User Agent, defaults to "InfluxDBClient".
-	UserAgent string
-
-	// Timeout for influxdb writes, defaults to no timeout.
-	Timeout time.Duration
-
-	// InsecureSkipVerify gets passed to the http client, if true, it will
-	// skip https certificate verification. Defaults to false.
-	InsecureSkipVerify bool
-
-	// TLSConfig allows the user to set their own TLS config for the HTTP
-	// Client. If set, this option overrides InsecureSkipVerify.
-	TLSConfig *tls.Config
-}
-
-// BatchPointsConfig is the config data needed to create an instance of the BatchPoints struct.
-type BatchPointsConfig struct {
-	// Precision is the write precision of the points, defaults to "ns".
-	Precision string
-
-	// Database is the database to write points to.
-	Database string
-
-	// RetentionPolicy is the retention policy of the points.
-	RetentionPolicy string
-
-	// Write consistency is the number of servers required to confirm write.
-	WriteConsistency string
-}
-
-// Client is a client interface for writing & querying the database.
-type Client interface {
-	// Ping checks that status of cluster, and will always return 0 time and no
-	// error for UDP clients.
-	Ping(timeout time.Duration) (time.Duration, string, error)
-
-	// Write takes a BatchPoints object and writes all Points to InfluxDB.
-	Write(bp BatchPoints) error
-
-	// Query makes an InfluxDB Query on the database. This will fail if using
-	// the UDP client.
-	Query(q Query) (*Response, error)
-
-	// Close releases any resources a Client may be using.
-	Close() error
-}
-
-// NewHTTPClient returns a new Client from the provided config.
-// Client is safe for concurrent use by multiple goroutines.
-func NewHTTPClient(conf HTTPConfig) (Client, error) {
-	if conf.UserAgent == "" {
-		conf.UserAgent = "InfluxDBClient"
-	}
-
-	u, err := url.Parse(conf.Addr)
-	if err != nil {
-		return nil, err
-	} else if u.Scheme != "http" && u.Scheme != "https" {
-		m := fmt.Sprintf("Unsupported protocol scheme: %s, your address"+
-			" must start with http:// or https://", u.Scheme)
-		return nil, errors.New(m)
-	}
-
-	tr := &http.Transport{
-		TLSClientConfig: &tls.Config{
-			InsecureSkipVerify: conf.InsecureSkipVerify,
-		},
-	}
-	if conf.TLSConfig != nil {
-		tr.TLSClientConfig = conf.TLSConfig
-	}
-	return &client{
-		url:       *u,
-		username:  conf.Username,
-		password:  conf.Password,
-		useragent: conf.UserAgent,
-		httpClient: &http.Client{
-			Timeout:   conf.Timeout,
-			Transport: tr,
-		},
-		transport: tr,
-	}, nil
-}
-
-// Ping will check to see if the server is up with an optional timeout on waiting for leader.
-// Ping returns how long the request took, the version of the server it connected to, and an error if one occurred.
-func (c *client) Ping(timeout time.Duration) (time.Duration, string, error) {
-	now := time.Now()
-
-	u := c.url
-	u.Path = path.Join(u.Path, "ping")
-
-	req, err := http.NewRequest("GET", u.String(), nil)
-	if err != nil {
-		return 0, "", err
-	}
-
-	req.Header.Set("User-Agent", c.useragent)
-
-	if c.username != "" {
-		req.SetBasicAuth(c.username, c.password)
-	}
-
-	if timeout > 0 {
-		params := req.URL.Query()
-		params.Set("wait_for_leader", fmt.Sprintf("%.0fs", timeout.Seconds()))
-		req.URL.RawQuery = params.Encode()
-	}
-
-	resp, err := c.httpClient.Do(req)
-	if err != nil {
-		return 0, "", err
-	}
-	defer resp.Body.Close()
-
-	body, err := ioutil.ReadAll(resp.Body)
-	if err != nil {
-		return 0, "", err
-	}
-
-	if resp.StatusCode != http.StatusNoContent {
-		var err = fmt.Errorf(string(body))
-		return 0, "", err
-	}
-
-	version := resp.Header.Get("X-Influxdb-Version")
-	return time.Since(now), version, nil
-}
-
-// Close releases the client's resources.
-func (c *client) Close() error {
-	c.transport.CloseIdleConnections()
-	return nil
-}
-
-// client is safe for concurrent use as the fields are all read-only
-// once the client is instantiated.
-type client struct {
-	// N.B - if url.UserInfo is accessed in future modifications to the
-	// methods on client, you will need to synchronize access to url.
-	url        url.URL
-	username   string
-	password   string
-	useragent  string
-	httpClient *http.Client
-	transport  *http.Transport
-}
-
-// BatchPoints is an interface into a batched grouping of points to write into
-// InfluxDB together. BatchPoints is NOT thread-safe, you must create a separate
-// batch for each goroutine.
-type BatchPoints interface {
-	// AddPoint adds the given point to the Batch of points.
-	AddPoint(p *Point)
-	// AddPoints adds the given points to the Batch of points.
-	AddPoints(ps []*Point)
-	// Points lists the points in the Batch.
-	Points() []*Point
-
-	// Precision returns the currently set precision of this Batch.
-	Precision() string
-	// SetPrecision sets the precision of this batch.
-	SetPrecision(s string) error
-
-	// Database returns the currently set database of this Batch.
-	Database() string
-	// SetDatabase sets the database of this Batch.
-	SetDatabase(s string)
-
-	// WriteConsistency returns the currently set write consistency of this Batch.
-	WriteConsistency() string
-	// SetWriteConsistency sets the write consistency of this Batch.
-	SetWriteConsistency(s string)
-
-	// RetentionPolicy returns the currently set retention policy of this Batch.
-	RetentionPolicy() string
-	// SetRetentionPolicy sets the retention policy of this Batch.
-	SetRetentionPolicy(s string)
-}
-
-// NewBatchPoints returns a BatchPoints interface based on the given config.
-func NewBatchPoints(conf BatchPointsConfig) (BatchPoints, error) {
-	if conf.Precision == "" {
-		conf.Precision = "ns"
-	}
-	if _, err := time.ParseDuration("1" + conf.Precision); err != nil {
-		return nil, err
-	}
-	bp := &batchpoints{
-		database:         conf.Database,
-		precision:        conf.Precision,
-		retentionPolicy:  conf.RetentionPolicy,
-		writeConsistency: conf.WriteConsistency,
-	}
-	return bp, nil
-}
-
-type batchpoints struct {
-	points           []*Point
-	database         string
-	precision        string
-	retentionPolicy  string
-	writeConsistency string
-}
-
-func (bp *batchpoints) AddPoint(p *Point) {
-	bp.points = append(bp.points, p)
-}
-
-func (bp *batchpoints) AddPoints(ps []*Point) {
-	bp.points = append(bp.points, ps...)
-}
-
-func (bp *batchpoints) Points() []*Point {
-	return bp.points
-}
-
-func (bp *batchpoints) Precision() string {
-	return bp.precision
-}
-
-func (bp *batchpoints) Database() string {
-	return bp.database
-}
-
-func (bp *batchpoints) WriteConsistency() string {
-	return bp.writeConsistency
-}
-
-func (bp *batchpoints) RetentionPolicy() string {
-	return bp.retentionPolicy
-}
-
-func (bp *batchpoints) SetPrecision(p string) error {
-	if _, err := time.ParseDuration("1" + p); err != nil {
-		return err
-	}
-	bp.precision = p
-	return nil
-}
-
-func (bp *batchpoints) SetDatabase(db string) {
-	bp.database = db
-}
-
-func (bp *batchpoints) SetWriteConsistency(wc string) {
-	bp.writeConsistency = wc
-}
-
-func (bp *batchpoints) SetRetentionPolicy(rp string) {
-	bp.retentionPolicy = rp
-}
-
-// Point represents a single data point.
-type Point struct {
-	pt models.Point
-}
-
-// NewPoint returns a point with the given timestamp. If a timestamp is not
-// given, then data is sent to the database without a timestamp, in which case
-// the server will assign local time upon reception. NOTE: it is recommended to
-// send data with a timestamp.
-func NewPoint(
-	name string,
-	tags map[string]string,
-	fields map[string]interface{},
-	t ...time.Time,
-) (*Point, error) {
-	var T time.Time
-	if len(t) > 0 {
-		T = t[0]
-	}
-
-	pt, err := models.NewPoint(name, models.NewTags(tags), fields, T)
-	if err != nil {
-		return nil, err
-	}
-	return &Point{
-		pt: pt,
-	}, nil
-}
-
-// String returns a line-protocol string of the Point.
-func (p *Point) String() string {
-	return p.pt.String()
-}
-
-// PrecisionString returns a line-protocol string of the Point,
-// with the timestamp formatted for the given precision.
-func (p *Point) PrecisionString(precision string) string {
-	return p.pt.PrecisionString(precision)
-}
-
-// Name returns the measurement name of the point.
-func (p *Point) Name() string {
-	return string(p.pt.Name())
-}
-
-// Tags returns the tags associated with the point.
-func (p *Point) Tags() map[string]string {
-	return p.pt.Tags().Map()
-}
-
-// Time return the timestamp for the point.
-func (p *Point) Time() time.Time {
-	return p.pt.Time()
-}
-
-// UnixNano returns timestamp of the point in nanoseconds since Unix epoch.
-func (p *Point) UnixNano() int64 {
-	return p.pt.UnixNano()
-}
-
-// Fields returns the fields for the point.
-func (p *Point) Fields() (map[string]interface{}, error) {
-	return p.pt.Fields()
-}
-
-// NewPointFrom returns a point from the provided models.Point.
-func NewPointFrom(pt models.Point) *Point {
-	return &Point{pt: pt}
-}
-
-func (c *client) Write(bp BatchPoints) error {
-	var b bytes.Buffer
-
-	for _, p := range bp.Points() {
-		if _, err := b.WriteString(p.pt.PrecisionString(bp.Precision())); err != nil {
-			return err
-		}
-
-		if err := b.WriteByte('\n'); err != nil {
-			return err
-		}
-	}
-
-	u := c.url
-	u.Path = path.Join(u.Path, "write")
-
-	req, err := http.NewRequest("POST", u.String(), &b)
-	if err != nil {
-		return err
-	}
-	req.Header.Set("Content-Type", "")
-	req.Header.Set("User-Agent", c.useragent)
-	if c.username != "" {
-		req.SetBasicAuth(c.username, c.password)
-	}
-
-	params := req.URL.Query()
-	params.Set("db", bp.Database())
-	params.Set("rp", bp.RetentionPolicy())
-	params.Set("precision", bp.Precision())
-	params.Set("consistency", bp.WriteConsistency())
-	req.URL.RawQuery = params.Encode()
-
-	resp, err := c.httpClient.Do(req)
-	if err != nil {
-		return err
-	}
-	defer resp.Body.Close()
-
-	body, err := ioutil.ReadAll(resp.Body)
-	if err != nil {
-		return err
-	}
-
-	if resp.StatusCode != http.StatusNoContent && resp.StatusCode != http.StatusOK {
-		var err = fmt.Errorf(string(body))
-		return err
-	}
-
-	return nil
-}
-
-// Query defines a query to send to the server.
-type Query struct {
-	Command    string
-	Database   string
-	Precision  string
-	Chunked    bool
-	ChunkSize  int
-	Parameters map[string]interface{}
-}
-
-// NewQuery returns a query object.
-// The database and precision arguments can be empty strings if they are not needed for the query.
-func NewQuery(command, database, precision string) Query {
-	return Query{
-		Command:    command,
-		Database:   database,
-		Precision:  precision,
-		Parameters: make(map[string]interface{}),
-	}
-}
-
-// NewQueryWithParameters returns a query object.
-// The database and precision arguments can be empty strings if they are not needed for the query.
-// parameters is a map of the parameter names used in the command to their values.
-func NewQueryWithParameters(command, database, precision string, parameters map[string]interface{}) Query {
-	return Query{
-		Command:    command,
-		Database:   database,
-		Precision:  precision,
-		Parameters: parameters,
-	}
-}
-
-// Response represents a list of statement results.
-type Response struct {
-	Results []Result
-	Err     string `json:"error,omitempty"`
-}
-
-// Error returns the first error from any statement.
-// It returns nil if no errors occurred on any statements.
-func (r *Response) Error() error {
-	if r.Err != "" {
-		return fmt.Errorf(r.Err)
-	}
-	for _, result := range r.Results {
-		if result.Err != "" {
-			return fmt.Errorf(result.Err)
-		}
-	}
-	return nil
-}
-
-// Message represents a user message.
-type Message struct {
-	Level string
-	Text  string
-}
-
-// Result represents a resultset returned from a single statement.
-type Result struct {
-	Series   []models.Row
-	Messages []*Message
-	Err      string `json:"error,omitempty"`
-}
-
-// Query sends a command to the server and returns the Response.
-func (c *client) Query(q Query) (*Response, error) {
-	u := c.url
-	u.Path = path.Join(u.Path, "query")
-
-	jsonParameters, err := json.Marshal(q.Parameters)
-
-	if err != nil {
-		return nil, err
-	}
-
-	req, err := http.NewRequest("POST", u.String(), nil)
-	if err != nil {
-		return nil, err
-	}
-
-	req.Header.Set("Content-Type", "")
-	req.Header.Set("User-Agent", c.useragent)
-
-	if c.username != "" {
-		req.SetBasicAuth(c.username, c.password)
-	}
-
-	params := req.URL.Query()
-	params.Set("q", q.Command)
-	params.Set("db", q.Database)
-	params.Set("params", string(jsonParameters))
-	if q.Chunked {
-		params.Set("chunked", "true")
-		if q.ChunkSize > 0 {
-			params.Set("chunk_size", strconv.Itoa(q.ChunkSize))
-		}
-	}
-
-	if q.Precision != "" {
-		params.Set("epoch", q.Precision)
-	}
-	req.URL.RawQuery = params.Encode()
-
-	resp, err := c.httpClient.Do(req)
-	if err != nil {
-		return nil, err
-	}
-	defer resp.Body.Close()
-
-	// If we lack a X-Influxdb-Version header, then we didn't get a response from influxdb
-	// but instead some other service. If the error code is also a 500+ code, then some
-	// downstream loadbalancer/proxy/etc had an issue and we should report that.
-	if resp.Header.Get("X-Influxdb-Version") == "" && resp.StatusCode >= http.StatusInternalServerError {
-		body, err := ioutil.ReadAll(resp.Body)
-		if err != nil || len(body) == 0 {
-			return nil, fmt.Errorf("received status code %d from downstream server", resp.StatusCode)
-		}
-
-		return nil, fmt.Errorf("received status code %d from downstream server, with response body: %q", resp.StatusCode, body)
-	}
-
-	// If we get an unexpected content type, then it is also not from influx direct and therefore
-	// we want to know what we received and what status code was returned for debugging purposes.
-	if cType, _, _ := mime.ParseMediaType(resp.Header.Get("Content-Type")); cType != "application/json" {
-		// Read up to 1kb of the body to help identify downstream errors and limit the impact of things
-		// like downstream serving a large file
-		body, err := ioutil.ReadAll(io.LimitReader(resp.Body, 1024))
-		if err != nil || len(body) == 0 {
-			return nil, fmt.Errorf("expected json response, got empty body, with status: %v", resp.StatusCode)
-		}
-
-		return nil, fmt.Errorf("expected json response, got %q, with status: %v and response body: %q", cType, resp.StatusCode, body)
-	}
-
-	var response Response
-	if q.Chunked {
-		cr := NewChunkedResponse(resp.Body)
-		for {
-			r, err := cr.NextResponse()
-			if err != nil {
-				// If we got an error while decoding the response, send that back.
-				return nil, err
-			}
-
-			if r == nil {
-				break
-			}
-
-			response.Results = append(response.Results, r.Results...)
-			if r.Err != "" {
-				response.Err = r.Err
-				break
-			}
-		}
-	} else {
-		dec := json.NewDecoder(resp.Body)
-		dec.UseNumber()
-		decErr := dec.Decode(&response)
-
-		// ignore this error if we got an invalid status code
-		if decErr != nil && decErr.Error() == "EOF" && resp.StatusCode != http.StatusOK {
-			decErr = nil
-		}
-		// If we got a valid decode error, send that back
-		if decErr != nil {
-			return nil, fmt.Errorf("unable to decode json: received status code %d err: %s", resp.StatusCode, decErr)
-		}
-	}
-
-	// If we don't have an error in our json response, and didn't get statusOK
-	// then send back an error
-	if resp.StatusCode != http.StatusOK && response.Error() == nil {
-		return &response, fmt.Errorf("received status code %d from server", resp.StatusCode)
-	}
-	return &response, nil
-}
-
-// duplexReader reads responses and writes it to another writer while
-// satisfying the reader interface.
-type duplexReader struct {
-	r io.Reader
-	w io.Writer
-}
-
-func (r *duplexReader) Read(p []byte) (n int, err error) {
-	n, err = r.r.Read(p)
-	if err == nil {
-		r.w.Write(p[:n])
-	}
-	return n, err
-}
-
-// ChunkedResponse represents a response from the server that
-// uses chunking to stream the output.
-type ChunkedResponse struct {
-	dec    *json.Decoder
-	duplex *duplexReader
-	buf    bytes.Buffer
-}
-
-// NewChunkedResponse reads a stream and produces responses from the stream.
-func NewChunkedResponse(r io.Reader) *ChunkedResponse {
-	resp := &ChunkedResponse{}
-	resp.duplex = &duplexReader{r: r, w: &resp.buf}
-	resp.dec = json.NewDecoder(resp.duplex)
-	resp.dec.UseNumber()
-	return resp
-}
-
-// NextResponse reads the next line of the stream and returns a response.
-func (r *ChunkedResponse) NextResponse() (*Response, error) {
-	var response Response
-
-	if err := r.dec.Decode(&response); err != nil {
-		if err == io.EOF {
-			return nil, nil
-		}
-		// A decoding error happened. This probably means the server crashed
-		// and sent a last-ditch error message to us. Ensure we have read the
-		// entirety of the connection to get any remaining error text.
-		io.Copy(ioutil.Discard, r.duplex)
-		return nil, errors.New(strings.TrimSpace(r.buf.String()))
-	}
-
-	r.buf.Reset()
-	return &response, nil
-}

+ 0 - 112
vendor/github.com/influxdata/influxdb/client/v2/udp.go

@@ -1,112 +0,0 @@
-package client
-
-import (
-	"fmt"
-	"io"
-	"net"
-	"time"
-)
-
-const (
-	// UDPPayloadSize is a reasonable default payload size for UDP packets that
-	// could be travelling over the internet.
-	UDPPayloadSize = 512
-)
-
-// UDPConfig is the config data needed to create a UDP Client.
-type UDPConfig struct {
-	// Addr should be of the form "host:port"
-	// or "[ipv6-host%zone]:port".
-	Addr string
-
-	// PayloadSize is the maximum size of a UDP client message, optional
-	// Tune this based on your network. Defaults to UDPPayloadSize.
-	PayloadSize int
-}
-
-// NewUDPClient returns a client interface for writing to an InfluxDB UDP
-// service from the given config.
-func NewUDPClient(conf UDPConfig) (Client, error) {
-	var udpAddr *net.UDPAddr
-	udpAddr, err := net.ResolveUDPAddr("udp", conf.Addr)
-	if err != nil {
-		return nil, err
-	}
-
-	conn, err := net.DialUDP("udp", nil, udpAddr)
-	if err != nil {
-		return nil, err
-	}
-
-	payloadSize := conf.PayloadSize
-	if payloadSize == 0 {
-		payloadSize = UDPPayloadSize
-	}
-
-	return &udpclient{
-		conn:        conn,
-		payloadSize: payloadSize,
-	}, nil
-}
-
-// Close releases the udpclient's resources.
-func (uc *udpclient) Close() error {
-	return uc.conn.Close()
-}
-
-type udpclient struct {
-	conn        io.WriteCloser
-	payloadSize int
-}
-
-func (uc *udpclient) Write(bp BatchPoints) error {
-	var b = make([]byte, 0, uc.payloadSize) // initial buffer size, it will grow as needed
-	var d, _ = time.ParseDuration("1" + bp.Precision())
-
-	var delayedError error
-
-	var checkBuffer = func(n int) {
-		if len(b) > 0 && len(b)+n > uc.payloadSize {
-			if _, err := uc.conn.Write(b); err != nil {
-				delayedError = err
-			}
-			b = b[:0]
-		}
-	}
-
-	for _, p := range bp.Points() {
-		p.pt.Round(d)
-		pointSize := p.pt.StringSize() + 1 // include newline in size
-		//point := p.pt.RoundedString(d) + "\n"
-
-		checkBuffer(pointSize)
-
-		if p.Time().IsZero() || pointSize <= uc.payloadSize {
-			b = p.pt.AppendString(b)
-			b = append(b, '\n')
-			continue
-		}
-
-		points := p.pt.Split(uc.payloadSize - 1) // account for newline character
-		for _, sp := range points {
-			checkBuffer(sp.StringSize() + 1)
-			b = sp.AppendString(b)
-			b = append(b, '\n')
-		}
-	}
-
-	if len(b) > 0 {
-		if _, err := uc.conn.Write(b); err != nil {
-			return err
-		}
-	}
-	return delayedError
-}
-
-func (uc *udpclient) Query(q Query) (*Response, error) {
-	return nil, fmt.Errorf("Querying via UDP is not supported")
-}
-
-func (uc *udpclient) Ping(timeout time.Duration) (time.Duration, string, error) {
-	return 0, "", nil
-}

+ 0 - 48
vendor/github.com/influxdata/influxdb/models/consistency.go

@@ -1,48 +0,0 @@
-package models
-
-import (
-	"errors"
-	"strings"
-)
-
-// ConsistencyLevel represent a required replication criteria before a write can
-// be returned as successful.
-//
-// The consistency level is handled in open-source InfluxDB but only applicable to clusters.
-type ConsistencyLevel int
-
-const (
-	// ConsistencyLevelAny allows for hinted handoff, potentially no write happened yet.
-	ConsistencyLevelAny ConsistencyLevel = iota
-
-	// ConsistencyLevelOne requires at least one data node acknowledged a write.
-	ConsistencyLevelOne
-
-	// ConsistencyLevelQuorum requires a quorum of data nodes to acknowledge a write.
-	ConsistencyLevelQuorum
-
-	// ConsistencyLevelAll requires all data nodes to acknowledge a write.
-	ConsistencyLevelAll
-)
-
-var (
-	// ErrInvalidConsistencyLevel is returned when parsing the string version
-	// of a consistency level.
-	ErrInvalidConsistencyLevel = errors.New("invalid consistency level")
-)
-
-// ParseConsistencyLevel converts a consistency level string to the corresponding ConsistencyLevel const.
-func ParseConsistencyLevel(level string) (ConsistencyLevel, error) {
-	switch strings.ToLower(level) {
-	case "any":
-		return ConsistencyLevelAny, nil
-	case "one":
-		return ConsistencyLevelOne, nil
-	case "quorum":
-		return ConsistencyLevelQuorum, nil
-	case "all":
-		return ConsistencyLevelAll, nil
-	default:
-		return 0, ErrInvalidConsistencyLevel
-	}
-}

+ 0 - 32
vendor/github.com/influxdata/influxdb/models/inline_fnv.go

@@ -1,32 +0,0 @@
-package models // import "github.com/influxdata/influxdb/models"
-
-// from stdlib hash/fnv/fnv.go
-const (
-	prime64  = 1099511628211
-	offset64 = 14695981039346656037
-)
-
-// InlineFNV64a is an alloc-free port of the standard library's fnv64a.
-// See https://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function.
-type InlineFNV64a uint64
-
-// NewInlineFNV64a returns a new instance of InlineFNV64a.
-func NewInlineFNV64a() InlineFNV64a {
-	return offset64
-}
-
-// Write adds data to the running hash.
-func (s *InlineFNV64a) Write(data []byte) (int, error) {
-	hash := uint64(*s)
-	for _, c := range data {
-		hash ^= uint64(c)
-		hash *= prime64
-	}
-	*s = InlineFNV64a(hash)
-	return len(data), nil
-}
-
-// Sum64 returns the uint64 of the current resulting hash.
-func (s *InlineFNV64a) Sum64() uint64 {
-	return uint64(*s)
-}

+ 0 - 44
vendor/github.com/influxdata/influxdb/models/inline_strconv_parse.go

@@ -1,44 +0,0 @@
-package models // import "github.com/influxdata/influxdb/models"
-
-import (
-	"reflect"
-	"strconv"
-	"unsafe"
-)
-
-// parseIntBytes is a zero-alloc wrapper around strconv.ParseInt.
-func parseIntBytes(b []byte, base int, bitSize int) (i int64, err error) {
-	s := unsafeBytesToString(b)
-	return strconv.ParseInt(s, base, bitSize)
-}
-
-// parseUintBytes is a zero-alloc wrapper around strconv.ParseUint.
-func parseUintBytes(b []byte, base int, bitSize int) (i uint64, err error) {
-	s := unsafeBytesToString(b)
-	return strconv.ParseUint(s, base, bitSize)
-}
-
-// parseFloatBytes is a zero-alloc wrapper around strconv.ParseFloat.
-func parseFloatBytes(b []byte, bitSize int) (float64, error) {
-	s := unsafeBytesToString(b)
-	return strconv.ParseFloat(s, bitSize)
-}
-
-// parseBoolBytes is a zero-alloc wrapper around strconv.ParseBool.
-func parseBoolBytes(b []byte) (bool, error) {
-	return strconv.ParseBool(unsafeBytesToString(b))
-}
-
-// unsafeBytesToString converts a []byte to a string without a heap allocation.
-//
-// It is unsafe, and is intended to prepare input to short-lived functions
-// that require strings.
-func unsafeBytesToString(in []byte) string {
-	src := *(*reflect.SliceHeader)(unsafe.Pointer(&in))
-	dst := reflect.StringHeader{
-		Data: src.Data,
-		Len:  src.Len,
-	}
-	s := *(*string)(unsafe.Pointer(&dst))
-	return s
-}

+ 0 - 2328
vendor/github.com/influxdata/influxdb/models/points.go

@@ -1,2328 +0,0 @@
-// Package models implements basic objects used throughout the TICK stack.
-package models // import "github.com/influxdata/influxdb/models"
-
-import (
-	"bytes"
-	"encoding/binary"
-	"errors"
-	"fmt"
-	"io"
-	"math"
-	"sort"
-	"strconv"
-	"strings"
-	"time"
-
-	"github.com/influxdata/influxdb/pkg/escape"
-)
-
-var (
-	measurementEscapeCodes = map[byte][]byte{
-		',': []byte(`\,`),
-		' ': []byte(`\ `),
-	}
-
-	tagEscapeCodes = map[byte][]byte{
-		',': []byte(`\,`),
-		' ': []byte(`\ `),
-		'=': []byte(`\=`),
-	}
-
-	// ErrPointMustHaveAField is returned when operating on a point that does not have any fields.
-	ErrPointMustHaveAField = errors.New("point without fields is unsupported")
-
-	// ErrInvalidNumber is returned when a number is expected but not provided.
-	ErrInvalidNumber = errors.New("invalid number")
-
-	// ErrInvalidPoint is returned when a point cannot be parsed correctly.
-	ErrInvalidPoint = errors.New("point is invalid")
-)
-
-const (
-	// MaxKeyLength is the largest allowed size of the combined measurement and tag keys.
-	MaxKeyLength = 65535
-)
-
-// enableUint64Support will enable uint64 support if set to true.
-var enableUint64Support = false
-
-// EnableUintSupport manually enables uint support for the point parser.
-// This function will be removed in the future and only exists for unit tests during the
-// transition.
-func EnableUintSupport() {
-	enableUint64Support = true
-}
-
-// Point defines the values that will be written to the database.
-type Point interface {
-	// Name return the measurement name for the point.
-	Name() []byte
-
-	// SetName updates the measurement name for the point.
-	SetName(string)
-
-	// Tags returns the tag set for the point.
-	Tags() Tags
-
-	// AddTag adds or replaces a tag value for a point.
-	AddTag(key, value string)
-
-	// SetTags replaces the tags for the point.
-	SetTags(tags Tags)
-
-	// HasTag returns true if the tag exists for the point.
-	HasTag(tag []byte) bool
-
-	// Fields returns the fields for the point.
-	Fields() (Fields, error)
-
-	// Time return the timestamp for the point.
-	Time() time.Time
-
-	// SetTime updates the timestamp for the point.
-	SetTime(t time.Time)
-
-	// UnixNano returns the timestamp of the point as nanoseconds since Unix epoch.
-	UnixNano() int64
-
-	// HashID returns a non-cryptographic checksum of the point's key.
-	HashID() uint64
-
-	// Key returns the key (measurement joined with tags) of the point.
-	Key() []byte
-
-	// String returns a string representation of the point. If there is a
-	// timestamp associated with the point then it will be specified with the default
-	// precision of nanoseconds.
-	String() string
-
-	// MarshalBinary returns a binary representation of the point.
-	MarshalBinary() ([]byte, error)
-
-	// PrecisionString returns a string representation of the point. If there
-	// is a timestamp associated with the point then it will be specified in the
-	// given unit.
-	PrecisionString(precision string) string
-
-	// RoundedString returns a string representation of the point. If there
-	// is a timestamp associated with the point, then it will be rounded to the
-	// given duration.
-	RoundedString(d time.Duration) string
-
-	// Split will attempt to return multiple points with the same timestamp whose
-	// string representations are no longer than size. Points with a single field or
-	// a point without a timestamp may exceed the requested size.
-	Split(size int) []Point
-
-	// Round will round the timestamp of the point to the given duration.
-	Round(d time.Duration)
-
-	// StringSize returns the length of the string that would be returned by String().
-	StringSize() int
-
-	// AppendString appends the result of String() to the provided buffer and returns
-	// the result, potentially reducing string allocations.
-	AppendString(buf []byte) []byte
-
-	// FieldIterator retuns a FieldIterator that can be used to traverse the
-	// fields of a point without constructing the in-memory map.
-	FieldIterator() FieldIterator
-}
-
-// FieldType represents the type of a field.
-type FieldType int
-
-const (
-	// Integer indicates the field's type is integer.
-	Integer FieldType = iota
-
-	// Float indicates the field's type is float.
-	Float
-
-	// Boolean indicates the field's type is boolean.
-	Boolean
-
-	// String indicates the field's type is string.
-	String
-
-	// Empty is used to indicate that there is no field.
-	Empty
-
-	// Unsigned indicates the field's type is an unsigned integer.
-	Unsigned
-)
-
-// FieldIterator provides a low-allocation interface to iterate through a point's fields.
-type FieldIterator interface {
-	// Next indicates whether there any fields remaining.
-	Next() bool
-
-	// FieldKey returns the key of the current field.
-	FieldKey() []byte
-
-	// Type returns the FieldType of the current field.
-	Type() FieldType
-
-	// StringValue returns the string value of the current field.
-	StringValue() string
-
-	// IntegerValue returns the integer value of the current field.
-	IntegerValue() (int64, error)
-
-	// UnsignedValue returns the unsigned value of the current field.
-	UnsignedValue() (uint64, error)
-
-	// BooleanValue returns the boolean value of the current field.
-	BooleanValue() (bool, error)
-
-	// FloatValue returns the float value of the current field.
-	FloatValue() (float64, error)
-
-	// Reset resets the iterator to its initial state.
-	Reset()
-}
-
-// Points represents a sortable list of points by timestamp.
-type Points []Point
-
-// Len implements sort.Interface.
-func (a Points) Len() int { return len(a) }
-
-// Less implements sort.Interface.
-func (a Points) Less(i, j int) bool { return a[i].Time().Before(a[j].Time()) }
-
-// Swap implements sort.Interface.
-func (a Points) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
-
-// point is the default implementation of Point.
-type point struct {
-	time time.Time
-
-	// text encoding of measurement and tags
-	// key must always be stored sorted by tags, if the original line was not sorted,
-	// we need to resort it
-	key []byte
-
-	// text encoding of field data
-	fields []byte
-
-	// text encoding of timestamp
-	ts []byte
-
-	// cached version of parsed fields from data
-	cachedFields map[string]interface{}
-
-	// cached version of parsed name from key
-	cachedName string
-
-	// cached version of parsed tags
-	cachedTags Tags
-
-	it fieldIterator
-}
-
-// type assertions
-var (
-	_ Point         = (*point)(nil)
-	_ FieldIterator = (*point)(nil)
-)
-
-const (
-	// the number of characters for the largest possible int64 (9223372036854775807)
-	maxInt64Digits = 19
-
-	// the number of characters for the smallest possible int64 (-9223372036854775808)
-	minInt64Digits = 20
-
-	// the number of characters for the largest possible uint64 (18446744073709551615)
-	maxUint64Digits = 20
-
-	// the number of characters required for the largest float64 before a range check
-	// would occur during parsing
-	maxFloat64Digits = 25
-
-	// the number of characters required for smallest float64 before a range check occur
-	// would occur during parsing
-	minFloat64Digits = 27
-)
-
-// ParsePoints returns a slice of Points from a text representation of a point
-// with each point separated by newlines.  If any points fail to parse, a non-nil error
-// will be returned in addition to the points that parsed successfully.
-func ParsePoints(buf []byte) ([]Point, error) {
-	return ParsePointsWithPrecision(buf, time.Now().UTC(), "n")
-}
-
-// ParsePointsString is identical to ParsePoints but accepts a string.
-func ParsePointsString(buf string) ([]Point, error) {
-	return ParsePoints([]byte(buf))
-}
-
-// ParseKey returns the measurement name and tags from a point.
-//
-// NOTE: to minimize heap allocations, the returned Tags will refer to subslices of buf.
-// This can have the unintended effect preventing buf from being garbage collected.
-func ParseKey(buf []byte) (string, Tags) {
-	meas, tags := ParseKeyBytes(buf)
-	return string(meas), tags
-}
-
-func ParseKeyBytes(buf []byte) ([]byte, Tags) {
-	// Ignore the error because scanMeasurement returns "missing fields" which we ignore
-	// when just parsing a key
-	state, i, _ := scanMeasurement(buf, 0)
-
-	var tags Tags
-	if state == tagKeyState {
-		tags = parseTags(buf)
-		// scanMeasurement returns the location of the comma if there are tags, strip that off
-		return buf[:i-1], tags
-	}
-	return buf[:i], tags
-}
-
-func ParseTags(buf []byte) Tags {
-	return parseTags(buf)
-}
-
-func ParseName(buf []byte) ([]byte, error) {
-	// Ignore the error because scanMeasurement returns "missing fields" which we ignore
-	// when just parsing a key
-	state, i, _ := scanMeasurement(buf, 0)
-	if state == tagKeyState {
-		return buf[:i-1], nil
-	}
-	return buf[:i], nil
-}
-
-// ParsePointsWithPrecision is similar to ParsePoints, but allows the
-// caller to provide a precision for time.
-//
-// NOTE: to minimize heap allocations, the returned Points will refer to subslices of buf.
-// This can have the unintended effect preventing buf from being garbage collected.
-func ParsePointsWithPrecision(buf []byte, defaultTime time.Time, precision string) ([]Point, error) {
-	points := make([]Point, 0, bytes.Count(buf, []byte{'\n'})+1)
-	var (
-		pos    int
-		block  []byte
-		failed []string
-	)
-	for pos < len(buf) {
-		pos, block = scanLine(buf, pos)
-		pos++
-
-		if len(block) == 0 {
-			continue
-		}
-
-		// lines which start with '#' are comments
-		start := skipWhitespace(block, 0)
-
-		// If line is all whitespace, just skip it
-		if start >= len(block) {
-			continue
-		}
-
-		if block[start] == '#' {
-			continue
-		}
-
-		// strip the newline if one is present
-		if block[len(block)-1] == '\n' {
-			block = block[:len(block)-1]
-		}
-
-		pt, err := parsePoint(block[start:], defaultTime, precision)
-		if err != nil {
-			failed = append(failed, fmt.Sprintf("unable to parse '%s': %v", string(block[start:]), err))
-		} else {
-			points = append(points, pt)
-		}
-
-	}
-	if len(failed) > 0 {
-		return points, fmt.Errorf("%s", strings.Join(failed, "\n"))
-	}
-	return points, nil
-
-}
-
-func parsePoint(buf []byte, defaultTime time.Time, precision string) (Point, error) {
-	// scan the first block which is measurement[,tag1=value1,tag2=value=2...]
-	pos, key, err := scanKey(buf, 0)
-	if err != nil {
-		return nil, err
-	}
-
-	// measurement name is required
-	if len(key) == 0 {
-		return nil, fmt.Errorf("missing measurement")
-	}
-
-	if len(key) > MaxKeyLength {
-		return nil, fmt.Errorf("max key length exceeded: %v > %v", len(key), MaxKeyLength)
-	}
-
-	// scan the second block is which is field1=value1[,field2=value2,...]
-	pos, fields, err := scanFields(buf, pos)
-	if err != nil {
-		return nil, err
-	}
-
-	// at least one field is required
-	if len(fields) == 0 {
-		return nil, fmt.Errorf("missing fields")
-	}
-
-	var maxKeyErr error
-	walkFields(fields, func(k, v []byte) bool {
-		if sz := seriesKeySize(key, k); sz > MaxKeyLength {
-			maxKeyErr = fmt.Errorf("max key length exceeded: %v > %v", sz, MaxKeyLength)
-			return false
-		}
-		return true
-	})
-
-	if maxKeyErr != nil {
-		return nil, maxKeyErr
-	}
-
-	// scan the last block which is an optional integer timestamp
-	pos, ts, err := scanTime(buf, pos)
-	if err != nil {
-		return nil, err
-	}
-
-	pt := &point{
-		key:    key,
-		fields: fields,
-		ts:     ts,
-	}
-
-	if len(ts) == 0 {
-		pt.time = defaultTime
-		pt.SetPrecision(precision)
-	} else {
-		ts, err := parseIntBytes(ts, 10, 64)
-		if err != nil {
-			return nil, err
-		}
-		pt.time, err = SafeCalcTime(ts, precision)
-		if err != nil {
-			return nil, err
-		}
-
-		// Determine if there are illegal non-whitespace characters after the
-		// timestamp block.
-		for pos < len(buf) {
-			if buf[pos] != ' ' {
-				return nil, ErrInvalidPoint
-			}
-			pos++
-		}
-	}
-	return pt, nil
-}
-
-// GetPrecisionMultiplier will return a multiplier for the precision specified.
-func GetPrecisionMultiplier(precision string) int64 {
-	d := time.Nanosecond
-	switch precision {
-	case "u":
-		d = time.Microsecond
-	case "ms":
-		d = time.Millisecond
-	case "s":
-		d = time.Second
-	case "m":
-		d = time.Minute
-	case "h":
-		d = time.Hour
-	}
-	return int64(d)
-}
-
-// scanKey scans buf starting at i for the measurement and tag portion of the point.
-// It returns the ending position and the byte slice of key within buf.  If there
-// are tags, they will be sorted if they are not already.
-func scanKey(buf []byte, i int) (int, []byte, error) {
-	start := skipWhitespace(buf, i)
-
-	i = start
-
-	// Determines whether the tags are sort, assume they are
-	sorted := true
-
-	// indices holds the indexes within buf of the start of each tag.  For example,
-	// a buf of 'cpu,host=a,region=b,zone=c' would have indices slice of [4,11,20]
-	// which indicates that the first tag starts at buf[4], seconds at buf[11], and
-	// last at buf[20]
-	indices := make([]int, 100)
-
-	// tracks how many commas we've seen so we know how many values are indices.
-	// Since indices is an arbitrarily large slice,
-	// we need to know how many values in the buffer are in use.
-	commas := 0
-
-	// First scan the Point's measurement.
-	state, i, err := scanMeasurement(buf, i)
-	if err != nil {
-		return i, buf[start:i], err
-	}
-
-	// Optionally scan tags if needed.
-	if state == tagKeyState {
-		i, commas, indices, err = scanTags(buf, i, indices)
-		if err != nil {
-			return i, buf[start:i], err
-		}
-	}
-
-	// Now we know where the key region is within buf, and the location of tags, we
-	// need to determine if duplicate tags exist and if the tags are sorted. This iterates
-	// over the list comparing each tag in the sequence with each other.
-	for j := 0; j < commas-1; j++ {
-		// get the left and right tags
-		_, left := scanTo(buf[indices[j]:indices[j+1]-1], 0, '=')
-		_, right := scanTo(buf[indices[j+1]:indices[j+2]-1], 0, '=')
-
-		// If left is greater than right, the tags are not sorted. We do not have to
-		// continue because the short path no longer works.
-		// If the tags are equal, then there are duplicate tags, and we should abort.
-		// If the tags are not sorted, this pass may not find duplicate tags and we
-		// need to do a more exhaustive search later.
-		if cmp := bytes.Compare(left, right); cmp > 0 {
-			sorted = false
-			break
-		} else if cmp == 0 {
-			return i, buf[start:i], fmt.Errorf("duplicate tags")
-		}
-	}
-
-	// If the tags are not sorted, then sort them.  This sort is inline and
-	// uses the tag indices we created earlier.  The actual buffer is not sorted, the
-	// indices are using the buffer for value comparison.  After the indices are sorted,
-	// the buffer is reconstructed from the sorted indices.
-	if !sorted && commas > 0 {
-		// Get the measurement name for later
-		measurement := buf[start : indices[0]-1]
-
-		// Sort the indices
-		indices := indices[:commas]
-		insertionSort(0, commas, buf, indices)
-
-		// Create a new key using the measurement and sorted indices
-		b := make([]byte, len(buf[start:i]))
-		pos := copy(b, measurement)
-		for _, i := range indices {
-			b[pos] = ','
-			pos++
-			_, v := scanToSpaceOr(buf, i, ',')
-			pos += copy(b[pos:], v)
-		}
-
-		// Check again for duplicate tags now that the tags are sorted.
-		for j := 0; j < commas-1; j++ {
-			// get the left and right tags
-			_, left := scanTo(buf[indices[j]:], 0, '=')
-			_, right := scanTo(buf[indices[j+1]:], 0, '=')
-
-			// If the tags are equal, then there are duplicate tags, and we should abort.
-			// If the tags are not sorted, this pass may not find duplicate tags and we
-			// need to do a more exhaustive search later.
-			if bytes.Equal(left, right) {
-				return i, b, fmt.Errorf("duplicate tags")
-			}
-		}
-
-		return i, b, nil
-	}
-
-	return i, buf[start:i], nil
-}
-
-// The following constants allow us to specify which state to move to
-// next, when scanning sections of a Point.
-const (
-	tagKeyState = iota
-	tagValueState
-	fieldsState
-)
-
-// scanMeasurement examines the measurement part of a Point, returning
-// the next state to move to, and the current location in the buffer.
-func scanMeasurement(buf []byte, i int) (int, int, error) {
-	// Check first byte of measurement, anything except a comma is fine.
-	// It can't be a space, since whitespace is stripped prior to this
-	// function call.
-	if i >= len(buf) || buf[i] == ',' {
-		return -1, i, fmt.Errorf("missing measurement")
-	}
-
-	for {
-		i++
-		if i >= len(buf) {
-			// cpu
-			return -1, i, fmt.Errorf("missing fields")
-		}
-
-		if buf[i-1] == '\\' {
-			// Skip character (it's escaped).
-			continue
-		}
-
-		// Unescaped comma; move onto scanning the tags.
-		if buf[i] == ',' {
-			return tagKeyState, i + 1, nil
-		}
-
-		// Unescaped space; move onto scanning the fields.
-		if buf[i] == ' ' {
-			// cpu value=1.0
-			return fieldsState, i, nil
-		}
-	}
-}
-
-// scanTags examines all the tags in a Point, keeping track of and
-// returning the updated indices slice, number of commas and location
-// in buf where to start examining the Point fields.
-func scanTags(buf []byte, i int, indices []int) (int, int, []int, error) {
-	var (
-		err    error
-		commas int
-		state  = tagKeyState
-	)
-
-	for {
-		switch state {
-		case tagKeyState:
-			// Grow our indices slice if we have too many tags.
-			if commas >= len(indices) {
-				newIndics := make([]int, cap(indices)*2)
-				copy(newIndics, indices)
-				indices = newIndics
-			}
-			indices[commas] = i
-			commas++
-
-			i, err = scanTagsKey(buf, i)
-			state = tagValueState // tag value always follows a tag key
-		case tagValueState:
-			state, i, err = scanTagsValue(buf, i)
-		case fieldsState:
-			indices[commas] = i + 1
-			return i, commas, indices, nil
-		}
-
-		if err != nil {
-			return i, commas, indices, err
-		}
-	}
-}
-
-// scanTagsKey scans each character in a tag key.
-func scanTagsKey(buf []byte, i int) (int, error) {
-	// First character of the key.
-	if i >= len(buf) || buf[i] == ' ' || buf[i] == ',' || buf[i] == '=' {
-		// cpu,{'', ' ', ',', '='}
-		return i, fmt.Errorf("missing tag key")
-	}
-
-	// Examine each character in the tag key until we hit an unescaped
-	// equals (the tag value), or we hit an error (i.e., unescaped
-	// space or comma).
-	for {
-		i++
-
-		// Either we reached the end of the buffer or we hit an
-		// unescaped comma or space.
-		if i >= len(buf) ||
-			((buf[i] == ' ' || buf[i] == ',') && buf[i-1] != '\\') {
-			// cpu,tag{'', ' ', ','}
-			return i, fmt.Errorf("missing tag value")
-		}
-
-		if buf[i] == '=' && buf[i-1] != '\\' {
-			// cpu,tag=
-			return i + 1, nil
-		}
-	}
-}
-
-// scanTagsValue scans each character in a tag value.
-func scanTagsValue(buf []byte, i int) (int, int, error) {
-	// Tag value cannot be empty.
-	if i >= len(buf) || buf[i] == ',' || buf[i] == ' ' {
-		// cpu,tag={',', ' '}
-		return -1, i, fmt.Errorf("missing tag value")
-	}
-
-	// Examine each character in the tag value until we hit an unescaped
-	// comma (move onto next tag key), an unescaped space (move onto
-	// fields), or we error out.
-	for {
-		i++
-		if i >= len(buf) {
-			// cpu,tag=value
-			return -1, i, fmt.Errorf("missing fields")
-		}
-
-		// An unescaped equals sign is an invalid tag value.
-		if buf[i] == '=' && buf[i-1] != '\\' {
-			// cpu,tag={'=', 'fo=o'}
-			return -1, i, fmt.Errorf("invalid tag format")
-		}
-
-		if buf[i] == ',' && buf[i-1] != '\\' {
-			// cpu,tag=foo,
-			return tagKeyState, i + 1, nil
-		}
-
-		// cpu,tag=foo value=1.0
-		// cpu, tag=foo\= value=1.0
-		if buf[i] == ' ' && buf[i-1] != '\\' {
-			return fieldsState, i, nil
-		}
-	}
-}
-
-func insertionSort(l, r int, buf []byte, indices []int) {
-	for i := l + 1; i < r; i++ {
-		for j := i; j > l && less(buf, indices, j, j-1); j-- {
-			indices[j], indices[j-1] = indices[j-1], indices[j]
-		}
-	}
-}
-
-func less(buf []byte, indices []int, i, j int) bool {
-	// This grabs the tag names for i & j, it ignores the values
-	_, a := scanTo(buf, indices[i], '=')
-	_, b := scanTo(buf, indices[j], '=')
-	return bytes.Compare(a, b) < 0
-}
-
-// scanFields scans buf, starting at i for the fields section of a point.  It returns
-// the ending position and the byte slice of the fields within buf.
-func scanFields(buf []byte, i int) (int, []byte, error) {
-	start := skipWhitespace(buf, i)
-	i = start
-	quoted := false
-
-	// tracks how many '=' we've seen
-	equals := 0
-
-	// tracks how many commas we've seen
-	commas := 0
-
-	for {
-		// reached the end of buf?
-		if i >= len(buf) {
-			break
-		}
-
-		// escaped characters?
-		if buf[i] == '\\' && i+1 < len(buf) {
-			i += 2
-			continue
-		}
-
-		// If the value is quoted, scan until we get to the end quote
-		// Only quote values in the field value since quotes are not significant
-		// in the field key
-		if buf[i] == '"' && equals > commas {
-			quoted = !quoted
-			i++
-			continue
-		}
-
-		// If we see an =, ensure that there is at least on char before and after it
-		if buf[i] == '=' && !quoted {
-			equals++
-
-			// check for "... =123" but allow "a\ =123"
-			if buf[i-1] == ' ' && buf[i-2] != '\\' {
-				return i, buf[start:i], fmt.Errorf("missing field key")
-			}
-
-			// check for "...a=123,=456" but allow "a=123,a\,=456"
-			if buf[i-1] == ',' && buf[i-2] != '\\' {
-				return i, buf[start:i], fmt.Errorf("missing field key")
-			}
-
-			// check for "... value="
-			if i+1 >= len(buf) {
-				return i, buf[start:i], fmt.Errorf("missing field value")
-			}
-
-			// check for "... value=,value2=..."
-			if buf[i+1] == ',' || buf[i+1] == ' ' {
-				return i, buf[start:i], fmt.Errorf("missing field value")
-			}
-
-			if isNumeric(buf[i+1]) || buf[i+1] == '-' || buf[i+1] == 'N' || buf[i+1] == 'n' {
-				var err error
-				i, err = scanNumber(buf, i+1)
-				if err != nil {
-					return i, buf[start:i], err
-				}
-				continue
-			}
-			// If next byte is not a double-quote, the value must be a boolean
-			if buf[i+1] != '"' {
-				var err error
-				i, _, err = scanBoolean(buf, i+1)
-				if err != nil {
-					return i, buf[start:i], err
-				}
-				continue
-			}
-		}
-
-		if buf[i] == ',' && !quoted {
-			commas++
-		}
-
-		// reached end of block?
-		if buf[i] == ' ' && !quoted {
-			break
-		}
-		i++
-	}
-
-	if quoted {
-		return i, buf[start:i], fmt.Errorf("unbalanced quotes")
-	}
-
-	// check that all field sections had key and values (e.g. prevent "a=1,b"
-	if equals == 0 || commas != equals-1 {
-		return i, buf[start:i], fmt.Errorf("invalid field format")
-	}
-
-	return i, buf[start:i], nil
-}
-
-// scanTime scans buf, starting at i for the time section of a point. It
-// returns the ending position and the byte slice of the timestamp within buf
-// and and error if the timestamp is not in the correct numeric format.
-func scanTime(buf []byte, i int) (int, []byte, error) {
-	start := skipWhitespace(buf, i)
-	i = start
-
-	for {
-		// reached the end of buf?
-		if i >= len(buf) {
-			break
-		}
-
-		// Reached end of block or trailing whitespace?
-		if buf[i] == '\n' || buf[i] == ' ' {
-			break
-		}
-
-		// Handle negative timestamps
-		if i == start && buf[i] == '-' {
-			i++
-			continue
-		}
-
-		// Timestamps should be integers, make sure they are so we don't need
-		// to actually  parse the timestamp until needed.
-		if buf[i] < '0' || buf[i] > '9' {
-			return i, buf[start:i], fmt.Errorf("bad timestamp")
-		}
-		i++
-	}
-	return i, buf[start:i], nil
-}
-
-func isNumeric(b byte) bool {
-	return (b >= '0' && b <= '9') || b == '.'
-}
-
-// scanNumber returns the end position within buf, start at i after
-// scanning over buf for an integer, or float.  It returns an
-// error if a invalid number is scanned.
-func scanNumber(buf []byte, i int) (int, error) {
-	start := i
-	var isInt, isUnsigned bool
-
-	// Is negative number?
-	if i < len(buf) && buf[i] == '-' {
-		i++
-		// There must be more characters now, as just '-' is illegal.
-		if i == len(buf) {
-			return i, ErrInvalidNumber
-		}
-	}
-
-	// how many decimal points we've see
-	decimal := false
-
-	// indicates the number is float in scientific notation
-	scientific := false
-
-	for {
-		if i >= len(buf) {
-			break
-		}
-
-		if buf[i] == ',' || buf[i] == ' ' {
-			break
-		}
-
-		if buf[i] == 'i' && i > start && !(isInt || isUnsigned) {
-			isInt = true
-			i++
-			continue
-		} else if buf[i] == 'u' && i > start && !(isInt || isUnsigned) {
-			isUnsigned = true
-			i++
-			continue
-		}
-
-		if buf[i] == '.' {
-			// Can't have more than 1 decimal (e.g. 1.1.1 should fail)
-			if decimal {
-				return i, ErrInvalidNumber
-			}
-			decimal = true
-		}
-
-		// `e` is valid for floats but not as the first char
-		if i > start && (buf[i] == 'e' || buf[i] == 'E') {
-			scientific = true
-			i++
-			continue
-		}
-
-		// + and - are only valid at this point if they follow an e (scientific notation)
-		if (buf[i] == '+' || buf[i] == '-') && (buf[i-1] == 'e' || buf[i-1] == 'E') {
-			i++
-			continue
-		}
-
-		// NaN is an unsupported value
-		if i+2 < len(buf) && (buf[i] == 'N' || buf[i] == 'n') {
-			return i, ErrInvalidNumber
-		}
-
-		if !isNumeric(buf[i]) {
-			return i, ErrInvalidNumber
-		}
-		i++
-	}
-
-	if (isInt || isUnsigned) && (decimal || scientific) {
-		return i, ErrInvalidNumber
-	}
-
-	numericDigits := i - start
-	if isInt {
-		numericDigits--
-	}
-	if decimal {
-		numericDigits--
-	}
-	if buf[start] == '-' {
-		numericDigits--
-	}
-
-	if numericDigits == 0 {
-		return i, ErrInvalidNumber
-	}
-
-	// It's more common that numbers will be within min/max range for their type but we need to prevent
-	// out or range numbers from being parsed successfully.  This uses some simple heuristics to decide
-	// if we should parse the number to the actual type.  It does not do it all the time because it incurs
-	// extra allocations and we end up converting the type again when writing points to disk.
-	if isInt {
-		// Make sure the last char is an 'i' for integers (e.g. 9i10 is not valid)
-		if buf[i-1] != 'i' {
-			return i, ErrInvalidNumber
-		}
-		// Parse the int to check bounds the number of digits could be larger than the max range
-		// We subtract 1 from the index to remove the `i` from our tests
-		if len(buf[start:i-1]) >= maxInt64Digits || len(buf[start:i-1]) >= minInt64Digits {
-			if _, err := parseIntBytes(buf[start:i-1], 10, 64); err != nil {
-				return i, fmt.Errorf("unable to parse integer %s: %s", buf[start:i-1], err)
-			}
-		}
-	} else if isUnsigned {
-		// Return an error if uint64 support has not been enabled.
-		if !enableUint64Support {
-			return i, ErrInvalidNumber
-		}
-		// Make sure the last char is a 'u' for unsigned
-		if buf[i-1] != 'u' {
-			return i, ErrInvalidNumber
-		}
-		// Make sure the first char is not a '-' for unsigned
-		if buf[start] == '-' {
-			return i, ErrInvalidNumber
-		}
-		// Parse the uint to check bounds the number of digits could be larger than the max range
-		// We subtract 1 from the index to remove the `u` from our tests
-		if len(buf[start:i-1]) >= maxUint64Digits {
-			if _, err := parseUintBytes(buf[start:i-1], 10, 64); err != nil {
-				return i, fmt.Errorf("unable to parse unsigned %s: %s", buf[start:i-1], err)
-			}
-		}
-	} else {
-		// Parse the float to check bounds if it's scientific or the number of digits could be larger than the max range
-		if scientific || len(buf[start:i]) >= maxFloat64Digits || len(buf[start:i]) >= minFloat64Digits {
-			if _, err := parseFloatBytes(buf[start:i], 10); err != nil {
-				return i, fmt.Errorf("invalid float")
-			}
-		}
-	}
-
-	return i, nil
-}
-
-// scanBoolean returns the end position within buf, start at i after
-// scanning over buf for boolean. Valid values for a boolean are
-// t, T, true, TRUE, f, F, false, FALSE.  It returns an error if a invalid boolean
-// is scanned.
-func scanBoolean(buf []byte, i int) (int, []byte, error) {
-	start := i
-
-	if i < len(buf) && (buf[i] != 't' && buf[i] != 'f' && buf[i] != 'T' && buf[i] != 'F') {
-		return i, buf[start:i], fmt.Errorf("invalid boolean")
-	}
-
-	i++
-	for {
-		if i >= len(buf) {
-			break
-		}
-
-		if buf[i] == ',' || buf[i] == ' ' {
-			break
-		}
-		i++
-	}
-
-	// Single char bool (t, T, f, F) is ok
-	if i-start == 1 {
-		return i, buf[start:i], nil
-	}
-
-	// length must be 4 for true or TRUE
-	if (buf[start] == 't' || buf[start] == 'T') && i-start != 4 {
-		return i, buf[start:i], fmt.Errorf("invalid boolean")
-	}
-
-	// length must be 5 for false or FALSE
-	if (buf[start] == 'f' || buf[start] == 'F') && i-start != 5 {
-		return i, buf[start:i], fmt.Errorf("invalid boolean")
-	}
-
-	// Otherwise
-	valid := false
-	switch buf[start] {
-	case 't':
-		valid = bytes.Equal(buf[start:i], []byte("true"))
-	case 'f':
-		valid = bytes.Equal(buf[start:i], []byte("false"))
-	case 'T':
-		valid = bytes.Equal(buf[start:i], []byte("TRUE")) || bytes.Equal(buf[start:i], []byte("True"))
-	case 'F':
-		valid = bytes.Equal(buf[start:i], []byte("FALSE")) || bytes.Equal(buf[start:i], []byte("False"))
-	}
-
-	if !valid {
-		return i, buf[start:i], fmt.Errorf("invalid boolean")
-	}
-
-	return i, buf[start:i], nil
-
-}
-
-// skipWhitespace returns the end position within buf, starting at i after
-// scanning over spaces in tags.
-func skipWhitespace(buf []byte, i int) int {
-	for i < len(buf) {
-		if buf[i] != ' ' && buf[i] != '\t' && buf[i] != 0 {
-			break
-		}
-		i++
-	}
-	return i
-}
-
-// scanLine returns the end position in buf and the next line found within
-// buf.
-func scanLine(buf []byte, i int) (int, []byte) {
-	start := i
-	quoted := false
-	fields := false
-
-	// tracks how many '=' and commas we've seen
-	// this duplicates some of the functionality in scanFields
-	equals := 0
-	commas := 0
-	for {
-		// reached the end of buf?
-		if i >= len(buf) {
-			break
-		}
-
-		// skip past escaped characters
-		if buf[i] == '\\' && i+2 < len(buf) {
-			i += 2
-			continue
-		}
-
-		if buf[i] == ' ' {
-			fields = true
-		}
-
-		// If we see a double quote, makes sure it is not escaped
-		if fields {
-			if !quoted && buf[i] == '=' {
-				i++
-				equals++
-				continue
-			} else if !quoted && buf[i] == ',' {
-				i++
-				commas++
-				continue
-			} else if buf[i] == '"' && equals > commas {
-				i++
-				quoted = !quoted
-				continue
-			}
-		}
-
-		if buf[i] == '\n' && !quoted {
-			break
-		}
-
-		i++
-	}
-
-	return i, buf[start:i]
-}
-
-// scanTo returns the end position in buf and the next consecutive block
-// of bytes, starting from i and ending with stop byte, where stop byte
-// has not been escaped.
-//
-// If there are leading spaces, they are skipped.
-func scanTo(buf []byte, i int, stop byte) (int, []byte) {
-	start := i
-	for {
-		// reached the end of buf?
-		if i >= len(buf) {
-			break
-		}
-
-		// Reached unescaped stop value?
-		if buf[i] == stop && (i == 0 || buf[i-1] != '\\') {
-			break
-		}
-		i++
-	}
-
-	return i, buf[start:i]
-}
-
-// scanTo returns the end position in buf and the next consecutive block
-// of bytes, starting from i and ending with stop byte.  If there are leading
-// spaces, they are skipped.
-func scanToSpaceOr(buf []byte, i int, stop byte) (int, []byte) {
-	start := i
-	if buf[i] == stop || buf[i] == ' ' {
-		return i, buf[start:i]
-	}
-
-	for {
-		i++
-		if buf[i-1] == '\\' {
-			continue
-		}
-
-		// reached the end of buf?
-		if i >= len(buf) {
-			return i, buf[start:i]
-		}
-
-		// reached end of block?
-		if buf[i] == stop || buf[i] == ' ' {
-			return i, buf[start:i]
-		}
-	}
-}
-
-func scanTagValue(buf []byte, i int) (int, []byte) {
-	start := i
-	for {
-		if i >= len(buf) {
-			break
-		}
-
-		if buf[i] == ',' && buf[i-1] != '\\' {
-			break
-		}
-		i++
-	}
-	if i > len(buf) {
-		return i, nil
-	}
-	return i, buf[start:i]
-}
-
-func scanFieldValue(buf []byte, i int) (int, []byte) {
-	start := i
-	quoted := false
-	for i < len(buf) {
-		// Only escape char for a field value is a double-quote and backslash
-		if buf[i] == '\\' && i+1 < len(buf) && (buf[i+1] == '"' || buf[i+1] == '\\') {
-			i += 2
-			continue
-		}
-
-		// Quoted value? (e.g. string)
-		if buf[i] == '"' {
-			i++
-			quoted = !quoted
-			continue
-		}
-
-		if buf[i] == ',' && !quoted {
-			break
-		}
-		i++
-	}
-	return i, buf[start:i]
-}
-
-func EscapeMeasurement(in []byte) []byte {
-	for b, esc := range measurementEscapeCodes {
-		in = bytes.Replace(in, []byte{b}, esc, -1)
-	}
-	return in
-}
-
-func unescapeMeasurement(in []byte) []byte {
-	for b, esc := range measurementEscapeCodes {
-		in = bytes.Replace(in, esc, []byte{b}, -1)
-	}
-	return in
-}
-
-func escapeTag(in []byte) []byte {
-	for b, esc := range tagEscapeCodes {
-		if bytes.IndexByte(in, b) != -1 {
-			in = bytes.Replace(in, []byte{b}, esc, -1)
-		}
-	}
-	return in
-}
-
-func unescapeTag(in []byte) []byte {
-	if bytes.IndexByte(in, '\\') == -1 {
-		return in
-	}
-
-	for b, esc := range tagEscapeCodes {
-		if bytes.IndexByte(in, b) != -1 {
-			in = bytes.Replace(in, esc, []byte{b}, -1)
-		}
-	}
-	return in
-}
-
-// escapeStringFieldReplacer replaces double quotes and backslashes
-// with the same character preceded by a backslash.
-// As of Go 1.7 this benchmarked better in allocations and CPU time
-// compared to iterating through a string byte-by-byte and appending to a new byte slice,
-// calling strings.Replace twice, and better than (*Regex).ReplaceAllString.
-var escapeStringFieldReplacer = strings.NewReplacer(`"`, `\"`, `\`, `\\`)
-
-// EscapeStringField returns a copy of in with any double quotes or
-// backslashes with escaped values.
-func EscapeStringField(in string) string {
-	return escapeStringFieldReplacer.Replace(in)
-}
-
-// unescapeStringField returns a copy of in with any escaped double-quotes
-// or backslashes unescaped.
-func unescapeStringField(in string) string {
-	if strings.IndexByte(in, '\\') == -1 {
-		return in
-	}
-
-	var out []byte
-	i := 0
-	for {
-		if i >= len(in) {
-			break
-		}
-		// unescape backslashes
-		if in[i] == '\\' && i+1 < len(in) && in[i+1] == '\\' {
-			out = append(out, '\\')
-			i += 2
-			continue
-		}
-		// unescape double-quotes
-		if in[i] == '\\' && i+1 < len(in) && in[i+1] == '"' {
-			out = append(out, '"')
-			i += 2
-			continue
-		}
-		out = append(out, in[i])
-		i++
-
-	}
-	return string(out)
-}
-
-// NewPoint returns a new point with the given measurement name, tags, fields and timestamp.  If
-// an unsupported field value (NaN) or out of range time is passed, this function returns an error.
-func NewPoint(name string, tags Tags, fields Fields, t time.Time) (Point, error) {
-	key, err := pointKey(name, tags, fields, t)
-	if err != nil {
-		return nil, err
-	}
-
-	return &point{
-		key:    key,
-		time:   t,
-		fields: fields.MarshalBinary(),
-	}, nil
-}
-
-// pointKey checks some basic requirements for valid points, and returns the
-// key, along with an possible error.
-func pointKey(measurement string, tags Tags, fields Fields, t time.Time) ([]byte, error) {
-	if len(fields) == 0 {
-		return nil, ErrPointMustHaveAField
-	}
-
-	if !t.IsZero() {
-		if err := CheckTime(t); err != nil {
-			return nil, err
-		}
-	}
-
-	for key, value := range fields {
-		switch value := value.(type) {
-		case float64:
-			// Ensure the caller validates and handles invalid field values
-			if math.IsNaN(value) {
-				return nil, fmt.Errorf("NaN is an unsupported value for field %s", key)
-			}
-		case float32:
-			// Ensure the caller validates and handles invalid field values
-			if math.IsNaN(float64(value)) {
-				return nil, fmt.Errorf("NaN is an unsupported value for field %s", key)
-			}
-		}
-		if len(key) == 0 {
-			return nil, fmt.Errorf("all fields must have non-empty names")
-		}
-	}
-
-	key := MakeKey([]byte(measurement), tags)
-	for field := range fields {
-		sz := seriesKeySize(key, []byte(field))
-		if sz > MaxKeyLength {
-			return nil, fmt.Errorf("max key length exceeded: %v > %v", sz, MaxKeyLength)
-		}
-	}
-
-	return key, nil
-}
-
-func seriesKeySize(key, field []byte) int {
-	// 4 is the length of the tsm1.fieldKeySeparator constant.  It's inlined here to avoid a circular
-	// dependency.
-	return len(key) + 4 + len(field)
-}
-
-// NewPointFromBytes returns a new Point from a marshalled Point.
-func NewPointFromBytes(b []byte) (Point, error) {
-	p := &point{}
-	if err := p.UnmarshalBinary(b); err != nil {
-		return nil, err
-	}
-
-	// This does some basic validation to ensure there are fields and they
-	// can be unmarshalled as well.
-	iter := p.FieldIterator()
-	var hasField bool
-	for iter.Next() {
-		if len(iter.FieldKey()) == 0 {
-			continue
-		}
-		hasField = true
-		switch iter.Type() {
-		case Float:
-			_, err := iter.FloatValue()
-			if err != nil {
-				return nil, fmt.Errorf("unable to unmarshal field %s: %s", string(iter.FieldKey()), err)
-			}
-		case Integer:
-			_, err := iter.IntegerValue()
-			if err != nil {
-				return nil, fmt.Errorf("unable to unmarshal field %s: %s", string(iter.FieldKey()), err)
-			}
-		case Unsigned:
-			_, err := iter.UnsignedValue()
-			if err != nil {
-				return nil, fmt.Errorf("unable to unmarshal field %s: %s", string(iter.FieldKey()), err)
-			}
-		case String:
-			// Skip since this won't return an error
-		case Boolean:
-			_, err := iter.BooleanValue()
-			if err != nil {
-				return nil, fmt.Errorf("unable to unmarshal field %s: %s", string(iter.FieldKey()), err)
-			}
-		}
-	}
-
-	if !hasField {
-		return nil, ErrPointMustHaveAField
-	}
-
-	return p, nil
-}
-
-// MustNewPoint returns a new point with the given measurement name, tags, fields and timestamp.  If
-// an unsupported field value (NaN) is passed, this function panics.
-func MustNewPoint(name string, tags Tags, fields Fields, time time.Time) Point {
-	pt, err := NewPoint(name, tags, fields, time)
-	if err != nil {
-		panic(err.Error())
-	}
-	return pt
-}
-
-// Key returns the key (measurement joined with tags) of the point.
-func (p *point) Key() []byte {
-	return p.key
-}
-
-func (p *point) name() []byte {
-	_, name := scanTo(p.key, 0, ',')
-	return name
-}
-
-func (p *point) Name() []byte {
-	return escape.Unescape(p.name())
-}
-
-// SetName updates the measurement name for the point.
-func (p *point) SetName(name string) {
-	p.cachedName = ""
-	p.key = MakeKey([]byte(name), p.Tags())
-}
-
-// Time return the timestamp for the point.
-func (p *point) Time() time.Time {
-	return p.time
-}
-
-// SetTime updates the timestamp for the point.
-func (p *point) SetTime(t time.Time) {
-	p.time = t
-}
-
-// Round will round the timestamp of the point to the given duration.
-func (p *point) Round(d time.Duration) {
-	p.time = p.time.Round(d)
-}
-
-// Tags returns the tag set for the point.
-func (p *point) Tags() Tags {
-	if p.cachedTags != nil {
-		return p.cachedTags
-	}
-	p.cachedTags = parseTags(p.key)
-	return p.cachedTags
-}
-
-func (p *point) HasTag(tag []byte) bool {
-	if len(p.key) == 0 {
-		return false
-	}
-
-	var exists bool
-	walkTags(p.key, func(key, value []byte) bool {
-		if bytes.Equal(tag, key) {
-			exists = true
-			return false
-		}
-		return true
-	})
-
-	return exists
-}
-
-func walkTags(buf []byte, fn func(key, value []byte) bool) {
-	if len(buf) == 0 {
-		return
-	}
-
-	pos, name := scanTo(buf, 0, ',')
-
-	// it's an empty key, so there are no tags
-	if len(name) == 0 {
-		return
-	}
-
-	hasEscape := bytes.IndexByte(buf, '\\') != -1
-	i := pos + 1
-	var key, value []byte
-	for {
-		if i >= len(buf) {
-			break
-		}
-		i, key = scanTo(buf, i, '=')
-		i, value = scanTagValue(buf, i+1)
-
-		if len(value) == 0 {
-			continue
-		}
-
-		if hasEscape {
-			if !fn(unescapeTag(key), unescapeTag(value)) {
-				return
-			}
-		} else {
-			if !fn(key, value) {
-				return
-			}
-		}
-
-		i++
-	}
-}
-
-// walkFields walks each field key and value via fn.  If fn returns false, the iteration
-// is stopped.  The values are the raw byte slices and not the converted types.
-func walkFields(buf []byte, fn func(key, value []byte) bool) {
-	var i int
-	var key, val []byte
-	for len(buf) > 0 {
-		i, key = scanTo(buf, 0, '=')
-		buf = buf[i+1:]
-		i, val = scanFieldValue(buf, 0)
-		buf = buf[i:]
-		if !fn(key, val) {
-			break
-		}
-
-		// slice off comma
-		if len(buf) > 0 {
-			buf = buf[1:]
-		}
-	}
-}
-
-func parseTags(buf []byte) Tags {
-	if len(buf) == 0 {
-		return nil
-	}
-
-	tags := make(Tags, bytes.Count(buf, []byte(",")))
-	p := 0
-	walkTags(buf, func(key, value []byte) bool {
-		tags[p].Key = key
-		tags[p].Value = value
-		p++
-		return true
-	})
-	return tags
-}
-
-// MakeKey creates a key for a set of tags.
-func MakeKey(name []byte, tags Tags) []byte {
-	// unescape the name and then re-escape it to avoid double escaping.
-	// The key should always be stored in escaped form.
-	return append(EscapeMeasurement(unescapeMeasurement(name)), tags.HashKey()...)
-}
-
-// SetTags replaces the tags for the point.
-func (p *point) SetTags(tags Tags) {
-	p.key = MakeKey(p.Name(), tags)
-	p.cachedTags = tags
-}
-
-// AddTag adds or replaces a tag value for a point.
-func (p *point) AddTag(key, value string) {
-	tags := p.Tags()
-	tags = append(tags, Tag{Key: []byte(key), Value: []byte(value)})
-	sort.Sort(tags)
-	p.cachedTags = tags
-	p.key = MakeKey(p.Name(), tags)
-}
-
-// Fields returns the fields for the point.
-func (p *point) Fields() (Fields, error) {
-	if p.cachedFields != nil {
-		return p.cachedFields, nil
-	}
-	cf, err := p.unmarshalBinary()
-	if err != nil {
-		return nil, err
-	}
-	p.cachedFields = cf
-	return p.cachedFields, nil
-}
-
-// SetPrecision will round a time to the specified precision.
-func (p *point) SetPrecision(precision string) {
-	switch precision {
-	case "n":
-	case "u":
-		p.SetTime(p.Time().Truncate(time.Microsecond))
-	case "ms":
-		p.SetTime(p.Time().Truncate(time.Millisecond))
-	case "s":
-		p.SetTime(p.Time().Truncate(time.Second))
-	case "m":
-		p.SetTime(p.Time().Truncate(time.Minute))
-	case "h":
-		p.SetTime(p.Time().Truncate(time.Hour))
-	}
-}
-
-// String returns the string representation of the point.
-func (p *point) String() string {
-	if p.Time().IsZero() {
-		return string(p.Key()) + " " + string(p.fields)
-	}
-	return string(p.Key()) + " " + string(p.fields) + " " + strconv.FormatInt(p.UnixNano(), 10)
-}
-
-// AppendString appends the string representation of the point to buf.
-func (p *point) AppendString(buf []byte) []byte {
-	buf = append(buf, p.key...)
-	buf = append(buf, ' ')
-	buf = append(buf, p.fields...)
-
-	if !p.time.IsZero() {
-		buf = append(buf, ' ')
-		buf = strconv.AppendInt(buf, p.UnixNano(), 10)
-	}
-
-	return buf
-}
-
-// StringSize returns the length of the string that would be returned by String().
-func (p *point) StringSize() int {
-	size := len(p.key) + len(p.fields) + 1
-
-	if !p.time.IsZero() {
-		digits := 1 // even "0" has one digit
-		t := p.UnixNano()
-		if t < 0 {
-			// account for negative sign, then negate
-			digits++
-			t = -t
-		}
-		for t > 9 { // already accounted for one digit
-			digits++
-			t /= 10
-		}
-		size += digits + 1 // digits and a space
-	}
-
-	return size
-}
-
-// MarshalBinary returns a binary representation of the point.
-func (p *point) MarshalBinary() ([]byte, error) {
-	if len(p.fields) == 0 {
-		return nil, ErrPointMustHaveAField
-	}
-
-	tb, err := p.time.MarshalBinary()
-	if err != nil {
-		return nil, err
-	}
-
-	b := make([]byte, 8+len(p.key)+len(p.fields)+len(tb))
-	i := 0
-
-	binary.BigEndian.PutUint32(b[i:], uint32(len(p.key)))
-	i += 4
-
-	i += copy(b[i:], p.key)
-
-	binary.BigEndian.PutUint32(b[i:i+4], uint32(len(p.fields)))
-	i += 4
-
-	i += copy(b[i:], p.fields)
-
-	copy(b[i:], tb)
-	return b, nil
-}
-
-// UnmarshalBinary decodes a binary representation of the point into a point struct.
-func (p *point) UnmarshalBinary(b []byte) error {
-	var n int
-
-	// Read key length.
-	if len(b) < 4 {
-		return io.ErrShortBuffer
-	}
-	n, b = int(binary.BigEndian.Uint32(b[:4])), b[4:]
-
-	// Read key.
-	if len(b) < n {
-		return io.ErrShortBuffer
-	}
-	p.key, b = b[:n], b[n:]
-
-	// Read fields length.
-	if len(b) < 4 {
-		return io.ErrShortBuffer
-	}
-	n, b = int(binary.BigEndian.Uint32(b[:4])), b[4:]
-
-	// Read fields.
-	if len(b) < n {
-		return io.ErrShortBuffer
-	}
-	p.fields, b = b[:n], b[n:]
-
-	// Read timestamp.
-	return p.time.UnmarshalBinary(b)
-}
-
-// PrecisionString returns a string representation of the point. If there
-// is a timestamp associated with the point then it will be specified in the
-// given unit.
-func (p *point) PrecisionString(precision string) string {
-	if p.Time().IsZero() {
-		return fmt.Sprintf("%s %s", p.Key(), string(p.fields))
-	}
-	return fmt.Sprintf("%s %s %d", p.Key(), string(p.fields),
-		p.UnixNano()/GetPrecisionMultiplier(precision))
-}
-
-// RoundedString returns a string representation of the point. If there
-// is a timestamp associated with the point, then it will be rounded to the
-// given duration.
-func (p *point) RoundedString(d time.Duration) string {
-	if p.Time().IsZero() {
-		return fmt.Sprintf("%s %s", p.Key(), string(p.fields))
-	}
-	return fmt.Sprintf("%s %s %d", p.Key(), string(p.fields),
-		p.time.Round(d).UnixNano())
-}
-
-func (p *point) unmarshalBinary() (Fields, error) {
-	iter := p.FieldIterator()
-	fields := make(Fields, 8)
-	for iter.Next() {
-		if len(iter.FieldKey()) == 0 {
-			continue
-		}
-		switch iter.Type() {
-		case Float:
-			v, err := iter.FloatValue()
-			if err != nil {
-				return nil, fmt.Errorf("unable to unmarshal field %s: %s", string(iter.FieldKey()), err)
-			}
-			fields[string(iter.FieldKey())] = v
-		case Integer:
-			v, err := iter.IntegerValue()
-			if err != nil {
-				return nil, fmt.Errorf("unable to unmarshal field %s: %s", string(iter.FieldKey()), err)
-			}
-			fields[string(iter.FieldKey())] = v
-		case Unsigned:
-			v, err := iter.UnsignedValue()
-			if err != nil {
-				return nil, fmt.Errorf("unable to unmarshal field %s: %s", string(iter.FieldKey()), err)
-			}
-			fields[string(iter.FieldKey())] = v
-		case String:
-			fields[string(iter.FieldKey())] = iter.StringValue()
-		case Boolean:
-			v, err := iter.BooleanValue()
-			if err != nil {
-				return nil, fmt.Errorf("unable to unmarshal field %s: %s", string(iter.FieldKey()), err)
-			}
-			fields[string(iter.FieldKey())] = v
-		}
-	}
-	return fields, nil
-}
-
-// HashID returns a non-cryptographic checksum of the point's key.
-func (p *point) HashID() uint64 {
-	h := NewInlineFNV64a()
-	h.Write(p.key)
-	sum := h.Sum64()
-	return sum
-}
-
-// UnixNano returns the timestamp of the point as nanoseconds since Unix epoch.
-func (p *point) UnixNano() int64 {
-	return p.Time().UnixNano()
-}
-
-// Split will attempt to return multiple points with the same timestamp whose
-// string representations are no longer than size. Points with a single field or
-// a point without a timestamp may exceed the requested size.
-func (p *point) Split(size int) []Point {
-	if p.time.IsZero() || p.StringSize() <= size {
-		return []Point{p}
-	}
-
-	// key string, timestamp string, spaces
-	size -= len(p.key) + len(strconv.FormatInt(p.time.UnixNano(), 10)) + 2
-
-	var points []Point
-	var start, cur int
-
-	for cur < len(p.fields) {
-		end, _ := scanTo(p.fields, cur, '=')
-		end, _ = scanFieldValue(p.fields, end+1)
-
-		if cur > start && end-start > size {
-			points = append(points, &point{
-				key:    p.key,
-				time:   p.time,
-				fields: p.fields[start : cur-1],
-			})
-			start = cur
-		}
-
-		cur = end + 1
-	}
-
-	points = append(points, &point{
-		key:    p.key,
-		time:   p.time,
-		fields: p.fields[start:],
-	})
-
-	return points
-}
-
-// Tag represents a single key/value tag pair.
-type Tag struct {
-	Key   []byte
-	Value []byte
-}
-
-// NewTag returns a new Tag.
-func NewTag(key, value []byte) Tag {
-	return Tag{
-		Key:   key,
-		Value: value,
-	}
-}
-
-// Size returns the size of the key and value.
-func (t Tag) Size() int { return len(t.Key) + len(t.Value) }
-
-// Clone returns a shallow copy of Tag.
-//
-// Tags associated with a Point created by ParsePointsWithPrecision will hold references to the byte slice that was parsed.
-// Use Clone to create a Tag with new byte slices that do not refer to the argument to ParsePointsWithPrecision.
-func (t Tag) Clone() Tag {
-	other := Tag{
-		Key:   make([]byte, len(t.Key)),
-		Value: make([]byte, len(t.Value)),
-	}
-
-	copy(other.Key, t.Key)
-	copy(other.Value, t.Value)
-
-	return other
-}
-
-// String returns the string reprsentation of the tag.
-func (t *Tag) String() string {
-	var buf bytes.Buffer
-	buf.WriteByte('{')
-	buf.WriteString(string(t.Key))
-	buf.WriteByte(' ')
-	buf.WriteString(string(t.Value))
-	buf.WriteByte('}')
-	return buf.String()
-}
-
-// Tags represents a sorted list of tags.
-type Tags []Tag
-
-// NewTags returns a new Tags from a map.
-func NewTags(m map[string]string) Tags {
-	if len(m) == 0 {
-		return nil
-	}
-	a := make(Tags, 0, len(m))
-	for k, v := range m {
-		a = append(a, NewTag([]byte(k), []byte(v)))
-	}
-	sort.Sort(a)
-	return a
-}
-
-// Keys returns the list of keys for a tag set.
-func (a Tags) Keys() []string {
-	if len(a) == 0 {
-		return nil
-	}
-	keys := make([]string, len(a))
-	for i, tag := range a {
-		keys[i] = string(tag.Key)
-	}
-	return keys
-}
-
-// Values returns the list of values for a tag set.
-func (a Tags) Values() []string {
-	if len(a) == 0 {
-		return nil
-	}
-	values := make([]string, len(a))
-	for i, tag := range a {
-		values[i] = string(tag.Value)
-	}
-	return values
-}
-
-// String returns the string representation of the tags.
-func (a Tags) String() string {
-	var buf bytes.Buffer
-	buf.WriteByte('[')
-	for i := range a {
-		buf.WriteString(a[i].String())
-		if i < len(a)-1 {
-			buf.WriteByte(' ')
-		}
-	}
-	buf.WriteByte(']')
-	return buf.String()
-}
-
-// Size returns the number of bytes needed to store all tags. Note, this is
-// the number of bytes needed to store all keys and values and does not account
-// for data structures or delimiters for example.
-func (a Tags) Size() int {
-	var total int
-	for _, t := range a {
-		total += t.Size()
-	}
-	return total
-}
-
-// Clone returns a copy of the slice where the elements are a result of calling `Clone` on the original elements
-//
-// Tags associated with a Point created by ParsePointsWithPrecision will hold references to the byte slice that was parsed.
-// Use Clone to create Tags with new byte slices that do not refer to the argument to ParsePointsWithPrecision.
-func (a Tags) Clone() Tags {
-	if len(a) == 0 {
-		return nil
-	}
-
-	others := make(Tags, len(a))
-	for i := range a {
-		others[i] = a[i].Clone()
-	}
-
-	return others
-}
-
-func (a Tags) Len() int           { return len(a) }
-func (a Tags) Less(i, j int) bool { return bytes.Compare(a[i].Key, a[j].Key) == -1 }
-func (a Tags) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
-
-// Equal returns true if a equals other.
-func (a Tags) Equal(other Tags) bool {
-	if len(a) != len(other) {
-		return false
-	}
-	for i := range a {
-		if !bytes.Equal(a[i].Key, other[i].Key) || !bytes.Equal(a[i].Value, other[i].Value) {
-			return false
-		}
-	}
-	return true
-}
-
-// CompareTags returns -1 if a < b, 1 if a > b, and 0 if a == b.
-func CompareTags(a, b Tags) int {
-	// Compare each key & value until a mismatch.
-	for i := 0; i < len(a) && i < len(b); i++ {
-		if cmp := bytes.Compare(a[i].Key, b[i].Key); cmp != 0 {
-			return cmp
-		}
-		if cmp := bytes.Compare(a[i].Value, b[i].Value); cmp != 0 {
-			return cmp
-		}
-	}
-
-	// If all tags are equal up to this point then return shorter tagset.
-	if len(a) < len(b) {
-		return -1
-	} else if len(a) > len(b) {
-		return 1
-	}
-
-	// All tags are equal.
-	return 0
-}
-
-// Get returns the value for a key.
-func (a Tags) Get(key []byte) []byte {
-	// OPTIMIZE: Use sort.Search if tagset is large.
-
-	for _, t := range a {
-		if bytes.Equal(t.Key, key) {
-			return t.Value
-		}
-	}
-	return nil
-}
-
-// GetString returns the string value for a string key.
-func (a Tags) GetString(key string) string {
-	return string(a.Get([]byte(key)))
-}
-
-// Set sets the value for a key.
-func (a *Tags) Set(key, value []byte) {
-	for i, t := range *a {
-		if bytes.Equal(t.Key, key) {
-			(*a)[i].Value = value
-			return
-		}
-	}
-	*a = append(*a, Tag{Key: key, Value: value})
-	sort.Sort(*a)
-}
-
-// SetString sets the string value for a string key.
-func (a *Tags) SetString(key, value string) {
-	a.Set([]byte(key), []byte(value))
-}
-
-// Delete removes a tag by key.
-func (a *Tags) Delete(key []byte) {
-	for i, t := range *a {
-		if bytes.Equal(t.Key, key) {
-			copy((*a)[i:], (*a)[i+1:])
-			(*a)[len(*a)-1] = Tag{}
-			*a = (*a)[:len(*a)-1]
-			return
-		}
-	}
-}
-
-// Map returns a map representation of the tags.
-func (a Tags) Map() map[string]string {
-	m := make(map[string]string, len(a))
-	for _, t := range a {
-		m[string(t.Key)] = string(t.Value)
-	}
-	return m
-}
-
-// Merge merges the tags combining the two. If both define a tag with the
-// same key, the merged value overwrites the old value.
-// A new map is returned.
-func (a Tags) Merge(other map[string]string) Tags {
-	merged := make(map[string]string, len(a)+len(other))
-	for _, t := range a {
-		merged[string(t.Key)] = string(t.Value)
-	}
-	for k, v := range other {
-		merged[k] = v
-	}
-	return NewTags(merged)
-}
-
-// HashKey hashes all of a tag's keys.
-func (a Tags) HashKey() []byte {
-	// Empty maps marshal to empty bytes.
-	if len(a) == 0 {
-		return nil
-	}
-
-	// Type invariant: Tags are sorted
-
-	escaped := make(Tags, 0, len(a))
-	sz := 0
-	for _, t := range a {
-		ek := escapeTag(t.Key)
-		ev := escapeTag(t.Value)
-
-		if len(ev) > 0 {
-			escaped = append(escaped, Tag{Key: ek, Value: ev})
-			sz += len(ek) + len(ev)
-		}
-	}
-
-	sz += len(escaped) + (len(escaped) * 2) // separators
-
-	// Generate marshaled bytes.
-	b := make([]byte, sz)
-	buf := b
-	idx := 0
-	for _, k := range escaped {
-		buf[idx] = ','
-		idx++
-		copy(buf[idx:idx+len(k.Key)], k.Key)
-		idx += len(k.Key)
-		buf[idx] = '='
-		idx++
-		copy(buf[idx:idx+len(k.Value)], k.Value)
-		idx += len(k.Value)
-	}
-	return b[:idx]
-}
-
-// CopyTags returns a shallow copy of tags.
-func CopyTags(a Tags) Tags {
-	other := make(Tags, len(a))
-	copy(other, a)
-	return other
-}
-
-// DeepCopyTags returns a deep copy of tags.
-func DeepCopyTags(a Tags) Tags {
-	// Calculate size of keys/values in bytes.
-	var n int
-	for _, t := range a {
-		n += len(t.Key) + len(t.Value)
-	}
-
-	// Build single allocation for all key/values.
-	buf := make([]byte, n)
-
-	// Copy tags to new set.
-	other := make(Tags, len(a))
-	for i, t := range a {
-		copy(buf, t.Key)
-		other[i].Key, buf = buf[:len(t.Key)], buf[len(t.Key):]
-
-		copy(buf, t.Value)
-		other[i].Value, buf = buf[:len(t.Value)], buf[len(t.Value):]
-	}
-
-	return other
-}
-
-// Fields represents a mapping between a Point's field names and their
-// values.
-type Fields map[string]interface{}
-
-// FieldIterator retuns a FieldIterator that can be used to traverse the
-// fields of a point without constructing the in-memory map.
-func (p *point) FieldIterator() FieldIterator {
-	p.Reset()
-	return p
-}
-
-type fieldIterator struct {
-	start, end  int
-	key, keybuf []byte
-	valueBuf    []byte
-	fieldType   FieldType
-}
-
-// Next indicates whether there any fields remaining.
-func (p *point) Next() bool {
-	p.it.start = p.it.end
-	if p.it.start >= len(p.fields) {
-		return false
-	}
-
-	p.it.end, p.it.key = scanTo(p.fields, p.it.start, '=')
-	if escape.IsEscaped(p.it.key) {
-		p.it.keybuf = escape.AppendUnescaped(p.it.keybuf[:0], p.it.key)
-		p.it.key = p.it.keybuf
-	}
-
-	p.it.end, p.it.valueBuf = scanFieldValue(p.fields, p.it.end+1)
-	p.it.end++
-
-	if len(p.it.valueBuf) == 0 {
-		p.it.fieldType = Empty
-		return true
-	}
-
-	c := p.it.valueBuf[0]
-
-	if c == '"' {
-		p.it.fieldType = String
-		return true
-	}
-
-	if strings.IndexByte(`0123456789-.nNiIu`, c) >= 0 {
-		if p.it.valueBuf[len(p.it.valueBuf)-1] == 'i' {
-			p.it.fieldType = Integer
-			p.it.valueBuf = p.it.valueBuf[:len(p.it.valueBuf)-1]
-		} else if p.it.valueBuf[len(p.it.valueBuf)-1] == 'u' {
-			p.it.fieldType = Unsigned
-			p.it.valueBuf = p.it.valueBuf[:len(p.it.valueBuf)-1]
-		} else {
-			p.it.fieldType = Float
-		}
-		return true
-	}
-
-	// to keep the same behavior that currently exists, default to boolean
-	p.it.fieldType = Boolean
-	return true
-}
-
-// FieldKey returns the key of the current field.
-func (p *point) FieldKey() []byte {
-	return p.it.key
-}
-
-// Type returns the FieldType of the current field.
-func (p *point) Type() FieldType {
-	return p.it.fieldType
-}
-
-// StringValue returns the string value of the current field.
-func (p *point) StringValue() string {
-	return unescapeStringField(string(p.it.valueBuf[1 : len(p.it.valueBuf)-1]))
-}
-
-// IntegerValue returns the integer value of the current field.
-func (p *point) IntegerValue() (int64, error) {
-	n, err := parseIntBytes(p.it.valueBuf, 10, 64)
-	if err != nil {
-		return 0, fmt.Errorf("unable to parse integer value %q: %v", p.it.valueBuf, err)
-	}
-	return n, nil
-}
-
-// UnsignedValue returns the unsigned value of the current field.
-func (p *point) UnsignedValue() (uint64, error) {
-	n, err := parseUintBytes(p.it.valueBuf, 10, 64)
-	if err != nil {
-		return 0, fmt.Errorf("unable to parse unsigned value %q: %v", p.it.valueBuf, err)
-	}
-	return n, nil
-}
-
-// BooleanValue returns the boolean value of the current field.
-func (p *point) BooleanValue() (bool, error) {
-	b, err := parseBoolBytes(p.it.valueBuf)
-	if err != nil {
-		return false, fmt.Errorf("unable to parse bool value %q: %v", p.it.valueBuf, err)
-	}
-	return b, nil
-}
-
-// FloatValue returns the float value of the current field.
-func (p *point) FloatValue() (float64, error) {
-	f, err := parseFloatBytes(p.it.valueBuf, 64)
-	if err != nil {
-		return 0, fmt.Errorf("unable to parse floating point value %q: %v", p.it.valueBuf, err)
-	}
-	return f, nil
-}
-
-// Reset resets the iterator to its initial state.
-func (p *point) Reset() {
-	p.it.fieldType = Empty
-	p.it.key = nil
-	p.it.valueBuf = nil
-	p.it.start = 0
-	p.it.end = 0
-}
-
-// MarshalBinary encodes all the fields to their proper type and returns the binary
-// represenation
-// NOTE: uint64 is specifically not supported due to potential overflow when we decode
-// again later to an int64
-// NOTE2: uint is accepted, and may be 64 bits, and is for some reason accepted...
-func (p Fields) MarshalBinary() []byte {
-	var b []byte
-	keys := make([]string, 0, len(p))
-
-	for k := range p {
-		keys = append(keys, k)
-	}
-
-	// Not really necessary, can probably be removed.
-	sort.Strings(keys)
-
-	for i, k := range keys {
-		if i > 0 {
-			b = append(b, ',')
-		}
-		b = appendField(b, k, p[k])
-	}
-
-	return b
-}
-
-func appendField(b []byte, k string, v interface{}) []byte {
-	b = append(b, []byte(escape.String(k))...)
-	b = append(b, '=')
-
-	// check popular types first
-	switch v := v.(type) {
-	case float64:
-		b = strconv.AppendFloat(b, v, 'f', -1, 64)
-	case int64:
-		b = strconv.AppendInt(b, v, 10)
-		b = append(b, 'i')
-	case string:
-		b = append(b, '"')
-		b = append(b, []byte(EscapeStringField(v))...)
-		b = append(b, '"')
-	case bool:
-		b = strconv.AppendBool(b, v)
-	case int32:
-		b = strconv.AppendInt(b, int64(v), 10)
-		b = append(b, 'i')
-	case int16:
-		b = strconv.AppendInt(b, int64(v), 10)
-		b = append(b, 'i')
-	case int8:
-		b = strconv.AppendInt(b, int64(v), 10)
-		b = append(b, 'i')
-	case int:
-		b = strconv.AppendInt(b, int64(v), 10)
-		b = append(b, 'i')
-	case uint64:
-		b = strconv.AppendUint(b, v, 10)
-		b = append(b, 'u')
-	case uint32:
-		b = strconv.AppendInt(b, int64(v), 10)
-		b = append(b, 'i')
-	case uint16:
-		b = strconv.AppendInt(b, int64(v), 10)
-		b = append(b, 'i')
-	case uint8:
-		b = strconv.AppendInt(b, int64(v), 10)
-		b = append(b, 'i')
-	case uint:
-		// TODO: 'uint' should be converted to writing as an unsigned integer,
-		// but we cannot since that would break backwards compatibility.
-		b = strconv.AppendInt(b, int64(v), 10)
-		b = append(b, 'i')
-	case float32:
-		b = strconv.AppendFloat(b, float64(v), 'f', -1, 32)
-	case []byte:
-		b = append(b, v...)
-	case nil:
-		// skip
-	default:
-		// Can't determine the type, so convert to string
-		b = append(b, '"')
-		b = append(b, []byte(EscapeStringField(fmt.Sprintf("%v", v)))...)
-		b = append(b, '"')
-
-	}
-
-	return b
-}

+ 0 - 62
vendor/github.com/influxdata/influxdb/models/rows.go

@@ -1,62 +0,0 @@
-package models
-
-import (
-	"sort"
-)
-
-// Row represents a single row returned from the execution of a statement.
-type Row struct {
-	Name    string            `json:"name,omitempty"`
-	Tags    map[string]string `json:"tags,omitempty"`
-	Columns []string          `json:"columns,omitempty"`
-	Values  [][]interface{}   `json:"values,omitempty"`
-	Partial bool              `json:"partial,omitempty"`
-}
-
-// SameSeries returns true if r contains values for the same series as o.
-func (r *Row) SameSeries(o *Row) bool {
-	return r.tagsHash() == o.tagsHash() && r.Name == o.Name
-}
-
-// tagsHash returns a hash of tag key/value pairs.
-func (r *Row) tagsHash() uint64 {
-	h := NewInlineFNV64a()
-	keys := r.tagsKeys()
-	for _, k := range keys {
-		h.Write([]byte(k))
-		h.Write([]byte(r.Tags[k]))
-	}
-	return h.Sum64()
-}
-
-// tagKeys returns a sorted list of tag keys.
-func (r *Row) tagsKeys() []string {
-	a := make([]string, 0, len(r.Tags))
-	for k := range r.Tags {
-		a = append(a, k)
-	}
-	sort.Strings(a)
-	return a
-}
-
-// Rows represents a collection of rows. Rows implements sort.Interface.
-type Rows []*Row
-
-// Len implements sort.Interface.
-func (p Rows) Len() int { return len(p) }
-
-// Less implements sort.Interface.
-func (p Rows) Less(i, j int) bool {
-	// Sort by name first.
-	if p[i].Name != p[j].Name {
-		return p[i].Name < p[j].Name
-	}
-
-	// Sort by tag set hash. Tags don't have a meaningful sort order so we
-	// just compute a hash and sort by that instead. This allows the tests
-	// to receive rows in a predictable order every time.
-	return p[i].tagsHash() < p[j].tagsHash()
-}
-
-// Swap implements sort.Interface.
-func (p Rows) Swap(i, j int) { p[i], p[j] = p[j], p[i] }

+ 0 - 42
vendor/github.com/influxdata/influxdb/models/statistic.go

@@ -1,42 +0,0 @@
-package models
-
-// Statistic is the representation of a statistic used by the monitoring service.
-type Statistic struct {
-	Name   string                 `json:"name"`
-	Tags   map[string]string      `json:"tags"`
-	Values map[string]interface{} `json:"values"`
-}
-
-// NewStatistic returns an initialized Statistic.
-func NewStatistic(name string) Statistic {
-	return Statistic{
-		Name:   name,
-		Tags:   make(map[string]string),
-		Values: make(map[string]interface{}),
-	}
-}
-
-// StatisticTags is a map that can be merged with others without causing
-// mutations to either map.
-type StatisticTags map[string]string
-
-// Merge creates a new map containing the merged contents of tags and t.
-// If both tags and the receiver map contain the same key, the value in tags
-// is used in the resulting map.
-//
-// Merge always returns a usable map.
-func (t StatisticTags) Merge(tags map[string]string) map[string]string {
-	// Add everything in tags to the result.
-	out := make(map[string]string, len(tags))
-	for k, v := range tags {
-		out[k] = v
-	}
-
-	// Only add values from t that don't appear in tags.
-	for k, v := range t {
-		if _, ok := tags[k]; !ok {
-			out[k] = v
-		}
-	}
-	return out
-}

+ 0 - 74
vendor/github.com/influxdata/influxdb/models/time.go

@@ -1,74 +0,0 @@
-package models
-
-// Helper time methods since parsing time can easily overflow and we only support a
-// specific time range.
-
-import (
-	"fmt"
-	"math"
-	"time"
-)
-
-const (
-	// MinNanoTime is the minumum time that can be represented.
-	//
-	// 1677-09-21 00:12:43.145224194 +0000 UTC
-	//
-	// The two lowest minimum integers are used as sentinel values.  The
-	// minimum value needs to be used as a value lower than any other value for
-	// comparisons and another separate value is needed to act as a sentinel
-	// default value that is unusable by the user, but usable internally.
-	// Because these two values need to be used for a special purpose, we do
-	// not allow users to write points at these two times.
-	MinNanoTime = int64(math.MinInt64) + 2
-
-	// MaxNanoTime is the maximum time that can be represented.
-	//
-	// 2262-04-11 23:47:16.854775806 +0000 UTC
-	//
-	// The highest time represented by a nanosecond needs to be used for an
-	// exclusive range in the shard group, so the maximum time needs to be one
-	// less than the possible maximum number of nanoseconds representable by an
-	// int64 so that we don't lose a point at that one time.
-	MaxNanoTime = int64(math.MaxInt64) - 1
-)
-
-var (
-	minNanoTime = time.Unix(0, MinNanoTime).UTC()
-	maxNanoTime = time.Unix(0, MaxNanoTime).UTC()
-
-	// ErrTimeOutOfRange gets returned when time is out of the representable range using int64 nanoseconds since the epoch.
-	ErrTimeOutOfRange = fmt.Errorf("time outside range %d - %d", MinNanoTime, MaxNanoTime)
-)
-
-// SafeCalcTime safely calculates the time given. Will return error if the time is outside the
-// supported range.
-func SafeCalcTime(timestamp int64, precision string) (time.Time, error) {
-	mult := GetPrecisionMultiplier(precision)
-	if t, ok := safeSignedMult(timestamp, mult); ok {
-		tme := time.Unix(0, t).UTC()
-		return tme, CheckTime(tme)
-	}
-
-	return time.Time{}, ErrTimeOutOfRange
-}
-
-// CheckTime checks that a time is within the safe range.
-func CheckTime(t time.Time) error {
-	if t.Before(minNanoTime) || t.After(maxNanoTime) {
-		return ErrTimeOutOfRange
-	}
-	return nil
-}
-
-// Perform the multiplication and check to make sure it didn't overflow.
-func safeSignedMult(a, b int64) (int64, bool) {
-	if a == 0 || b == 0 || a == 1 || b == 1 {
-		return a * b, true
-	}
-	if a == MinNanoTime || b == MaxNanoTime {
-		return 0, false
-	}
-	c := a * b
-	return c, c/b == a
-}

+ 0 - 7
vendor/github.com/influxdata/influxdb/models/uint_support.go

@@ -1,7 +0,0 @@
-// +build uint uint64
-
-package models
-
-func init() {
-	EnableUintSupport()
-}

+ 0 - 115
vendor/github.com/influxdata/influxdb/pkg/escape/bytes.go

@@ -1,115 +0,0 @@
-// Package escape contains utilities for escaping parts of InfluxQL
-// and InfluxDB line protocol.
-package escape // import "github.com/influxdata/influxdb/pkg/escape"
-
-import (
-	"bytes"
-	"strings"
-)
-
-// Codes is a map of bytes to be escaped.
-var Codes = map[byte][]byte{
-	',': []byte(`\,`),
-	'"': []byte(`\"`),
-	' ': []byte(`\ `),
-	'=': []byte(`\=`),
-}
-
-// Bytes escapes characters on the input slice, as defined by Codes.
-func Bytes(in []byte) []byte {
-	for b, esc := range Codes {
-		in = bytes.Replace(in, []byte{b}, esc, -1)
-	}
-	return in
-}
-
-const escapeChars = `," =`
-
-// IsEscaped returns whether b has any escaped characters,
-// i.e. whether b seems to have been processed by Bytes.
-func IsEscaped(b []byte) bool {
-	for len(b) > 0 {
-		i := bytes.IndexByte(b, '\\')
-		if i < 0 {
-			return false
-		}
-
-		if i+1 < len(b) && strings.IndexByte(escapeChars, b[i+1]) >= 0 {
-			return true
-		}
-		b = b[i+1:]
-	}
-	return false
-}
-
-// AppendUnescaped appends the unescaped version of src to dst
-// and returns the resulting slice.
-func AppendUnescaped(dst, src []byte) []byte {
-	var pos int
-	for len(src) > 0 {
-		next := bytes.IndexByte(src[pos:], '\\')
-		if next < 0 || pos+next+1 >= len(src) {
-			return append(dst, src...)
-		}
-
-		if pos+next+1 < len(src) && strings.IndexByte(escapeChars, src[pos+next+1]) >= 0 {
-			if pos+next > 0 {
-				dst = append(dst, src[:pos+next]...)
-			}
-			src = src[pos+next+1:]
-			pos = 0
-		} else {
-			pos += next + 1
-		}
-	}
-
-	return dst
-}
-
-// Unescape returns a new slice containing the unescaped version of in.
-func Unescape(in []byte) []byte {
-	if len(in) == 0 {
-		return nil
-	}
-
-	if bytes.IndexByte(in, '\\') == -1 {
-		return in
-	}
-
-	i := 0
-	inLen := len(in)
-
-	// The output size will be no more than inLen. Preallocating the
-	// capacity of the output is faster and uses less memory than
-	// letting append() do its own (over)allocation.
-	out := make([]byte, 0, inLen)
-
-	for {
-		if i >= inLen {
-			break
-		}
-		if in[i] == '\\' && i+1 < inLen {
-			switch in[i+1] {
-			case ',':
-				out = append(out, ',')
-				i += 2
-				continue
-			case '"':
-				out = append(out, '"')
-				i += 2
-				continue
-			case ' ':
-				out = append(out, ' ')
-				i += 2
-				continue
-			case '=':
-				out = append(out, '=')
-				i += 2
-				continue
-			}
-		}
-		out = append(out, in[i])
-		i += 1
-	}
-	return out
-}

+ 0 - 21
vendor/github.com/influxdata/influxdb/pkg/escape/strings.go

@@ -1,21 +0,0 @@
-package escape
-
-import "strings"
-
-var (
-	escaper   = strings.NewReplacer(`,`, `\,`, `"`, `\"`, ` `, `\ `, `=`, `\=`)
-	unescaper = strings.NewReplacer(`\,`, `,`, `\"`, `"`, `\ `, ` `, `\=`, `=`)
-)
-
-// UnescapeString returns unescaped version of in.
-func UnescapeString(in string) string {
-	if strings.IndexByte(in, '\\') == -1 {
-		return in
-	}
-	return unescaper.Replace(in)
-}
-
-// String returns the escaped version of in.
-func String(in string) string {
-	return escaper.Replace(in)
-}

+ 0 - 21
vendor/github.com/kr/pretty/License

@@ -1,21 +0,0 @@
-The MIT License (MIT)
-
-Copyright 2012 Keith Rarick
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-THE SOFTWARE.

+ 0 - 265
vendor/github.com/kr/pretty/diff.go

@@ -1,265 +0,0 @@
-package pretty
-
-import (
-	"fmt"
-	"io"
-	"reflect"
-)
-
-type sbuf []string
-
-func (p *sbuf) Printf(format string, a ...interface{}) {
-	s := fmt.Sprintf(format, a...)
-	*p = append(*p, s)
-}
-
-// Diff returns a slice where each element describes
-// a difference between a and b.
-func Diff(a, b interface{}) (desc []string) {
-	Pdiff((*sbuf)(&desc), a, b)
-	return desc
-}
-
-// wprintfer calls Fprintf on w for each Printf call
-// with a trailing newline.
-type wprintfer struct{ w io.Writer }
-
-func (p *wprintfer) Printf(format string, a ...interface{}) {
-	fmt.Fprintf(p.w, format+"\n", a...)
-}
-
-// Fdiff writes to w a description of the differences between a and b.
-func Fdiff(w io.Writer, a, b interface{}) {
-	Pdiff(&wprintfer{w}, a, b)
-}
-
-type Printfer interface {
-	Printf(format string, a ...interface{})
-}
-
-// Pdiff prints to p a description of the differences between a and b.
-// It calls Printf once for each difference, with no trailing newline.
-// The standard library log.Logger is a Printfer.
-func Pdiff(p Printfer, a, b interface{}) {
-	diffPrinter{w: p}.diff(reflect.ValueOf(a), reflect.ValueOf(b))
-}
-
-type Logfer interface {
-	Logf(format string, a ...interface{})
-}
-
-// logprintfer calls Fprintf on w for each Printf call
-// with a trailing newline.
-type logprintfer struct{ l Logfer }
-
-func (p *logprintfer) Printf(format string, a ...interface{}) {
-	p.l.Logf(format, a...)
-}
-
-// Ldiff prints to l a description of the differences between a and b.
-// It calls Logf once for each difference, with no trailing newline.
-// The standard library testing.T and testing.B are Logfers.
-func Ldiff(l Logfer, a, b interface{}) {
-	Pdiff(&logprintfer{l}, a, b)
-}
-
-type diffPrinter struct {
-	w Printfer
-	l string // label
-}
-
-func (w diffPrinter) printf(f string, a ...interface{}) {
-	var l string
-	if w.l != "" {
-		l = w.l + ": "
-	}
-	w.w.Printf(l+f, a...)
-}
-
-func (w diffPrinter) diff(av, bv reflect.Value) {
-	if !av.IsValid() && bv.IsValid() {
-		w.printf("nil != %# v", formatter{v: bv, quote: true})
-		return
-	}
-	if av.IsValid() && !bv.IsValid() {
-		w.printf("%# v != nil", formatter{v: av, quote: true})
-		return
-	}
-	if !av.IsValid() && !bv.IsValid() {
-		return
-	}
-
-	at := av.Type()
-	bt := bv.Type()
-	if at != bt {
-		w.printf("%v != %v", at, bt)
-		return
-	}
-
-	switch kind := at.Kind(); kind {
-	case reflect.Bool:
-		if a, b := av.Bool(), bv.Bool(); a != b {
-			w.printf("%v != %v", a, b)
-		}
-	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
-		if a, b := av.Int(), bv.Int(); a != b {
-			w.printf("%d != %d", a, b)
-		}
-	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
-		if a, b := av.Uint(), bv.Uint(); a != b {
-			w.printf("%d != %d", a, b)
-		}
-	case reflect.Float32, reflect.Float64:
-		if a, b := av.Float(), bv.Float(); a != b {
-			w.printf("%v != %v", a, b)
-		}
-	case reflect.Complex64, reflect.Complex128:
-		if a, b := av.Complex(), bv.Complex(); a != b {
-			w.printf("%v != %v", a, b)
-		}
-	case reflect.Array:
-		n := av.Len()
-		for i := 0; i < n; i++ {
-			w.relabel(fmt.Sprintf("[%d]", i)).diff(av.Index(i), bv.Index(i))
-		}
-	case reflect.Chan, reflect.Func, reflect.UnsafePointer:
-		if a, b := av.Pointer(), bv.Pointer(); a != b {
-			w.printf("%#x != %#x", a, b)
-		}
-	case reflect.Interface:
-		w.diff(av.Elem(), bv.Elem())
-	case reflect.Map:
-		ak, both, bk := keyDiff(av.MapKeys(), bv.MapKeys())
-		for _, k := range ak {
-			w := w.relabel(fmt.Sprintf("[%#v]", k))
-			w.printf("%q != (missing)", av.MapIndex(k))
-		}
-		for _, k := range both {
-			w := w.relabel(fmt.Sprintf("[%#v]", k))
-			w.diff(av.MapIndex(k), bv.MapIndex(k))
-		}
-		for _, k := range bk {
-			w := w.relabel(fmt.Sprintf("[%#v]", k))
-			w.printf("(missing) != %q", bv.MapIndex(k))
-		}
-	case reflect.Ptr:
-		switch {
-		case av.IsNil() && !bv.IsNil():
-			w.printf("nil != %# v", formatter{v: bv, quote: true})
-		case !av.IsNil() && bv.IsNil():
-			w.printf("%# v != nil", formatter{v: av, quote: true})
-		case !av.IsNil() && !bv.IsNil():
-			w.diff(av.Elem(), bv.Elem())
-		}
-	case reflect.Slice:
-		lenA := av.Len()
-		lenB := bv.Len()
-		if lenA != lenB {
-			w.printf("%s[%d] != %s[%d]", av.Type(), lenA, bv.Type(), lenB)
-			break
-		}
-		for i := 0; i < lenA; i++ {
-			w.relabel(fmt.Sprintf("[%d]", i)).diff(av.Index(i), bv.Index(i))
-		}
-	case reflect.String:
-		if a, b := av.String(), bv.String(); a != b {
-			w.printf("%q != %q", a, b)
-		}
-	case reflect.Struct:
-		for i := 0; i < av.NumField(); i++ {
-			w.relabel(at.Field(i).Name).diff(av.Field(i), bv.Field(i))
-		}
-	default:
-		panic("unknown reflect Kind: " + kind.String())
-	}
-}
-
-func (d diffPrinter) relabel(name string) (d1 diffPrinter) {
-	d1 = d
-	if d.l != "" && name[0] != '[' {
-		d1.l += "."
-	}
-	d1.l += name
-	return d1
-}
-
-// keyEqual compares a and b for equality.
-// Both a and b must be valid map keys.
-func keyEqual(av, bv reflect.Value) bool {
-	if !av.IsValid() && !bv.IsValid() {
-		return true
-	}
-	if !av.IsValid() || !bv.IsValid() || av.Type() != bv.Type() {
-		return false
-	}
-	switch kind := av.Kind(); kind {
-	case reflect.Bool:
-		a, b := av.Bool(), bv.Bool()
-		return a == b
-	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
-		a, b := av.Int(), bv.Int()
-		return a == b
-	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
-		a, b := av.Uint(), bv.Uint()
-		return a == b
-	case reflect.Float32, reflect.Float64:
-		a, b := av.Float(), bv.Float()
-		return a == b
-	case reflect.Complex64, reflect.Complex128:
-		a, b := av.Complex(), bv.Complex()
-		return a == b
-	case reflect.Array:
-		for i := 0; i < av.Len(); i++ {
-			if !keyEqual(av.Index(i), bv.Index(i)) {
-				return false
-			}
-		}
-		return true
-	case reflect.Chan, reflect.UnsafePointer, reflect.Ptr:
-		a, b := av.Pointer(), bv.Pointer()
-		return a == b
-	case reflect.Interface:
-		return keyEqual(av.Elem(), bv.Elem())
-	case reflect.String:
-		a, b := av.String(), bv.String()
-		return a == b
-	case reflect.Struct:
-		for i := 0; i < av.NumField(); i++ {
-			if !keyEqual(av.Field(i), bv.Field(i)) {
-				return false
-			}
-		}
-		return true
-	default:
-		panic("invalid map key type " + av.Type().String())
-	}
-}
-
-func keyDiff(a, b []reflect.Value) (ak, both, bk []reflect.Value) {
-	for _, av := range a {
-		inBoth := false
-		for _, bv := range b {
-			if keyEqual(av, bv) {
-				inBoth = true
-				both = append(both, av)
-				break
-			}
-		}
-		if !inBoth {
-			ak = append(ak, av)
-		}
-	}
-	for _, bv := range b {
-		inBoth := false
-		for _, av := range a {
-			if keyEqual(av, bv) {
-				inBoth = true
-				break
-			}
-		}
-		if !inBoth {
-			bk = append(bk, bv)
-		}
-	}
-	return
-}

+ 0 - 328
vendor/github.com/kr/pretty/formatter.go

@@ -1,328 +0,0 @@
-package pretty
-
-import (
-	"fmt"
-	"io"
-	"reflect"
-	"strconv"
-	"text/tabwriter"
-
-	"github.com/kr/text"
-)
-
-type formatter struct {
-	v     reflect.Value
-	force bool
-	quote bool
-}
-
-// Formatter makes a wrapper, f, that will format x as go source with line
-// breaks and tabs. Object f responds to the "%v" formatting verb when both the
-// "#" and " " (space) flags are set, for example:
-//
-//     fmt.Sprintf("%# v", Formatter(x))
-//
-// If one of these two flags is not set, or any other verb is used, f will
-// format x according to the usual rules of package fmt.
-// In particular, if x satisfies fmt.Formatter, then x.Format will be called.
-func Formatter(x interface{}) (f fmt.Formatter) {
-	return formatter{v: reflect.ValueOf(x), quote: true}
-}
-
-func (fo formatter) String() string {
-	return fmt.Sprint(fo.v.Interface()) // unwrap it
-}
-
-func (fo formatter) passThrough(f fmt.State, c rune) {
-	s := "%"
-	for i := 0; i < 128; i++ {
-		if f.Flag(i) {
-			s += string(i)
-		}
-	}
-	if w, ok := f.Width(); ok {
-		s += fmt.Sprintf("%d", w)
-	}
-	if p, ok := f.Precision(); ok {
-		s += fmt.Sprintf(".%d", p)
-	}
-	s += string(c)
-	fmt.Fprintf(f, s, fo.v.Interface())
-}
-
-func (fo formatter) Format(f fmt.State, c rune) {
-	if fo.force || c == 'v' && f.Flag('#') && f.Flag(' ') {
-		w := tabwriter.NewWriter(f, 4, 4, 1, ' ', 0)
-		p := &printer{tw: w, Writer: w, visited: make(map[visit]int)}
-		p.printValue(fo.v, true, fo.quote)
-		w.Flush()
-		return
-	}
-	fo.passThrough(f, c)
-}
-
-type printer struct {
-	io.Writer
-	tw      *tabwriter.Writer
-	visited map[visit]int
-	depth   int
-}
-
-func (p *printer) indent() *printer {
-	q := *p
-	q.tw = tabwriter.NewWriter(p.Writer, 4, 4, 1, ' ', 0)
-	q.Writer = text.NewIndentWriter(q.tw, []byte{'\t'})
-	return &q
-}
-
-func (p *printer) printInline(v reflect.Value, x interface{}, showType bool) {
-	if showType {
-		io.WriteString(p, v.Type().String())
-		fmt.Fprintf(p, "(%#v)", x)
-	} else {
-		fmt.Fprintf(p, "%#v", x)
-	}
-}
-
-// printValue must keep track of already-printed pointer values to avoid
-// infinite recursion.
-type visit struct {
-	v   uintptr
-	typ reflect.Type
-}
-
-func (p *printer) printValue(v reflect.Value, showType, quote bool) {
-	if p.depth > 10 {
-		io.WriteString(p, "!%v(DEPTH EXCEEDED)")
-		return
-	}
-
-	switch v.Kind() {
-	case reflect.Bool:
-		p.printInline(v, v.Bool(), showType)
-	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
-		p.printInline(v, v.Int(), showType)
-	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
-		p.printInline(v, v.Uint(), showType)
-	case reflect.Float32, reflect.Float64:
-		p.printInline(v, v.Float(), showType)
-	case reflect.Complex64, reflect.Complex128:
-		fmt.Fprintf(p, "%#v", v.Complex())
-	case reflect.String:
-		p.fmtString(v.String(), quote)
-	case reflect.Map:
-		t := v.Type()
-		if showType {
-			io.WriteString(p, t.String())
-		}
-		writeByte(p, '{')
-		if nonzero(v) {
-			expand := !canInline(v.Type())
-			pp := p
-			if expand {
-				writeByte(p, '\n')
-				pp = p.indent()
-			}
-			keys := v.MapKeys()
-			for i := 0; i < v.Len(); i++ {
-				showTypeInStruct := true
-				k := keys[i]
-				mv := v.MapIndex(k)
-				pp.printValue(k, false, true)
-				writeByte(pp, ':')
-				if expand {
-					writeByte(pp, '\t')
-				}
-				showTypeInStruct = t.Elem().Kind() == reflect.Interface
-				pp.printValue(mv, showTypeInStruct, true)
-				if expand {
-					io.WriteString(pp, ",\n")
-				} else if i < v.Len()-1 {
-					io.WriteString(pp, ", ")
-				}
-			}
-			if expand {
-				pp.tw.Flush()
-			}
-		}
-		writeByte(p, '}')
-	case reflect.Struct:
-		t := v.Type()
-		if v.CanAddr() {
-			addr := v.UnsafeAddr()
-			vis := visit{addr, t}
-			if vd, ok := p.visited[vis]; ok && vd < p.depth {
-				p.fmtString(t.String()+"{(CYCLIC REFERENCE)}", false)
-				break // don't print v again
-			}
-			p.visited[vis] = p.depth
-		}
-
-		if showType {
-			io.WriteString(p, t.String())
-		}
-		writeByte(p, '{')
-		if nonzero(v) {
-			expand := !canInline(v.Type())
-			pp := p
-			if expand {
-				writeByte(p, '\n')
-				pp = p.indent()
-			}
-			for i := 0; i < v.NumField(); i++ {
-				showTypeInStruct := true
-				if f := t.Field(i); f.Name != "" {
-					io.WriteString(pp, f.Name)
-					writeByte(pp, ':')
-					if expand {
-						writeByte(pp, '\t')
-					}
-					showTypeInStruct = labelType(f.Type)
-				}
-				pp.printValue(getField(v, i), showTypeInStruct, true)
-				if expand {
-					io.WriteString(pp, ",\n")
-				} else if i < v.NumField()-1 {
-					io.WriteString(pp, ", ")
-				}
-			}
-			if expand {
-				pp.tw.Flush()
-			}
-		}
-		writeByte(p, '}')
-	case reflect.Interface:
-		switch e := v.Elem(); {
-		case e.Kind() == reflect.Invalid:
-			io.WriteString(p, "nil")
-		case e.IsValid():
-			pp := *p
-			pp.depth++
-			pp.printValue(e, showType, true)
-		default:
-			io.WriteString(p, v.Type().String())
-			io.WriteString(p, "(nil)")
-		}
-	case reflect.Array, reflect.Slice:
-		t := v.Type()
-		if showType {
-			io.WriteString(p, t.String())
-		}
-		if v.Kind() == reflect.Slice && v.IsNil() && showType {
-			io.WriteString(p, "(nil)")
-			break
-		}
-		if v.Kind() == reflect.Slice && v.IsNil() {
-			io.WriteString(p, "nil")
-			break
-		}
-		writeByte(p, '{')
-		expand := !canInline(v.Type())
-		pp := p
-		if expand {
-			writeByte(p, '\n')
-			pp = p.indent()
-		}
-		for i := 0; i < v.Len(); i++ {
-			showTypeInSlice := t.Elem().Kind() == reflect.Interface
-			pp.printValue(v.Index(i), showTypeInSlice, true)
-			if expand {
-				io.WriteString(pp, ",\n")
-			} else if i < v.Len()-1 {
-				io.WriteString(pp, ", ")
-			}
-		}
-		if expand {
-			pp.tw.Flush()
-		}
-		writeByte(p, '}')
-	case reflect.Ptr:
-		e := v.Elem()
-		if !e.IsValid() {
-			writeByte(p, '(')
-			io.WriteString(p, v.Type().String())
-			io.WriteString(p, ")(nil)")
-		} else {
-			pp := *p
-			pp.depth++
-			writeByte(pp, '&')
-			pp.printValue(e, true, true)
-		}
-	case reflect.Chan:
-		x := v.Pointer()
-		if showType {
-			writeByte(p, '(')
-			io.WriteString(p, v.Type().String())
-			fmt.Fprintf(p, ")(%#v)", x)
-		} else {
-			fmt.Fprintf(p, "%#v", x)
-		}
-	case reflect.Func:
-		io.WriteString(p, v.Type().String())
-		io.WriteString(p, " {...}")
-	case reflect.UnsafePointer:
-		p.printInline(v, v.Pointer(), showType)
-	case reflect.Invalid:
-		io.WriteString(p, "nil")
-	}
-}
-
-func canInline(t reflect.Type) bool {
-	switch t.Kind() {
-	case reflect.Map:
-		return !canExpand(t.Elem())
-	case reflect.Struct:
-		for i := 0; i < t.NumField(); i++ {
-			if canExpand(t.Field(i).Type) {
-				return false
-			}
-		}
-		return true
-	case reflect.Interface:
-		return false
-	case reflect.Array, reflect.Slice:
-		return !canExpand(t.Elem())
-	case reflect.Ptr:
-		return false
-	case reflect.Chan, reflect.Func, reflect.UnsafePointer:
-		return false
-	}
-	return true
-}
-
-func canExpand(t reflect.Type) bool {
-	switch t.Kind() {
-	case reflect.Map, reflect.Struct,
-		reflect.Interface, reflect.Array, reflect.Slice,
-		reflect.Ptr:
-		return true
-	}
-	return false
-}
-
-func labelType(t reflect.Type) bool {
-	switch t.Kind() {
-	case reflect.Interface, reflect.Struct:
-		return true
-	}
-	return false
-}
-
-func (p *printer) fmtString(s string, quote bool) {
-	if quote {
-		s = strconv.Quote(s)
-	}
-	io.WriteString(p, s)
-}
-
-func writeByte(w io.Writer, b byte) {
-	w.Write([]byte{b})
-}
-
-func getField(v reflect.Value, i int) reflect.Value {
-	val := v.Field(i)
-	if val.Kind() == reflect.Interface && !val.IsNil() {
-		val = val.Elem()
-	}
-	return val
-}

+ 0 - 108
vendor/github.com/kr/pretty/pretty.go

@@ -1,108 +0,0 @@
-// Package pretty provides pretty-printing for Go values. This is
-// useful during debugging, to avoid wrapping long output lines in
-// the terminal.
-//
-// It provides a function, Formatter, that can be used with any
-// function that accepts a format string. It also provides
-// convenience wrappers for functions in packages fmt and log.
-package pretty
-
-import (
-	"fmt"
-	"io"
-	"log"
-	"reflect"
-)
-
-// Errorf is a convenience wrapper for fmt.Errorf.
-//
-// Calling Errorf(f, x, y) is equivalent to
-// fmt.Errorf(f, Formatter(x), Formatter(y)).
-func Errorf(format string, a ...interface{}) error {
-	return fmt.Errorf(format, wrap(a, false)...)
-}
-
-// Fprintf is a convenience wrapper for fmt.Fprintf.
-//
-// Calling Fprintf(w, f, x, y) is equivalent to
-// fmt.Fprintf(w, f, Formatter(x), Formatter(y)).
-func Fprintf(w io.Writer, format string, a ...interface{}) (n int, error error) {
-	return fmt.Fprintf(w, format, wrap(a, false)...)
-}
-
-// Log is a convenience wrapper for log.Printf.
-//
-// Calling Log(x, y) is equivalent to
-// log.Print(Formatter(x), Formatter(y)), but each operand is
-// formatted with "%# v".
-func Log(a ...interface{}) {
-	log.Print(wrap(a, true)...)
-}
-
-// Logf is a convenience wrapper for log.Printf.
-//
-// Calling Logf(f, x, y) is equivalent to
-// log.Printf(f, Formatter(x), Formatter(y)).
-func Logf(format string, a ...interface{}) {
-	log.Printf(format, wrap(a, false)...)
-}
-
-// Logln is a convenience wrapper for log.Printf.
-//
-// Calling Logln(x, y) is equivalent to
-// log.Println(Formatter(x), Formatter(y)), but each operand is
-// formatted with "%# v".
-func Logln(a ...interface{}) {
-	log.Println(wrap(a, true)...)
-}
-
-// Print pretty-prints its operands and writes to standard output.
-//
-// Calling Print(x, y) is equivalent to
-// fmt.Print(Formatter(x), Formatter(y)), but each operand is
-// formatted with "%# v".
-func Print(a ...interface{}) (n int, errno error) {
-	return fmt.Print(wrap(a, true)...)
-}
-
-// Printf is a convenience wrapper for fmt.Printf.
-//
-// Calling Printf(f, x, y) is equivalent to
-// fmt.Printf(f, Formatter(x), Formatter(y)).
-func Printf(format string, a ...interface{}) (n int, errno error) {
-	return fmt.Printf(format, wrap(a, false)...)
-}
-
-// Println pretty-prints its operands and writes to standard output.
-//
-// Calling Print(x, y) is equivalent to
-// fmt.Println(Formatter(x), Formatter(y)), but each operand is
-// formatted with "%# v".
-func Println(a ...interface{}) (n int, errno error) {
-	return fmt.Println(wrap(a, true)...)
-}
-
-// Sprint is a convenience wrapper for fmt.Sprintf.
-//
-// Calling Sprint(x, y) is equivalent to
-// fmt.Sprint(Formatter(x), Formatter(y)), but each operand is
-// formatted with "%# v".
-func Sprint(a ...interface{}) string {
-	return fmt.Sprint(wrap(a, true)...)
-}
-
-// Sprintf is a convenience wrapper for fmt.Sprintf.
-//
-// Calling Sprintf(f, x, y) is equivalent to
-// fmt.Sprintf(f, Formatter(x), Formatter(y)).
-func Sprintf(format string, a ...interface{}) string {
-	return fmt.Sprintf(format, wrap(a, false)...)
-}
-
-func wrap(a []interface{}, force bool) []interface{} {
-	w := make([]interface{}, len(a))
-	for i, x := range a {
-		w[i] = formatter{v: reflect.ValueOf(x), force: force}
-	}
-	return w
-}

+ 0 - 41
vendor/github.com/kr/pretty/zero.go

@@ -1,41 +0,0 @@
-package pretty
-
-import (
-	"reflect"
-)
-
-func nonzero(v reflect.Value) bool {
-	switch v.Kind() {
-	case reflect.Bool:
-		return v.Bool()
-	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
-		return v.Int() != 0
-	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
-		return v.Uint() != 0
-	case reflect.Float32, reflect.Float64:
-		return v.Float() != 0
-	case reflect.Complex64, reflect.Complex128:
-		return v.Complex() != complex(0, 0)
-	case reflect.String:
-		return v.String() != ""
-	case reflect.Struct:
-		for i := 0; i < v.NumField(); i++ {
-			if nonzero(getField(v, i)) {
-				return true
-			}
-		}
-		return false
-	case reflect.Array:
-		for i := 0; i < v.Len(); i++ {
-			if nonzero(v.Index(i)) {
-				return true
-			}
-		}
-		return false
-	case reflect.Map, reflect.Interface, reflect.Slice, reflect.Ptr, reflect.Chan, reflect.Func:
-		return !v.IsNil()
-	case reflect.UnsafePointer:
-		return v.Pointer() != 0
-	}
-	return true
-}

+ 0 - 19
vendor/github.com/kr/text/License

@@ -1,19 +0,0 @@
-Copyright 2012 Keith Rarick
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-THE SOFTWARE.

+ 0 - 3
vendor/github.com/kr/text/doc.go

@@ -1,3 +0,0 @@
-// Package text provides rudimentary functions for manipulating text in
-// paragraphs.
-package text

+ 0 - 74
vendor/github.com/kr/text/indent.go

@@ -1,74 +0,0 @@
-package text
-
-import (
-	"io"
-)
-
-// Indent inserts prefix at the beginning of each non-empty line of s. The
-// end-of-line marker is NL.
-func Indent(s, prefix string) string {
-	return string(IndentBytes([]byte(s), []byte(prefix)))
-}
-
-// IndentBytes inserts prefix at the beginning of each non-empty line of b.
-// The end-of-line marker is NL.
-func IndentBytes(b, prefix []byte) []byte {
-	var res []byte
-	bol := true
-	for _, c := range b {
-		if bol && c != '\n' {
-			res = append(res, prefix...)
-		}
-		res = append(res, c)
-		bol = c == '\n'
-	}
-	return res
-}
-
-// Writer indents each line of its input.
-type indentWriter struct {
-	w   io.Writer
-	bol bool
-	pre [][]byte
-	sel int
-	off int
-}
-
-// NewIndentWriter makes a new write filter that indents the input
-// lines. Each line is prefixed in order with the corresponding
-// element of pre. If there are more lines than elements, the last
-// element of pre is repeated for each subsequent line.
-func NewIndentWriter(w io.Writer, pre ...[]byte) io.Writer {
-	return &indentWriter{
-		w:   w,
-		pre: pre,
-		bol: true,
-	}
-}
-
-// The only errors returned are from the underlying indentWriter.
-func (w *indentWriter) Write(p []byte) (n int, err error) {
-	for _, c := range p {
-		if w.bol {
-			var i int
-			i, err = w.w.Write(w.pre[w.sel][w.off:])
-			w.off += i
-			if err != nil {
-				return n, err
-			}
-		}
-		_, err = w.w.Write([]byte{c})
-		if err != nil {
-			return n, err
-		}
-		n++
-		w.bol = c == '\n'
-		if w.bol {
-			w.off = 0
-			if w.sel < len(w.pre)-1 {
-				w.sel++
-			}
-		}
-	}
-	return n, nil
-}

+ 0 - 86
vendor/github.com/kr/text/wrap.go

@@ -1,86 +0,0 @@
-package text
-
-import (
-	"bytes"
-	"math"
-)
-
-var (
-	nl = []byte{'\n'}
-	sp = []byte{' '}
-)
-
-const defaultPenalty = 1e5
-
-// Wrap wraps s into a paragraph of lines of length lim, with minimal
-// raggedness.
-func Wrap(s string, lim int) string {
-	return string(WrapBytes([]byte(s), lim))
-}
-
-// WrapBytes wraps b into a paragraph of lines of length lim, with minimal
-// raggedness.
-func WrapBytes(b []byte, lim int) []byte {
-	words := bytes.Split(bytes.Replace(bytes.TrimSpace(b), nl, sp, -1), sp)
-	var lines [][]byte
-	for _, line := range WrapWords(words, 1, lim, defaultPenalty) {
-		lines = append(lines, bytes.Join(line, sp))
-	}
-	return bytes.Join(lines, nl)
-}
-
-// WrapWords is the low-level line-breaking algorithm, useful if you need more
-// control over the details of the text wrapping process. For most uses, either
-// Wrap or WrapBytes will be sufficient and more convenient.
-//
-// WrapWords splits a list of words into lines with minimal "raggedness",
-// treating each byte as one unit, accounting for spc units between adjacent
-// words on each line, and attempting to limit lines to lim units. Raggedness
-// is the total error over all lines, where error is the square of the
-// difference of the length of the line and lim. Too-long lines (which only
-// happen when a single word is longer than lim units) have pen penalty units
-// added to the error.
-func WrapWords(words [][]byte, spc, lim, pen int) [][][]byte {
-	n := len(words)
-
-	length := make([][]int, n)
-	for i := 0; i < n; i++ {
-		length[i] = make([]int, n)
-		length[i][i] = len(words[i])
-		for j := i + 1; j < n; j++ {
-			length[i][j] = length[i][j-1] + spc + len(words[j])
-		}
-	}
-
-	nbrk := make([]int, n)
-	cost := make([]int, n)
-	for i := range cost {
-		cost[i] = math.MaxInt32
-	}
-	for i := n - 1; i >= 0; i-- {
-		if length[i][n-1] <= lim || i == n-1 {
-			cost[i] = 0
-			nbrk[i] = n
-		} else {
-			for j := i + 1; j < n; j++ {
-				d := lim - length[i][j-1]
-				c := d*d + cost[j]
-				if length[i][j-1] > lim {
-					c += pen // too-long lines get a worse penalty
-				}
-				if c < cost[i] {
-					cost[i] = c
-					nbrk[i] = j
-				}
-			}
-		}
-	}
-
-	var lines [][][]byte
-	i := 0
-	for i < n {
-		lines = append(lines, words[i:nbrk[i]])
-		i = nbrk[i]
-	}
-	return lines
-}

+ 201 - 0
vendor/github.com/matttproud/golang_protobuf_extensions/LICENSE

@@ -0,0 +1,201 @@
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
+   APPENDIX: How to apply the Apache License to your work.
+
+      To apply the Apache License to your work, attach the following
+      boilerplate notice, with the fields enclosed by brackets "{}"
+      replaced with your own identifying information. (Don't include
+      the brackets!)  The text should be enclosed in the appropriate
+      comment syntax for the file format. We also recommend that a
+      file or class name and description of purpose be included on the
+      same "printed page" as the copyright notice for easier
+      identification within third-party archives.
+
+   Copyright {yyyy} {name of copyright owner}
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.

+ 1 - 0
vendor/github.com/matttproud/golang_protobuf_extensions/NOTICE

@@ -0,0 +1 @@
+Copyright 2012 Matt T. Proud ([email protected])

+ 75 - 0
vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/decode.go

@@ -0,0 +1,75 @@
+// Copyright 2013 Matt T. Proud
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package pbutil
+
+import (
+	"encoding/binary"
+	"errors"
+	"io"
+
+	"github.com/golang/protobuf/proto"
+)
+
+var errInvalidVarint = errors.New("invalid varint32 encountered")
+
+// ReadDelimited decodes a message from the provided length-delimited stream,
+// where the length is encoded as 32-bit varint prefix to the message body.
+// It returns the total number of bytes read and any applicable error.  This is
+// roughly equivalent to the companion Java API's
+// MessageLite#parseDelimitedFrom.  As per the reader contract, this function
+// calls r.Read repeatedly as required until exactly one message including its
+// prefix is read and decoded (or an error has occurred).  The function never
+// reads more bytes from the stream than required.  The function never returns
+// an error if a message has been read and decoded correctly, even if the end
+// of the stream has been reached in doing so.  In that case, any subsequent
+// calls return (0, io.EOF).
+func ReadDelimited(r io.Reader, m proto.Message) (n int, err error) {
+	// Per AbstractParser#parsePartialDelimitedFrom with
+	// CodedInputStream#readRawVarint32.
+	var headerBuf [binary.MaxVarintLen32]byte
+	var bytesRead, varIntBytes int
+	var messageLength uint64
+	for varIntBytes == 0 { // i.e. no varint has been decoded yet.
+		if bytesRead >= len(headerBuf) {
+			return bytesRead, errInvalidVarint
+		}
+		// We have to read byte by byte here to avoid reading more bytes
+		// than required. Each read byte is appended to what we have
+		// read before.
+		newBytesRead, err := r.Read(headerBuf[bytesRead : bytesRead+1])
+		if newBytesRead == 0 {
+			if err != nil {
+				return bytesRead, err
+			}
+			// A Reader should not return (0, nil), but if it does,
+			// it should be treated as no-op (according to the
+			// Reader contract). So let's go on...
+			continue
+		}
+		bytesRead += newBytesRead
+		// Now present everything read so far to the varint decoder and
+		// see if a varint can be decoded already.
+		messageLength, varIntBytes = proto.DecodeVarint(headerBuf[:bytesRead])
+	}
+
+	messageBuf := make([]byte, messageLength)
+	newBytesRead, err := io.ReadFull(r, messageBuf)
+	bytesRead += newBytesRead
+	if err != nil {
+		return bytesRead, err
+	}
+
+	return bytesRead, proto.Unmarshal(messageBuf, m)
+}

+ 16 - 0
vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/doc.go

@@ -0,0 +1,16 @@
+// Copyright 2013 Matt T. Proud
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// Package pbutil provides record length-delimited Protocol Buffer streaming.
+package pbutil

+ 46 - 0
vendor/github.com/matttproud/golang_protobuf_extensions/pbutil/encode.go

@@ -0,0 +1,46 @@
+// Copyright 2013 Matt T. Proud
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//     http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package pbutil
+
+import (
+	"encoding/binary"
+	"io"
+
+	"github.com/golang/protobuf/proto"
+)
+
+// WriteDelimited encodes and dumps a message to the provided writer prefixed
+// with a 32-bit varint indicating the length of the encoded message, producing
+// a length-delimited record stream, which can be used to chain together
+// encoded messages of the same type together in a file.  It returns the total
+// number of bytes written and any applicable error.  This is roughly
+// equivalent to the companion Java API's MessageLite#writeDelimitedTo.
+func WriteDelimited(w io.Writer, m proto.Message) (n int, err error) {
+	buffer, err := proto.Marshal(m)
+	if err != nil {
+		return 0, err
+	}
+
+	var buf [binary.MaxVarintLen32]byte
+	encodedLength := binary.PutUvarint(buf[:], uint64(len(buffer)))
+
+	sync, err := w.Write(buf[:encodedLength])
+	if err != nil {
+		return sync, err
+	}
+
+	n, err = w.Write(buffer)
+	return n + sync, err
+}

+ 4 - 7
vendor/github.com/miekg/dns/client.go

@@ -21,8 +21,6 @@ type Conn struct {
 	net.Conn                         // a net.Conn holding the connection
 	UDPSize        uint16            // minimum receive buffer for UDP messages
 	TsigSecret     map[string]string // secret(s) for Tsig map[<zonename>]<base64 secret>, zonename must be in canonical form (lowercase, fqdn, see RFC 4034 Section 6.2)
-	rtt            time.Duration
-	t              time.Time
 	tsigRequestMAC string
 }
 
@@ -177,8 +175,9 @@ func (c *Client) exchange(m *Msg, a string) (r *Msg, rtt time.Duration, err erro
 	}
 
 	co.TsigSecret = c.TsigSecret
+	t := time.Now()
 	// write with the appropriate write timeout
-	co.SetWriteDeadline(time.Now().Add(c.getTimeoutForRequest(c.writeTimeout())))
+	co.SetWriteDeadline(t.Add(c.getTimeoutForRequest(c.writeTimeout())))
 	if err = co.WriteMsg(m); err != nil {
 		return nil, 0, err
 	}
@@ -188,7 +187,8 @@ func (c *Client) exchange(m *Msg, a string) (r *Msg, rtt time.Duration, err erro
 	if err == nil && r.Id != m.Id {
 		err = ErrId
 	}
-	return r, co.rtt, err
+	rtt = time.Since(t)
+	return r, rtt, err
 }
 
 // ReadMsg reads a message from the connection co.
@@ -240,7 +240,6 @@ func (co *Conn) ReadMsgHeader(hdr *Header) ([]byte, error) {
 		}
 		p = make([]byte, l)
 		n, err = tcpRead(r, p)
-		co.rtt = time.Since(co.t)
 	default:
 		if co.UDPSize > MinMsgSize {
 			p = make([]byte, co.UDPSize)
@@ -248,7 +247,6 @@ func (co *Conn) ReadMsgHeader(hdr *Header) ([]byte, error) {
 			p = make([]byte, MinMsgSize)
 		}
 		n, err = co.Read(p)
-		co.rtt = time.Since(co.t)
 	}
 
 	if err != nil {
@@ -361,7 +359,6 @@ func (co *Conn) WriteMsg(m *Msg) (err error) {
 	if err != nil {
 		return err
 	}
-	co.t = time.Now()
 	if _, err = co.Write(out); err != nil {
 		return err
 	}

+ 1 - 1
vendor/github.com/miekg/dns/clientconfig.go

@@ -91,7 +91,7 @@ func ClientConfigFromReader(resolvconf io.Reader) (*ClientConfig, error) {
 						n = 1
 					}
 					c.Timeout = n
-				case len(s) >= 8 && s[:9] == "attempts:":
+				case len(s) >= 9 && s[:9] == "attempts:":
 					n, _ := strconv.Atoi(s[9:])
 					if n < 1 {
 						n = 1

+ 2 - 2
vendor/github.com/miekg/dns/doc.go

@@ -73,11 +73,11 @@ and port to use for the connection:
 		Port: 12345,
 		Zone: "",
 	}
-	d := net.Dialer{
+	c.Dialer := &net.Dialer{
 		Timeout: 200 * time.Millisecond,
 		LocalAddr: &laddr,
 	}
-	in, rtt, err := c.ExchangeWithDialer(&d, m1, "8.8.8.8:53")
+	in, rtt, err := c.Exchange(m1, "8.8.8.8:53")
 
 If these "advanced" features are not needed, a simple UDP query can be sent,
 with:

+ 45 - 22
vendor/github.com/miekg/dns/msg.go

@@ -595,6 +595,13 @@ func UnpackRR(msg []byte, off int) (rr RR, off1 int, err error) {
 	if err != nil {
 		return nil, len(msg), err
 	}
+
+	return UnpackRRWithHeader(h, msg, off)
+}
+
+// UnpackRRWithHeader unpacks the record type specific payload given an existing
+// RR_Header.
+func UnpackRRWithHeader(h RR_Header, msg []byte, off int) (rr RR, off1 int, err error) {
 	end := off + int(h.Rdlength)
 
 	if fn, known := typeToUnpack[h.Rrtype]; !known {
@@ -926,49 +933,65 @@ func compressedLen(dns *Msg, compress bool) int {
 			l += r.len()
 			compressionLenHelper(compression, r.Name)
 		}
-		l += compressionLenSlice(compression, dns.Answer)
-		l += compressionLenSlice(compression, dns.Ns)
-		l += compressionLenSlice(compression, dns.Extra)
-	} else {
-		for _, r := range dns.Question {
+		l += compressionLenSlice(l, compression, dns.Answer)
+		l += compressionLenSlice(l, compression, dns.Ns)
+		l += compressionLenSlice(l, compression, dns.Extra)
+
+		return l
+	}
+
+	for _, r := range dns.Question {
+		l += r.len()
+	}
+	for _, r := range dns.Answer {
+		if r != nil {
 			l += r.len()
 		}
-		for _, r := range dns.Answer {
-			if r != nil {
-				l += r.len()
-			}
-		}
-		for _, r := range dns.Ns {
-			if r != nil {
-				l += r.len()
-			}
+	}
+	for _, r := range dns.Ns {
+		if r != nil {
+			l += r.len()
 		}
-		for _, r := range dns.Extra {
-			if r != nil {
-				l += r.len()
-			}
+	}
+	for _, r := range dns.Extra {
+		if r != nil {
+			l += r.len()
 		}
 	}
+
 	return l
 }
 
-func compressionLenSlice(c map[string]int, rs []RR) int {
+func compressionLenSlice(len int, c map[string]int, rs []RR) int {
 	var l int
 	for _, r := range rs {
 		if r == nil {
 			continue
 		}
-		l += r.len()
+		// track this length, and the global length in len, while taking compression into account for both.
+		x := r.len()
+		l += x
+		len += x
+
 		k, ok := compressionLenSearch(c, r.Header().Name)
 		if ok {
 			l += 1 - k
+			len += 1 - k
+		}
+
+		if len < maxCompressionOffset {
+			compressionLenHelper(c, r.Header().Name)
 		}
-		compressionLenHelper(c, r.Header().Name)
+
 		k, ok = compressionLenSearchType(c, r)
 		if ok {
 			l += 1 - k
+			len += 1 - k
+		}
+
+		if len < maxCompressionOffset {
+			compressionLenHelperType(c, r)
 		}
-		compressionLenHelperType(c, r)
 	}
 	return l
 }

+ 65 - 60
vendor/github.com/miekg/dns/server.go

@@ -51,7 +51,6 @@ type response struct {
 	udp            *net.UDPConn      // i/o connection if UDP was used
 	tcp            net.Conn          // i/o connection if TCP was used
 	udpSession     *SessionUDP       // oob data to get egress interface right
-	remoteAddr     net.Addr          // address of the client
 	writer         Writer            // writer to output the raw DNS bits
 }
 
@@ -447,16 +446,10 @@ func (srv *Server) serveTCP(l net.Listener) error {
 		srv.NotifyStartedFunc()
 	}
 
-	reader := Reader(&defaultReader{srv})
-	if srv.DecorateReader != nil {
-		reader = srv.DecorateReader(reader)
-	}
-
 	handler := srv.Handler
 	if handler == nil {
 		handler = DefaultServeMux
 	}
-	rtimeout := srv.getReadTimeout()
 	// deadline is not used here
 	for {
 		rw, err := l.Accept()
@@ -472,14 +465,7 @@ func (srv *Server) serveTCP(l net.Listener) error {
 			}
 			return err
 		}
-		go func() {
-			m, err := reader.ReadTCP(rw, rtimeout)
-			if err != nil {
-				rw.Close()
-				return
-			}
-			srv.serve(rw.RemoteAddr(), handler, m, nil, nil, rw)
-		}()
+		go srv.serveTCPConn(handler, rw)
 	}
 }
 
@@ -520,80 +506,94 @@ func (srv *Server) serveUDP(l *net.UDPConn) error {
 		if len(m) < headerSize {
 			continue
 		}
-		go srv.serve(s.RemoteAddr(), handler, m, l, s, nil)
+		go srv.serveUDPPacket(handler, m, l, s)
 	}
 }
 
-// Serve a new connection.
-func (srv *Server) serve(a net.Addr, h Handler, m []byte, u *net.UDPConn, s *SessionUDP, t net.Conn) {
-	w := &response{tsigSecret: srv.TsigSecret, udp: u, tcp: t, remoteAddr: a, udpSession: s}
+// Serve a new TCP connection.
+func (srv *Server) serveTCPConn(h Handler, t net.Conn) {
+	reader := Reader(&defaultReader{srv})
+	if srv.DecorateReader != nil {
+		reader = srv.DecorateReader(reader)
+	}
+
+	w := &response{tsigSecret: srv.TsigSecret, tcp: t}
 	if srv.DecorateWriter != nil {
 		w.writer = srv.DecorateWriter(w)
 	} else {
 		w.writer = w
 	}
 
-	q := 0 // counter for the amount of TCP queries we get
+	defer func() {
+		if !w.hijacked {
+			w.Close()
+		}
+	}()
+
+	idleTimeout := tcpIdleTimeout
+	if srv.IdleTimeout != nil {
+		idleTimeout = srv.IdleTimeout()
+	}
+
+	timeout := srv.getReadTimeout()
 
-	reader := Reader(&defaultReader{srv})
-	if srv.DecorateReader != nil {
-		reader = srv.DecorateReader(reader)
+	// TODO(miek): make maxTCPQueries configurable?
+	for q := 0; q < maxTCPQueries; q++ {
+		m, err := reader.ReadTCP(t, timeout)
+		if err != nil {
+			// TODO(tmthrgd): handle error
+			break
+		}
+		srv.serveDNS(h, m, w)
+		if w.tcp == nil {
+			break // Close() was called
+		}
+		if w.hijacked {
+			break // client will call Close() themselves
+		}
+		// The first read uses the read timeout, the rest use the
+		// idle timeout.
+		timeout = idleTimeout
 	}
-Redo:
+}
+
+// Serve a new UDP request.
+func (srv *Server) serveUDPPacket(h Handler, m []byte, u *net.UDPConn, s *SessionUDP) {
+	w := &response{tsigSecret: srv.TsigSecret, udp: u, udpSession: s}
+	if srv.DecorateWriter != nil {
+		w.writer = srv.DecorateWriter(w)
+	} else {
+		w.writer = w
+	}
+	srv.serveDNS(h, m, w)
+}
+
+func (srv *Server) serveDNS(h Handler, m []byte, w *response) {
 	req := new(Msg)
 	err := req.Unpack(m)
 	if err != nil { // Send a FormatError back
 		x := new(Msg)
 		x.SetRcodeFormatError(req)
 		w.WriteMsg(x)
-		goto Exit
+		return
 	}
 	if !srv.Unsafe && req.Response {
-		goto Exit
+		return
 	}
 
 	w.tsigStatus = nil
 	if w.tsigSecret != nil {
 		if t := req.IsTsig(); t != nil {
-			secret := t.Hdr.Name
-			if _, ok := w.tsigSecret[secret]; !ok {
-				w.tsigStatus = ErrKeyAlg
+			if secret, ok := w.tsigSecret[t.Hdr.Name]; ok {
+				w.tsigStatus = TsigVerify(m, secret, "", false)
+			} else {
+				w.tsigStatus = ErrSecret
 			}
-			w.tsigStatus = TsigVerify(m, w.tsigSecret[secret], "", false)
 			w.tsigTimersOnly = false
 			w.tsigRequestMAC = req.Extra[len(req.Extra)-1].(*TSIG).MAC
 		}
 	}
 	h.ServeDNS(w, req) // Writes back to the client
-
-Exit:
-	if w.tcp == nil {
-		return
-	}
-	// TODO(miek): make this number configurable?
-	if q > maxTCPQueries { // close socket after this many queries
-		w.Close()
-		return
-	}
-
-	if w.hijacked {
-		return // client calls Close()
-	}
-	if u != nil { // UDP, "close" and return
-		w.Close()
-		return
-	}
-	idleTimeout := tcpIdleTimeout
-	if srv.IdleTimeout != nil {
-		idleTimeout = srv.IdleTimeout()
-	}
-	m, err = reader.ReadTCP(w.tcp, idleTimeout)
-	if err == nil {
-		q++
-		goto Redo
-	}
-	w.Close()
-	return
 }
 
 func (srv *Server) readTCP(conn net.Conn, timeout time.Duration) ([]byte, error) {
@@ -696,7 +696,12 @@ func (w *response) LocalAddr() net.Addr {
 }
 
 // RemoteAddr implements the ResponseWriter.RemoteAddr method.
-func (w *response) RemoteAddr() net.Addr { return w.remoteAddr }
+func (w *response) RemoteAddr() net.Addr {
+	if w.tcp != nil {
+		return w.tcp.RemoteAddr()
+	}
+	return w.udpSession.RemoteAddr()
+}
 
 // TsigStatus implements the ResponseWriter.TsigStatus method.
 func (w *response) TsigStatus() error { return w.tsigStatus }

+ 23 - 10
vendor/github.com/miekg/dns/udp.go

@@ -9,6 +9,22 @@ import (
 	"golang.org/x/net/ipv6"
 )
 
+// This is the required size of the OOB buffer to pass to ReadMsgUDP.
+var udpOOBSize = func() int {
+	// We can't know whether we'll get an IPv4 control message or an
+	// IPv6 control message ahead of time. To get around this, we size
+	// the buffer equal to the largest of the two.
+
+	oob4 := ipv4.NewControlMessage(ipv4.FlagDst | ipv4.FlagInterface)
+	oob6 := ipv6.NewControlMessage(ipv6.FlagDst | ipv6.FlagInterface)
+
+	if len(oob4) > len(oob6) {
+		return len(oob4)
+	}
+
+	return len(oob6)
+}()
+
 // SessionUDP holds the remote address and the associated
 // out-of-band data.
 type SessionUDP struct {
@@ -22,7 +38,7 @@ func (s *SessionUDP) RemoteAddr() net.Addr { return s.raddr }
 // ReadFromSessionUDP acts just like net.UDPConn.ReadFrom(), but returns a session object instead of a
 // net.UDPAddr.
 func ReadFromSessionUDP(conn *net.UDPConn, b []byte) (int, *SessionUDP, error) {
-	oob := make([]byte, 40)
+	oob := make([]byte, udpOOBSize)
 	n, oobn, _, raddr, err := conn.ReadMsgUDP(b, oob)
 	if err != nil {
 		return n, nil, err
@@ -53,18 +69,15 @@ func parseDstFromOOB(oob []byte) net.IP {
 	// Start with IPv6 and then fallback to IPv4
 	// TODO(fastest963): Figure out a way to prefer one or the other. Looking at
 	// the lvl of the header for a 0 or 41 isn't cross-platform.
-	var dst net.IP
 	cm6 := new(ipv6.ControlMessage)
-	if cm6.Parse(oob) == nil {
-		dst = cm6.Dst
+	if cm6.Parse(oob) == nil && cm6.Dst != nil {
+		return cm6.Dst
 	}
-	if dst == nil {
-		cm4 := new(ipv4.ControlMessage)
-		if cm4.Parse(oob) == nil {
-			dst = cm4.Dst
-		}
+	cm4 := new(ipv4.ControlMessage)
+	if cm4.Parse(oob) == nil && cm4.Dst != nil {
+		return cm4.Dst
 	}
-	return dst
+	return nil
 }
 
 // correctSource takes oob data and returns new oob data with the Src equal to the Dst

+ 1 - 1
vendor/github.com/miekg/dns/version.go

@@ -3,7 +3,7 @@ package dns
 import "fmt"
 
 // Version is current version of this library.
-var Version = V{1, 0, 4}
+var Version = V{1, 0, 5}
 
 // V holds the version of this library.
 type V struct {

+ 1 - 3
vendor/github.com/oschwald/maxminddb-golang/mmap_unix.go

@@ -3,13 +3,11 @@
 package maxminddb
 
 import (
-	"syscall"
-
 	"golang.org/x/sys/unix"
 )
 
 func mmap(fd int, length int) (data []byte, err error) {
-	return unix.Mmap(fd, 0, length, syscall.PROT_READ, syscall.MAP_SHARED)
+	return unix.Mmap(fd, 0, length, unix.PROT_READ, unix.MAP_SHARED)
 }
 
 func munmap(b []byte) (err error) {

+ 14 - 1
vendor/github.com/oschwald/maxminddb-golang/reader.go

@@ -107,6 +107,9 @@ func (r *Reader) startNode() (uint, error) {
 // Lookup takes an IP address as a net.IP structure and a pointer to the
 // result value to Decode into.
 func (r *Reader) Lookup(ipAddress net.IP, result interface{}) error {
+	if r.buffer == nil {
+		return errors.New("cannot call Lookup on a closed database")
+	}
 	pointer, err := r.lookupPointer(ipAddress)
 	if pointer == 0 || err != nil {
 		return err
@@ -120,6 +123,9 @@ func (r *Reader) Lookup(ipAddress net.IP, result interface{}) error {
 // is an advanced API, which exists to provide clients with a means to cache
 // previously-decoded records.
 func (r *Reader) LookupOffset(ipAddress net.IP) (uintptr, error) {
+	if r.buffer == nil {
+		return 0, errors.New("cannot call LookupOffset on a closed database")
+	}
 	pointer, err := r.lookupPointer(ipAddress)
 	if pointer == 0 || err != nil {
 		return NotFound, err
@@ -144,6 +150,13 @@ func (r *Reader) LookupOffset(ipAddress net.IP) (uintptr, error) {
 // single representative record for that country. This uintptr behavior allows
 // clients to leverage this normalization in their own sub-record caching.
 func (r *Reader) Decode(offset uintptr, result interface{}) error {
+	if r.buffer == nil {
+		return errors.New("cannot call Decode on a closed database")
+	}
+	return r.decode(offset, result)
+}
+
+func (r *Reader) decode(offset uintptr, result interface{}) error {
 	rv := reflect.ValueOf(result)
 	if rv.Kind() != reflect.Ptr || rv.IsNil() {
 		return errors.New("result param must be a pointer")
@@ -233,7 +246,7 @@ func (r *Reader) retrieveData(pointer uint, result interface{}) error {
 	if err != nil {
 		return err
 	}
-	return r.Decode(offset, result)
+	return r.decode(offset, result)
 }
 
 func (r *Reader) resolveDataPointer(pointer uint) (uintptr, error) {

+ 3 - 1
vendor/github.com/oschwald/maxminddb-golang/reader_appengine.go

@@ -20,7 +20,9 @@ func Open(file string) (*Reader, error) {
 
 // Close unmaps the database file from virtual memory and returns the
 // resources to the system. If called on a Reader opened using FromBytes
-// or Open on Google App Engine, this method does nothing.
+// or Open on Google App Engine, this method sets the underlying buffer
+// to nil, returning the resources to the system.
 func (r *Reader) Close() error {
+	r.buffer = nil
 	return nil
 }

+ 7 - 5
vendor/github.com/oschwald/maxminddb-golang/reader_other.go

@@ -52,10 +52,12 @@ func Open(file string) (*Reader, error) {
 // resources to the system. If called on a Reader opened using FromBytes
 // or Open on Google App Engine, this method does nothing.
 func (r *Reader) Close() error {
-	if !r.hasMappedFile {
-		return nil
+	var err error
+	if r.hasMappedFile {
+		runtime.SetFinalizer(r, nil)
+		r.hasMappedFile = false
+		err = munmap(r.buffer)
 	}
-	runtime.SetFinalizer(r, nil)
-	r.hasMappedFile = false
-	return munmap(r.buffer)
+	r.buffer = nil
+	return err
 }

+ 18 - 0
vendor/github.com/prometheus/client_golang/AUTHORS.md

@@ -0,0 +1,18 @@
+The Prometheus project was started by Matt T. Proud (emeritus) and
+Julius Volz in 2012.
+
+Maintainers of this repository:
+
+* Björn Rabenstein <[email protected]>
+
+The following individuals have contributed code to this repository
+(listed in alphabetical order):
+
+* Bernerd Schaefer <[email protected]>
+* Björn Rabenstein <[email protected]>
+* Daniel Bornkessel <[email protected]>
+* Jeff Younker <[email protected]>
+* Julius Volz <[email protected]>
+* Matt T. Proud <[email protected]>
+* Tobias Schmidt <[email protected]>
+

+ 201 - 0
vendor/github.com/prometheus/client_golang/LICENSE

@@ -0,0 +1,201 @@
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
+   APPENDIX: How to apply the Apache License to your work.
+
+      To apply the Apache License to your work, attach the following
+      boilerplate notice, with the fields enclosed by brackets "[]"
+      replaced with your own identifying information. (Don't include
+      the brackets!)  The text should be enclosed in the appropriate
+      comment syntax for the file format. We also recommend that a
+      file or class name and description of purpose be included on the
+      same "printed page" as the copyright notice for easier
+      identification within third-party archives.
+
+   Copyright [yyyy] [name of copyright owner]
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.

+ 23 - 0
vendor/github.com/prometheus/client_golang/NOTICE

@@ -0,0 +1,23 @@
+Prometheus instrumentation library for Go applications
+Copyright 2012-2015 The Prometheus Authors
+
+This product includes software developed at
+SoundCloud Ltd. (http://soundcloud.com/).
+
+
+The following components are included in this product:
+
+perks - a fork of https://github.com/bmizerany/perks
+https://github.com/beorn7/perks
+Copyright 2013-2015 Blake Mizerany, Björn Rabenstein
+See https://github.com/beorn7/perks/blob/master/README.md for license details.
+
+Go support for Protocol Buffers - Google's data interchange format
+http://github.com/golang/protobuf/
+Copyright 2010 The Go Authors
+See source code for license details.
+
+Support for streaming Protocol Buffer messages for the Go language (golang).
+https://github.com/matttproud/golang_protobuf_extensions
+Copyright 2013 Matt T. Proud
+Licensed under the Apache License, Version 2.0

+ 75 - 0
vendor/github.com/prometheus/client_golang/prometheus/collector.go

@@ -0,0 +1,75 @@
+// Copyright 2014 The Prometheus Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package prometheus
+
+// Collector is the interface implemented by anything that can be used by
+// Prometheus to collect metrics. A Collector has to be registered for
+// collection. See Registerer.Register.
+//
+// The stock metrics provided by this package (Gauge, Counter, Summary,
+// Histogram, Untyped) are also Collectors (which only ever collect one metric,
+// namely itself). An implementer of Collector may, however, collect multiple
+// metrics in a coordinated fashion and/or create metrics on the fly. Examples
+// for collectors already implemented in this library are the metric vectors
+// (i.e. collection of multiple instances of the same Metric but with different
+// label values) like GaugeVec or SummaryVec, and the ExpvarCollector.
+type Collector interface {
+	// Describe sends the super-set of all possible descriptors of metrics
+	// collected by this Collector to the provided channel and returns once
+	// the last descriptor has been sent. The sent descriptors fulfill the
+	// consistency and uniqueness requirements described in the Desc
+	// documentation. (It is valid if one and the same Collector sends
+	// duplicate descriptors. Those duplicates are simply ignored. However,
+	// two different Collectors must not send duplicate descriptors.) This
+	// method idempotently sends the same descriptors throughout the
+	// lifetime of the Collector. If a Collector encounters an error while
+	// executing this method, it must send an invalid descriptor (created
+	// with NewInvalidDesc) to signal the error to the registry.
+	Describe(chan<- *Desc)
+	// Collect is called by the Prometheus registry when collecting
+	// metrics. The implementation sends each collected metric via the
+	// provided channel and returns once the last metric has been sent. The
+	// descriptor of each sent metric is one of those returned by
+	// Describe. Returned metrics that share the same descriptor must differ
+	// in their variable label values. This method may be called
+	// concurrently and must therefore be implemented in a concurrency safe
+	// way. Blocking occurs at the expense of total performance of rendering
+	// all registered metrics. Ideally, Collector implementations support
+	// concurrent readers.
+	Collect(chan<- Metric)
+}
+
+// selfCollector implements Collector for a single Metric so that the Metric
+// collects itself. Add it as an anonymous field to a struct that implements
+// Metric, and call init with the Metric itself as an argument.
+type selfCollector struct {
+	self Metric
+}
+
+// init provides the selfCollector with a reference to the metric it is supposed
+// to collect. It is usually called within the factory function to create a
+// metric. See example.
+func (c *selfCollector) init(self Metric) {
+	c.self = self
+}
+
+// Describe implements Collector.
+func (c *selfCollector) Describe(ch chan<- *Desc) {
+	ch <- c.self.Desc()
+}
+
+// Collect implements Collector.
+func (c *selfCollector) Collect(ch chan<- Metric) {
+	ch <- c.self
+}

+ 172 - 0
vendor/github.com/prometheus/client_golang/prometheus/counter.go

@@ -0,0 +1,172 @@
+// Copyright 2014 The Prometheus Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package prometheus
+
+import (
+	"errors"
+)
+
+// Counter is a Metric that represents a single numerical value that only ever
+// goes up. That implies that it cannot be used to count items whose number can
+// also go down, e.g. the number of currently running goroutines. Those
+// "counters" are represented by Gauges.
+//
+// A Counter is typically used to count requests served, tasks completed, errors
+// occurred, etc.
+//
+// To create Counter instances, use NewCounter.
+type Counter interface {
+	Metric
+	Collector
+
+	// Set is used to set the Counter to an arbitrary value. It is only used
+	// if you have to transfer a value from an external counter into this
+	// Prometheus metric. Do not use it for regular handling of a
+	// Prometheus counter (as it can be used to break the contract of
+	// monotonically increasing values).
+	//
+	// Deprecated: Use NewConstMetric to create a counter for an external
+	// value. A Counter should never be set.
+	Set(float64)
+	// Inc increments the counter by 1.
+	Inc()
+	// Add adds the given value to the counter. It panics if the value is <
+	// 0.
+	Add(float64)
+}
+
+// CounterOpts is an alias for Opts. See there for doc comments.
+type CounterOpts Opts
+
+// NewCounter creates a new Counter based on the provided CounterOpts.
+func NewCounter(opts CounterOpts) Counter {
+	desc := NewDesc(
+		BuildFQName(opts.Namespace, opts.Subsystem, opts.Name),
+		opts.Help,
+		nil,
+		opts.ConstLabels,
+	)
+	result := &counter{value: value{desc: desc, valType: CounterValue, labelPairs: desc.constLabelPairs}}
+	result.init(result) // Init self-collection.
+	return result
+}
+
+type counter struct {
+	value
+}
+
+func (c *counter) Add(v float64) {
+	if v < 0 {
+		panic(errors.New("counter cannot decrease in value"))
+	}
+	c.value.Add(v)
+}
+
+// CounterVec is a Collector that bundles a set of Counters that all share the
+// same Desc, but have different values for their variable labels. This is used
+// if you want to count the same thing partitioned by various dimensions
+// (e.g. number of HTTP requests, partitioned by response code and
+// method). Create instances with NewCounterVec.
+//
+// CounterVec embeds MetricVec. See there for a full list of methods with
+// detailed documentation.
+type CounterVec struct {
+	*MetricVec
+}
+
+// NewCounterVec creates a new CounterVec based on the provided CounterOpts and
+// partitioned by the given label names. At least one label name must be
+// provided.
+func NewCounterVec(opts CounterOpts, labelNames []string) *CounterVec {
+	desc := NewDesc(
+		BuildFQName(opts.Namespace, opts.Subsystem, opts.Name),
+		opts.Help,
+		labelNames,
+		opts.ConstLabels,
+	)
+	return &CounterVec{
+		MetricVec: newMetricVec(desc, func(lvs ...string) Metric {
+			result := &counter{value: value{
+				desc:       desc,
+				valType:    CounterValue,
+				labelPairs: makeLabelPairs(desc, lvs),
+			}}
+			result.init(result) // Init self-collection.
+			return result
+		}),
+	}
+}
+
+// GetMetricWithLabelValues replaces the method of the same name in
+// MetricVec. The difference is that this method returns a Counter and not a
+// Metric so that no type conversion is required.
+func (m *CounterVec) GetMetricWithLabelValues(lvs ...string) (Counter, error) {
+	metric, err := m.MetricVec.GetMetricWithLabelValues(lvs...)
+	if metric != nil {
+		return metric.(Counter), err
+	}
+	return nil, err
+}
+
+// GetMetricWith replaces the method of the same name in MetricVec. The
+// difference is that this method returns a Counter and not a Metric so that no
+// type conversion is required.
+func (m *CounterVec) GetMetricWith(labels Labels) (Counter, error) {
+	metric, err := m.MetricVec.GetMetricWith(labels)
+	if metric != nil {
+		return metric.(Counter), err
+	}
+	return nil, err
+}
+
+// WithLabelValues works as GetMetricWithLabelValues, but panics where
+// GetMetricWithLabelValues would have returned an error. By not returning an
+// error, WithLabelValues allows shortcuts like
+//     myVec.WithLabelValues("404", "GET").Add(42)
+func (m *CounterVec) WithLabelValues(lvs ...string) Counter {
+	return m.MetricVec.WithLabelValues(lvs...).(Counter)
+}
+
+// With works as GetMetricWith, but panics where GetMetricWithLabels would have
+// returned an error. By not returning an error, With allows shortcuts like
+//     myVec.With(Labels{"code": "404", "method": "GET"}).Add(42)
+func (m *CounterVec) With(labels Labels) Counter {
+	return m.MetricVec.With(labels).(Counter)
+}
+
+// CounterFunc is a Counter whose value is determined at collect time by calling a
+// provided function.
+//
+// To create CounterFunc instances, use NewCounterFunc.
+type CounterFunc interface {
+	Metric
+	Collector
+}
+
+// NewCounterFunc creates a new CounterFunc based on the provided
+// CounterOpts. The value reported is determined by calling the given function
+// from within the Write method. Take into account that metric collection may
+// happen concurrently. If that results in concurrent calls to Write, like in
+// the case where a CounterFunc is directly registered with Prometheus, the
+// provided function must be concurrency-safe. The function should also honor
+// the contract for a Counter (values only go up, not down), but compliance will
+// not be checked.
+func NewCounterFunc(opts CounterOpts, function func() float64) CounterFunc {
+	return newValueFunc(NewDesc(
+		BuildFQName(opts.Namespace, opts.Subsystem, opts.Name),
+		opts.Help,
+		nil,
+		opts.ConstLabels,
+	), CounterValue, function)
+}

+ 205 - 0
vendor/github.com/prometheus/client_golang/prometheus/desc.go

@@ -0,0 +1,205 @@
+// Copyright 2016 The Prometheus Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package prometheus
+
+import (
+	"errors"
+	"fmt"
+	"regexp"
+	"sort"
+	"strings"
+
+	"github.com/golang/protobuf/proto"
+
+	dto "github.com/prometheus/client_model/go"
+)
+
+var (
+	metricNameRE = regexp.MustCompile(`^[a-zA-Z_][a-zA-Z0-9_:]*$`)
+	labelNameRE  = regexp.MustCompile("^[a-zA-Z_][a-zA-Z0-9_]*$")
+)
+
+// reservedLabelPrefix is a prefix which is not legal in user-supplied
+// label names.
+const reservedLabelPrefix = "__"
+
+// Labels represents a collection of label name -> value mappings. This type is
+// commonly used with the With(Labels) and GetMetricWith(Labels) methods of
+// metric vector Collectors, e.g.:
+//     myVec.With(Labels{"code": "404", "method": "GET"}).Add(42)
+//
+// The other use-case is the specification of constant label pairs in Opts or to
+// create a Desc.
+type Labels map[string]string
+
+// Desc is the descriptor used by every Prometheus Metric. It is essentially
+// the immutable meta-data of a Metric. The normal Metric implementations
+// included in this package manage their Desc under the hood. Users only have to
+// deal with Desc if they use advanced features like the ExpvarCollector or
+// custom Collectors and Metrics.
+//
+// Descriptors registered with the same registry have to fulfill certain
+// consistency and uniqueness criteria if they share the same fully-qualified
+// name: They must have the same help string and the same label names (aka label
+// dimensions) in each, constLabels and variableLabels, but they must differ in
+// the values of the constLabels.
+//
+// Descriptors that share the same fully-qualified names and the same label
+// values of their constLabels are considered equal.
+//
+// Use NewDesc to create new Desc instances.
+type Desc struct {
+	// fqName has been built from Namespace, Subsystem, and Name.
+	fqName string
+	// help provides some helpful information about this metric.
+	help string
+	// constLabelPairs contains precalculated DTO label pairs based on
+	// the constant labels.
+	constLabelPairs []*dto.LabelPair
+	// VariableLabels contains names of labels for which the metric
+	// maintains variable values.
+	variableLabels []string
+	// id is a hash of the values of the ConstLabels and fqName. This
+	// must be unique among all registered descriptors and can therefore be
+	// used as an identifier of the descriptor.
+	id uint64
+	// dimHash is a hash of the label names (preset and variable) and the
+	// Help string. Each Desc with the same fqName must have the same
+	// dimHash.
+	dimHash uint64
+	// err is an error that occured during construction. It is reported on
+	// registration time.
+	err error
+}
+
+// NewDesc allocates and initializes a new Desc. Errors are recorded in the Desc
+// and will be reported on registration time. variableLabels and constLabels can
+// be nil if no such labels should be set. fqName and help must not be empty.
+//
+// variableLabels only contain the label names. Their label values are variable
+// and therefore not part of the Desc. (They are managed within the Metric.)
+//
+// For constLabels, the label values are constant. Therefore, they are fully
+// specified in the Desc. See the Opts documentation for the implications of
+// constant labels.
+func NewDesc(fqName, help string, variableLabels []string, constLabels Labels) *Desc {
+	d := &Desc{
+		fqName:         fqName,
+		help:           help,
+		variableLabels: variableLabels,
+	}
+	if help == "" {
+		d.err = errors.New("empty help string")
+		return d
+	}
+	if !metricNameRE.MatchString(fqName) {
+		d.err = fmt.Errorf("%q is not a valid metric name", fqName)
+		return d
+	}
+	// labelValues contains the label values of const labels (in order of
+	// their sorted label names) plus the fqName (at position 0).
+	labelValues := make([]string, 1, len(constLabels)+1)
+	labelValues[0] = fqName
+	labelNames := make([]string, 0, len(constLabels)+len(variableLabels))
+	labelNameSet := map[string]struct{}{}
+	// First add only the const label names and sort them...
+	for labelName := range constLabels {
+		if !checkLabelName(labelName) {
+			d.err = fmt.Errorf("%q is not a valid label name", labelName)
+			return d
+		}
+		labelNames = append(labelNames, labelName)
+		labelNameSet[labelName] = struct{}{}
+	}
+	sort.Strings(labelNames)
+	// ... so that we can now add const label values in the order of their names.
+	for _, labelName := range labelNames {
+		labelValues = append(labelValues, constLabels[labelName])
+	}
+	// Now add the variable label names, but prefix them with something that
+	// cannot be in a regular label name. That prevents matching the label
+	// dimension with a different mix between preset and variable labels.
+	for _, labelName := range variableLabels {
+		if !checkLabelName(labelName) {
+			d.err = fmt.Errorf("%q is not a valid label name", labelName)
+			return d
+		}
+		labelNames = append(labelNames, "$"+labelName)
+		labelNameSet[labelName] = struct{}{}
+	}
+	if len(labelNames) != len(labelNameSet) {
+		d.err = errors.New("duplicate label names")
+		return d
+	}
+	vh := hashNew()
+	for _, val := range labelValues {
+		vh = hashAdd(vh, val)
+		vh = hashAddByte(vh, separatorByte)
+	}
+	d.id = vh
+	// Sort labelNames so that order doesn't matter for the hash.
+	sort.Strings(labelNames)
+	// Now hash together (in this order) the help string and the sorted
+	// label names.
+	lh := hashNew()
+	lh = hashAdd(lh, help)
+	lh = hashAddByte(lh, separatorByte)
+	for _, labelName := range labelNames {
+		lh = hashAdd(lh, labelName)
+		lh = hashAddByte(lh, separatorByte)
+	}
+	d.dimHash = lh
+
+	d.constLabelPairs = make([]*dto.LabelPair, 0, len(constLabels))
+	for n, v := range constLabels {
+		d.constLabelPairs = append(d.constLabelPairs, &dto.LabelPair{
+			Name:  proto.String(n),
+			Value: proto.String(v),
+		})
+	}
+	sort.Sort(LabelPairSorter(d.constLabelPairs))
+	return d
+}
+
+// NewInvalidDesc returns an invalid descriptor, i.e. a descriptor with the
+// provided error set. If a collector returning such a descriptor is registered,
+// registration will fail with the provided error. NewInvalidDesc can be used by
+// a Collector to signal inability to describe itself.
+func NewInvalidDesc(err error) *Desc {
+	return &Desc{
+		err: err,
+	}
+}
+
+func (d *Desc) String() string {
+	lpStrings := make([]string, 0, len(d.constLabelPairs))
+	for _, lp := range d.constLabelPairs {
+		lpStrings = append(
+			lpStrings,
+			fmt.Sprintf("%s=%q", lp.GetName(), lp.GetValue()),
+		)
+	}
+	return fmt.Sprintf(
+		"Desc{fqName: %q, help: %q, constLabels: {%s}, variableLabels: %v}",
+		d.fqName,
+		d.help,
+		strings.Join(lpStrings, ","),
+		d.variableLabels,
+	)
+}
+
+func checkLabelName(l string) bool {
+	return labelNameRE.MatchString(l) &&
+		!strings.HasPrefix(l, reservedLabelPrefix)
+}

+ 181 - 0
vendor/github.com/prometheus/client_golang/prometheus/doc.go

@@ -0,0 +1,181 @@
+// Copyright 2014 The Prometheus Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// Package prometheus provides metrics primitives to instrument code for
+// monitoring. It also offers a registry for metrics. Sub-packages allow to
+// expose the registered metrics via HTTP (package promhttp) or push them to a
+// Pushgateway (package push).
+//
+// All exported functions and methods are safe to be used concurrently unless
+//specified otherwise.
+//
+// A Basic Example
+//
+// As a starting point, a very basic usage example:
+//
+//    package main
+//
+//    import (
+//    	"net/http"
+//
+//    	"github.com/prometheus/client_golang/prometheus"
+//    	"github.com/prometheus/client_golang/prometheus/promhttp"
+//    )
+//
+//    var (
+//    	cpuTemp = prometheus.NewGauge(prometheus.GaugeOpts{
+//    		Name: "cpu_temperature_celsius",
+//    		Help: "Current temperature of the CPU.",
+//    	})
+//    	hdFailures = prometheus.NewCounterVec(
+//    		prometheus.CounterOpts{
+//    			Name: "hd_errors_total",
+//    			Help: "Number of hard-disk errors.",
+//    		},
+//    		[]string{"device"},
+//    	)
+//    )
+//
+//    func init() {
+//    	// Metrics have to be registered to be exposed:
+//    	prometheus.MustRegister(cpuTemp)
+//    	prometheus.MustRegister(hdFailures)
+//    }
+//
+//    func main() {
+//    	cpuTemp.Set(65.3)
+//    	hdFailures.With(prometheus.Labels{"device":"/dev/sda"}).Inc()
+//
+//    	// The Handler function provides a default handler to expose metrics
+//    	// via an HTTP server. "/metrics" is the usual endpoint for that.
+//    	http.Handle("/metrics", promhttp.Handler())
+//    	http.ListenAndServe(":8080", nil)
+//    }
+//
+//
+// This is a complete program that exports two metrics, a Gauge and a Counter,
+// the latter with a label attached to turn it into a (one-dimensional) vector.
+//
+// Metrics
+//
+// The number of exported identifiers in this package might appear a bit
+// overwhelming. Hovever, in addition to the basic plumbing shown in the example
+// above, you only need to understand the different metric types and their
+// vector versions for basic usage.
+//
+// Above, you have already touched the Counter and the Gauge. There are two more
+// advanced metric types: the Summary and Histogram. A more thorough description
+// of those four metric types can be found in the Prometheus docs:
+// https://prometheus.io/docs/concepts/metric_types/
+//
+// A fifth "type" of metric is Untyped. It behaves like a Gauge, but signals the
+// Prometheus server not to assume anything about its type.
+//
+// In addition to the fundamental metric types Gauge, Counter, Summary,
+// Histogram, and Untyped, a very important part of the Prometheus data model is
+// the partitioning of samples along dimensions called labels, which results in
+// metric vectors. The fundamental types are GaugeVec, CounterVec, SummaryVec,
+// HistogramVec, and UntypedVec.
+//
+// While only the fundamental metric types implement the Metric interface, both
+// the metrics and their vector versions implement the Collector interface. A
+// Collector manages the collection of a number of Metrics, but for convenience,
+// a Metric can also “collect itself”. Note that Gauge, Counter, Summary,
+// Histogram, and Untyped are interfaces themselves while GaugeVec, CounterVec,
+// SummaryVec, HistogramVec, and UntypedVec are not.
+//
+// To create instances of Metrics and their vector versions, you need a suitable
+// …Opts struct, i.e. GaugeOpts, CounterOpts, SummaryOpts,
+// HistogramOpts, or UntypedOpts.
+//
+// Custom Collectors and constant Metrics
+//
+// While you could create your own implementations of Metric, most likely you
+// will only ever implement the Collector interface on your own. At a first
+// glance, a custom Collector seems handy to bundle Metrics for common
+// registration (with the prime example of the different metric vectors above,
+// which bundle all the metrics of the same name but with different labels).
+//
+// There is a more involved use case, too: If you already have metrics
+// available, created outside of the Prometheus context, you don't need the
+// interface of the various Metric types. You essentially want to mirror the
+// existing numbers into Prometheus Metrics during collection. An own
+// implementation of the Collector interface is perfect for that. You can create
+// Metric instances “on the fly” using NewConstMetric, NewConstHistogram, and
+// NewConstSummary (and their respective Must… versions). That will happen in
+// the Collect method. The Describe method has to return separate Desc
+// instances, representative of the “throw-away” metrics to be created
+// later. NewDesc comes in handy to create those Desc instances.
+//
+// The Collector example illustrates the use case. You can also look at the
+// source code of the processCollector (mirroring process metrics), the
+// goCollector (mirroring Go metrics), or the expvarCollector (mirroring expvar
+// metrics) as examples that are used in this package itself.
+//
+// If you just need to call a function to get a single float value to collect as
+// a metric, GaugeFunc, CounterFunc, or UntypedFunc might be interesting
+// shortcuts.
+//
+// Advanced Uses of the Registry
+//
+// While MustRegister is the by far most common way of registering a Collector,
+// sometimes you might want to handle the errors the registration might
+// cause. As suggested by the name, MustRegister panics if an error occurs. With
+// the Register function, the error is returned and can be handled.
+//
+// An error is returned if the registered Collector is incompatible or
+// inconsistent with already registered metrics. The registry aims for
+// consistency of the collected metrics according to the Prometheus data
+// model. Inconsistencies are ideally detected at registration time, not at
+// collect time. The former will usually be detected at start-up time of a
+// program, while the latter will only happen at scrape time, possibly not even
+// on the first scrape if the inconsistency only becomes relevant later. That is
+// the main reason why a Collector and a Metric have to describe themselves to
+// the registry.
+//
+// So far, everything we did operated on the so-called default registry, as it
+// can be found in the global DefaultRegistry variable. With NewRegistry, you
+// can create a custom registry, or you can even implement the Registerer or
+// Gatherer interfaces yourself. The methods Register and Unregister work in
+// the same way on a custom registry as the global functions Register and
+// Unregister on the default registry.
+//
+// There are a number of uses for custom registries: You can use registries
+// with special properties, see NewPedanticRegistry. You can avoid global state,
+// as it is imposed by the DefaultRegistry. You can use multiple registries at
+// the same time to expose different metrics in different ways. You can use
+// separate registries for testing purposes.
+//
+// Also note that the DefaultRegistry comes registered with a Collector for Go
+// runtime metrics (via NewGoCollector) and a Collector for process metrics (via
+// NewProcessCollector). With a custom registry, you are in control and decide
+// yourself about the Collectors to register.
+//
+// HTTP Exposition
+//
+// The Registry implements the Gatherer interface. The caller of the Gather
+// method can then expose the gathered metrics in some way. Usually, the metrics
+// are served via HTTP on the /metrics endpoint. That's happening in the example
+// above. The tools to expose metrics via HTTP are in the promhttp
+// sub-package. (The top-level functions in the prometheus package are
+// deprecated.)
+//
+// Pushing to the Pushgateway
+//
+// Function for pushing to the Pushgateway can be found in the push sub-package.
+//
+// Other Means of Exposition
+//
+// More ways of exposing metrics can easily be added. Sending metrics to
+// Graphite would be an example that will soon be implemented.
+package prometheus

+ 119 - 0
vendor/github.com/prometheus/client_golang/prometheus/expvar_collector.go

@@ -0,0 +1,119 @@
+// Copyright 2014 The Prometheus Authors
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package prometheus
+
+import (
+	"encoding/json"
+	"expvar"
+)
+
+type expvarCollector struct {
+	exports map[string]*Desc
+}
+
+// NewExpvarCollector returns a newly allocated expvar Collector that still has
+// to be registered with a Prometheus registry.
+//
+// An expvar Collector collects metrics from the expvar interface. It provides a
+// quick way to expose numeric values that are already exported via expvar as
+// Prometheus metrics. Note that the data models of expvar and Prometheus are
+// fundamentally different, and that the expvar Collector is inherently slower
+// than native Prometheus metrics. Thus, the expvar Collector is probably great
+// for experiments and prototying, but you should seriously consider a more
+// direct implementation of Prometheus metrics for monitoring production
+// systems.
+//
+// The exports map has the following meaning:
+//
+// The keys in the map correspond to expvar keys, i.e. for every expvar key you
+// want to export as Prometheus metric, you need an entry in the exports
+// map. The descriptor mapped to each key describes how to export the expvar
+// value. It defines the name and the help string of the Prometheus metric
+// proxying the expvar value. The type will always be Untyped.
+//
+// For descriptors without variable labels, the expvar value must be a number or
+// a bool. The number is then directly exported as the Prometheus sample
+// value. (For a bool, 'false' translates to 0 and 'true' to 1). Expvar values
+// that are not numbers or bools are silently ignored.
+//
+// If the descriptor has one variable label, the expvar value must be an expvar
+// map. The keys in the expvar map become the various values of the one
+// Prometheus label. The values in the expvar map must be numbers or bools again
+// as above.
+//
+// For descriptors with more than one variable label, the expvar must be a
+// nested expvar map, i.e. where the values of the topmost map are maps again
+// etc. until a depth is reached that corresponds to the number of labels. The
+// leaves of that structure must be numbers or bools as above to serve as the
+// sample values.
+//
+// Anything that does not fit into the scheme above is silently ignored.
+func NewExpvarCollector(exports map[string]*Desc) Collector {
+	return &expvarCollector{
+		exports: exports,
+	}
+}
+
+// Describe implements Collector.
+func (e *expvarCollector) Describe(ch chan<- *Desc) {
+	for _, desc := range e.exports {
+		ch <- desc
+	}
+}
+
+// Collect implements Collector.
+func (e *expvarCollector) Collect(ch chan<- Metric) {
+	for name, desc := range e.exports {
+		var m Metric
+		expVar := expvar.Get(name)
+		if expVar == nil {
+			continue
+		}
+		var v interface{}
+		labels := make([]string, len(desc.variableLabels))
+		if err := json.Unmarshal([]byte(expVar.String()), &v); err != nil {
+			ch <- NewInvalidMetric(desc, err)
+			continue
+		}
+		var processValue func(v interface{}, i int)
+		processValue = func(v interface{}, i int) {
+			if i >= len(labels) {
+				copiedLabels := append(make([]string, 0, len(labels)), labels...)
+				switch v := v.(type) {
+				case float64:
+					m = MustNewConstMetric(desc, UntypedValue, v, copiedLabels...)
+				case bool:
+					if v {
+						m = MustNewConstMetric(desc, UntypedValue, 1, copiedLabels...)
+					} else {
+						m = MustNewConstMetric(desc, UntypedValue, 0, copiedLabels...)
+					}
+				default:
+					return
+				}
+				ch <- m
+				return
+			}
+			vm, ok := v.(map[string]interface{})
+			if !ok {
+				return
+			}
+			for lv, val := range vm {
+				labels[i] = lv
+				processValue(val, i+1)
+			}
+		}
+		processValue(v, 0)
+	}
+}

+ 29 - 0
vendor/github.com/prometheus/client_golang/prometheus/fnv.go

@@ -0,0 +1,29 @@
+package prometheus
+
+// Inline and byte-free variant of hash/fnv's fnv64a.
+
+const (
+	offset64 = 14695981039346656037
+	prime64  = 1099511628211
+)
+
+// hashNew initializies a new fnv64a hash value.
+func hashNew() uint64 {
+	return offset64
+}
+
+// hashAdd adds a string to a fnv64a hash value, returning the updated hash.
+func hashAdd(h uint64, s string) uint64 {
+	for i := 0; i < len(s); i++ {
+		h ^= uint64(s[i])
+		h *= prime64
+	}
+	return h
+}
+
+// hashAddByte adds a byte to a fnv64a hash value, returning the updated hash.
+func hashAddByte(h uint64, b byte) uint64 {
+	h ^= uint64(b)
+	h *= prime64
+	return h
+}

Some files were not shown because too many files changed in this diff