diff --git a/Godeps/Godeps.json b/Godeps/Godeps.json
deleted file mode 100644
index efae49efff..0000000000
--- a/Godeps/Godeps.json
+++ /dev/null
@@ -1,104 +0,0 @@
-{
- "ImportPath": "github.com/prometheus/prometheus",
- "GoVersion": "go1.4.2",
- "Deps": [
- {
- "ImportPath": "bitbucket.org/ww/goautoneg",
- "Comment": "null-5",
- "Rev": "75cd24fc2f2c2a2088577d12123ddee5f54e0675"
- },
- {
- "ImportPath": "github.com/Sirupsen/logrus",
- "Comment": "v0.8.5-1-g11538ee",
- "Rev": "11538ee6888f72d4ab44a1aeba06b9bc4cb134a1"
- },
- {
- "ImportPath": "github.com/beorn7/perks/quantile",
- "Rev": "b965b613227fddccbfffe13eae360ed3fa822f8d"
- },
- {
- "ImportPath": "github.com/golang/protobuf/proto",
- "Rev": "0f7a9caded1fb3c9cc5a9b4bcf2ff633cc8ae644"
- },
- {
- "ImportPath": "github.com/golang/snappy",
- "Rev": "0c7f8a7704bfec561913f4df52c832f094ef56f0"
- },
- {
- "ImportPath": "github.com/hashicorp/consul/api",
- "Comment": "v0.5.2-180-ga6317f2",
- "Rev": "a6317f2fb2ba9d5ae695f7fa703cfb30a1c59af1"
- },
- {
- "ImportPath": "github.com/julienschmidt/httprouter",
- "Comment": "v1.1-3-g6aacfd5",
- "Rev": "6aacfd5ab513e34f7e64ea9627ab9670371b34e7"
- },
- {
- "ImportPath": "github.com/matttproud/golang_protobuf_extensions/pbutil",
- "Rev": "fc2b8d3a73c4867e51861bbdd5ae3c1f0869dd6a"
- },
- {
- "ImportPath": "github.com/miekg/dns",
- "Rev": "e59f851c912767b1db587dcabee6e6652e495c75"
- },
- {
- "ImportPath": "github.com/prometheus/client_golang/extraction",
- "Rev": "3a499bf7fc46bc58337ce612d0cbb29c550b8118"
- },
- {
- "ImportPath": "github.com/prometheus/client_golang/model",
- "Rev": "3a499bf7fc46bc58337ce612d0cbb29c550b8118"
- },
- {
- "ImportPath": "github.com/prometheus/client_golang/prometheus",
- "Rev": "3a499bf7fc46bc58337ce612d0cbb29c550b8118"
- },
- {
- "ImportPath": "github.com/prometheus/client_golang/text",
- "Rev": "3a499bf7fc46bc58337ce612d0cbb29c550b8118"
- },
- {
- "ImportPath": "github.com/prometheus/common/expfmt",
- "Rev": "7cd9f43750daf997c60f33f46680780067410f28"
- },
- {
- "ImportPath": "github.com/prometheus/common/model",
- "Rev": "7cd9f43750daf997c60f33f46680780067410f28"
- },
- {
- "ImportPath": "github.com/prometheus/client_model/go",
- "Comment": "model-0.0.2-12-gfa8ad6f",
- "Rev": "fa8ad6fec33561be4280a8f0514318c79d7f6cb6"
- },
- {
- "ImportPath": "github.com/prometheus/log",
- "Rev": "439e5db48fbb50ebbaf2c816030473a62f505f55"
- },
- {
- "ImportPath": "github.com/prometheus/procfs",
- "Rev": "c91d8eefde16bd047416409eb56353ea84a186e4"
- },
- {
- "ImportPath": "github.com/samuel/go-zookeeper/zk",
- "Rev": "5bb5cfc093ad18a28148c578f8632cfdb4d802e4"
- },
- {
- "ImportPath": "github.com/syndtr/goleveldb/leveldb",
- "Rev": "183614d6b32571e867df4cf086f5480ceefbdfac"
- },
- {
- "ImportPath": "golang.org/x/net/context",
- "Rev": "b71143c25f0aad5f54981684b715686d34c56d25"
- },
- {
- "ImportPath": "gopkg.in/fsnotify.v1",
- "Comment": "v1.2.0",
- "Rev": "96c060f6a6b7e0d6f75fddd10efeaca3e5d1bcb0"
- },
- {
- "ImportPath": "gopkg.in/yaml.v2",
- "Rev": "7ad95dd0798a40da1ccdff6dff35fd177b5edf40"
- }
- ]
-}
diff --git a/Godeps/Readme b/Godeps/Readme
deleted file mode 100644
index 4cdaa53d56..0000000000
--- a/Godeps/Readme
+++ /dev/null
@@ -1,5 +0,0 @@
-This directory tree is generated automatically by godep.
-
-Please do not edit.
-
-See https://github.com/tools/godep for more information.
diff --git a/Godeps/_workspace/.gitignore b/Godeps/_workspace/.gitignore
deleted file mode 100644
index f037d684ef..0000000000
--- a/Godeps/_workspace/.gitignore
+++ /dev/null
@@ -1,2 +0,0 @@
-/pkg
-/bin
diff --git a/Godeps/_workspace/src/bitbucket.org/ww/goautoneg/Makefile b/Godeps/_workspace/src/bitbucket.org/ww/goautoneg/Makefile
deleted file mode 100644
index e33ee17303..0000000000
--- a/Godeps/_workspace/src/bitbucket.org/ww/goautoneg/Makefile
+++ /dev/null
@@ -1,13 +0,0 @@
-include $(GOROOT)/src/Make.inc
-
-TARG=bitbucket.org/ww/goautoneg
-GOFILES=autoneg.go
-
-include $(GOROOT)/src/Make.pkg
-
-format:
- gofmt -w *.go
-
-docs:
- gomake clean
- godoc ${TARG} > README.txt
diff --git a/Godeps/_workspace/src/bitbucket.org/ww/goautoneg/README.txt b/Godeps/_workspace/src/bitbucket.org/ww/goautoneg/README.txt
deleted file mode 100644
index 7723656d58..0000000000
--- a/Godeps/_workspace/src/bitbucket.org/ww/goautoneg/README.txt
+++ /dev/null
@@ -1,67 +0,0 @@
-PACKAGE
-
-package goautoneg
-import "bitbucket.org/ww/goautoneg"
-
-HTTP Content-Type Autonegotiation.
-
-The functions in this package implement the behaviour specified in
-http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
-
-Copyright (c) 2011, Open Knowledge Foundation Ltd.
-All rights reserved.
-
-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 the Open Knowledge Foundation Ltd. 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
-HOLDER 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.
-
-
-FUNCTIONS
-
-func Negotiate(header string, alternatives []string) (content_type string)
-Negotiate the most appropriate content_type given the accept header
-and a list of alternatives.
-
-func ParseAccept(header string) (accept []Accept)
-Parse an Accept Header string returning a sorted list
-of clauses
-
-
-TYPES
-
-type Accept struct {
- Type, SubType string
- Q float32
- Params map[string]string
-}
-Structure to represent a clause in an HTTP Accept Header
-
-
-SUBDIRECTORIES
-
- .hg
diff --git a/Godeps/_workspace/src/bitbucket.org/ww/goautoneg/autoneg.go b/Godeps/_workspace/src/bitbucket.org/ww/goautoneg/autoneg.go
deleted file mode 100644
index 648b38cb65..0000000000
--- a/Godeps/_workspace/src/bitbucket.org/ww/goautoneg/autoneg.go
+++ /dev/null
@@ -1,162 +0,0 @@
-/*
-HTTP Content-Type Autonegotiation.
-
-The functions in this package implement the behaviour specified in
-http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
-
-Copyright (c) 2011, Open Knowledge Foundation Ltd.
-All rights reserved.
-
-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 the Open Knowledge Foundation Ltd. 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
-HOLDER 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 goautoneg
-
-import (
- "sort"
- "strconv"
- "strings"
-)
-
-// Structure to represent a clause in an HTTP Accept Header
-type Accept struct {
- Type, SubType string
- Q float64
- Params map[string]string
-}
-
-// For internal use, so that we can use the sort interface
-type accept_slice []Accept
-
-func (accept accept_slice) Len() int {
- slice := []Accept(accept)
- return len(slice)
-}
-
-func (accept accept_slice) Less(i, j int) bool {
- slice := []Accept(accept)
- ai, aj := slice[i], slice[j]
- if ai.Q > aj.Q {
- return true
- }
- if ai.Type != "*" && aj.Type == "*" {
- return true
- }
- if ai.SubType != "*" && aj.SubType == "*" {
- return true
- }
- return false
-}
-
-func (accept accept_slice) Swap(i, j int) {
- slice := []Accept(accept)
- slice[i], slice[j] = slice[j], slice[i]
-}
-
-// Parse an Accept Header string returning a sorted list
-// of clauses
-func ParseAccept(header string) (accept []Accept) {
- parts := strings.Split(header, ",")
- accept = make([]Accept, 0, len(parts))
- for _, part := range parts {
- part := strings.Trim(part, " ")
-
- a := Accept{}
- a.Params = make(map[string]string)
- a.Q = 1.0
-
- mrp := strings.Split(part, ";")
-
- media_range := mrp[0]
- sp := strings.Split(media_range, "/")
- a.Type = strings.Trim(sp[0], " ")
-
- switch {
- case len(sp) == 1 && a.Type == "*":
- a.SubType = "*"
- case len(sp) == 2:
- a.SubType = strings.Trim(sp[1], " ")
- default:
- continue
- }
-
- if len(mrp) == 1 {
- accept = append(accept, a)
- continue
- }
-
- for _, param := range mrp[1:] {
- sp := strings.SplitN(param, "=", 2)
- if len(sp) != 2 {
- continue
- }
- token := strings.Trim(sp[0], " ")
- if token == "q" {
- a.Q, _ = strconv.ParseFloat(sp[1], 32)
- } else {
- a.Params[token] = strings.Trim(sp[1], " ")
- }
- }
-
- accept = append(accept, a)
- }
-
- slice := accept_slice(accept)
- sort.Sort(slice)
-
- return
-}
-
-// Negotiate the most appropriate content_type given the accept header
-// and a list of alternatives.
-func Negotiate(header string, alternatives []string) (content_type string) {
- asp := make([][]string, 0, len(alternatives))
- for _, ctype := range alternatives {
- asp = append(asp, strings.SplitN(ctype, "/", 2))
- }
- for _, clause := range ParseAccept(header) {
- for i, ctsp := range asp {
- if clause.Type == ctsp[0] && clause.SubType == ctsp[1] {
- content_type = alternatives[i]
- return
- }
- if clause.Type == ctsp[0] && clause.SubType == "*" {
- content_type = alternatives[i]
- return
- }
- if clause.Type == "*" && clause.SubType == "*" {
- content_type = alternatives[i]
- return
- }
- }
- }
- return
-}
diff --git a/Godeps/_workspace/src/bitbucket.org/ww/goautoneg/autoneg_test.go b/Godeps/_workspace/src/bitbucket.org/ww/goautoneg/autoneg_test.go
deleted file mode 100644
index 41d328f1d5..0000000000
--- a/Godeps/_workspace/src/bitbucket.org/ww/goautoneg/autoneg_test.go
+++ /dev/null
@@ -1,33 +0,0 @@
-package goautoneg
-
-import (
- "testing"
-)
-
-var chrome = "application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"
-
-func TestParseAccept(t *testing.T) {
- alternatives := []string{"text/html", "image/png"}
- content_type := Negotiate(chrome, alternatives)
- if content_type != "image/png" {
- t.Errorf("got %s expected image/png", content_type)
- }
-
- alternatives = []string{"text/html", "text/plain", "text/n3"}
- content_type = Negotiate(chrome, alternatives)
- if content_type != "text/html" {
- t.Errorf("got %s expected text/html", content_type)
- }
-
- alternatives = []string{"text/n3", "text/plain"}
- content_type = Negotiate(chrome, alternatives)
- if content_type != "text/plain" {
- t.Errorf("got %s expected text/plain", content_type)
- }
-
- alternatives = []string{"text/n3", "application/rdf+xml"}
- content_type = Negotiate(chrome, alternatives)
- if content_type != "text/n3" {
- t.Errorf("got %s expected text/n3", content_type)
- }
-}
diff --git a/Godeps/_workspace/src/github.com/Sirupsen/logrus/.gitignore b/Godeps/_workspace/src/github.com/Sirupsen/logrus/.gitignore
deleted file mode 100644
index 66be63a005..0000000000
--- a/Godeps/_workspace/src/github.com/Sirupsen/logrus/.gitignore
+++ /dev/null
@@ -1 +0,0 @@
-logrus
diff --git a/Godeps/_workspace/src/github.com/Sirupsen/logrus/.travis.yml b/Godeps/_workspace/src/github.com/Sirupsen/logrus/.travis.yml
deleted file mode 100644
index 2d8c086617..0000000000
--- a/Godeps/_workspace/src/github.com/Sirupsen/logrus/.travis.yml
+++ /dev/null
@@ -1,8 +0,0 @@
-language: go
-go:
- - 1.2
- - 1.3
- - 1.4
- - tip
-install:
- - go get -t ./...
diff --git a/Godeps/_workspace/src/github.com/Sirupsen/logrus/CHANGELOG.md b/Godeps/_workspace/src/github.com/Sirupsen/logrus/CHANGELOG.md
deleted file mode 100644
index ab18440107..0000000000
--- a/Godeps/_workspace/src/github.com/Sirupsen/logrus/CHANGELOG.md
+++ /dev/null
@@ -1,37 +0,0 @@
-# 0.8.5
-
-* logrus/core: revert #208
-
-# 0.8.4
-
-* formatter/text: fix data race (#218)
-
-# 0.8.3
-
-* logrus/core: fix entry log level (#208)
-* logrus/core: improve performance of text formatter by 40%
-* logrus/core: expose `LevelHooks` type
-* logrus/core: add support for DragonflyBSD and NetBSD
-* formatter/text: print structs more verbosely
-
-# 0.8.2
-
-* logrus: fix more Fatal family functions
-
-# 0.8.1
-
-* logrus: fix not exiting on `Fatalf` and `Fatalln`
-
-# 0.8.0
-
-* logrus: defaults to stderr instead of stdout
-* hooks/sentry: add special field for `*http.Request`
-* formatter/text: ignore Windows for colors
-
-# 0.7.3
-
-* formatter/\*: allow configuration of timestamp layout
-
-# 0.7.2
-
-* formatter/text: Add configuration option for time format (#158)
diff --git a/Godeps/_workspace/src/github.com/Sirupsen/logrus/LICENSE b/Godeps/_workspace/src/github.com/Sirupsen/logrus/LICENSE
deleted file mode 100644
index f090cb42f3..0000000000
--- a/Godeps/_workspace/src/github.com/Sirupsen/logrus/LICENSE
+++ /dev/null
@@ -1,21 +0,0 @@
-The MIT License (MIT)
-
-Copyright (c) 2014 Simon Eskildsen
-
-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.
diff --git a/Godeps/_workspace/src/github.com/Sirupsen/logrus/README.md b/Godeps/_workspace/src/github.com/Sirupsen/logrus/README.md
deleted file mode 100644
index bd9ffb6eda..0000000000
--- a/Godeps/_workspace/src/github.com/Sirupsen/logrus/README.md
+++ /dev/null
@@ -1,356 +0,0 @@
-# Logrus
[](https://travis-ci.org/Sirupsen/logrus) [][godoc]
-
-Logrus is a structured logger for Go (golang), completely API compatible with
-the standard library logger. [Godoc][godoc]. **Please note the Logrus API is not
-yet stable (pre 1.0). Logrus itself is completely stable and has been used in
-many large deployments. The core API is unlikely to change much but please
-version control your Logrus to make sure you aren't fetching latest `master` on
-every build.**
-
-Nicely color-coded in development (when a TTY is attached, otherwise just
-plain text):
-
-
-
-With `log.Formatter = new(logrus.JSONFormatter)`, for easy parsing by logstash
-or Splunk:
-
-```json
-{"animal":"walrus","level":"info","msg":"A group of walrus emerges from the
-ocean","size":10,"time":"2014-03-10 19:57:38.562264131 -0400 EDT"}
-
-{"level":"warning","msg":"The group's number increased tremendously!",
-"number":122,"omg":true,"time":"2014-03-10 19:57:38.562471297 -0400 EDT"}
-
-{"animal":"walrus","level":"info","msg":"A giant walrus appears!",
-"size":10,"time":"2014-03-10 19:57:38.562500591 -0400 EDT"}
-
-{"animal":"walrus","level":"info","msg":"Tremendously sized cow enters the ocean.",
-"size":9,"time":"2014-03-10 19:57:38.562527896 -0400 EDT"}
-
-{"level":"fatal","msg":"The ice breaks!","number":100,"omg":true,
-"time":"2014-03-10 19:57:38.562543128 -0400 EDT"}
-```
-
-With the default `log.Formatter = new(&log.TextFormatter{})` when a TTY is not
-attached, the output is compatible with the
-[logfmt](http://godoc.org/github.com/kr/logfmt) format:
-
-```text
-time="2015-03-26T01:27:38-04:00" level=debug msg="Started observing beach" animal=walrus number=8
-time="2015-03-26T01:27:38-04:00" level=info msg="A group of walrus emerges from the ocean" animal=walrus size=10
-time="2015-03-26T01:27:38-04:00" level=warning msg="The group's number increased tremendously!" number=122 omg=true
-time="2015-03-26T01:27:38-04:00" level=debug msg="Temperature changes" temperature=-4
-time="2015-03-26T01:27:38-04:00" level=panic msg="It's over 9000!" animal=orca size=9009
-time="2015-03-26T01:27:38-04:00" level=fatal msg="The ice breaks!" err=&{0x2082280c0 map[animal:orca size:9009] 2015-03-26 01:27:38.441574009 -0400 EDT panic It's over 9000!} number=100 omg=true
-exit status 1
-```
-
-#### Example
-
-The simplest way to use Logrus is simply the package-level exported logger:
-
-```go
-package main
-
-import (
- log "github.com/Sirupsen/logrus"
-)
-
-func main() {
- log.WithFields(log.Fields{
- "animal": "walrus",
- }).Info("A walrus appears")
-}
-```
-
-Note that it's completely api-compatible with the stdlib logger, so you can
-replace your `log` imports everywhere with `log "github.com/Sirupsen/logrus"`
-and you'll now have the flexibility of Logrus. You can customize it all you
-want:
-
-```go
-package main
-
-import (
- "os"
- log "github.com/Sirupsen/logrus"
- "github.com/Sirupsen/logrus/hooks/airbrake"
-)
-
-func init() {
- // Log as JSON instead of the default ASCII formatter.
- log.SetFormatter(&log.JSONFormatter{})
-
- // Use the Airbrake hook to report errors that have Error severity or above to
- // an exception tracker. You can create custom hooks, see the Hooks section.
- log.AddHook(airbrake.NewHook("https://example.com", "xyz", "development"))
-
- // Output to stderr instead of stdout, could also be a file.
- log.SetOutput(os.Stderr)
-
- // Only log the warning severity or above.
- log.SetLevel(log.WarnLevel)
-}
-
-func main() {
- log.WithFields(log.Fields{
- "animal": "walrus",
- "size": 10,
- }).Info("A group of walrus emerges from the ocean")
-
- log.WithFields(log.Fields{
- "omg": true,
- "number": 122,
- }).Warn("The group's number increased tremendously!")
-
- log.WithFields(log.Fields{
- "omg": true,
- "number": 100,
- }).Fatal("The ice breaks!")
-
- // A common pattern is to re-use fields between logging statements by re-using
- // the logrus.Entry returned from WithFields()
- contextLogger := log.WithFields(log.Fields{
- "common": "this is a common field",
- "other": "I also should be logged always",
- })
-
- contextLogger.Info("I'll be logged with common and other field")
- contextLogger.Info("Me too")
-}
-```
-
-For more advanced usage such as logging to multiple locations from the same
-application, you can also create an instance of the `logrus` Logger:
-
-```go
-package main
-
-import (
- "github.com/Sirupsen/logrus"
-)
-
-// Create a new instance of the logger. You can have any number of instances.
-var log = logrus.New()
-
-func main() {
- // The API for setting attributes is a little different than the package level
- // exported logger. See Godoc.
- log.Out = os.Stderr
-
- log.WithFields(logrus.Fields{
- "animal": "walrus",
- "size": 10,
- }).Info("A group of walrus emerges from the ocean")
-}
-```
-
-#### Fields
-
-Logrus encourages careful, structured logging though logging fields instead of
-long, unparseable error messages. For example, instead of: `log.Fatalf("Failed
-to send event %s to topic %s with key %d")`, you should log the much more
-discoverable:
-
-```go
-log.WithFields(log.Fields{
- "event": event,
- "topic": topic,
- "key": key,
-}).Fatal("Failed to send event")
-```
-
-We've found this API forces you to think about logging in a way that produces
-much more useful logging messages. We've been in countless situations where just
-a single added field to a log statement that was already there would've saved us
-hours. The `WithFields` call is optional.
-
-In general, with Logrus using any of the `printf`-family functions should be
-seen as a hint you should add a field, however, you can still use the
-`printf`-family functions with Logrus.
-
-#### Hooks
-
-You can add hooks for logging levels. For example to send errors to an exception
-tracking service on `Error`, `Fatal` and `Panic`, info to StatsD or log to
-multiple places simultaneously, e.g. syslog.
-
-Logrus comes with [built-in hooks](hooks/). Add those, or your custom hook, in
-`init`:
-
-```go
-import (
- log "github.com/Sirupsen/logrus"
- "github.com/Sirupsen/logrus/hooks/airbrake"
- logrus_syslog "github.com/Sirupsen/logrus/hooks/syslog"
- "log/syslog"
-)
-
-func init() {
- log.AddHook(airbrake.NewHook("https://example.com", "xyz", "development"))
-
- hook, err := logrus_syslog.NewSyslogHook("udp", "localhost:514", syslog.LOG_INFO, "")
- if err != nil {
- log.Error("Unable to connect to local syslog daemon")
- } else {
- log.AddHook(hook)
- }
-}
-```
-
-
-| Hook | Description |
-| ----- | ----------- |
-| [Airbrake](https://github.com/Sirupsen/logrus/blob/master/hooks/airbrake/airbrake.go) | Send errors to an exception tracking service compatible with the Airbrake API. Uses [`airbrake-go`](https://github.com/tobi/airbrake-go) behind the scenes. |
-| [Papertrail](https://github.com/Sirupsen/logrus/blob/master/hooks/papertrail/papertrail.go) | Send errors to the Papertrail hosted logging service via UDP. |
-| [Syslog](https://github.com/Sirupsen/logrus/blob/master/hooks/syslog/syslog.go) | Send errors to remote syslog server. Uses standard library `log/syslog` behind the scenes. |
-| [BugSnag](https://github.com/Sirupsen/logrus/blob/master/hooks/bugsnag/bugsnag.go) | Send errors to the Bugsnag exception tracking service. |
-| [Sentry](https://github.com/Sirupsen/logrus/blob/master/hooks/sentry/sentry.go) | Send errors to the Sentry error logging and aggregation service. |
-| [Hiprus](https://github.com/nubo/hiprus) | Send errors to a channel in hipchat. |
-| [Logrusly](https://github.com/sebest/logrusly) | Send logs to [Loggly](https://www.loggly.com/) |
-| [Slackrus](https://github.com/johntdyer/slackrus) | Hook for Slack chat. |
-| [Journalhook](https://github.com/wercker/journalhook) | Hook for logging to `systemd-journald` |
-| [Graylog](https://github.com/gemnasium/logrus-hooks/tree/master/graylog) | Hook for logging to [Graylog](http://graylog2.org/) |
-| [Raygun](https://github.com/squirkle/logrus-raygun-hook) | Hook for logging to [Raygun.io](http://raygun.io/) |
-| [LFShook](https://github.com/rifflock/lfshook) | Hook for logging to the local filesystem |
-| [Honeybadger](https://github.com/agonzalezro/logrus_honeybadger) | Hook for sending exceptions to Honeybadger |
-| [Mail](https://github.com/zbindenren/logrus_mail) | Hook for sending exceptions via mail |
-| [Rollrus](https://github.com/heroku/rollrus) | Hook for sending errors to rollbar |
-| [Fluentd](https://github.com/evalphobia/logrus_fluent) | Hook for logging to fluentd |
-
-#### Level logging
-
-Logrus has six logging levels: Debug, Info, Warning, Error, Fatal and Panic.
-
-```go
-log.Debug("Useful debugging information.")
-log.Info("Something noteworthy happened!")
-log.Warn("You should probably take a look at this.")
-log.Error("Something failed but I'm not quitting.")
-// Calls os.Exit(1) after logging
-log.Fatal("Bye.")
-// Calls panic() after logging
-log.Panic("I'm bailing.")
-```
-
-You can set the logging level on a `Logger`, then it will only log entries with
-that severity or anything above it:
-
-```go
-// Will log anything that is info or above (warn, error, fatal, panic). Default.
-log.SetLevel(log.InfoLevel)
-```
-
-It may be useful to set `log.Level = logrus.DebugLevel` in a debug or verbose
-environment if your application has that.
-
-#### Entries
-
-Besides the fields added with `WithField` or `WithFields` some fields are
-automatically added to all logging events:
-
-1. `time`. The timestamp when the entry was created.
-2. `msg`. The logging message passed to `{Info,Warn,Error,Fatal,Panic}` after
- the `AddFields` call. E.g. `Failed to send event.`
-3. `level`. The logging level. E.g. `info`.
-
-#### Environments
-
-Logrus has no notion of environment.
-
-If you wish for hooks and formatters to only be used in specific environments,
-you should handle that yourself. For example, if your application has a global
-variable `Environment`, which is a string representation of the environment you
-could do:
-
-```go
-import (
- log "github.com/Sirupsen/logrus"
-)
-
-init() {
- // do something here to set environment depending on an environment variable
- // or command-line flag
- if Environment == "production" {
- log.SetFormatter(&logrus.JSONFormatter{})
- } else {
- // The TextFormatter is default, you don't actually have to do this.
- log.SetFormatter(&log.TextFormatter{})
- }
-}
-```
-
-This configuration is how `logrus` was intended to be used, but JSON in
-production is mostly only useful if you do log aggregation with tools like
-Splunk or Logstash.
-
-#### Formatters
-
-The built-in logging formatters are:
-
-* `logrus.TextFormatter`. Logs the event in colors if stdout is a tty, otherwise
- without colors.
- * *Note:* to force colored output when there is no TTY, set the `ForceColors`
- field to `true`. To force no colored output even if there is a TTY set the
- `DisableColors` field to `true`
-* `logrus.JSONFormatter`. Logs fields as JSON.
-* `logrus_logstash.LogstashFormatter`. Logs fields as Logstash Events (http://logstash.net).
-
- ```go
- logrus.SetFormatter(&logrus_logstash.LogstashFormatter{Type: “application_name"})
- ```
-
-Third party logging formatters:
-
-* [`zalgo`](https://github.com/aybabtme/logzalgo): invoking the P͉̫o̳̼̊w̖͈̰͎e̬͔̭͂r͚̼̹̲ ̫͓͉̳͈ō̠͕͖̚f̝͍̠ ͕̲̞͖͑Z̖̫̤̫ͪa͉̬͈̗l͖͎g̳̥o̰̥̅!̣͔̲̻͊̄ ̙̘̦̹̦.
-
-You can define your formatter by implementing the `Formatter` interface,
-requiring a `Format` method. `Format` takes an `*Entry`. `entry.Data` is a
-`Fields` type (`map[string]interface{}`) with all your fields as well as the
-default ones (see Entries section above):
-
-```go
-type MyJSONFormatter struct {
-}
-
-log.SetFormatter(new(MyJSONFormatter))
-
-func (f *JSONFormatter) Format(entry *Entry) ([]byte, error) {
- // Note this doesn't include Time, Level and Message which are available on
- // the Entry. Consult `godoc` on information about those fields or read the
- // source of the official loggers.
- serialized, err := json.Marshal(entry.Data)
- if err != nil {
- return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err)
- }
- return append(serialized, '\n'), nil
-}
-```
-
-#### Logger as an `io.Writer`
-
-Logrus can be transformed into an `io.Writer`. That writer is the end of an `io.Pipe` and it is your responsibility to close it.
-
-```go
-w := logger.Writer()
-defer w.Close()
-
-srv := http.Server{
- // create a stdlib log.Logger that writes to
- // logrus.Logger.
- ErrorLog: log.New(w, "", 0),
-}
-```
-
-Each line written to that writer will be printed the usual way, using formatters
-and hooks. The level for those entries is `info`.
-
-#### Rotation
-
-Log rotation is not provided with Logrus. Log rotation should be done by an
-external program (like `logrotate(8)`) that can compress and delete old log
-entries. It should not be a feature of the application-level logger.
-
-
-[godoc]: https://godoc.org/github.com/Sirupsen/logrus
diff --git a/Godeps/_workspace/src/github.com/Sirupsen/logrus/entry.go b/Godeps/_workspace/src/github.com/Sirupsen/logrus/entry.go
deleted file mode 100644
index 699ea035cc..0000000000
--- a/Godeps/_workspace/src/github.com/Sirupsen/logrus/entry.go
+++ /dev/null
@@ -1,254 +0,0 @@
-package logrus
-
-import (
- "bytes"
- "fmt"
- "io"
- "os"
- "time"
-)
-
-// An entry is the final or intermediate Logrus logging entry. It contains all
-// the fields passed with WithField{,s}. It's finally logged when Debug, Info,
-// Warn, Error, Fatal or Panic is called on it. These objects can be reused and
-// passed around as much as you wish to avoid field duplication.
-type Entry struct {
- Logger *Logger
-
- // Contains all the fields set by the user.
- Data Fields
-
- // Time at which the log entry was created
- Time time.Time
-
- // Level the log entry was logged at: Debug, Info, Warn, Error, Fatal or Panic
- Level Level
-
- // Message passed to Debug, Info, Warn, Error, Fatal or Panic
- Message string
-}
-
-func NewEntry(logger *Logger) *Entry {
- return &Entry{
- Logger: logger,
- // Default is three fields, give a little extra room
- Data: make(Fields, 5),
- }
-}
-
-// Returns a reader for the entry, which is a proxy to the formatter.
-func (entry *Entry) Reader() (*bytes.Buffer, error) {
- serialized, err := entry.Logger.Formatter.Format(entry)
- return bytes.NewBuffer(serialized), err
-}
-
-// Returns the string representation from the reader and ultimately the
-// formatter.
-func (entry *Entry) String() (string, error) {
- reader, err := entry.Reader()
- if err != nil {
- return "", err
- }
-
- return reader.String(), err
-}
-
-// Add a single field to the Entry.
-func (entry *Entry) WithField(key string, value interface{}) *Entry {
- return entry.WithFields(Fields{key: value})
-}
-
-// Add a map of fields to the Entry.
-func (entry *Entry) WithFields(fields Fields) *Entry {
- data := Fields{}
- for k, v := range entry.Data {
- data[k] = v
- }
- for k, v := range fields {
- data[k] = v
- }
- return &Entry{Logger: entry.Logger, Data: data}
-}
-
-func (entry *Entry) log(level Level, msg string) {
- entry.Time = time.Now()
- entry.Level = level
- entry.Message = msg
-
- if err := entry.Logger.Hooks.Fire(level, entry); err != nil {
- entry.Logger.mu.Lock()
- fmt.Fprintf(os.Stderr, "Failed to fire hook: %v\n", err)
- entry.Logger.mu.Unlock()
- }
-
- reader, err := entry.Reader()
- if err != nil {
- entry.Logger.mu.Lock()
- fmt.Fprintf(os.Stderr, "Failed to obtain reader, %v\n", err)
- entry.Logger.mu.Unlock()
- }
-
- entry.Logger.mu.Lock()
- defer entry.Logger.mu.Unlock()
-
- _, err = io.Copy(entry.Logger.Out, reader)
- if err != nil {
- fmt.Fprintf(os.Stderr, "Failed to write to log, %v\n", err)
- }
-
- // To avoid Entry#log() returning a value that only would make sense for
- // panic() to use in Entry#Panic(), we avoid the allocation by checking
- // directly here.
- if level <= PanicLevel {
- panic(entry)
- }
-}
-
-func (entry *Entry) Debug(args ...interface{}) {
- if entry.Logger.Level >= DebugLevel {
- entry.log(DebugLevel, fmt.Sprint(args...))
- }
-}
-
-func (entry *Entry) Print(args ...interface{}) {
- entry.Info(args...)
-}
-
-func (entry *Entry) Info(args ...interface{}) {
- if entry.Logger.Level >= InfoLevel {
- entry.log(InfoLevel, fmt.Sprint(args...))
- }
-}
-
-func (entry *Entry) Warn(args ...interface{}) {
- if entry.Logger.Level >= WarnLevel {
- entry.log(WarnLevel, fmt.Sprint(args...))
- }
-}
-
-func (entry *Entry) Warning(args ...interface{}) {
- entry.Warn(args...)
-}
-
-func (entry *Entry) Error(args ...interface{}) {
- if entry.Logger.Level >= ErrorLevel {
- entry.log(ErrorLevel, fmt.Sprint(args...))
- }
-}
-
-func (entry *Entry) Fatal(args ...interface{}) {
- if entry.Logger.Level >= FatalLevel {
- entry.log(FatalLevel, fmt.Sprint(args...))
- }
- os.Exit(1)
-}
-
-func (entry *Entry) Panic(args ...interface{}) {
- if entry.Logger.Level >= PanicLevel {
- entry.log(PanicLevel, fmt.Sprint(args...))
- }
- panic(fmt.Sprint(args...))
-}
-
-// Entry Printf family functions
-
-func (entry *Entry) Debugf(format string, args ...interface{}) {
- if entry.Logger.Level >= DebugLevel {
- entry.Debug(fmt.Sprintf(format, args...))
- }
-}
-
-func (entry *Entry) Infof(format string, args ...interface{}) {
- if entry.Logger.Level >= InfoLevel {
- entry.Info(fmt.Sprintf(format, args...))
- }
-}
-
-func (entry *Entry) Printf(format string, args ...interface{}) {
- entry.Infof(format, args...)
-}
-
-func (entry *Entry) Warnf(format string, args ...interface{}) {
- if entry.Logger.Level >= WarnLevel {
- entry.Warn(fmt.Sprintf(format, args...))
- }
-}
-
-func (entry *Entry) Warningf(format string, args ...interface{}) {
- entry.Warnf(format, args...)
-}
-
-func (entry *Entry) Errorf(format string, args ...interface{}) {
- if entry.Logger.Level >= ErrorLevel {
- entry.Error(fmt.Sprintf(format, args...))
- }
-}
-
-func (entry *Entry) Fatalf(format string, args ...interface{}) {
- if entry.Logger.Level >= FatalLevel {
- entry.Fatal(fmt.Sprintf(format, args...))
- }
- os.Exit(1)
-}
-
-func (entry *Entry) Panicf(format string, args ...interface{}) {
- if entry.Logger.Level >= PanicLevel {
- entry.Panic(fmt.Sprintf(format, args...))
- }
-}
-
-// Entry Println family functions
-
-func (entry *Entry) Debugln(args ...interface{}) {
- if entry.Logger.Level >= DebugLevel {
- entry.Debug(entry.sprintlnn(args...))
- }
-}
-
-func (entry *Entry) Infoln(args ...interface{}) {
- if entry.Logger.Level >= InfoLevel {
- entry.Info(entry.sprintlnn(args...))
- }
-}
-
-func (entry *Entry) Println(args ...interface{}) {
- entry.Infoln(args...)
-}
-
-func (entry *Entry) Warnln(args ...interface{}) {
- if entry.Logger.Level >= WarnLevel {
- entry.Warn(entry.sprintlnn(args...))
- }
-}
-
-func (entry *Entry) Warningln(args ...interface{}) {
- entry.Warnln(args...)
-}
-
-func (entry *Entry) Errorln(args ...interface{}) {
- if entry.Logger.Level >= ErrorLevel {
- entry.Error(entry.sprintlnn(args...))
- }
-}
-
-func (entry *Entry) Fatalln(args ...interface{}) {
- if entry.Logger.Level >= FatalLevel {
- entry.Fatal(entry.sprintlnn(args...))
- }
- os.Exit(1)
-}
-
-func (entry *Entry) Panicln(args ...interface{}) {
- if entry.Logger.Level >= PanicLevel {
- entry.Panic(entry.sprintlnn(args...))
- }
-}
-
-// Sprintlnn => Sprint no newline. This is to get the behavior of how
-// fmt.Sprintln where spaces are always added between operands, regardless of
-// their type. Instead of vendoring the Sprintln implementation to spare a
-// string allocation, we do the simplest thing.
-func (entry *Entry) sprintlnn(args ...interface{}) string {
- msg := fmt.Sprintln(args...)
- return msg[:len(msg)-1]
-}
diff --git a/Godeps/_workspace/src/github.com/Sirupsen/logrus/entry_test.go b/Godeps/_workspace/src/github.com/Sirupsen/logrus/entry_test.go
deleted file mode 100644
index 98717df490..0000000000
--- a/Godeps/_workspace/src/github.com/Sirupsen/logrus/entry_test.go
+++ /dev/null
@@ -1,53 +0,0 @@
-package logrus
-
-import (
- "bytes"
- "fmt"
- "testing"
-
- "github.com/stretchr/testify/assert"
-)
-
-func TestEntryPanicln(t *testing.T) {
- errBoom := fmt.Errorf("boom time")
-
- defer func() {
- p := recover()
- assert.NotNil(t, p)
-
- switch pVal := p.(type) {
- case *Entry:
- assert.Equal(t, "kaboom", pVal.Message)
- assert.Equal(t, errBoom, pVal.Data["err"])
- default:
- t.Fatalf("want type *Entry, got %T: %#v", pVal, pVal)
- }
- }()
-
- logger := New()
- logger.Out = &bytes.Buffer{}
- entry := NewEntry(logger)
- entry.WithField("err", errBoom).Panicln("kaboom")
-}
-
-func TestEntryPanicf(t *testing.T) {
- errBoom := fmt.Errorf("boom again")
-
- defer func() {
- p := recover()
- assert.NotNil(t, p)
-
- switch pVal := p.(type) {
- case *Entry:
- assert.Equal(t, "kaboom true", pVal.Message)
- assert.Equal(t, errBoom, pVal.Data["err"])
- default:
- t.Fatalf("want type *Entry, got %T: %#v", pVal, pVal)
- }
- }()
-
- logger := New()
- logger.Out = &bytes.Buffer{}
- entry := NewEntry(logger)
- entry.WithField("err", errBoom).Panicf("kaboom %v", true)
-}
diff --git a/Godeps/_workspace/src/github.com/Sirupsen/logrus/examples/basic/basic.go b/Godeps/_workspace/src/github.com/Sirupsen/logrus/examples/basic/basic.go
deleted file mode 100644
index a1623ec003..0000000000
--- a/Godeps/_workspace/src/github.com/Sirupsen/logrus/examples/basic/basic.go
+++ /dev/null
@@ -1,50 +0,0 @@
-package main
-
-import (
- "github.com/Sirupsen/logrus"
-)
-
-var log = logrus.New()
-
-func init() {
- log.Formatter = new(logrus.JSONFormatter)
- log.Formatter = new(logrus.TextFormatter) // default
- log.Level = logrus.DebugLevel
-}
-
-func main() {
- defer func() {
- err := recover()
- if err != nil {
- log.WithFields(logrus.Fields{
- "omg": true,
- "err": err,
- "number": 100,
- }).Fatal("The ice breaks!")
- }
- }()
-
- log.WithFields(logrus.Fields{
- "animal": "walrus",
- "number": 8,
- }).Debug("Started observing beach")
-
- log.WithFields(logrus.Fields{
- "animal": "walrus",
- "size": 10,
- }).Info("A group of walrus emerges from the ocean")
-
- log.WithFields(logrus.Fields{
- "omg": true,
- "number": 122,
- }).Warn("The group's number increased tremendously!")
-
- log.WithFields(logrus.Fields{
- "temperature": -4,
- }).Debug("Temperature changes")
-
- log.WithFields(logrus.Fields{
- "animal": "orca",
- "size": 9009,
- }).Panic("It's over 9000!")
-}
diff --git a/Godeps/_workspace/src/github.com/Sirupsen/logrus/examples/hook/hook.go b/Godeps/_workspace/src/github.com/Sirupsen/logrus/examples/hook/hook.go
deleted file mode 100644
index cb5759a35c..0000000000
--- a/Godeps/_workspace/src/github.com/Sirupsen/logrus/examples/hook/hook.go
+++ /dev/null
@@ -1,30 +0,0 @@
-package main
-
-import (
- "github.com/Sirupsen/logrus"
- "github.com/Sirupsen/logrus/hooks/airbrake"
-)
-
-var log = logrus.New()
-
-func init() {
- log.Formatter = new(logrus.TextFormatter) // default
- log.Hooks.Add(airbrake.NewHook("https://example.com", "xyz", "development"))
-}
-
-func main() {
- log.WithFields(logrus.Fields{
- "animal": "walrus",
- "size": 10,
- }).Info("A group of walrus emerges from the ocean")
-
- log.WithFields(logrus.Fields{
- "omg": true,
- "number": 122,
- }).Warn("The group's number increased tremendously!")
-
- log.WithFields(logrus.Fields{
- "omg": true,
- "number": 100,
- }).Fatal("The ice breaks!")
-}
diff --git a/Godeps/_workspace/src/github.com/Sirupsen/logrus/exported.go b/Godeps/_workspace/src/github.com/Sirupsen/logrus/exported.go
deleted file mode 100644
index a67e1b802d..0000000000
--- a/Godeps/_workspace/src/github.com/Sirupsen/logrus/exported.go
+++ /dev/null
@@ -1,188 +0,0 @@
-package logrus
-
-import (
- "io"
-)
-
-var (
- // std is the name of the standard logger in stdlib `log`
- std = New()
-)
-
-func StandardLogger() *Logger {
- return std
-}
-
-// SetOutput sets the standard logger output.
-func SetOutput(out io.Writer) {
- std.mu.Lock()
- defer std.mu.Unlock()
- std.Out = out
-}
-
-// SetFormatter sets the standard logger formatter.
-func SetFormatter(formatter Formatter) {
- std.mu.Lock()
- defer std.mu.Unlock()
- std.Formatter = formatter
-}
-
-// SetLevel sets the standard logger level.
-func SetLevel(level Level) {
- std.mu.Lock()
- defer std.mu.Unlock()
- std.Level = level
-}
-
-// GetLevel returns the standard logger level.
-func GetLevel() Level {
- std.mu.Lock()
- defer std.mu.Unlock()
- return std.Level
-}
-
-// AddHook adds a hook to the standard logger hooks.
-func AddHook(hook Hook) {
- std.mu.Lock()
- defer std.mu.Unlock()
- std.Hooks.Add(hook)
-}
-
-// WithField creates an entry from the standard logger and adds a field to
-// it. If you want multiple fields, use `WithFields`.
-//
-// Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal
-// or Panic on the Entry it returns.
-func WithField(key string, value interface{}) *Entry {
- return std.WithField(key, value)
-}
-
-// WithFields creates an entry from the standard logger and adds multiple
-// fields to it. This is simply a helper for `WithField`, invoking it
-// once for each field.
-//
-// Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal
-// or Panic on the Entry it returns.
-func WithFields(fields Fields) *Entry {
- return std.WithFields(fields)
-}
-
-// Debug logs a message at level Debug on the standard logger.
-func Debug(args ...interface{}) {
- std.Debug(args...)
-}
-
-// Print logs a message at level Info on the standard logger.
-func Print(args ...interface{}) {
- std.Print(args...)
-}
-
-// Info logs a message at level Info on the standard logger.
-func Info(args ...interface{}) {
- std.Info(args...)
-}
-
-// Warn logs a message at level Warn on the standard logger.
-func Warn(args ...interface{}) {
- std.Warn(args...)
-}
-
-// Warning logs a message at level Warn on the standard logger.
-func Warning(args ...interface{}) {
- std.Warning(args...)
-}
-
-// Error logs a message at level Error on the standard logger.
-func Error(args ...interface{}) {
- std.Error(args...)
-}
-
-// Panic logs a message at level Panic on the standard logger.
-func Panic(args ...interface{}) {
- std.Panic(args...)
-}
-
-// Fatal logs a message at level Fatal on the standard logger.
-func Fatal(args ...interface{}) {
- std.Fatal(args...)
-}
-
-// Debugf logs a message at level Debug on the standard logger.
-func Debugf(format string, args ...interface{}) {
- std.Debugf(format, args...)
-}
-
-// Printf logs a message at level Info on the standard logger.
-func Printf(format string, args ...interface{}) {
- std.Printf(format, args...)
-}
-
-// Infof logs a message at level Info on the standard logger.
-func Infof(format string, args ...interface{}) {
- std.Infof(format, args...)
-}
-
-// Warnf logs a message at level Warn on the standard logger.
-func Warnf(format string, args ...interface{}) {
- std.Warnf(format, args...)
-}
-
-// Warningf logs a message at level Warn on the standard logger.
-func Warningf(format string, args ...interface{}) {
- std.Warningf(format, args...)
-}
-
-// Errorf logs a message at level Error on the standard logger.
-func Errorf(format string, args ...interface{}) {
- std.Errorf(format, args...)
-}
-
-// Panicf logs a message at level Panic on the standard logger.
-func Panicf(format string, args ...interface{}) {
- std.Panicf(format, args...)
-}
-
-// Fatalf logs a message at level Fatal on the standard logger.
-func Fatalf(format string, args ...interface{}) {
- std.Fatalf(format, args...)
-}
-
-// Debugln logs a message at level Debug on the standard logger.
-func Debugln(args ...interface{}) {
- std.Debugln(args...)
-}
-
-// Println logs a message at level Info on the standard logger.
-func Println(args ...interface{}) {
- std.Println(args...)
-}
-
-// Infoln logs a message at level Info on the standard logger.
-func Infoln(args ...interface{}) {
- std.Infoln(args...)
-}
-
-// Warnln logs a message at level Warn on the standard logger.
-func Warnln(args ...interface{}) {
- std.Warnln(args...)
-}
-
-// Warningln logs a message at level Warn on the standard logger.
-func Warningln(args ...interface{}) {
- std.Warningln(args...)
-}
-
-// Errorln logs a message at level Error on the standard logger.
-func Errorln(args ...interface{}) {
- std.Errorln(args...)
-}
-
-// Panicln logs a message at level Panic on the standard logger.
-func Panicln(args ...interface{}) {
- std.Panicln(args...)
-}
-
-// Fatalln logs a message at level Fatal on the standard logger.
-func Fatalln(args ...interface{}) {
- std.Fatalln(args...)
-}
diff --git a/Godeps/_workspace/src/github.com/Sirupsen/logrus/formatter.go b/Godeps/_workspace/src/github.com/Sirupsen/logrus/formatter.go
deleted file mode 100644
index 104d689f18..0000000000
--- a/Godeps/_workspace/src/github.com/Sirupsen/logrus/formatter.go
+++ /dev/null
@@ -1,48 +0,0 @@
-package logrus
-
-import "time"
-
-const DefaultTimestampFormat = time.RFC3339
-
-// The Formatter interface is used to implement a custom Formatter. It takes an
-// `Entry`. It exposes all the fields, including the default ones:
-//
-// * `entry.Data["msg"]`. The message passed from Info, Warn, Error ..
-// * `entry.Data["time"]`. The timestamp.
-// * `entry.Data["level"]. The level the entry was logged at.
-//
-// Any additional fields added with `WithField` or `WithFields` are also in
-// `entry.Data`. Format is expected to return an array of bytes which are then
-// logged to `logger.Out`.
-type Formatter interface {
- Format(*Entry) ([]byte, error)
-}
-
-// This is to not silently overwrite `time`, `msg` and `level` fields when
-// dumping it. If this code wasn't there doing:
-//
-// logrus.WithField("level", 1).Info("hello")
-//
-// Would just silently drop the user provided level. Instead with this code
-// it'll logged as:
-//
-// {"level": "info", "fields.level": 1, "msg": "hello", "time": "..."}
-//
-// It's not exported because it's still using Data in an opinionated way. It's to
-// avoid code duplication between the two default formatters.
-func prefixFieldClashes(data Fields) {
- _, ok := data["time"]
- if ok {
- data["fields.time"] = data["time"]
- }
-
- _, ok = data["msg"]
- if ok {
- data["fields.msg"] = data["msg"]
- }
-
- _, ok = data["level"]
- if ok {
- data["fields.level"] = data["level"]
- }
-}
diff --git a/Godeps/_workspace/src/github.com/Sirupsen/logrus/formatter_bench_test.go b/Godeps/_workspace/src/github.com/Sirupsen/logrus/formatter_bench_test.go
deleted file mode 100644
index c6d290c77f..0000000000
--- a/Godeps/_workspace/src/github.com/Sirupsen/logrus/formatter_bench_test.go
+++ /dev/null
@@ -1,98 +0,0 @@
-package logrus
-
-import (
- "fmt"
- "testing"
- "time"
-)
-
-// smallFields is a small size data set for benchmarking
-var smallFields = Fields{
- "foo": "bar",
- "baz": "qux",
- "one": "two",
- "three": "four",
-}
-
-// largeFields is a large size data set for benchmarking
-var largeFields = Fields{
- "foo": "bar",
- "baz": "qux",
- "one": "two",
- "three": "four",
- "five": "six",
- "seven": "eight",
- "nine": "ten",
- "eleven": "twelve",
- "thirteen": "fourteen",
- "fifteen": "sixteen",
- "seventeen": "eighteen",
- "nineteen": "twenty",
- "a": "b",
- "c": "d",
- "e": "f",
- "g": "h",
- "i": "j",
- "k": "l",
- "m": "n",
- "o": "p",
- "q": "r",
- "s": "t",
- "u": "v",
- "w": "x",
- "y": "z",
- "this": "will",
- "make": "thirty",
- "entries": "yeah",
-}
-
-var errorFields = Fields{
- "foo": fmt.Errorf("bar"),
- "baz": fmt.Errorf("qux"),
-}
-
-func BenchmarkErrorTextFormatter(b *testing.B) {
- doBenchmark(b, &TextFormatter{DisableColors: true}, errorFields)
-}
-
-func BenchmarkSmallTextFormatter(b *testing.B) {
- doBenchmark(b, &TextFormatter{DisableColors: true}, smallFields)
-}
-
-func BenchmarkLargeTextFormatter(b *testing.B) {
- doBenchmark(b, &TextFormatter{DisableColors: true}, largeFields)
-}
-
-func BenchmarkSmallColoredTextFormatter(b *testing.B) {
- doBenchmark(b, &TextFormatter{ForceColors: true}, smallFields)
-}
-
-func BenchmarkLargeColoredTextFormatter(b *testing.B) {
- doBenchmark(b, &TextFormatter{ForceColors: true}, largeFields)
-}
-
-func BenchmarkSmallJSONFormatter(b *testing.B) {
- doBenchmark(b, &JSONFormatter{}, smallFields)
-}
-
-func BenchmarkLargeJSONFormatter(b *testing.B) {
- doBenchmark(b, &JSONFormatter{}, largeFields)
-}
-
-func doBenchmark(b *testing.B, formatter Formatter, fields Fields) {
- entry := &Entry{
- Time: time.Time{},
- Level: InfoLevel,
- Message: "message",
- Data: fields,
- }
- var d []byte
- var err error
- for i := 0; i < b.N; i++ {
- d, err = formatter.Format(entry)
- if err != nil {
- b.Fatal(err)
- }
- b.SetBytes(int64(len(d)))
- }
-}
diff --git a/Godeps/_workspace/src/github.com/Sirupsen/logrus/formatters/logstash/logstash.go b/Godeps/_workspace/src/github.com/Sirupsen/logrus/formatters/logstash/logstash.go
deleted file mode 100644
index 8ea93ddf20..0000000000
--- a/Godeps/_workspace/src/github.com/Sirupsen/logrus/formatters/logstash/logstash.go
+++ /dev/null
@@ -1,56 +0,0 @@
-package logstash
-
-import (
- "encoding/json"
- "fmt"
-
- "github.com/Sirupsen/logrus"
-)
-
-// Formatter generates json in logstash format.
-// Logstash site: http://logstash.net/
-type LogstashFormatter struct {
- Type string // if not empty use for logstash type field.
-
- // TimestampFormat sets the format used for timestamps.
- TimestampFormat string
-}
-
-func (f *LogstashFormatter) Format(entry *logrus.Entry) ([]byte, error) {
- entry.Data["@version"] = 1
-
- if f.TimestampFormat == "" {
- f.TimestampFormat = logrus.DefaultTimestampFormat
- }
-
- entry.Data["@timestamp"] = entry.Time.Format(f.TimestampFormat)
-
- // set message field
- v, ok := entry.Data["message"]
- if ok {
- entry.Data["fields.message"] = v
- }
- entry.Data["message"] = entry.Message
-
- // set level field
- v, ok = entry.Data["level"]
- if ok {
- entry.Data["fields.level"] = v
- }
- entry.Data["level"] = entry.Level.String()
-
- // set type field
- if f.Type != "" {
- v, ok = entry.Data["type"]
- if ok {
- entry.Data["fields.type"] = v
- }
- entry.Data["type"] = f.Type
- }
-
- serialized, err := json.Marshal(entry.Data)
- if err != nil {
- return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err)
- }
- return append(serialized, '\n'), nil
-}
diff --git a/Godeps/_workspace/src/github.com/Sirupsen/logrus/formatters/logstash/logstash_test.go b/Godeps/_workspace/src/github.com/Sirupsen/logrus/formatters/logstash/logstash_test.go
deleted file mode 100644
index d8814a0eae..0000000000
--- a/Godeps/_workspace/src/github.com/Sirupsen/logrus/formatters/logstash/logstash_test.go
+++ /dev/null
@@ -1,52 +0,0 @@
-package logstash
-
-import (
- "bytes"
- "encoding/json"
- "github.com/Sirupsen/logrus"
- "github.com/stretchr/testify/assert"
- "testing"
-)
-
-func TestLogstashFormatter(t *testing.T) {
- assert := assert.New(t)
-
- lf := LogstashFormatter{Type: "abc"}
-
- fields := logrus.Fields{
- "message": "def",
- "level": "ijk",
- "type": "lmn",
- "one": 1,
- "pi": 3.14,
- "bool": true,
- }
-
- entry := logrus.WithFields(fields)
- entry.Message = "msg"
- entry.Level = logrus.InfoLevel
-
- b, _ := lf.Format(entry)
-
- var data map[string]interface{}
- dec := json.NewDecoder(bytes.NewReader(b))
- dec.UseNumber()
- dec.Decode(&data)
-
- // base fields
- assert.Equal(json.Number("1"), data["@version"])
- assert.NotEmpty(data["@timestamp"])
- assert.Equal("abc", data["type"])
- assert.Equal("msg", data["message"])
- assert.Equal("info", data["level"])
-
- // substituted fields
- assert.Equal("def", data["fields.message"])
- assert.Equal("ijk", data["fields.level"])
- assert.Equal("lmn", data["fields.type"])
-
- // formats
- assert.Equal(json.Number("1"), data["one"])
- assert.Equal(json.Number("3.14"), data["pi"])
- assert.Equal(true, data["bool"])
-}
diff --git a/Godeps/_workspace/src/github.com/Sirupsen/logrus/hook_test.go b/Godeps/_workspace/src/github.com/Sirupsen/logrus/hook_test.go
deleted file mode 100644
index 13f34cb6f8..0000000000
--- a/Godeps/_workspace/src/github.com/Sirupsen/logrus/hook_test.go
+++ /dev/null
@@ -1,122 +0,0 @@
-package logrus
-
-import (
- "testing"
-
- "github.com/stretchr/testify/assert"
-)
-
-type TestHook struct {
- Fired bool
-}
-
-func (hook *TestHook) Fire(entry *Entry) error {
- hook.Fired = true
- return nil
-}
-
-func (hook *TestHook) Levels() []Level {
- return []Level{
- DebugLevel,
- InfoLevel,
- WarnLevel,
- ErrorLevel,
- FatalLevel,
- PanicLevel,
- }
-}
-
-func TestHookFires(t *testing.T) {
- hook := new(TestHook)
-
- LogAndAssertJSON(t, func(log *Logger) {
- log.Hooks.Add(hook)
- assert.Equal(t, hook.Fired, false)
-
- log.Print("test")
- }, func(fields Fields) {
- assert.Equal(t, hook.Fired, true)
- })
-}
-
-type ModifyHook struct {
-}
-
-func (hook *ModifyHook) Fire(entry *Entry) error {
- entry.Data["wow"] = "whale"
- return nil
-}
-
-func (hook *ModifyHook) Levels() []Level {
- return []Level{
- DebugLevel,
- InfoLevel,
- WarnLevel,
- ErrorLevel,
- FatalLevel,
- PanicLevel,
- }
-}
-
-func TestHookCanModifyEntry(t *testing.T) {
- hook := new(ModifyHook)
-
- LogAndAssertJSON(t, func(log *Logger) {
- log.Hooks.Add(hook)
- log.WithField("wow", "elephant").Print("test")
- }, func(fields Fields) {
- assert.Equal(t, fields["wow"], "whale")
- })
-}
-
-func TestCanFireMultipleHooks(t *testing.T) {
- hook1 := new(ModifyHook)
- hook2 := new(TestHook)
-
- LogAndAssertJSON(t, func(log *Logger) {
- log.Hooks.Add(hook1)
- log.Hooks.Add(hook2)
-
- log.WithField("wow", "elephant").Print("test")
- }, func(fields Fields) {
- assert.Equal(t, fields["wow"], "whale")
- assert.Equal(t, hook2.Fired, true)
- })
-}
-
-type ErrorHook struct {
- Fired bool
-}
-
-func (hook *ErrorHook) Fire(entry *Entry) error {
- hook.Fired = true
- return nil
-}
-
-func (hook *ErrorHook) Levels() []Level {
- return []Level{
- ErrorLevel,
- }
-}
-
-func TestErrorHookShouldntFireOnInfo(t *testing.T) {
- hook := new(ErrorHook)
-
- LogAndAssertJSON(t, func(log *Logger) {
- log.Hooks.Add(hook)
- log.Info("test")
- }, func(fields Fields) {
- assert.Equal(t, hook.Fired, false)
- })
-}
-
-func TestErrorHookShouldFireOnError(t *testing.T) {
- hook := new(ErrorHook)
-
- LogAndAssertJSON(t, func(log *Logger) {
- log.Hooks.Add(hook)
- log.Error("test")
- }, func(fields Fields) {
- assert.Equal(t, hook.Fired, true)
- })
-}
diff --git a/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks.go b/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks.go
deleted file mode 100644
index 3f151cdc39..0000000000
--- a/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks.go
+++ /dev/null
@@ -1,34 +0,0 @@
-package logrus
-
-// A hook to be fired when logging on the logging levels returned from
-// `Levels()` on your implementation of the interface. Note that this is not
-// fired in a goroutine or a channel with workers, you should handle such
-// functionality yourself if your call is non-blocking and you don't wish for
-// the logging calls for levels returned from `Levels()` to block.
-type Hook interface {
- Levels() []Level
- Fire(*Entry) error
-}
-
-// Internal type for storing the hooks on a logger instance.
-type LevelHooks map[Level][]Hook
-
-// Add a hook to an instance of logger. This is called with
-// `log.Hooks.Add(new(MyHook))` where `MyHook` implements the `Hook` interface.
-func (hooks LevelHooks) Add(hook Hook) {
- for _, level := range hook.Levels() {
- hooks[level] = append(hooks[level], hook)
- }
-}
-
-// Fire all the hooks for the passed level. Used by `entry.log` to fire
-// appropriate hooks for a log entry.
-func (hooks LevelHooks) Fire(level Level, entry *Entry) error {
- for _, hook := range hooks[level] {
- if err := hook.Fire(entry); err != nil {
- return err
- }
- }
-
- return nil
-}
diff --git a/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/airbrake/airbrake.go b/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/airbrake/airbrake.go
deleted file mode 100644
index b0502c335a..0000000000
--- a/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/airbrake/airbrake.go
+++ /dev/null
@@ -1,54 +0,0 @@
-package airbrake
-
-import (
- "errors"
- "fmt"
-
- "github.com/Sirupsen/logrus"
- "github.com/tobi/airbrake-go"
-)
-
-// AirbrakeHook to send exceptions to an exception-tracking service compatible
-// with the Airbrake API.
-type airbrakeHook struct {
- APIKey string
- Endpoint string
- Environment string
-}
-
-func NewHook(endpoint, apiKey, env string) *airbrakeHook {
- return &airbrakeHook{
- APIKey: apiKey,
- Endpoint: endpoint,
- Environment: env,
- }
-}
-
-func (hook *airbrakeHook) Fire(entry *logrus.Entry) error {
- airbrake.ApiKey = hook.APIKey
- airbrake.Endpoint = hook.Endpoint
- airbrake.Environment = hook.Environment
-
- var notifyErr error
- err, ok := entry.Data["error"].(error)
- if ok {
- notifyErr = err
- } else {
- notifyErr = errors.New(entry.Message)
- }
-
- airErr := airbrake.Notify(notifyErr)
- if airErr != nil {
- return fmt.Errorf("Failed to send error to Airbrake: %s", airErr)
- }
-
- return nil
-}
-
-func (hook *airbrakeHook) Levels() []logrus.Level {
- return []logrus.Level{
- logrus.ErrorLevel,
- logrus.FatalLevel,
- logrus.PanicLevel,
- }
-}
diff --git a/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/airbrake/airbrake_test.go b/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/airbrake/airbrake_test.go
deleted file mode 100644
index 058a91e343..0000000000
--- a/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/airbrake/airbrake_test.go
+++ /dev/null
@@ -1,133 +0,0 @@
-package airbrake
-
-import (
- "encoding/xml"
- "net/http"
- "net/http/httptest"
- "testing"
- "time"
-
- "github.com/Sirupsen/logrus"
-)
-
-type notice struct {
- Error NoticeError `xml:"error"`
-}
-type NoticeError struct {
- Class string `xml:"class"`
- Message string `xml:"message"`
-}
-
-type customErr struct {
- msg string
-}
-
-func (e *customErr) Error() string {
- return e.msg
-}
-
-const (
- testAPIKey = "abcxyz"
- testEnv = "development"
- expectedClass = "*airbrake.customErr"
- expectedMsg = "foo"
- unintendedMsg = "Airbrake will not see this string"
-)
-
-var (
- noticeError = make(chan NoticeError, 1)
-)
-
-// TestLogEntryMessageReceived checks if invoking Logrus' log.Error
-// method causes an XML payload containing the log entry message is received
-// by a HTTP server emulating an Airbrake-compatible endpoint.
-func TestLogEntryMessageReceived(t *testing.T) {
- log := logrus.New()
- ts := startAirbrakeServer(t)
- defer ts.Close()
-
- hook := NewHook(ts.URL, testAPIKey, "production")
- log.Hooks.Add(hook)
-
- log.Error(expectedMsg)
-
- select {
- case received := <-noticeError:
- if received.Message != expectedMsg {
- t.Errorf("Unexpected message received: %s", received.Message)
- }
- case <-time.After(time.Second):
- t.Error("Timed out; no notice received by Airbrake API")
- }
-}
-
-// TestLogEntryMessageReceived confirms that, when passing an error type using
-// logrus.Fields, a HTTP server emulating an Airbrake endpoint receives the
-// error message returned by the Error() method on the error interface
-// rather than the logrus.Entry.Message string.
-func TestLogEntryWithErrorReceived(t *testing.T) {
- log := logrus.New()
- ts := startAirbrakeServer(t)
- defer ts.Close()
-
- hook := NewHook(ts.URL, testAPIKey, "production")
- log.Hooks.Add(hook)
-
- log.WithFields(logrus.Fields{
- "error": &customErr{expectedMsg},
- }).Error(unintendedMsg)
-
- select {
- case received := <-noticeError:
- if received.Message != expectedMsg {
- t.Errorf("Unexpected message received: %s", received.Message)
- }
- if received.Class != expectedClass {
- t.Errorf("Unexpected error class: %s", received.Class)
- }
- case <-time.After(time.Second):
- t.Error("Timed out; no notice received by Airbrake API")
- }
-}
-
-// TestLogEntryWithNonErrorTypeNotReceived confirms that, when passing a
-// non-error type using logrus.Fields, a HTTP server emulating an Airbrake
-// endpoint receives the logrus.Entry.Message string.
-//
-// Only error types are supported when setting the 'error' field using
-// logrus.WithFields().
-func TestLogEntryWithNonErrorTypeNotReceived(t *testing.T) {
- log := logrus.New()
- ts := startAirbrakeServer(t)
- defer ts.Close()
-
- hook := NewHook(ts.URL, testAPIKey, "production")
- log.Hooks.Add(hook)
-
- log.WithFields(logrus.Fields{
- "error": expectedMsg,
- }).Error(unintendedMsg)
-
- select {
- case received := <-noticeError:
- if received.Message != unintendedMsg {
- t.Errorf("Unexpected message received: %s", received.Message)
- }
- case <-time.After(time.Second):
- t.Error("Timed out; no notice received by Airbrake API")
- }
-}
-
-func startAirbrakeServer(t *testing.T) *httptest.Server {
- ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- var notice notice
- if err := xml.NewDecoder(r.Body).Decode(¬ice); err != nil {
- t.Error(err)
- }
- r.Body.Close()
-
- noticeError <- notice.Error
- }))
-
- return ts
-}
diff --git a/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/bugsnag/bugsnag.go b/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/bugsnag/bugsnag.go
deleted file mode 100644
index d20a0f54ab..0000000000
--- a/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/bugsnag/bugsnag.go
+++ /dev/null
@@ -1,68 +0,0 @@
-package logrus_bugsnag
-
-import (
- "errors"
-
- "github.com/Sirupsen/logrus"
- "github.com/bugsnag/bugsnag-go"
-)
-
-type bugsnagHook struct{}
-
-// ErrBugsnagUnconfigured is returned if NewBugsnagHook is called before
-// bugsnag.Configure. Bugsnag must be configured before the hook.
-var ErrBugsnagUnconfigured = errors.New("bugsnag must be configured before installing this logrus hook")
-
-// ErrBugsnagSendFailed indicates that the hook failed to submit an error to
-// bugsnag. The error was successfully generated, but `bugsnag.Notify()`
-// failed.
-type ErrBugsnagSendFailed struct {
- err error
-}
-
-func (e ErrBugsnagSendFailed) Error() string {
- return "failed to send error to Bugsnag: " + e.err.Error()
-}
-
-// NewBugsnagHook initializes a logrus hook which sends exceptions to an
-// exception-tracking service compatible with the Bugsnag API. Before using
-// this hook, you must call bugsnag.Configure(). The returned object should be
-// registered with a log via `AddHook()`
-//
-// Entries that trigger an Error, Fatal or Panic should now include an "error"
-// field to send to Bugsnag.
-func NewBugsnagHook() (*bugsnagHook, error) {
- if bugsnag.Config.APIKey == "" {
- return nil, ErrBugsnagUnconfigured
- }
- return &bugsnagHook{}, nil
-}
-
-// Fire forwards an error to Bugsnag. Given a logrus.Entry, it extracts the
-// "error" field (or the Message if the error isn't present) and sends it off.
-func (hook *bugsnagHook) Fire(entry *logrus.Entry) error {
- var notifyErr error
- err, ok := entry.Data["error"].(error)
- if ok {
- notifyErr = err
- } else {
- notifyErr = errors.New(entry.Message)
- }
-
- bugsnagErr := bugsnag.Notify(notifyErr)
- if bugsnagErr != nil {
- return ErrBugsnagSendFailed{bugsnagErr}
- }
-
- return nil
-}
-
-// Levels enumerates the log levels on which the error should be forwarded to
-// bugsnag: everything at or above the "Error" level.
-func (hook *bugsnagHook) Levels() []logrus.Level {
- return []logrus.Level{
- logrus.ErrorLevel,
- logrus.FatalLevel,
- logrus.PanicLevel,
- }
-}
diff --git a/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/bugsnag/bugsnag_test.go b/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/bugsnag/bugsnag_test.go
deleted file mode 100644
index e9ea298d89..0000000000
--- a/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/bugsnag/bugsnag_test.go
+++ /dev/null
@@ -1,64 +0,0 @@
-package logrus_bugsnag
-
-import (
- "encoding/json"
- "errors"
- "io/ioutil"
- "net/http"
- "net/http/httptest"
- "testing"
- "time"
-
- "github.com/Sirupsen/logrus"
- "github.com/bugsnag/bugsnag-go"
-)
-
-type notice struct {
- Events []struct {
- Exceptions []struct {
- Message string `json:"message"`
- } `json:"exceptions"`
- } `json:"events"`
-}
-
-func TestNoticeReceived(t *testing.T) {
- msg := make(chan string, 1)
- expectedMsg := "foo"
-
- ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- var notice notice
- data, _ := ioutil.ReadAll(r.Body)
- if err := json.Unmarshal(data, ¬ice); err != nil {
- t.Error(err)
- }
- _ = r.Body.Close()
-
- msg <- notice.Events[0].Exceptions[0].Message
- }))
- defer ts.Close()
-
- hook := &bugsnagHook{}
-
- bugsnag.Configure(bugsnag.Configuration{
- Endpoint: ts.URL,
- ReleaseStage: "production",
- APIKey: "12345678901234567890123456789012",
- Synchronous: true,
- })
-
- log := logrus.New()
- log.Hooks.Add(hook)
-
- log.WithFields(logrus.Fields{
- "error": errors.New(expectedMsg),
- }).Error("Bugsnag will not see this string")
-
- select {
- case received := <-msg:
- if received != expectedMsg {
- t.Errorf("Unexpected message received: %s", received)
- }
- case <-time.After(time.Second):
- t.Error("Timed out; no notice received by Bugsnag API")
- }
-}
diff --git a/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/papertrail/README.md b/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/papertrail/README.md
deleted file mode 100644
index ae61e9229a..0000000000
--- a/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/papertrail/README.md
+++ /dev/null
@@ -1,28 +0,0 @@
-# Papertrail Hook for Logrus
-
-[Papertrail](https://papertrailapp.com) provides hosted log management. Once stored in Papertrail, you can [group](http://help.papertrailapp.com/kb/how-it-works/groups/) your logs on various dimensions, [search](http://help.papertrailapp.com/kb/how-it-works/search-syntax) them, and trigger [alerts](http://help.papertrailapp.com/kb/how-it-works/alerts).
-
-In most deployments, you'll want to send logs to Papertrail via their [remote_syslog](http://help.papertrailapp.com/kb/configuration/configuring-centralized-logging-from-text-log-files-in-unix/) daemon, which requires no application-specific configuration. This hook is intended for relatively low-volume logging, likely in managed cloud hosting deployments where installing `remote_syslog` is not possible.
-
-## Usage
-
-You can find your Papertrail UDP port on your [Papertrail account page](https://papertrailapp.com/account/destinations). Substitute it below for `YOUR_PAPERTRAIL_UDP_PORT`.
-
-For `YOUR_APP_NAME`, substitute a short string that will readily identify your application or service in the logs.
-
-```go
-import (
- "log/syslog"
- "github.com/Sirupsen/logrus"
- "github.com/Sirupsen/logrus/hooks/papertrail"
-)
-
-func main() {
- log := logrus.New()
- hook, err := logrus_papertrail.NewPapertrailHook("logs.papertrailapp.com", YOUR_PAPERTRAIL_UDP_PORT, YOUR_APP_NAME)
-
- if err == nil {
- log.Hooks.Add(hook)
- }
-}
-```
diff --git a/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/papertrail/papertrail.go b/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/papertrail/papertrail.go
deleted file mode 100644
index c0f10c1bda..0000000000
--- a/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/papertrail/papertrail.go
+++ /dev/null
@@ -1,55 +0,0 @@
-package logrus_papertrail
-
-import (
- "fmt"
- "net"
- "os"
- "time"
-
- "github.com/Sirupsen/logrus"
-)
-
-const (
- format = "Jan 2 15:04:05"
-)
-
-// PapertrailHook to send logs to a logging service compatible with the Papertrail API.
-type PapertrailHook struct {
- Host string
- Port int
- AppName string
- UDPConn net.Conn
-}
-
-// NewPapertrailHook creates a hook to be added to an instance of logger.
-func NewPapertrailHook(host string, port int, appName string) (*PapertrailHook, error) {
- conn, err := net.Dial("udp", fmt.Sprintf("%s:%d", host, port))
- return &PapertrailHook{host, port, appName, conn}, err
-}
-
-// Fire is called when a log event is fired.
-func (hook *PapertrailHook) Fire(entry *logrus.Entry) error {
- date := time.Now().Format(format)
- msg, _ := entry.String()
- payload := fmt.Sprintf("<22> %s %s: %s", date, hook.AppName, msg)
-
- bytesWritten, err := hook.UDPConn.Write([]byte(payload))
- if err != nil {
- fmt.Fprintf(os.Stderr, "Unable to send log line to Papertrail via UDP. Wrote %d bytes before error: %v", bytesWritten, err)
- return err
- }
-
- return nil
-}
-
-// Levels returns the available logging levels.
-func (hook *PapertrailHook) Levels() []logrus.Level {
- return []logrus.Level{
- logrus.PanicLevel,
- logrus.FatalLevel,
- logrus.ErrorLevel,
- logrus.WarnLevel,
- logrus.InfoLevel,
- logrus.DebugLevel,
- }
-}
diff --git a/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/papertrail/papertrail_test.go b/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/papertrail/papertrail_test.go
deleted file mode 100644
index 96318d0030..0000000000
--- a/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/papertrail/papertrail_test.go
+++ /dev/null
@@ -1,26 +0,0 @@
-package logrus_papertrail
-
-import (
- "fmt"
- "testing"
-
- "github.com/Sirupsen/logrus"
- "github.com/stvp/go-udp-testing"
-)
-
-func TestWritingToUDP(t *testing.T) {
- port := 16661
- udp.SetAddr(fmt.Sprintf(":%d", port))
-
- hook, err := NewPapertrailHook("localhost", port, "test")
- if err != nil {
- t.Errorf("Unable to connect to local UDP server.")
- }
-
- log := logrus.New()
- log.Hooks.Add(hook)
-
- udp.ShouldReceive(t, "foo", func() {
- log.Info("foo")
- })
-}
diff --git a/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/sentry/README.md b/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/sentry/README.md
deleted file mode 100644
index 8b1f9a16f3..0000000000
--- a/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/sentry/README.md
+++ /dev/null
@@ -1,78 +0,0 @@
-# Sentry Hook for Logrus
-
-[Sentry](https://getsentry.com) provides both self-hosted and hosted
-solutions for exception tracking.
-Both client and server are
-[open source](https://github.com/getsentry/sentry).
-
-## Usage
-
-Every sentry application defined on the server gets a different
-[DSN](https://www.getsentry.com/docs/). In the example below replace
-`YOUR_DSN` with the one created for your application.
-
-```go
-import (
- "github.com/Sirupsen/logrus"
- "github.com/Sirupsen/logrus/hooks/sentry"
-)
-
-func main() {
- log := logrus.New()
- hook, err := logrus_sentry.NewSentryHook(YOUR_DSN, []logrus.Level{
- logrus.PanicLevel,
- logrus.FatalLevel,
- logrus.ErrorLevel,
- })
-
- if err == nil {
- log.Hooks.Add(hook)
- }
-}
-```
-
-If you wish to initialize a SentryHook with tags, you can use the `NewWithTagsSentryHook` constructor to provide default tags:
-
-```go
-tags := map[string]string{
- "site": "example.com",
-}
-levels := []logrus.Level{
- logrus.PanicLevel,
- logrus.FatalLevel,
- logrus.ErrorLevel,
-}
-hook, err := logrus_sentry.NewWithTagsSentryHook(YOUR_DSN, tags, levels)
-
-```
-
-
-## Special fields
-
-Some logrus fields have a special meaning in this hook,
-these are `server_name`, `logger` and `http_request`.
-When logs are sent to sentry these fields are treated differently.
-- `server_name` (also known as hostname) is the name of the server which
-is logging the event (hostname.example.com)
-- `logger` is the part of the application which is logging the event.
-In go this usually means setting it to the name of the package.
-- `http_request` is the in-coming request(*http.Request). The detailed request data are sent to Sentry.
-
-## Timeout
-
-`Timeout` is the time the sentry hook will wait for a response
-from the sentry server.
-
-If this time elapses with no response from
-the server an error will be returned.
-
-If `Timeout` is set to 0 the SentryHook will not wait for a reply
-and will assume a correct delivery.
-
-The SentryHook has a default timeout of `100 milliseconds` when created
-with a call to `NewSentryHook`. This can be changed by assigning a value to the `Timeout` field:
-
-```go
-hook, _ := logrus_sentry.NewSentryHook(...)
-hook.Timeout = 20*time.Second
-```
diff --git a/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/sentry/sentry.go b/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/sentry/sentry.go
deleted file mode 100644
index 4d184b2fc9..0000000000
--- a/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/sentry/sentry.go
+++ /dev/null
@@ -1,131 +0,0 @@
-package logrus_sentry
-
-import (
- "fmt"
- "net/http"
- "time"
-
- "github.com/Sirupsen/logrus"
- "github.com/getsentry/raven-go"
-)
-
-var (
- severityMap = map[logrus.Level]raven.Severity{
- logrus.DebugLevel: raven.DEBUG,
- logrus.InfoLevel: raven.INFO,
- logrus.WarnLevel: raven.WARNING,
- logrus.ErrorLevel: raven.ERROR,
- logrus.FatalLevel: raven.FATAL,
- logrus.PanicLevel: raven.FATAL,
- }
-)
-
-func getAndDel(d logrus.Fields, key string) (string, bool) {
- var (
- ok bool
- v interface{}
- val string
- )
- if v, ok = d[key]; !ok {
- return "", false
- }
-
- if val, ok = v.(string); !ok {
- return "", false
- }
- delete(d, key)
- return val, true
-}
-
-func getAndDelRequest(d logrus.Fields, key string) (*http.Request, bool) {
- var (
- ok bool
- v interface{}
- req *http.Request
- )
- if v, ok = d[key]; !ok {
- return nil, false
- }
- if req, ok = v.(*http.Request); !ok || req == nil {
- return nil, false
- }
- delete(d, key)
- return req, true
-}
-
-// SentryHook delivers logs to a sentry server.
-type SentryHook struct {
- // Timeout sets the time to wait for a delivery error from the sentry server.
- // If this is set to zero the server will not wait for any response and will
- // consider the message correctly sent
- Timeout time.Duration
-
- client *raven.Client
- levels []logrus.Level
-}
-
-// NewSentryHook creates a hook to be added to an instance of logger
-// and initializes the raven client.
-// This method sets the timeout to 100 milliseconds.
-func NewSentryHook(DSN string, levels []logrus.Level) (*SentryHook, error) {
- client, err := raven.New(DSN)
- if err != nil {
- return nil, err
- }
- return &SentryHook{100 * time.Millisecond, client, levels}, nil
-}
-
-// NewWithTagsSentryHook creates a hook with tags to be added to an instance
-// of logger and initializes the raven client. This method sets the timeout to
-// 100 milliseconds.
-func NewWithTagsSentryHook(DSN string, tags map[string]string, levels []logrus.Level) (*SentryHook, error) {
- client, err := raven.NewWithTags(DSN, tags)
- if err != nil {
- return nil, err
- }
- return &SentryHook{100 * time.Millisecond, client, levels}, nil
-}
-
-// Called when an event should be sent to sentry
-// Special fields that sentry uses to give more information to the server
-// are extracted from entry.Data (if they are found)
-// These fields are: logger, server_name and http_request
-func (hook *SentryHook) Fire(entry *logrus.Entry) error {
- packet := &raven.Packet{
- Message: entry.Message,
- Timestamp: raven.Timestamp(entry.Time),
- Level: severityMap[entry.Level],
- Platform: "go",
- }
-
- d := entry.Data
-
- if logger, ok := getAndDel(d, "logger"); ok {
- packet.Logger = logger
- }
- if serverName, ok := getAndDel(d, "server_name"); ok {
- packet.ServerName = serverName
- }
- if req, ok := getAndDelRequest(d, "http_request"); ok {
- packet.Interfaces = append(packet.Interfaces, raven.NewHttp(req))
- }
- packet.Extra = map[string]interface{}(d)
-
- _, errCh := hook.client.Capture(packet, nil)
- timeout := hook.Timeout
- if timeout != 0 {
- timeoutCh := time.After(timeout)
- select {
- case err := <-errCh:
- return err
- case <-timeoutCh:
- return fmt.Errorf("no response from sentry server in %s", timeout)
- }
- }
- return nil
-}
-
-// Levels returns the available logging levels.
-func (hook *SentryHook) Levels() []logrus.Level {
- return hook.levels
-}
diff --git a/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/sentry/sentry_test.go b/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/sentry/sentry_test.go
deleted file mode 100644
index 5f59f699cb..0000000000
--- a/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/sentry/sentry_test.go
+++ /dev/null
@@ -1,132 +0,0 @@
-package logrus_sentry
-
-import (
- "encoding/json"
- "fmt"
- "io/ioutil"
- "net/http"
- "net/http/httptest"
- "reflect"
- "strings"
- "testing"
-
- "github.com/Sirupsen/logrus"
- "github.com/getsentry/raven-go"
-)
-
-const (
- message = "error message"
- server_name = "testserver.internal"
- logger_name = "test.logger"
-)
-
-func getTestLogger() *logrus.Logger {
- l := logrus.New()
- l.Out = ioutil.Discard
- return l
-}
-
-func WithTestDSN(t *testing.T, tf func(string, <-chan *raven.Packet)) {
- pch := make(chan *raven.Packet, 1)
- s := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
- defer req.Body.Close()
- d := json.NewDecoder(req.Body)
- p := &raven.Packet{}
- err := d.Decode(p)
- if err != nil {
- t.Fatal(err.Error())
- }
-
- pch <- p
- }))
- defer s.Close()
-
- fragments := strings.SplitN(s.URL, "://", 2)
- dsn := fmt.Sprintf(
- "%s://public:secret@%s/sentry/project-id",
- fragments[0],
- fragments[1],
- )
- tf(dsn, pch)
-}
-
-func TestSpecialFields(t *testing.T) {
- WithTestDSN(t, func(dsn string, pch <-chan *raven.Packet) {
- logger := getTestLogger()
-
- hook, err := NewSentryHook(dsn, []logrus.Level{
- logrus.ErrorLevel,
- })
-
- if err != nil {
- t.Fatal(err.Error())
- }
- logger.Hooks.Add(hook)
-
- req, _ := http.NewRequest("GET", "url", nil)
- logger.WithFields(logrus.Fields{
- "server_name": server_name,
- "logger": logger_name,
- "http_request": req,
- }).Error(message)
-
- packet := <-pch
- if packet.Logger != logger_name {
- t.Errorf("logger should have been %s, was %s", logger_name, packet.Logger)
- }
-
- if packet.ServerName != server_name {
- t.Errorf("server_name should have been %s, was %s", server_name, packet.ServerName)
- }
- })
-}
-
-func TestSentryHandler(t *testing.T) {
- WithTestDSN(t, func(dsn string, pch <-chan *raven.Packet) {
- logger := getTestLogger()
- hook, err := NewSentryHook(dsn, []logrus.Level{
- logrus.ErrorLevel,
- })
- if err != nil {
- t.Fatal(err.Error())
- }
- logger.Hooks.Add(hook)
-
- logger.Error(message)
- packet := <-pch
- if packet.Message != message {
- t.Errorf("message should have been %s, was %s", message, packet.Message)
- }
- })
-}
-
-func TestSentryTags(t *testing.T) {
- WithTestDSN(t, func(dsn string, pch <-chan *raven.Packet) {
- logger := getTestLogger()
- tags := map[string]string{
- "site": "test",
- }
- levels := []logrus.Level{
- logrus.ErrorLevel,
- }
-
- hook, err := NewWithTagsSentryHook(dsn, tags, levels)
- if err != nil {
- t.Fatal(err.Error())
- }
-
- logger.Hooks.Add(hook)
-
- logger.Error(message)
- packet := <-pch
- expected := raven.Tags{
- raven.Tag{
- Key: "site",
- Value: "test",
- },
- }
- if !reflect.DeepEqual(packet.Tags, expected) {
- t.Errorf("message should have been %s, was %s", message, packet.Message)
- }
- })
-}
diff --git a/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/syslog/README.md b/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/syslog/README.md
deleted file mode 100644
index 4dbb8e7290..0000000000
--- a/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/syslog/README.md
+++ /dev/null
@@ -1,20 +0,0 @@
-# Syslog Hooks for Logrus
-
-## Usage
-
-```go
-import (
- "log/syslog"
- "github.com/Sirupsen/logrus"
- logrus_syslog "github.com/Sirupsen/logrus/hooks/syslog"
-)
-
-func main() {
- log := logrus.New()
- hook, err := logrus_syslog.NewSyslogHook("udp", "localhost:514", syslog.LOG_INFO, "")
-
- if err == nil {
- log.Hooks.Add(hook)
- }
-}
-```
diff --git a/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/syslog/syslog.go b/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/syslog/syslog.go
deleted file mode 100644
index b6fa374628..0000000000
--- a/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/syslog/syslog.go
+++ /dev/null
@@ -1,59 +0,0 @@
-package logrus_syslog
-
-import (
- "fmt"
- "github.com/Sirupsen/logrus"
- "log/syslog"
- "os"
-)
-
-// SyslogHook to send logs via syslog.
-type SyslogHook struct {
- Writer *syslog.Writer
- SyslogNetwork string
- SyslogRaddr string
-}
-
-// Creates a hook to be added to an instance of logger. This is called with
-// `hook, err := NewSyslogHook("udp", "localhost:514", syslog.LOG_DEBUG, "")`
-// `if err == nil { log.Hooks.Add(hook) }`
-func NewSyslogHook(network, raddr string, priority syslog.Priority, tag string) (*SyslogHook, error) {
- w, err := syslog.Dial(network, raddr, priority, tag)
- return &SyslogHook{w, network, raddr}, err
-}
-
-func (hook *SyslogHook) Fire(entry *logrus.Entry) error {
- line, err := entry.String()
- if err != nil {
- fmt.Fprintf(os.Stderr, "Unable to read entry, %v", err)
- return err
- }
-
- switch entry.Level {
- case logrus.PanicLevel:
- return hook.Writer.Crit(line)
- case logrus.FatalLevel:
- return hook.Writer.Crit(line)
- case logrus.ErrorLevel:
- return hook.Writer.Err(line)
- case logrus.WarnLevel:
- return hook.Writer.Warning(line)
- case logrus.InfoLevel:
- return hook.Writer.Info(line)
- case logrus.DebugLevel:
- return hook.Writer.Debug(line)
- default:
- return nil
- }
-}
-
-func (hook *SyslogHook) Levels() []logrus.Level {
- return []logrus.Level{
- logrus.PanicLevel,
- logrus.FatalLevel,
- logrus.ErrorLevel,
- logrus.WarnLevel,
- logrus.InfoLevel,
- logrus.DebugLevel,
- }
-}
diff --git a/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/syslog/syslog_test.go b/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/syslog/syslog_test.go
deleted file mode 100644
index 42762dc10d..0000000000
--- a/Godeps/_workspace/src/github.com/Sirupsen/logrus/hooks/syslog/syslog_test.go
+++ /dev/null
@@ -1,26 +0,0 @@
-package logrus_syslog
-
-import (
- "github.com/Sirupsen/logrus"
- "log/syslog"
- "testing"
-)
-
-func TestLocalhostAddAndPrint(t *testing.T) {
- log := logrus.New()
- hook, err := NewSyslogHook("udp", "localhost:514", syslog.LOG_INFO, "")
-
- if err != nil {
- t.Errorf("Unable to connect to local syslog.")
- }
-
- log.Hooks.Add(hook)
-
- for _, level := range hook.Levels() {
- if len(log.Hooks[level]) != 1 {
- t.Errorf("SyslogHook was not added. The length of log.Hooks[%v]: %v", level, len(log.Hooks[level]))
- }
- }
-
- log.Info("Congratulations!")
-}
diff --git a/Godeps/_workspace/src/github.com/Sirupsen/logrus/json_formatter.go b/Godeps/_workspace/src/github.com/Sirupsen/logrus/json_formatter.go
deleted file mode 100644
index 2ad6dc5cf4..0000000000
--- a/Godeps/_workspace/src/github.com/Sirupsen/logrus/json_formatter.go
+++ /dev/null
@@ -1,41 +0,0 @@
-package logrus
-
-import (
- "encoding/json"
- "fmt"
-)
-
-type JSONFormatter struct {
- // TimestampFormat sets the format used for marshaling timestamps.
- TimestampFormat string
-}
-
-func (f *JSONFormatter) Format(entry *Entry) ([]byte, error) {
- data := make(Fields, len(entry.Data)+3)
- for k, v := range entry.Data {
- switch v := v.(type) {
- case error:
- // Otherwise errors are ignored by `encoding/json`
- // https://github.com/Sirupsen/logrus/issues/137
- data[k] = v.Error()
- default:
- data[k] = v
- }
- }
- prefixFieldClashes(data)
-
- timestampFormat := f.TimestampFormat
- if timestampFormat == "" {
- timestampFormat = DefaultTimestampFormat
- }
-
- data["time"] = entry.Time.Format(timestampFormat)
- data["msg"] = entry.Message
- data["level"] = entry.Level.String()
-
- serialized, err := json.Marshal(data)
- if err != nil {
- return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err)
- }
- return append(serialized, '\n'), nil
-}
diff --git a/Godeps/_workspace/src/github.com/Sirupsen/logrus/json_formatter_test.go b/Godeps/_workspace/src/github.com/Sirupsen/logrus/json_formatter_test.go
deleted file mode 100644
index 1d70873254..0000000000
--- a/Godeps/_workspace/src/github.com/Sirupsen/logrus/json_formatter_test.go
+++ /dev/null
@@ -1,120 +0,0 @@
-package logrus
-
-import (
- "encoding/json"
- "errors"
-
- "testing"
-)
-
-func TestErrorNotLost(t *testing.T) {
- formatter := &JSONFormatter{}
-
- b, err := formatter.Format(WithField("error", errors.New("wild walrus")))
- if err != nil {
- t.Fatal("Unable to format entry: ", err)
- }
-
- entry := make(map[string]interface{})
- err = json.Unmarshal(b, &entry)
- if err != nil {
- t.Fatal("Unable to unmarshal formatted entry: ", err)
- }
-
- if entry["error"] != "wild walrus" {
- t.Fatal("Error field not set")
- }
-}
-
-func TestErrorNotLostOnFieldNotNamedError(t *testing.T) {
- formatter := &JSONFormatter{}
-
- b, err := formatter.Format(WithField("omg", errors.New("wild walrus")))
- if err != nil {
- t.Fatal("Unable to format entry: ", err)
- }
-
- entry := make(map[string]interface{})
- err = json.Unmarshal(b, &entry)
- if err != nil {
- t.Fatal("Unable to unmarshal formatted entry: ", err)
- }
-
- if entry["omg"] != "wild walrus" {
- t.Fatal("Error field not set")
- }
-}
-
-func TestFieldClashWithTime(t *testing.T) {
- formatter := &JSONFormatter{}
-
- b, err := formatter.Format(WithField("time", "right now!"))
- if err != nil {
- t.Fatal("Unable to format entry: ", err)
- }
-
- entry := make(map[string]interface{})
- err = json.Unmarshal(b, &entry)
- if err != nil {
- t.Fatal("Unable to unmarshal formatted entry: ", err)
- }
-
- if entry["fields.time"] != "right now!" {
- t.Fatal("fields.time not set to original time field")
- }
-
- if entry["time"] != "0001-01-01T00:00:00Z" {
- t.Fatal("time field not set to current time, was: ", entry["time"])
- }
-}
-
-func TestFieldClashWithMsg(t *testing.T) {
- formatter := &JSONFormatter{}
-
- b, err := formatter.Format(WithField("msg", "something"))
- if err != nil {
- t.Fatal("Unable to format entry: ", err)
- }
-
- entry := make(map[string]interface{})
- err = json.Unmarshal(b, &entry)
- if err != nil {
- t.Fatal("Unable to unmarshal formatted entry: ", err)
- }
-
- if entry["fields.msg"] != "something" {
- t.Fatal("fields.msg not set to original msg field")
- }
-}
-
-func TestFieldClashWithLevel(t *testing.T) {
- formatter := &JSONFormatter{}
-
- b, err := formatter.Format(WithField("level", "something"))
- if err != nil {
- t.Fatal("Unable to format entry: ", err)
- }
-
- entry := make(map[string]interface{})
- err = json.Unmarshal(b, &entry)
- if err != nil {
- t.Fatal("Unable to unmarshal formatted entry: ", err)
- }
-
- if entry["fields.level"] != "something" {
- t.Fatal("fields.level not set to original level field")
- }
-}
-
-func TestJSONEntryEndsWithNewline(t *testing.T) {
- formatter := &JSONFormatter{}
-
- b, err := formatter.Format(WithField("level", "something"))
- if err != nil {
- t.Fatal("Unable to format entry: ", err)
- }
-
- if b[len(b)-1] != '\n' {
- t.Fatal("Expected JSON log entry to end with a newline")
- }
-}
diff --git a/Godeps/_workspace/src/github.com/Sirupsen/logrus/logger.go b/Godeps/_workspace/src/github.com/Sirupsen/logrus/logger.go
deleted file mode 100644
index e4974bfbe7..0000000000
--- a/Godeps/_workspace/src/github.com/Sirupsen/logrus/logger.go
+++ /dev/null
@@ -1,206 +0,0 @@
-package logrus
-
-import (
- "io"
- "os"
- "sync"
-)
-
-type Logger struct {
- // The logs are `io.Copy`'d to this in a mutex. It's common to set this to a
- // file, or leave it default which is `os.Stdout`. You can also set this to
- // something more adventorous, such as logging to Kafka.
- Out io.Writer
- // Hooks for the logger instance. These allow firing events based on logging
- // levels and log entries. For example, to send errors to an error tracking
- // service, log to StatsD or dump the core on fatal errors.
- Hooks LevelHooks
- // All log entries pass through the formatter before logged to Out. The
- // included formatters are `TextFormatter` and `JSONFormatter` for which
- // TextFormatter is the default. In development (when a TTY is attached) it
- // logs with colors, but to a file it wouldn't. You can easily implement your
- // own that implements the `Formatter` interface, see the `README` or included
- // formatters for examples.
- Formatter Formatter
- // The logging level the logger should log at. This is typically (and defaults
- // to) `logrus.Info`, which allows Info(), Warn(), Error() and Fatal() to be
- // logged. `logrus.Debug` is useful in
- Level Level
- // Used to sync writing to the log.
- mu sync.Mutex
-}
-
-// Creates a new logger. Configuration should be set by changing `Formatter`,
-// `Out` and `Hooks` directly on the default logger instance. You can also just
-// instantiate your own:
-//
-// var log = &Logger{
-// Out: os.Stderr,
-// Formatter: new(JSONFormatter),
-// Hooks: make(LevelHooks),
-// Level: logrus.DebugLevel,
-// }
-//
-// It's recommended to make this a global instance called `log`.
-func New() *Logger {
- return &Logger{
- Out: os.Stderr,
- Formatter: new(TextFormatter),
- Hooks: make(LevelHooks),
- Level: InfoLevel,
- }
-}
-
-// Adds a field to the log entry, note that you it doesn't log until you call
-// Debug, Print, Info, Warn, Fatal or Panic. It only creates a log entry.
-// Ff you want multiple fields, use `WithFields`.
-func (logger *Logger) WithField(key string, value interface{}) *Entry {
- return NewEntry(logger).WithField(key, value)
-}
-
-// Adds a struct of fields to the log entry. All it does is call `WithField` for
-// each `Field`.
-func (logger *Logger) WithFields(fields Fields) *Entry {
- return NewEntry(logger).WithFields(fields)
-}
-
-func (logger *Logger) Debugf(format string, args ...interface{}) {
- if logger.Level >= DebugLevel {
- NewEntry(logger).Debugf(format, args...)
- }
-}
-
-func (logger *Logger) Infof(format string, args ...interface{}) {
- if logger.Level >= InfoLevel {
- NewEntry(logger).Infof(format, args...)
- }
-}
-
-func (logger *Logger) Printf(format string, args ...interface{}) {
- NewEntry(logger).Printf(format, args...)
-}
-
-func (logger *Logger) Warnf(format string, args ...interface{}) {
- if logger.Level >= WarnLevel {
- NewEntry(logger).Warnf(format, args...)
- }
-}
-
-func (logger *Logger) Warningf(format string, args ...interface{}) {
- if logger.Level >= WarnLevel {
- NewEntry(logger).Warnf(format, args...)
- }
-}
-
-func (logger *Logger) Errorf(format string, args ...interface{}) {
- if logger.Level >= ErrorLevel {
- NewEntry(logger).Errorf(format, args...)
- }
-}
-
-func (logger *Logger) Fatalf(format string, args ...interface{}) {
- if logger.Level >= FatalLevel {
- NewEntry(logger).Fatalf(format, args...)
- }
- os.Exit(1)
-}
-
-func (logger *Logger) Panicf(format string, args ...interface{}) {
- if logger.Level >= PanicLevel {
- NewEntry(logger).Panicf(format, args...)
- }
-}
-
-func (logger *Logger) Debug(args ...interface{}) {
- if logger.Level >= DebugLevel {
- NewEntry(logger).Debug(args...)
- }
-}
-
-func (logger *Logger) Info(args ...interface{}) {
- if logger.Level >= InfoLevel {
- NewEntry(logger).Info(args...)
- }
-}
-
-func (logger *Logger) Print(args ...interface{}) {
- NewEntry(logger).Info(args...)
-}
-
-func (logger *Logger) Warn(args ...interface{}) {
- if logger.Level >= WarnLevel {
- NewEntry(logger).Warn(args...)
- }
-}
-
-func (logger *Logger) Warning(args ...interface{}) {
- if logger.Level >= WarnLevel {
- NewEntry(logger).Warn(args...)
- }
-}
-
-func (logger *Logger) Error(args ...interface{}) {
- if logger.Level >= ErrorLevel {
- NewEntry(logger).Error(args...)
- }
-}
-
-func (logger *Logger) Fatal(args ...interface{}) {
- if logger.Level >= FatalLevel {
- NewEntry(logger).Fatal(args...)
- }
- os.Exit(1)
-}
-
-func (logger *Logger) Panic(args ...interface{}) {
- if logger.Level >= PanicLevel {
- NewEntry(logger).Panic(args...)
- }
-}
-
-func (logger *Logger) Debugln(args ...interface{}) {
- if logger.Level >= DebugLevel {
- NewEntry(logger).Debugln(args...)
- }
-}
-
-func (logger *Logger) Infoln(args ...interface{}) {
- if logger.Level >= InfoLevel {
- NewEntry(logger).Infoln(args...)
- }
-}
-
-func (logger *Logger) Println(args ...interface{}) {
- NewEntry(logger).Println(args...)
-}
-
-func (logger *Logger) Warnln(args ...interface{}) {
- if logger.Level >= WarnLevel {
- NewEntry(logger).Warnln(args...)
- }
-}
-
-func (logger *Logger) Warningln(args ...interface{}) {
- if logger.Level >= WarnLevel {
- NewEntry(logger).Warnln(args...)
- }
-}
-
-func (logger *Logger) Errorln(args ...interface{}) {
- if logger.Level >= ErrorLevel {
- NewEntry(logger).Errorln(args...)
- }
-}
-
-func (logger *Logger) Fatalln(args ...interface{}) {
- if logger.Level >= FatalLevel {
- NewEntry(logger).Fatalln(args...)
- }
- os.Exit(1)
-}
-
-func (logger *Logger) Panicln(args ...interface{}) {
- if logger.Level >= PanicLevel {
- NewEntry(logger).Panicln(args...)
- }
-}
diff --git a/Godeps/_workspace/src/github.com/Sirupsen/logrus/logrus.go b/Godeps/_workspace/src/github.com/Sirupsen/logrus/logrus.go
deleted file mode 100644
index 43ee12e90e..0000000000
--- a/Godeps/_workspace/src/github.com/Sirupsen/logrus/logrus.go
+++ /dev/null
@@ -1,94 +0,0 @@
-package logrus
-
-import (
- "fmt"
- "log"
-)
-
-// Fields type, used to pass to `WithFields`.
-type Fields map[string]interface{}
-
-// Level type
-type Level uint8
-
-// Convert the Level to a string. E.g. PanicLevel becomes "panic".
-func (level Level) String() string {
- switch level {
- case DebugLevel:
- return "debug"
- case InfoLevel:
- return "info"
- case WarnLevel:
- return "warning"
- case ErrorLevel:
- return "error"
- case FatalLevel:
- return "fatal"
- case PanicLevel:
- return "panic"
- }
-
- return "unknown"
-}
-
-// ParseLevel takes a string level and returns the Logrus log level constant.
-func ParseLevel(lvl string) (Level, error) {
- switch lvl {
- case "panic":
- return PanicLevel, nil
- case "fatal":
- return FatalLevel, nil
- case "error":
- return ErrorLevel, nil
- case "warn", "warning":
- return WarnLevel, nil
- case "info":
- return InfoLevel, nil
- case "debug":
- return DebugLevel, nil
- }
-
- var l Level
- return l, fmt.Errorf("not a valid logrus Level: %q", lvl)
-}
-
-// These are the different logging levels. You can set the logging level to log
-// on your instance of logger, obtained with `logrus.New()`.
-const (
- // PanicLevel level, highest level of severity. Logs and then calls panic with the
- // message passed to Debug, Info, ...
- PanicLevel Level = iota
- // FatalLevel level. Logs and then calls `os.Exit(1)`. It will exit even if the
- // logging level is set to Panic.
- FatalLevel
- // ErrorLevel level. Logs. Used for errors that should definitely be noted.
- // Commonly used for hooks to send errors to an error tracking service.
- ErrorLevel
- // WarnLevel level. Non-critical entries that deserve eyes.
- WarnLevel
- // InfoLevel level. General operational entries about what's going on inside the
- // application.
- InfoLevel
- // DebugLevel level. Usually only enabled when debugging. Very verbose logging.
- DebugLevel
-)
-
-// Won't compile if StdLogger can't be realized by a log.Logger
-var _ StdLogger = &log.Logger{}
-
-// StdLogger is what your logrus-enabled library should take, that way
-// it'll accept a stdlib logger and a logrus logger. There's no standard
-// interface, this is the closest we get, unfortunately.
-type StdLogger interface {
- Print(...interface{})
- Printf(string, ...interface{})
- Println(...interface{})
-
- Fatal(...interface{})
- Fatalf(string, ...interface{})
- Fatalln(...interface{})
-
- Panic(...interface{})
- Panicf(string, ...interface{})
- Panicln(...interface{})
-}
diff --git a/Godeps/_workspace/src/github.com/Sirupsen/logrus/logrus_test.go b/Godeps/_workspace/src/github.com/Sirupsen/logrus/logrus_test.go
deleted file mode 100644
index efaacea236..0000000000
--- a/Godeps/_workspace/src/github.com/Sirupsen/logrus/logrus_test.go
+++ /dev/null
@@ -1,301 +0,0 @@
-package logrus
-
-import (
- "bytes"
- "encoding/json"
- "strconv"
- "strings"
- "sync"
- "testing"
-
- "github.com/stretchr/testify/assert"
-)
-
-func LogAndAssertJSON(t *testing.T, log func(*Logger), assertions func(fields Fields)) {
- var buffer bytes.Buffer
- var fields Fields
-
- logger := New()
- logger.Out = &buffer
- logger.Formatter = new(JSONFormatter)
-
- log(logger)
-
- err := json.Unmarshal(buffer.Bytes(), &fields)
- assert.Nil(t, err)
-
- assertions(fields)
-}
-
-func LogAndAssertText(t *testing.T, log func(*Logger), assertions func(fields map[string]string)) {
- var buffer bytes.Buffer
-
- logger := New()
- logger.Out = &buffer
- logger.Formatter = &TextFormatter{
- DisableColors: true,
- }
-
- log(logger)
-
- fields := make(map[string]string)
- for _, kv := range strings.Split(buffer.String(), " ") {
- if !strings.Contains(kv, "=") {
- continue
- }
- kvArr := strings.Split(kv, "=")
- key := strings.TrimSpace(kvArr[0])
- val := kvArr[1]
- if kvArr[1][0] == '"' {
- var err error
- val, err = strconv.Unquote(val)
- assert.NoError(t, err)
- }
- fields[key] = val
- }
- assertions(fields)
-}
-
-func TestPrint(t *testing.T) {
- LogAndAssertJSON(t, func(log *Logger) {
- log.Print("test")
- }, func(fields Fields) {
- assert.Equal(t, fields["msg"], "test")
- assert.Equal(t, fields["level"], "info")
- })
-}
-
-func TestInfo(t *testing.T) {
- LogAndAssertJSON(t, func(log *Logger) {
- log.Info("test")
- }, func(fields Fields) {
- assert.Equal(t, fields["msg"], "test")
- assert.Equal(t, fields["level"], "info")
- })
-}
-
-func TestWarn(t *testing.T) {
- LogAndAssertJSON(t, func(log *Logger) {
- log.Warn("test")
- }, func(fields Fields) {
- assert.Equal(t, fields["msg"], "test")
- assert.Equal(t, fields["level"], "warning")
- })
-}
-
-func TestInfolnShouldAddSpacesBetweenStrings(t *testing.T) {
- LogAndAssertJSON(t, func(log *Logger) {
- log.Infoln("test", "test")
- }, func(fields Fields) {
- assert.Equal(t, fields["msg"], "test test")
- })
-}
-
-func TestInfolnShouldAddSpacesBetweenStringAndNonstring(t *testing.T) {
- LogAndAssertJSON(t, func(log *Logger) {
- log.Infoln("test", 10)
- }, func(fields Fields) {
- assert.Equal(t, fields["msg"], "test 10")
- })
-}
-
-func TestInfolnShouldAddSpacesBetweenTwoNonStrings(t *testing.T) {
- LogAndAssertJSON(t, func(log *Logger) {
- log.Infoln(10, 10)
- }, func(fields Fields) {
- assert.Equal(t, fields["msg"], "10 10")
- })
-}
-
-func TestInfoShouldAddSpacesBetweenTwoNonStrings(t *testing.T) {
- LogAndAssertJSON(t, func(log *Logger) {
- log.Infoln(10, 10)
- }, func(fields Fields) {
- assert.Equal(t, fields["msg"], "10 10")
- })
-}
-
-func TestInfoShouldNotAddSpacesBetweenStringAndNonstring(t *testing.T) {
- LogAndAssertJSON(t, func(log *Logger) {
- log.Info("test", 10)
- }, func(fields Fields) {
- assert.Equal(t, fields["msg"], "test10")
- })
-}
-
-func TestInfoShouldNotAddSpacesBetweenStrings(t *testing.T) {
- LogAndAssertJSON(t, func(log *Logger) {
- log.Info("test", "test")
- }, func(fields Fields) {
- assert.Equal(t, fields["msg"], "testtest")
- })
-}
-
-func TestWithFieldsShouldAllowAssignments(t *testing.T) {
- var buffer bytes.Buffer
- var fields Fields
-
- logger := New()
- logger.Out = &buffer
- logger.Formatter = new(JSONFormatter)
-
- localLog := logger.WithFields(Fields{
- "key1": "value1",
- })
-
- localLog.WithField("key2", "value2").Info("test")
- err := json.Unmarshal(buffer.Bytes(), &fields)
- assert.Nil(t, err)
-
- assert.Equal(t, "value2", fields["key2"])
- assert.Equal(t, "value1", fields["key1"])
-
- buffer = bytes.Buffer{}
- fields = Fields{}
- localLog.Info("test")
- err = json.Unmarshal(buffer.Bytes(), &fields)
- assert.Nil(t, err)
-
- _, ok := fields["key2"]
- assert.Equal(t, false, ok)
- assert.Equal(t, "value1", fields["key1"])
-}
-
-func TestUserSuppliedFieldDoesNotOverwriteDefaults(t *testing.T) {
- LogAndAssertJSON(t, func(log *Logger) {
- log.WithField("msg", "hello").Info("test")
- }, func(fields Fields) {
- assert.Equal(t, fields["msg"], "test")
- })
-}
-
-func TestUserSuppliedMsgFieldHasPrefix(t *testing.T) {
- LogAndAssertJSON(t, func(log *Logger) {
- log.WithField("msg", "hello").Info("test")
- }, func(fields Fields) {
- assert.Equal(t, fields["msg"], "test")
- assert.Equal(t, fields["fields.msg"], "hello")
- })
-}
-
-func TestUserSuppliedTimeFieldHasPrefix(t *testing.T) {
- LogAndAssertJSON(t, func(log *Logger) {
- log.WithField("time", "hello").Info("test")
- }, func(fields Fields) {
- assert.Equal(t, fields["fields.time"], "hello")
- })
-}
-
-func TestUserSuppliedLevelFieldHasPrefix(t *testing.T) {
- LogAndAssertJSON(t, func(log *Logger) {
- log.WithField("level", 1).Info("test")
- }, func(fields Fields) {
- assert.Equal(t, fields["level"], "info")
- assert.Equal(t, fields["fields.level"], 1.0) // JSON has floats only
- })
-}
-
-func TestDefaultFieldsAreNotPrefixed(t *testing.T) {
- LogAndAssertText(t, func(log *Logger) {
- ll := log.WithField("herp", "derp")
- ll.Info("hello")
- ll.Info("bye")
- }, func(fields map[string]string) {
- for _, fieldName := range []string{"fields.level", "fields.time", "fields.msg"} {
- if _, ok := fields[fieldName]; ok {
- t.Fatalf("should not have prefixed %q: %v", fieldName, fields)
- }
- }
- })
-}
-
-func TestDoubleLoggingDoesntPrefixPreviousFields(t *testing.T) {
-
- var buffer bytes.Buffer
- var fields Fields
-
- logger := New()
- logger.Out = &buffer
- logger.Formatter = new(JSONFormatter)
-
- llog := logger.WithField("context", "eating raw fish")
-
- llog.Info("looks delicious")
-
- err := json.Unmarshal(buffer.Bytes(), &fields)
- assert.NoError(t, err, "should have decoded first message")
- assert.Equal(t, len(fields), 4, "should only have msg/time/level/context fields")
- assert.Equal(t, fields["msg"], "looks delicious")
- assert.Equal(t, fields["context"], "eating raw fish")
-
- buffer.Reset()
-
- llog.Warn("omg it is!")
-
- err = json.Unmarshal(buffer.Bytes(), &fields)
- assert.NoError(t, err, "should have decoded second message")
- assert.Equal(t, len(fields), 4, "should only have msg/time/level/context fields")
- assert.Equal(t, fields["msg"], "omg it is!")
- assert.Equal(t, fields["context"], "eating raw fish")
- assert.Nil(t, fields["fields.msg"], "should not have prefixed previous `msg` entry")
-
-}
-
-func TestConvertLevelToString(t *testing.T) {
- assert.Equal(t, "debug", DebugLevel.String())
- assert.Equal(t, "info", InfoLevel.String())
- assert.Equal(t, "warning", WarnLevel.String())
- assert.Equal(t, "error", ErrorLevel.String())
- assert.Equal(t, "fatal", FatalLevel.String())
- assert.Equal(t, "panic", PanicLevel.String())
-}
-
-func TestParseLevel(t *testing.T) {
- l, err := ParseLevel("panic")
- assert.Nil(t, err)
- assert.Equal(t, PanicLevel, l)
-
- l, err = ParseLevel("fatal")
- assert.Nil(t, err)
- assert.Equal(t, FatalLevel, l)
-
- l, err = ParseLevel("error")
- assert.Nil(t, err)
- assert.Equal(t, ErrorLevel, l)
-
- l, err = ParseLevel("warn")
- assert.Nil(t, err)
- assert.Equal(t, WarnLevel, l)
-
- l, err = ParseLevel("warning")
- assert.Nil(t, err)
- assert.Equal(t, WarnLevel, l)
-
- l, err = ParseLevel("info")
- assert.Nil(t, err)
- assert.Equal(t, InfoLevel, l)
-
- l, err = ParseLevel("debug")
- assert.Nil(t, err)
- assert.Equal(t, DebugLevel, l)
-
- l, err = ParseLevel("invalid")
- assert.Equal(t, "not a valid logrus Level: \"invalid\"", err.Error())
-}
-
-func TestGetSetLevelRace(t *testing.T) {
- wg := sync.WaitGroup{}
- for i := 0; i < 100; i++ {
- wg.Add(1)
- go func(i int) {
- defer wg.Done()
- if i%2 == 0 {
- SetLevel(InfoLevel)
- } else {
- GetLevel()
- }
- }(i)
-
- }
- wg.Wait()
-}
diff --git a/Godeps/_workspace/src/github.com/Sirupsen/logrus/terminal_bsd.go b/Godeps/_workspace/src/github.com/Sirupsen/logrus/terminal_bsd.go
deleted file mode 100644
index 71f8d67a55..0000000000
--- a/Godeps/_workspace/src/github.com/Sirupsen/logrus/terminal_bsd.go
+++ /dev/null
@@ -1,9 +0,0 @@
-// +build darwin freebsd openbsd netbsd dragonfly
-
-package logrus
-
-import "syscall"
-
-const ioctlReadTermios = syscall.TIOCGETA
-
-type Termios syscall.Termios
diff --git a/Godeps/_workspace/src/github.com/Sirupsen/logrus/terminal_linux.go b/Godeps/_workspace/src/github.com/Sirupsen/logrus/terminal_linux.go
deleted file mode 100644
index a2c0b40db6..0000000000
--- a/Godeps/_workspace/src/github.com/Sirupsen/logrus/terminal_linux.go
+++ /dev/null
@@ -1,12 +0,0 @@
-// Based on ssh/terminal:
-// Copyright 2013 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package logrus
-
-import "syscall"
-
-const ioctlReadTermios = syscall.TCGETS
-
-type Termios syscall.Termios
diff --git a/Godeps/_workspace/src/github.com/Sirupsen/logrus/terminal_notwindows.go b/Godeps/_workspace/src/github.com/Sirupsen/logrus/terminal_notwindows.go
deleted file mode 100644
index 4bb5376028..0000000000
--- a/Godeps/_workspace/src/github.com/Sirupsen/logrus/terminal_notwindows.go
+++ /dev/null
@@ -1,21 +0,0 @@
-// Based on ssh/terminal:
-// Copyright 2011 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// +build linux darwin freebsd openbsd netbsd dragonfly
-
-package logrus
-
-import (
- "syscall"
- "unsafe"
-)
-
-// IsTerminal returns true if the given file descriptor is a terminal.
-func IsTerminal() bool {
- fd := syscall.Stdout
- var termios Termios
- _, _, err := syscall.Syscall6(syscall.SYS_IOCTL, uintptr(fd), ioctlReadTermios, uintptr(unsafe.Pointer(&termios)), 0, 0, 0)
- return err == 0
-}
diff --git a/Godeps/_workspace/src/github.com/Sirupsen/logrus/terminal_windows.go b/Godeps/_workspace/src/github.com/Sirupsen/logrus/terminal_windows.go
deleted file mode 100644
index 2e09f6f7e3..0000000000
--- a/Godeps/_workspace/src/github.com/Sirupsen/logrus/terminal_windows.go
+++ /dev/null
@@ -1,27 +0,0 @@
-// Based on ssh/terminal:
-// Copyright 2011 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// +build windows
-
-package logrus
-
-import (
- "syscall"
- "unsafe"
-)
-
-var kernel32 = syscall.NewLazyDLL("kernel32.dll")
-
-var (
- procGetConsoleMode = kernel32.NewProc("GetConsoleMode")
-)
-
-// IsTerminal returns true if the given file descriptor is a terminal.
-func IsTerminal() bool {
- fd := syscall.Stdout
- var st uint32
- r, _, e := syscall.Syscall(procGetConsoleMode.Addr(), 2, uintptr(fd), uintptr(unsafe.Pointer(&st)), 0)
- return r != 0 && e == 0
-}
diff --git a/Godeps/_workspace/src/github.com/Sirupsen/logrus/text_formatter.go b/Godeps/_workspace/src/github.com/Sirupsen/logrus/text_formatter.go
deleted file mode 100644
index 17cc298484..0000000000
--- a/Godeps/_workspace/src/github.com/Sirupsen/logrus/text_formatter.go
+++ /dev/null
@@ -1,159 +0,0 @@
-package logrus
-
-import (
- "bytes"
- "fmt"
- "runtime"
- "sort"
- "strings"
- "time"
-)
-
-const (
- nocolor = 0
- red = 31
- green = 32
- yellow = 33
- blue = 34
- gray = 37
-)
-
-var (
- baseTimestamp time.Time
- isTerminal bool
-)
-
-func init() {
- baseTimestamp = time.Now()
- isTerminal = IsTerminal()
-}
-
-func miniTS() int {
- return int(time.Since(baseTimestamp) / time.Second)
-}
-
-type TextFormatter struct {
- // Set to true to bypass checking for a TTY before outputting colors.
- ForceColors bool
-
- // Force disabling colors.
- DisableColors bool
-
- // Disable timestamp logging. useful when output is redirected to logging
- // system that already adds timestamps.
- DisableTimestamp bool
-
- // Enable logging the full timestamp when a TTY is attached instead of just
- // the time passed since beginning of execution.
- FullTimestamp bool
-
- // TimestampFormat to use for display when a full timestamp is printed
- TimestampFormat string
-
- // The fields are sorted by default for a consistent output. For applications
- // that log extremely frequently and don't use the JSON formatter this may not
- // be desired.
- DisableSorting bool
-}
-
-func (f *TextFormatter) Format(entry *Entry) ([]byte, error) {
- var keys []string = make([]string, 0, len(entry.Data))
- for k := range entry.Data {
- keys = append(keys, k)
- }
-
- if !f.DisableSorting {
- sort.Strings(keys)
- }
-
- b := &bytes.Buffer{}
-
- prefixFieldClashes(entry.Data)
-
- isColorTerminal := isTerminal && (runtime.GOOS != "windows")
- isColored := (f.ForceColors || isColorTerminal) && !f.DisableColors
-
- timestampFormat := f.TimestampFormat
- if timestampFormat == "" {
- timestampFormat = DefaultTimestampFormat
- }
- if isColored {
- f.printColored(b, entry, keys, timestampFormat)
- } else {
- if !f.DisableTimestamp {
- f.appendKeyValue(b, "time", entry.Time.Format(timestampFormat))
- }
- f.appendKeyValue(b, "level", entry.Level.String())
- f.appendKeyValue(b, "msg", entry.Message)
- for _, key := range keys {
- f.appendKeyValue(b, key, entry.Data[key])
- }
- }
-
- b.WriteByte('\n')
- return b.Bytes(), nil
-}
-
-func (f *TextFormatter) printColored(b *bytes.Buffer, entry *Entry, keys []string, timestampFormat string) {
- var levelColor int
- switch entry.Level {
- case DebugLevel:
- levelColor = gray
- case WarnLevel:
- levelColor = yellow
- case ErrorLevel, FatalLevel, PanicLevel:
- levelColor = red
- default:
- levelColor = blue
- }
-
- levelText := strings.ToUpper(entry.Level.String())[0:4]
-
- if !f.FullTimestamp {
- fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%04d] %-44s ", levelColor, levelText, miniTS(), entry.Message)
- } else {
- fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%s] %-44s ", levelColor, levelText, entry.Time.Format(timestampFormat), entry.Message)
- }
- for _, k := range keys {
- v := entry.Data[k]
- fmt.Fprintf(b, " \x1b[%dm%s\x1b[0m=%+v", levelColor, k, v)
- }
-}
-
-func needsQuoting(text string) bool {
- for _, ch := range text {
- if !((ch >= 'a' && ch <= 'z') ||
- (ch >= 'A' && ch <= 'Z') ||
- (ch >= '0' && ch <= '9') ||
- ch == '-' || ch == '.') {
- return false
- }
- }
- return true
-}
-
-func (f *TextFormatter) appendKeyValue(b *bytes.Buffer, key string, value interface{}) {
-
- b.WriteString(key)
- b.WriteByte('=')
-
- switch value := value.(type) {
- case string:
- if needsQuoting(value) {
- b.WriteString(value)
- } else {
- fmt.Fprintf(b, "%q", value)
- }
- case error:
- errmsg := value.Error()
- if needsQuoting(errmsg) {
- b.WriteString(errmsg)
- } else {
- fmt.Fprintf(b, "%q", value)
- }
- default:
- fmt.Fprint(b, value)
- }
-
- b.WriteByte(' ')
-}
diff --git a/Godeps/_workspace/src/github.com/Sirupsen/logrus/text_formatter_test.go b/Godeps/_workspace/src/github.com/Sirupsen/logrus/text_formatter_test.go
deleted file mode 100644
index e25a44f67b..0000000000
--- a/Godeps/_workspace/src/github.com/Sirupsen/logrus/text_formatter_test.go
+++ /dev/null
@@ -1,61 +0,0 @@
-package logrus
-
-import (
- "bytes"
- "errors"
- "testing"
- "time"
-)
-
-func TestQuoting(t *testing.T) {
- tf := &TextFormatter{DisableColors: true}
-
- checkQuoting := func(q bool, value interface{}) {
- b, _ := tf.Format(WithField("test", value))
- idx := bytes.Index(b, ([]byte)("test="))
- cont := bytes.Contains(b[idx+5:], []byte{'"'})
- if cont != q {
- if q {
- t.Errorf("quoting expected for: %#v", value)
- } else {
- t.Errorf("quoting not expected for: %#v", value)
- }
- }
- }
-
- checkQuoting(false, "abcd")
- checkQuoting(false, "v1.0")
- checkQuoting(false, "1234567890")
- checkQuoting(true, "/foobar")
- checkQuoting(true, "x y")
- checkQuoting(true, "x,y")
- checkQuoting(false, errors.New("invalid"))
- checkQuoting(true, errors.New("invalid argument"))
-}
-
-func TestTimestampFormat(t *testing.T) {
- checkTimeStr := func(format string) {
- customFormatter := &TextFormatter{DisableColors: true, TimestampFormat: format}
- customStr, _ := customFormatter.Format(WithField("test", "test"))
- timeStart := bytes.Index(customStr, ([]byte)("time="))
- timeEnd := bytes.Index(customStr, ([]byte)("level="))
- timeStr := customStr[timeStart+5 : timeEnd-1]
- if timeStr[0] == '"' && timeStr[len(timeStr)-1] == '"' {
- timeStr = timeStr[1 : len(timeStr)-1]
- }
- if format == "" {
- format = time.RFC3339
- }
- _, e := time.Parse(format, (string)(timeStr))
- if e != nil {
- t.Errorf("time string \"%s\" did not match provided time format \"%s\": %s", timeStr, format, e)
- }
- }
-
- checkTimeStr("2006-01-02T15:04:05.000000000Z07:00")
- checkTimeStr("Mon Jan _2 15:04:05 2006")
- checkTimeStr("")
-}
-
-// TODO add tests for sorting etc., this requires a parser for the text
-// formatter output.
diff --git a/Godeps/_workspace/src/github.com/Sirupsen/logrus/writer.go b/Godeps/_workspace/src/github.com/Sirupsen/logrus/writer.go
deleted file mode 100644
index 1e30b1c753..0000000000
--- a/Godeps/_workspace/src/github.com/Sirupsen/logrus/writer.go
+++ /dev/null
@@ -1,31 +0,0 @@
-package logrus
-
-import (
- "bufio"
- "io"
- "runtime"
-)
-
-func (logger *Logger) Writer() *io.PipeWriter {
- reader, writer := io.Pipe()
-
- go logger.writerScanner(reader)
- runtime.SetFinalizer(writer, writerFinalizer)
-
- return writer
-}
-
-func (logger *Logger) writerScanner(reader *io.PipeReader) {
- scanner := bufio.NewScanner(reader)
- for scanner.Scan() {
- logger.Print(scanner.Text())
- }
- if err := scanner.Err(); err != nil {
- logger.Errorf("Error while reading from Writer: %s", err)
- }
- reader.Close()
-}
-
-func writerFinalizer(writer *io.PipeWriter) {
- writer.Close()
-}
diff --git a/Godeps/_workspace/src/github.com/beorn7/perks/README.md b/Godeps/_workspace/src/github.com/beorn7/perks/README.md
deleted file mode 100644
index fc05777701..0000000000
--- a/Godeps/_workspace/src/github.com/beorn7/perks/README.md
+++ /dev/null
@@ -1,31 +0,0 @@
-# Perks for Go (golang.org)
-
-Perks contains the Go package quantile that computes approximate quantiles over
-an unbounded data stream within low memory and CPU bounds.
-
-For more information and examples, see:
-http://godoc.org/github.com/bmizerany/perks
-
-A very special thank you and shout out to Graham Cormode (Rutgers University),
-Flip Korn (AT&T Labs–Research), S. Muthukrishnan (Rutgers University), and
-Divesh Srivastava (AT&T Labs–Research) for their research and publication of
-[Effective Computation of Biased Quantiles over Data Streams](http://www.cs.rutgers.edu/~muthu/bquant.pdf)
-
-Thank you, also:
-* Armon Dadgar (@armon)
-* Andrew Gerrand (@nf)
-* Brad Fitzpatrick (@bradfitz)
-* Keith Rarick (@kr)
-
-FAQ:
-
-Q: Why not move the quantile package into the project root?
-A: I want to add more packages to perks later.
-
-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.
diff --git a/Godeps/_workspace/src/github.com/beorn7/perks/quantile/bench_test.go b/Godeps/_workspace/src/github.com/beorn7/perks/quantile/bench_test.go
deleted file mode 100644
index 0bd0e4e775..0000000000
--- a/Godeps/_workspace/src/github.com/beorn7/perks/quantile/bench_test.go
+++ /dev/null
@@ -1,63 +0,0 @@
-package quantile
-
-import (
- "testing"
-)
-
-func BenchmarkInsertTargeted(b *testing.B) {
- b.ReportAllocs()
-
- s := NewTargeted(Targets)
- b.ResetTimer()
- for i := float64(0); i < float64(b.N); i++ {
- s.Insert(i)
- }
-}
-
-func BenchmarkInsertTargetedSmallEpsilon(b *testing.B) {
- s := NewTargeted(TargetsSmallEpsilon)
- b.ResetTimer()
- for i := float64(0); i < float64(b.N); i++ {
- s.Insert(i)
- }
-}
-
-func BenchmarkInsertBiased(b *testing.B) {
- s := NewLowBiased(0.01)
- b.ResetTimer()
- for i := float64(0); i < float64(b.N); i++ {
- s.Insert(i)
- }
-}
-
-func BenchmarkInsertBiasedSmallEpsilon(b *testing.B) {
- s := NewLowBiased(0.0001)
- b.ResetTimer()
- for i := float64(0); i < float64(b.N); i++ {
- s.Insert(i)
- }
-}
-
-func BenchmarkQuery(b *testing.B) {
- s := NewTargeted(Targets)
- for i := float64(0); i < 1e6; i++ {
- s.Insert(i)
- }
- b.ResetTimer()
- n := float64(b.N)
- for i := float64(0); i < n; i++ {
- s.Query(i / n)
- }
-}
-
-func BenchmarkQuerySmallEpsilon(b *testing.B) {
- s := NewTargeted(TargetsSmallEpsilon)
- for i := float64(0); i < 1e6; i++ {
- s.Insert(i)
- }
- b.ResetTimer()
- n := float64(b.N)
- for i := float64(0); i < n; i++ {
- s.Query(i / n)
- }
-}
diff --git a/Godeps/_workspace/src/github.com/beorn7/perks/quantile/example_test.go b/Godeps/_workspace/src/github.com/beorn7/perks/quantile/example_test.go
deleted file mode 100644
index ab3293aaf2..0000000000
--- a/Godeps/_workspace/src/github.com/beorn7/perks/quantile/example_test.go
+++ /dev/null
@@ -1,121 +0,0 @@
-// +build go1.1
-
-package quantile_test
-
-import (
- "bufio"
- "fmt"
- "log"
- "os"
- "strconv"
- "time"
-
- "github.com/beorn7/perks/quantile"
-)
-
-func Example_simple() {
- ch := make(chan float64)
- go sendFloats(ch)
-
- // Compute the 50th, 90th, and 99th percentile.
- q := quantile.NewTargeted(map[float64]float64{
- 0.50: 0.005,
- 0.90: 0.001,
- 0.99: 0.0001,
- })
- for v := range ch {
- q.Insert(v)
- }
-
- fmt.Println("perc50:", q.Query(0.50))
- fmt.Println("perc90:", q.Query(0.90))
- fmt.Println("perc99:", q.Query(0.99))
- fmt.Println("count:", q.Count())
- // Output:
- // perc50: 5
- // perc90: 16
- // perc99: 223
- // count: 2388
-}
-
-func Example_mergeMultipleStreams() {
- // Scenario:
- // We have multiple database shards. On each shard, there is a process
- // collecting query response times from the database logs and inserting
- // them into a Stream (created via NewTargeted(0.90)), much like the
- // Simple example. These processes expose a network interface for us to
- // ask them to serialize and send us the results of their
- // Stream.Samples so we may Merge and Query them.
- //
- // NOTES:
- // * These sample sets are small, allowing us to get them
- // across the network much faster than sending the entire list of data
- // points.
- //
- // * For this to work correctly, we must supply the same quantiles
- // a priori the process collecting the samples supplied to NewTargeted,
- // even if we do not plan to query them all here.
- ch := make(chan quantile.Samples)
- getDBQuerySamples(ch)
- q := quantile.NewTargeted(map[float64]float64{0.90: 0.001})
- for samples := range ch {
- q.Merge(samples)
- }
- fmt.Println("perc90:", q.Query(0.90))
-}
-
-func Example_window() {
- // Scenario: We want the 90th, 95th, and 99th percentiles for each
- // minute.
-
- ch := make(chan float64)
- go sendStreamValues(ch)
-
- tick := time.NewTicker(1 * time.Minute)
- q := quantile.NewTargeted(map[float64]float64{
- 0.90: 0.001,
- 0.95: 0.0005,
- 0.99: 0.0001,
- })
- for {
- select {
- case t := <-tick.C:
- flushToDB(t, q.Samples())
- q.Reset()
- case v := <-ch:
- q.Insert(v)
- }
- }
-}
-
-func sendStreamValues(ch chan float64) {
- // Use your imagination
-}
-
-func flushToDB(t time.Time, samples quantile.Samples) {
- // Use your imagination
-}
-
-// This is a stub for the above example. In reality this would hit the remote
-// servers via http or something like it.
-func getDBQuerySamples(ch chan quantile.Samples) {}
-
-func sendFloats(ch chan<- float64) {
- f, err := os.Open("exampledata.txt")
- if err != nil {
- log.Fatal(err)
- }
- sc := bufio.NewScanner(f)
- for sc.Scan() {
- b := sc.Bytes()
- v, err := strconv.ParseFloat(string(b), 64)
- if err != nil {
- log.Fatal(err)
- }
- ch <- v
- }
- if sc.Err() != nil {
- log.Fatal(sc.Err())
- }
- close(ch)
-}
diff --git a/Godeps/_workspace/src/github.com/beorn7/perks/quantile/exampledata.txt b/Godeps/_workspace/src/github.com/beorn7/perks/quantile/exampledata.txt
deleted file mode 100644
index 1602287d7c..0000000000
--- a/Godeps/_workspace/src/github.com/beorn7/perks/quantile/exampledata.txt
+++ /dev/null
@@ -1,2388 +0,0 @@
-8
-5
-26
-12
-5
-235
-13
-6
-28
-30
-3
-3
-3
-3
-5
-2
-33
-7
-2
-4
-7
-12
-14
-5
-8
-3
-10
-4
-5
-3
-6
-6
-209
-20
-3
-10
-14
-3
-4
-6
-8
-5
-11
-7
-3
-2
-3
-3
-212
-5
-222
-4
-10
-10
-5
-6
-3
-8
-3
-10
-254
-220
-2
-3
-5
-24
-5
-4
-222
-7
-3
-3
-223
-8
-15
-12
-14
-14
-3
-2
-2
-3
-13
-3
-11
-4
-4
-6
-5
-7
-13
-5
-3
-5
-2
-5
-3
-5
-2
-7
-15
-17
-14
-3
-6
-6
-3
-17
-5
-4
-7
-6
-4
-4
-8
-6
-8
-3
-9
-3
-6
-3
-4
-5
-3
-3
-660
-4
-6
-10
-3
-6
-3
-2
-5
-13
-2
-4
-4
-10
-4
-8
-4
-3
-7
-9
-9
-3
-10
-37
-3
-13
-4
-12
-3
-6
-10
-8
-5
-21
-2
-3
-8
-3
-2
-3
-3
-4
-12
-2
-4
-8
-8
-4
-3
-2
-20
-1
-6
-32
-2
-11
-6
-18
-3
-8
-11
-3
-212
-3
-4
-2
-6
-7
-12
-11
-3
-2
-16
-10
-6
-4
-6
-3
-2
-7
-3
-2
-2
-2
-2
-5
-6
-4
-3
-10
-3
-4
-6
-5
-3
-4
-4
-5
-6
-4
-3
-4
-4
-5
-7
-5
-5
-3
-2
-7
-2
-4
-12
-4
-5
-6
-2
-4
-4
-8
-4
-15
-13
-7
-16
-5
-3
-23
-5
-5
-7
-3
-2
-9
-8
-7
-5
-8
-11
-4
-10
-76
-4
-47
-4
-3
-2
-7
-4
-2
-3
-37
-10
-4
-2
-20
-5
-4
-4
-10
-10
-4
-3
-7
-23
-240
-7
-13
-5
-5
-3
-3
-2
-5
-4
-2
-8
-7
-19
-2
-23
-8
-7
-2
-5
-3
-8
-3
-8
-13
-5
-5
-5
-2
-3
-23
-4
-9
-8
-4
-3
-3
-5
-220
-2
-3
-4
-6
-14
-3
-53
-6
-2
-5
-18
-6
-3
-219
-6
-5
-2
-5
-3
-6
-5
-15
-4
-3
-17
-3
-2
-4
-7
-2
-3
-3
-4
-4
-3
-2
-664
-6
-3
-23
-5
-5
-16
-5
-8
-2
-4
-2
-24
-12
-3
-2
-3
-5
-8
-3
-5
-4
-3
-14
-3
-5
-8
-2
-3
-7
-9
-4
-2
-3
-6
-8
-4
-3
-4
-6
-5
-3
-3
-6
-3
-19
-4
-4
-6
-3
-6
-3
-5
-22
-5
-4
-4
-3
-8
-11
-4
-9
-7
-6
-13
-4
-4
-4
-6
-17
-9
-3
-3
-3
-4
-3
-221
-5
-11
-3
-4
-2
-12
-6
-3
-5
-7
-5
-7
-4
-9
-7
-14
-37
-19
-217
-16
-3
-5
-2
-2
-7
-19
-7
-6
-7
-4
-24
-5
-11
-4
-7
-7
-9
-13
-3
-4
-3
-6
-28
-4
-4
-5
-5
-2
-5
-6
-4
-4
-6
-10
-5
-4
-3
-2
-3
-3
-6
-5
-5
-4
-3
-2
-3
-7
-4
-6
-18
-16
-8
-16
-4
-5
-8
-6
-9
-13
-1545
-6
-215
-6
-5
-6
-3
-45
-31
-5
-2
-2
-4
-3
-3
-2
-5
-4
-3
-5
-7
-7
-4
-5
-8
-5
-4
-749
-2
-31
-9
-11
-2
-11
-5
-4
-4
-7
-9
-11
-4
-5
-4
-7
-3
-4
-6
-2
-15
-3
-4
-3
-4
-3
-5
-2
-13
-5
-5
-3
-3
-23
-4
-4
-5
-7
-4
-13
-2
-4
-3
-4
-2
-6
-2
-7
-3
-5
-5
-3
-29
-5
-4
-4
-3
-10
-2
-3
-79
-16
-6
-6
-7
-7
-3
-5
-5
-7
-4
-3
-7
-9
-5
-6
-5
-9
-6
-3
-6
-4
-17
-2
-10
-9
-3
-6
-2
-3
-21
-22
-5
-11
-4
-2
-17
-2
-224
-2
-14
-3
-4
-4
-2
-4
-4
-4
-4
-5
-3
-4
-4
-10
-2
-6
-3
-3
-5
-7
-2
-7
-5
-6
-3
-218
-2
-2
-5
-2
-6
-3
-5
-222
-14
-6
-33
-3
-2
-5
-3
-3
-3
-9
-5
-3
-3
-2
-7
-4
-3
-4
-3
-5
-6
-5
-26
-4
-13
-9
-7
-3
-221
-3
-3
-4
-4
-4
-4
-2
-18
-5
-3
-7
-9
-6
-8
-3
-10
-3
-11
-9
-5
-4
-17
-5
-5
-6
-6
-3
-2
-4
-12
-17
-6
-7
-218
-4
-2
-4
-10
-3
-5
-15
-3
-9
-4
-3
-3
-6
-29
-3
-3
-4
-5
-5
-3
-8
-5
-6
-6
-7
-5
-3
-5
-3
-29
-2
-31
-5
-15
-24
-16
-5
-207
-4
-3
-3
-2
-15
-4
-4
-13
-5
-5
-4
-6
-10
-2
-7
-8
-4
-6
-20
-5
-3
-4
-3
-12
-12
-5
-17
-7
-3
-3
-3
-6
-10
-3
-5
-25
-80
-4
-9
-3
-2
-11
-3
-3
-2
-3
-8
-7
-5
-5
-19
-5
-3
-3
-12
-11
-2
-6
-5
-5
-5
-3
-3
-3
-4
-209
-14
-3
-2
-5
-19
-4
-4
-3
-4
-14
-5
-6
-4
-13
-9
-7
-4
-7
-10
-2
-9
-5
-7
-2
-8
-4
-6
-5
-5
-222
-8
-7
-12
-5
-216
-3
-4
-4
-6
-3
-14
-8
-7
-13
-4
-3
-3
-3
-3
-17
-5
-4
-3
-33
-6
-6
-33
-7
-5
-3
-8
-7
-5
-2
-9
-4
-2
-233
-24
-7
-4
-8
-10
-3
-4
-15
-2
-16
-3
-3
-13
-12
-7
-5
-4
-207
-4
-2
-4
-27
-15
-2
-5
-2
-25
-6
-5
-5
-6
-13
-6
-18
-6
-4
-12
-225
-10
-7
-5
-2
-2
-11
-4
-14
-21
-8
-10
-3
-5
-4
-232
-2
-5
-5
-3
-7
-17
-11
-6
-6
-23
-4
-6
-3
-5
-4
-2
-17
-3
-6
-5
-8
-3
-2
-2
-14
-9
-4
-4
-2
-5
-5
-3
-7
-6
-12
-6
-10
-3
-6
-2
-2
-19
-5
-4
-4
-9
-2
-4
-13
-3
-5
-6
-3
-6
-5
-4
-9
-6
-3
-5
-7
-3
-6
-6
-4
-3
-10
-6
-3
-221
-3
-5
-3
-6
-4
-8
-5
-3
-6
-4
-4
-2
-54
-5
-6
-11
-3
-3
-4
-4
-4
-3
-7
-3
-11
-11
-7
-10
-6
-13
-223
-213
-15
-231
-7
-3
-7
-228
-2
-3
-4
-4
-5
-6
-7
-4
-13
-3
-4
-5
-3
-6
-4
-6
-7
-2
-4
-3
-4
-3
-3
-6
-3
-7
-3
-5
-18
-5
-6
-8
-10
-3
-3
-3
-2
-4
-2
-4
-4
-5
-6
-6
-4
-10
-13
-3
-12
-5
-12
-16
-8
-4
-19
-11
-2
-4
-5
-6
-8
-5
-6
-4
-18
-10
-4
-2
-216
-6
-6
-6
-2
-4
-12
-8
-3
-11
-5
-6
-14
-5
-3
-13
-4
-5
-4
-5
-3
-28
-6
-3
-7
-219
-3
-9
-7
-3
-10
-6
-3
-4
-19
-5
-7
-11
-6
-15
-19
-4
-13
-11
-3
-7
-5
-10
-2
-8
-11
-2
-6
-4
-6
-24
-6
-3
-3
-3
-3
-6
-18
-4
-11
-4
-2
-5
-10
-8
-3
-9
-5
-3
-4
-5
-6
-2
-5
-7
-4
-4
-14
-6
-4
-4
-5
-5
-7
-2
-4
-3
-7
-3
-3
-6
-4
-5
-4
-4
-4
-3
-3
-3
-3
-8
-14
-2
-3
-5
-3
-2
-4
-5
-3
-7
-3
-3
-18
-3
-4
-4
-5
-7
-3
-3
-3
-13
-5
-4
-8
-211
-5
-5
-3
-5
-2
-5
-4
-2
-655
-6
-3
-5
-11
-2
-5
-3
-12
-9
-15
-11
-5
-12
-217
-2
-6
-17
-3
-3
-207
-5
-5
-4
-5
-9
-3
-2
-8
-5
-4
-3
-2
-5
-12
-4
-14
-5
-4
-2
-13
-5
-8
-4
-225
-4
-3
-4
-5
-4
-3
-3
-6
-23
-9
-2
-6
-7
-233
-4
-4
-6
-18
-3
-4
-6
-3
-4
-4
-2
-3
-7
-4
-13
-227
-4
-3
-5
-4
-2
-12
-9
-17
-3
-7
-14
-6
-4
-5
-21
-4
-8
-9
-2
-9
-25
-16
-3
-6
-4
-7
-8
-5
-2
-3
-5
-4
-3
-3
-5
-3
-3
-3
-2
-3
-19
-2
-4
-3
-4
-2
-3
-4
-4
-2
-4
-3
-3
-3
-2
-6
-3
-17
-5
-6
-4
-3
-13
-5
-3
-3
-3
-4
-9
-4
-2
-14
-12
-4
-5
-24
-4
-3
-37
-12
-11
-21
-3
-4
-3
-13
-4
-2
-3
-15
-4
-11
-4
-4
-3
-8
-3
-4
-4
-12
-8
-5
-3
-3
-4
-2
-220
-3
-5
-223
-3
-3
-3
-10
-3
-15
-4
-241
-9
-7
-3
-6
-6
-23
-4
-13
-7
-3
-4
-7
-4
-9
-3
-3
-4
-10
-5
-5
-1
-5
-24
-2
-4
-5
-5
-6
-14
-3
-8
-2
-3
-5
-13
-13
-3
-5
-2
-3
-15
-3
-4
-2
-10
-4
-4
-4
-5
-5
-3
-5
-3
-4
-7
-4
-27
-3
-6
-4
-15
-3
-5
-6
-6
-5
-4
-8
-3
-9
-2
-6
-3
-4
-3
-7
-4
-18
-3
-11
-3
-3
-8
-9
-7
-24
-3
-219
-7
-10
-4
-5
-9
-12
-2
-5
-4
-4
-4
-3
-3
-19
-5
-8
-16
-8
-6
-22
-3
-23
-3
-242
-9
-4
-3
-3
-5
-7
-3
-3
-5
-8
-3
-7
-5
-14
-8
-10
-3
-4
-3
-7
-4
-6
-7
-4
-10
-4
-3
-11
-3
-7
-10
-3
-13
-6
-8
-12
-10
-5
-7
-9
-3
-4
-7
-7
-10
-8
-30
-9
-19
-4
-3
-19
-15
-4
-13
-3
-215
-223
-4
-7
-4
-8
-17
-16
-3
-7
-6
-5
-5
-4
-12
-3
-7
-4
-4
-13
-4
-5
-2
-5
-6
-5
-6
-6
-7
-10
-18
-23
-9
-3
-3
-6
-5
-2
-4
-2
-7
-3
-3
-2
-5
-5
-14
-10
-224
-6
-3
-4
-3
-7
-5
-9
-3
-6
-4
-2
-5
-11
-4
-3
-3
-2
-8
-4
-7
-4
-10
-7
-3
-3
-18
-18
-17
-3
-3
-3
-4
-5
-3
-3
-4
-12
-7
-3
-11
-13
-5
-4
-7
-13
-5
-4
-11
-3
-12
-3
-6
-4
-4
-21
-4
-6
-9
-5
-3
-10
-8
-4
-6
-4
-4
-6
-5
-4
-8
-6
-4
-6
-4
-4
-5
-9
-6
-3
-4
-2
-9
-3
-18
-2
-4
-3
-13
-3
-6
-6
-8
-7
-9
-3
-2
-16
-3
-4
-6
-3
-2
-33
-22
-14
-4
-9
-12
-4
-5
-6
-3
-23
-9
-4
-3
-5
-5
-3
-4
-5
-3
-5
-3
-10
-4
-5
-5
-8
-4
-4
-6
-8
-5
-4
-3
-4
-6
-3
-3
-3
-5
-9
-12
-6
-5
-9
-3
-5
-3
-2
-2
-2
-18
-3
-2
-21
-2
-5
-4
-6
-4
-5
-10
-3
-9
-3
-2
-10
-7
-3
-6
-6
-4
-4
-8
-12
-7
-3
-7
-3
-3
-9
-3
-4
-5
-4
-4
-5
-5
-10
-15
-4
-4
-14
-6
-227
-3
-14
-5
-216
-22
-5
-4
-2
-2
-6
-3
-4
-2
-9
-9
-4
-3
-28
-13
-11
-4
-5
-3
-3
-2
-3
-3
-5
-3
-4
-3
-5
-23
-26
-3
-4
-5
-6
-4
-6
-3
-5
-5
-3
-4
-3
-2
-2
-2
-7
-14
-3
-6
-7
-17
-2
-2
-15
-14
-16
-4
-6
-7
-13
-6
-4
-5
-6
-16
-3
-3
-28
-3
-6
-15
-3
-9
-2
-4
-6
-3
-3
-22
-4
-12
-6
-7
-2
-5
-4
-10
-3
-16
-6
-9
-2
-5
-12
-7
-5
-5
-5
-5
-2
-11
-9
-17
-4
-3
-11
-7
-3
-5
-15
-4
-3
-4
-211
-8
-7
-5
-4
-7
-6
-7
-6
-3
-6
-5
-6
-5
-3
-4
-4
-26
-4
-6
-10
-4
-4
-3
-2
-3
-3
-4
-5
-9
-3
-9
-4
-4
-5
-5
-8
-2
-4
-2
-3
-8
-4
-11
-19
-5
-8
-6
-3
-5
-6
-12
-3
-2
-4
-16
-12
-3
-4
-4
-8
-6
-5
-6
-6
-219
-8
-222
-6
-16
-3
-13
-19
-5
-4
-3
-11
-6
-10
-4
-7
-7
-12
-5
-3
-3
-5
-6
-10
-3
-8
-2
-5
-4
-7
-2
-4
-4
-2
-12
-9
-6
-4
-2
-40
-2
-4
-10
-4
-223
-4
-2
-20
-6
-7
-24
-5
-4
-5
-2
-20
-16
-6
-5
-13
-2
-3
-3
-19
-3
-2
-4
-5
-6
-7
-11
-12
-5
-6
-7
-7
-3
-5
-3
-5
-3
-14
-3
-4
-4
-2
-11
-1
-7
-3
-9
-6
-11
-12
-5
-8
-6
-221
-4
-2
-12
-4
-3
-15
-4
-5
-226
-7
-218
-7
-5
-4
-5
-18
-4
-5
-9
-4
-4
-2
-9
-18
-18
-9
-5
-6
-6
-3
-3
-7
-3
-5
-4
-4
-4
-12
-3
-6
-31
-5
-4
-7
-3
-6
-5
-6
-5
-11
-2
-2
-11
-11
-6
-7
-5
-8
-7
-10
-5
-23
-7
-4
-3
-5
-34
-2
-5
-23
-7
-3
-6
-8
-4
-4
-4
-2
-5
-3
-8
-5
-4
-8
-25
-2
-3
-17
-8
-3
-4
-8
-7
-3
-15
-6
-5
-7
-21
-9
-5
-6
-6
-5
-3
-2
-3
-10
-3
-6
-3
-14
-7
-4
-4
-8
-7
-8
-2
-6
-12
-4
-213
-6
-5
-21
-8
-2
-5
-23
-3
-11
-2
-3
-6
-25
-2
-3
-6
-7
-6
-6
-4
-4
-6
-3
-17
-9
-7
-6
-4
-3
-10
-7
-2
-3
-3
-3
-11
-8
-3
-7
-6
-4
-14
-36
-3
-4
-3
-3
-22
-13
-21
-4
-2
-7
-4
-4
-17
-15
-3
-7
-11
-2
-4
-7
-6
-209
-6
-3
-2
-2
-24
-4
-9
-4
-3
-3
-3
-29
-2
-2
-4
-3
-3
-5
-4
-6
-3
-3
-2
-4
diff --git a/Godeps/_workspace/src/github.com/beorn7/perks/quantile/stream.go b/Godeps/_workspace/src/github.com/beorn7/perks/quantile/stream.go
deleted file mode 100644
index 587b1fc5ba..0000000000
--- a/Godeps/_workspace/src/github.com/beorn7/perks/quantile/stream.go
+++ /dev/null
@@ -1,292 +0,0 @@
-// 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(targets map[float64]float64) *Stream {
- ƒ := func(s *stream, r float64) float64 {
- var m = math.MaxFloat64
- var f float64
- for quantile, epsilon := range targets {
- if quantile*s.n <= r {
- f = (2 * epsilon * r) / quantile
- } else {
- f = (2 * epsilon * (s.n - r)) / (1 - quantile)
- }
- if f < m {
- m = f
- }
- }
- return m
- }
- return newStream(ƒ)
-}
-
-// 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(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
-}
diff --git a/Godeps/_workspace/src/github.com/beorn7/perks/quantile/stream_test.go b/Godeps/_workspace/src/github.com/beorn7/perks/quantile/stream_test.go
deleted file mode 100644
index 4dba05449c..0000000000
--- a/Godeps/_workspace/src/github.com/beorn7/perks/quantile/stream_test.go
+++ /dev/null
@@ -1,188 +0,0 @@
-package quantile
-
-import (
- "math"
- "math/rand"
- "sort"
- "testing"
-)
-
-var (
- Targets = map[float64]float64{
- 0.01: 0.001,
- 0.10: 0.01,
- 0.50: 0.05,
- 0.90: 0.01,
- 0.99: 0.001,
- }
- TargetsSmallEpsilon = map[float64]float64{
- 0.01: 0.0001,
- 0.10: 0.001,
- 0.50: 0.005,
- 0.90: 0.001,
- 0.99: 0.0001,
- }
- LowQuantiles = []float64{0.01, 0.1, 0.5}
- HighQuantiles = []float64{0.99, 0.9, 0.5}
-)
-
-const RelativeEpsilon = 0.01
-
-func verifyPercsWithAbsoluteEpsilon(t *testing.T, a []float64, s *Stream) {
- sort.Float64s(a)
- for quantile, epsilon := range Targets {
- n := float64(len(a))
- k := int(quantile * n)
- lower := int((quantile - epsilon) * n)
- if lower < 1 {
- lower = 1
- }
- upper := int(math.Ceil((quantile + epsilon) * n))
- if upper > len(a) {
- upper = len(a)
- }
- w, min, max := a[k-1], a[lower-1], a[upper-1]
- if g := s.Query(quantile); g < min || g > max {
- t.Errorf("q=%f: want %v [%f,%f], got %v", quantile, w, min, max, g)
- }
- }
-}
-
-func verifyLowPercsWithRelativeEpsilon(t *testing.T, a []float64, s *Stream) {
- sort.Float64s(a)
- for _, qu := range LowQuantiles {
- n := float64(len(a))
- k := int(qu * n)
-
- lowerRank := int((1 - RelativeEpsilon) * qu * n)
- upperRank := int(math.Ceil((1 + RelativeEpsilon) * qu * n))
- w, min, max := a[k-1], a[lowerRank-1], a[upperRank-1]
- if g := s.Query(qu); g < min || g > max {
- t.Errorf("q=%f: want %v [%f,%f], got %v", qu, w, min, max, g)
- }
- }
-}
-
-func verifyHighPercsWithRelativeEpsilon(t *testing.T, a []float64, s *Stream) {
- sort.Float64s(a)
- for _, qu := range HighQuantiles {
- n := float64(len(a))
- k := int(qu * n)
-
- lowerRank := int((1 - (1+RelativeEpsilon)*(1-qu)) * n)
- upperRank := int(math.Ceil((1 - (1-RelativeEpsilon)*(1-qu)) * n))
- w, min, max := a[k-1], a[lowerRank-1], a[upperRank-1]
- if g := s.Query(qu); g < min || g > max {
- t.Errorf("q=%f: want %v [%f,%f], got %v", qu, w, min, max, g)
- }
- }
-}
-
-func populateStream(s *Stream) []float64 {
- a := make([]float64, 0, 1e5+100)
- for i := 0; i < cap(a); i++ {
- v := rand.NormFloat64()
- // Add 5% asymmetric outliers.
- if i%20 == 0 {
- v = v*v + 1
- }
- s.Insert(v)
- a = append(a, v)
- }
- return a
-}
-
-func TestTargetedQuery(t *testing.T) {
- rand.Seed(42)
- s := NewTargeted(Targets)
- a := populateStream(s)
- verifyPercsWithAbsoluteEpsilon(t, a, s)
-}
-
-func TestLowBiasedQuery(t *testing.T) {
- rand.Seed(42)
- s := NewLowBiased(RelativeEpsilon)
- a := populateStream(s)
- verifyLowPercsWithRelativeEpsilon(t, a, s)
-}
-
-func TestHighBiasedQuery(t *testing.T) {
- rand.Seed(42)
- s := NewHighBiased(RelativeEpsilon)
- a := populateStream(s)
- verifyHighPercsWithRelativeEpsilon(t, a, s)
-}
-
-// BrokenTestTargetedMerge is broken, see Merge doc comment.
-func BrokenTestTargetedMerge(t *testing.T) {
- rand.Seed(42)
- s1 := NewTargeted(Targets)
- s2 := NewTargeted(Targets)
- a := populateStream(s1)
- a = append(a, populateStream(s2)...)
- s1.Merge(s2.Samples())
- verifyPercsWithAbsoluteEpsilon(t, a, s1)
-}
-
-// BrokenTestLowBiasedMerge is broken, see Merge doc comment.
-func BrokenTestLowBiasedMerge(t *testing.T) {
- rand.Seed(42)
- s1 := NewLowBiased(RelativeEpsilon)
- s2 := NewLowBiased(RelativeEpsilon)
- a := populateStream(s1)
- a = append(a, populateStream(s2)...)
- s1.Merge(s2.Samples())
- verifyLowPercsWithRelativeEpsilon(t, a, s2)
-}
-
-// BrokenTestHighBiasedMerge is broken, see Merge doc comment.
-func BrokenTestHighBiasedMerge(t *testing.T) {
- rand.Seed(42)
- s1 := NewHighBiased(RelativeEpsilon)
- s2 := NewHighBiased(RelativeEpsilon)
- a := populateStream(s1)
- a = append(a, populateStream(s2)...)
- s1.Merge(s2.Samples())
- verifyHighPercsWithRelativeEpsilon(t, a, s2)
-}
-
-func TestUncompressed(t *testing.T) {
- q := NewTargeted(Targets)
- for i := 100; i > 0; i-- {
- q.Insert(float64(i))
- }
- if g := q.Count(); g != 100 {
- t.Errorf("want count 100, got %d", g)
- }
- // Before compression, Query should have 100% accuracy.
- for quantile := range Targets {
- w := quantile * 100
- if g := q.Query(quantile); g != w {
- t.Errorf("want %f, got %f", w, g)
- }
- }
-}
-
-func TestUncompressedSamples(t *testing.T) {
- q := NewTargeted(map[float64]float64{0.99: 0.001})
- for i := 1; i <= 100; i++ {
- q.Insert(float64(i))
- }
- if g := q.Samples().Len(); g != 100 {
- t.Errorf("want count 100, got %d", g)
- }
-}
-
-func TestUncompressedOne(t *testing.T) {
- q := NewTargeted(map[float64]float64{0.99: 0.01})
- q.Insert(3.14)
- if g := q.Query(0.90); g != 3.14 {
- t.Error("want PI, got", g)
- }
-}
-
-func TestDefaults(t *testing.T) {
- if g := NewTargeted(map[float64]float64{0.99: 0.001}).Query(0.99); g != 0 {
- t.Errorf("want 0, got %f", g)
- }
-}
diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/LICENSE b/Godeps/_workspace/src/github.com/golang/protobuf/LICENSE
deleted file mode 100644
index 1b1b1921ef..0000000000
--- a/Godeps/_workspace/src/github.com/golang/protobuf/LICENSE
+++ /dev/null
@@ -1,31 +0,0 @@
-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.
-
diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/Makefile b/Godeps/_workspace/src/github.com/golang/protobuf/proto/Makefile
deleted file mode 100644
index f1f06564a1..0000000000
--- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/Makefile
+++ /dev/null
@@ -1,43 +0,0 @@
-# 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.
-
-install:
- go install
-
-test: install generate-test-pbs
- go test
-
-
-generate-test-pbs:
- make install
- make -C testdata
- protoc --go_out=Mtestdata/test.proto=github.com/golang/protobuf/proto/testdata:. proto3_proto/proto3.proto
- make
diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/all_test.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/all_test.go
deleted file mode 100644
index 5a9b6a47f6..0000000000
--- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/all_test.go
+++ /dev/null
@@ -1,2083 +0,0 @@
-// 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_test
-
-import (
- "bytes"
- "encoding/json"
- "errors"
- "fmt"
- "math"
- "math/rand"
- "reflect"
- "runtime/debug"
- "strings"
- "testing"
- "time"
-
- . "github.com/golang/protobuf/proto"
- . "github.com/golang/protobuf/proto/testdata"
-)
-
-var globalO *Buffer
-
-func old() *Buffer {
- if globalO == nil {
- globalO = NewBuffer(nil)
- }
- globalO.Reset()
- return globalO
-}
-
-func equalbytes(b1, b2 []byte, t *testing.T) {
- if len(b1) != len(b2) {
- t.Errorf("wrong lengths: 2*%d != %d", len(b1), len(b2))
- return
- }
- for i := 0; i < len(b1); i++ {
- if b1[i] != b2[i] {
- t.Errorf("bad byte[%d]:%x %x: %s %s", i, b1[i], b2[i], b1, b2)
- }
- }
-}
-
-func initGoTestField() *GoTestField {
- f := new(GoTestField)
- f.Label = String("label")
- f.Type = String("type")
- return f
-}
-
-// These are all structurally equivalent but the tag numbers differ.
-// (It's remarkable that required, optional, and repeated all have
-// 8 letters.)
-func initGoTest_RequiredGroup() *GoTest_RequiredGroup {
- return &GoTest_RequiredGroup{
- RequiredField: String("required"),
- }
-}
-
-func initGoTest_OptionalGroup() *GoTest_OptionalGroup {
- return &GoTest_OptionalGroup{
- RequiredField: String("optional"),
- }
-}
-
-func initGoTest_RepeatedGroup() *GoTest_RepeatedGroup {
- return &GoTest_RepeatedGroup{
- RequiredField: String("repeated"),
- }
-}
-
-func initGoTest(setdefaults bool) *GoTest {
- pb := new(GoTest)
- if setdefaults {
- pb.F_BoolDefaulted = Bool(Default_GoTest_F_BoolDefaulted)
- pb.F_Int32Defaulted = Int32(Default_GoTest_F_Int32Defaulted)
- pb.F_Int64Defaulted = Int64(Default_GoTest_F_Int64Defaulted)
- pb.F_Fixed32Defaulted = Uint32(Default_GoTest_F_Fixed32Defaulted)
- pb.F_Fixed64Defaulted = Uint64(Default_GoTest_F_Fixed64Defaulted)
- pb.F_Uint32Defaulted = Uint32(Default_GoTest_F_Uint32Defaulted)
- pb.F_Uint64Defaulted = Uint64(Default_GoTest_F_Uint64Defaulted)
- pb.F_FloatDefaulted = Float32(Default_GoTest_F_FloatDefaulted)
- pb.F_DoubleDefaulted = Float64(Default_GoTest_F_DoubleDefaulted)
- pb.F_StringDefaulted = String(Default_GoTest_F_StringDefaulted)
- pb.F_BytesDefaulted = Default_GoTest_F_BytesDefaulted
- pb.F_Sint32Defaulted = Int32(Default_GoTest_F_Sint32Defaulted)
- pb.F_Sint64Defaulted = Int64(Default_GoTest_F_Sint64Defaulted)
- }
-
- pb.Kind = GoTest_TIME.Enum()
- pb.RequiredField = initGoTestField()
- pb.F_BoolRequired = Bool(true)
- pb.F_Int32Required = Int32(3)
- pb.F_Int64Required = Int64(6)
- pb.F_Fixed32Required = Uint32(32)
- pb.F_Fixed64Required = Uint64(64)
- pb.F_Uint32Required = Uint32(3232)
- pb.F_Uint64Required = Uint64(6464)
- pb.F_FloatRequired = Float32(3232)
- pb.F_DoubleRequired = Float64(6464)
- pb.F_StringRequired = String("string")
- pb.F_BytesRequired = []byte("bytes")
- pb.F_Sint32Required = Int32(-32)
- pb.F_Sint64Required = Int64(-64)
- pb.Requiredgroup = initGoTest_RequiredGroup()
-
- return pb
-}
-
-func fail(msg string, b *bytes.Buffer, s string, t *testing.T) {
- data := b.Bytes()
- ld := len(data)
- ls := len(s) / 2
-
- fmt.Printf("fail %s ld=%d ls=%d\n", msg, ld, ls)
-
- // find the interesting spot - n
- n := ls
- if ld < ls {
- n = ld
- }
- j := 0
- for i := 0; i < n; i++ {
- bs := hex(s[j])*16 + hex(s[j+1])
- j += 2
- if data[i] == bs {
- continue
- }
- n = i
- break
- }
- l := n - 10
- if l < 0 {
- l = 0
- }
- h := n + 10
-
- // find the interesting spot - n
- fmt.Printf("is[%d]:", l)
- for i := l; i < h; i++ {
- if i >= ld {
- fmt.Printf(" --")
- continue
- }
- fmt.Printf(" %.2x", data[i])
- }
- fmt.Printf("\n")
-
- fmt.Printf("sb[%d]:", l)
- for i := l; i < h; i++ {
- if i >= ls {
- fmt.Printf(" --")
- continue
- }
- bs := hex(s[j])*16 + hex(s[j+1])
- j += 2
- fmt.Printf(" %.2x", bs)
- }
- fmt.Printf("\n")
-
- t.Fail()
-
- // t.Errorf("%s: \ngood: %s\nbad: %x", msg, s, b.Bytes())
- // Print the output in a partially-decoded format; can
- // be helpful when updating the test. It produces the output
- // that is pasted, with minor edits, into the argument to verify().
- // data := b.Bytes()
- // nesting := 0
- // for b.Len() > 0 {
- // start := len(data) - b.Len()
- // var u uint64
- // u, err := DecodeVarint(b)
- // if err != nil {
- // fmt.Printf("decode error on varint:", err)
- // return
- // }
- // wire := u & 0x7
- // tag := u >> 3
- // switch wire {
- // case WireVarint:
- // v, err := DecodeVarint(b)
- // if err != nil {
- // fmt.Printf("decode error on varint:", err)
- // return
- // }
- // fmt.Printf("\t\t\"%x\" // field %d, encoding %d, value %d\n",
- // data[start:len(data)-b.Len()], tag, wire, v)
- // case WireFixed32:
- // v, err := DecodeFixed32(b)
- // if err != nil {
- // fmt.Printf("decode error on fixed32:", err)
- // return
- // }
- // fmt.Printf("\t\t\"%x\" // field %d, encoding %d, value %d\n",
- // data[start:len(data)-b.Len()], tag, wire, v)
- // case WireFixed64:
- // v, err := DecodeFixed64(b)
- // if err != nil {
- // fmt.Printf("decode error on fixed64:", err)
- // return
- // }
- // fmt.Printf("\t\t\"%x\" // field %d, encoding %d, value %d\n",
- // data[start:len(data)-b.Len()], tag, wire, v)
- // case WireBytes:
- // nb, err := DecodeVarint(b)
- // if err != nil {
- // fmt.Printf("decode error on bytes:", err)
- // return
- // }
- // after_tag := len(data) - b.Len()
- // str := make([]byte, nb)
- // _, err = b.Read(str)
- // if err != nil {
- // fmt.Printf("decode error on bytes:", err)
- // return
- // }
- // fmt.Printf("\t\t\"%x\" \"%x\" // field %d, encoding %d (FIELD)\n",
- // data[start:after_tag], str, tag, wire)
- // case WireStartGroup:
- // nesting++
- // fmt.Printf("\t\t\"%x\"\t\t// start group field %d level %d\n",
- // data[start:len(data)-b.Len()], tag, nesting)
- // case WireEndGroup:
- // fmt.Printf("\t\t\"%x\"\t\t// end group field %d level %d\n",
- // data[start:len(data)-b.Len()], tag, nesting)
- // nesting--
- // default:
- // fmt.Printf("unrecognized wire type %d\n", wire)
- // return
- // }
- // }
-}
-
-func hex(c uint8) uint8 {
- if '0' <= c && c <= '9' {
- return c - '0'
- }
- if 'a' <= c && c <= 'f' {
- return 10 + c - 'a'
- }
- if 'A' <= c && c <= 'F' {
- return 10 + c - 'A'
- }
- return 0
-}
-
-func equal(b []byte, s string, t *testing.T) bool {
- if 2*len(b) != len(s) {
- // fail(fmt.Sprintf("wrong lengths: 2*%d != %d", len(b), len(s)), b, s, t)
- fmt.Printf("wrong lengths: 2*%d != %d\n", len(b), len(s))
- return false
- }
- for i, j := 0, 0; i < len(b); i, j = i+1, j+2 {
- x := hex(s[j])*16 + hex(s[j+1])
- if b[i] != x {
- // fail(fmt.Sprintf("bad byte[%d]:%x %x", i, b[i], x), b, s, t)
- fmt.Printf("bad byte[%d]:%x %x", i, b[i], x)
- return false
- }
- }
- return true
-}
-
-func overify(t *testing.T, pb *GoTest, expected string) {
- o := old()
- err := o.Marshal(pb)
- if err != nil {
- fmt.Printf("overify marshal-1 err = %v", err)
- o.DebugPrint("", o.Bytes())
- t.Fatalf("expected = %s", expected)
- }
- if !equal(o.Bytes(), expected, t) {
- o.DebugPrint("overify neq 1", o.Bytes())
- t.Fatalf("expected = %s", expected)
- }
-
- // Now test Unmarshal by recreating the original buffer.
- pbd := new(GoTest)
- err = o.Unmarshal(pbd)
- if err != nil {
- t.Fatalf("overify unmarshal err = %v", err)
- o.DebugPrint("", o.Bytes())
- t.Fatalf("string = %s", expected)
- }
- o.Reset()
- err = o.Marshal(pbd)
- if err != nil {
- t.Errorf("overify marshal-2 err = %v", err)
- o.DebugPrint("", o.Bytes())
- t.Fatalf("string = %s", expected)
- }
- if !equal(o.Bytes(), expected, t) {
- o.DebugPrint("overify neq 2", o.Bytes())
- t.Fatalf("string = %s", expected)
- }
-}
-
-// Simple tests for numeric encode/decode primitives (varint, etc.)
-func TestNumericPrimitives(t *testing.T) {
- for i := uint64(0); i < 1e6; i += 111 {
- o := old()
- if o.EncodeVarint(i) != nil {
- t.Error("EncodeVarint")
- break
- }
- x, e := o.DecodeVarint()
- if e != nil {
- t.Fatal("DecodeVarint")
- }
- if x != i {
- t.Fatal("varint decode fail:", i, x)
- }
-
- o = old()
- if o.EncodeFixed32(i) != nil {
- t.Fatal("encFixed32")
- }
- x, e = o.DecodeFixed32()
- if e != nil {
- t.Fatal("decFixed32")
- }
- if x != i {
- t.Fatal("fixed32 decode fail:", i, x)
- }
-
- o = old()
- if o.EncodeFixed64(i*1234567) != nil {
- t.Error("encFixed64")
- break
- }
- x, e = o.DecodeFixed64()
- if e != nil {
- t.Error("decFixed64")
- break
- }
- if x != i*1234567 {
- t.Error("fixed64 decode fail:", i*1234567, x)
- break
- }
-
- o = old()
- i32 := int32(i - 12345)
- if o.EncodeZigzag32(uint64(i32)) != nil {
- t.Fatal("EncodeZigzag32")
- }
- x, e = o.DecodeZigzag32()
- if e != nil {
- t.Fatal("DecodeZigzag32")
- }
- if x != uint64(uint32(i32)) {
- t.Fatal("zigzag32 decode fail:", i32, x)
- }
-
- o = old()
- i64 := int64(i - 12345)
- if o.EncodeZigzag64(uint64(i64)) != nil {
- t.Fatal("EncodeZigzag64")
- }
- x, e = o.DecodeZigzag64()
- if e != nil {
- t.Fatal("DecodeZigzag64")
- }
- if x != uint64(i64) {
- t.Fatal("zigzag64 decode fail:", i64, x)
- }
- }
-}
-
-// fakeMarshaler is a simple struct implementing Marshaler and Message interfaces.
-type fakeMarshaler struct {
- b []byte
- err error
-}
-
-func (f fakeMarshaler) Marshal() ([]byte, error) {
- return f.b, f.err
-}
-
-func (f fakeMarshaler) String() string {
- return fmt.Sprintf("Bytes: %v Error: %v", f.b, f.err)
-}
-
-func (f fakeMarshaler) ProtoMessage() {}
-
-func (f fakeMarshaler) Reset() {}
-
-// Simple tests for proto messages that implement the Marshaler interface.
-func TestMarshalerEncoding(t *testing.T) {
- tests := []struct {
- name string
- m Message
- want []byte
- wantErr error
- }{
- {
- name: "Marshaler that fails",
- m: fakeMarshaler{
- err: errors.New("some marshal err"),
- b: []byte{5, 6, 7},
- },
- // Since there's an error, nothing should be written to buffer.
- want: nil,
- wantErr: errors.New("some marshal err"),
- },
- {
- name: "Marshaler that succeeds",
- m: fakeMarshaler{
- b: []byte{0, 1, 2, 3, 4, 127, 255},
- },
- want: []byte{0, 1, 2, 3, 4, 127, 255},
- wantErr: nil,
- },
- }
- for _, test := range tests {
- b := NewBuffer(nil)
- err := b.Marshal(test.m)
- if !reflect.DeepEqual(test.wantErr, err) {
- t.Errorf("%s: got err %v wanted %v", test.name, err, test.wantErr)
- }
- if !reflect.DeepEqual(test.want, b.Bytes()) {
- t.Errorf("%s: got bytes %v wanted %v", test.name, b.Bytes(), test.want)
- }
- }
-}
-
-// Simple tests for bytes
-func TestBytesPrimitives(t *testing.T) {
- o := old()
- bytes := []byte{'n', 'o', 'w', ' ', 'i', 's', ' ', 't', 'h', 'e', ' ', 't', 'i', 'm', 'e'}
- if o.EncodeRawBytes(bytes) != nil {
- t.Error("EncodeRawBytes")
- }
- decb, e := o.DecodeRawBytes(false)
- if e != nil {
- t.Error("DecodeRawBytes")
- }
- equalbytes(bytes, decb, t)
-}
-
-// Simple tests for strings
-func TestStringPrimitives(t *testing.T) {
- o := old()
- s := "now is the time"
- if o.EncodeStringBytes(s) != nil {
- t.Error("enc_string")
- }
- decs, e := o.DecodeStringBytes()
- if e != nil {
- t.Error("dec_string")
- }
- if s != decs {
- t.Error("string encode/decode fail:", s, decs)
- }
-}
-
-// Do we catch the "required bit not set" case?
-func TestRequiredBit(t *testing.T) {
- o := old()
- pb := new(GoTest)
- err := o.Marshal(pb)
- if err == nil {
- t.Error("did not catch missing required fields")
- } else if strings.Index(err.Error(), "Kind") < 0 {
- t.Error("wrong error type:", err)
- }
-}
-
-// Check that all fields are nil.
-// Clearly silly, and a residue from a more interesting test with an earlier,
-// different initialization property, but it once caught a compiler bug so
-// it lives.
-func checkInitialized(pb *GoTest, t *testing.T) {
- if pb.F_BoolDefaulted != nil {
- t.Error("New or Reset did not set boolean:", *pb.F_BoolDefaulted)
- }
- if pb.F_Int32Defaulted != nil {
- t.Error("New or Reset did not set int32:", *pb.F_Int32Defaulted)
- }
- if pb.F_Int64Defaulted != nil {
- t.Error("New or Reset did not set int64:", *pb.F_Int64Defaulted)
- }
- if pb.F_Fixed32Defaulted != nil {
- t.Error("New or Reset did not set fixed32:", *pb.F_Fixed32Defaulted)
- }
- if pb.F_Fixed64Defaulted != nil {
- t.Error("New or Reset did not set fixed64:", *pb.F_Fixed64Defaulted)
- }
- if pb.F_Uint32Defaulted != nil {
- t.Error("New or Reset did not set uint32:", *pb.F_Uint32Defaulted)
- }
- if pb.F_Uint64Defaulted != nil {
- t.Error("New or Reset did not set uint64:", *pb.F_Uint64Defaulted)
- }
- if pb.F_FloatDefaulted != nil {
- t.Error("New or Reset did not set float:", *pb.F_FloatDefaulted)
- }
- if pb.F_DoubleDefaulted != nil {
- t.Error("New or Reset did not set double:", *pb.F_DoubleDefaulted)
- }
- if pb.F_StringDefaulted != nil {
- t.Error("New or Reset did not set string:", *pb.F_StringDefaulted)
- }
- if pb.F_BytesDefaulted != nil {
- t.Error("New or Reset did not set bytes:", string(pb.F_BytesDefaulted))
- }
- if pb.F_Sint32Defaulted != nil {
- t.Error("New or Reset did not set int32:", *pb.F_Sint32Defaulted)
- }
- if pb.F_Sint64Defaulted != nil {
- t.Error("New or Reset did not set int64:", *pb.F_Sint64Defaulted)
- }
-}
-
-// Does Reset() reset?
-func TestReset(t *testing.T) {
- pb := initGoTest(true)
- // muck with some values
- pb.F_BoolDefaulted = Bool(false)
- pb.F_Int32Defaulted = Int32(237)
- pb.F_Int64Defaulted = Int64(12346)
- pb.F_Fixed32Defaulted = Uint32(32000)
- pb.F_Fixed64Defaulted = Uint64(666)
- pb.F_Uint32Defaulted = Uint32(323232)
- pb.F_Uint64Defaulted = nil
- pb.F_FloatDefaulted = nil
- pb.F_DoubleDefaulted = Float64(0)
- pb.F_StringDefaulted = String("gotcha")
- pb.F_BytesDefaulted = []byte("asdfasdf")
- pb.F_Sint32Defaulted = Int32(123)
- pb.F_Sint64Defaulted = Int64(789)
- pb.Reset()
- checkInitialized(pb, t)
-}
-
-// All required fields set, no defaults provided.
-func TestEncodeDecode1(t *testing.T) {
- pb := initGoTest(false)
- overify(t, pb,
- "0807"+ // field 1, encoding 0, value 7
- "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField)
- "5001"+ // field 10, encoding 0, value 1
- "5803"+ // field 11, encoding 0, value 3
- "6006"+ // field 12, encoding 0, value 6
- "6d20000000"+ // field 13, encoding 5, value 0x20
- "714000000000000000"+ // field 14, encoding 1, value 0x40
- "78a019"+ // field 15, encoding 0, value 0xca0 = 3232
- "8001c032"+ // field 16, encoding 0, value 0x1940 = 6464
- "8d0100004a45"+ // field 17, encoding 5, value 3232.0
- "9101000000000040b940"+ // field 18, encoding 1, value 6464.0
- "9a0106"+"737472696e67"+ // field 19, encoding 2, string "string"
- "b304"+ // field 70, encoding 3, start group
- "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required"
- "b404"+ // field 70, encoding 4, end group
- "aa0605"+"6279746573"+ // field 101, encoding 2, string "bytes"
- "b0063f"+ // field 102, encoding 0, 0x3f zigzag32
- "b8067f") // field 103, encoding 0, 0x7f zigzag64
-}
-
-// All required fields set, defaults provided.
-func TestEncodeDecode2(t *testing.T) {
- pb := initGoTest(true)
- overify(t, pb,
- "0807"+ // field 1, encoding 0, value 7
- "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField)
- "5001"+ // field 10, encoding 0, value 1
- "5803"+ // field 11, encoding 0, value 3
- "6006"+ // field 12, encoding 0, value 6
- "6d20000000"+ // field 13, encoding 5, value 32
- "714000000000000000"+ // field 14, encoding 1, value 64
- "78a019"+ // field 15, encoding 0, value 3232
- "8001c032"+ // field 16, encoding 0, value 6464
- "8d0100004a45"+ // field 17, encoding 5, value 3232.0
- "9101000000000040b940"+ // field 18, encoding 1, value 6464.0
- "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string"
- "c00201"+ // field 40, encoding 0, value 1
- "c80220"+ // field 41, encoding 0, value 32
- "d00240"+ // field 42, encoding 0, value 64
- "dd0240010000"+ // field 43, encoding 5, value 320
- "e1028002000000000000"+ // field 44, encoding 1, value 640
- "e8028019"+ // field 45, encoding 0, value 3200
- "f0028032"+ // field 46, encoding 0, value 6400
- "fd02e0659948"+ // field 47, encoding 5, value 314159.0
- "81030000000050971041"+ // field 48, encoding 1, value 271828.0
- "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n"
- "b304"+ // start group field 70 level 1
- "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required"
- "b404"+ // end group field 70 level 1
- "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes"
- "b0063f"+ // field 102, encoding 0, 0x3f zigzag32
- "b8067f"+ // field 103, encoding 0, 0x7f zigzag64
- "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose"
- "90193f"+ // field 402, encoding 0, value 63
- "98197f") // field 403, encoding 0, value 127
-
-}
-
-// All default fields set to their default value by hand
-func TestEncodeDecode3(t *testing.T) {
- pb := initGoTest(false)
- pb.F_BoolDefaulted = Bool(true)
- pb.F_Int32Defaulted = Int32(32)
- pb.F_Int64Defaulted = Int64(64)
- pb.F_Fixed32Defaulted = Uint32(320)
- pb.F_Fixed64Defaulted = Uint64(640)
- pb.F_Uint32Defaulted = Uint32(3200)
- pb.F_Uint64Defaulted = Uint64(6400)
- pb.F_FloatDefaulted = Float32(314159)
- pb.F_DoubleDefaulted = Float64(271828)
- pb.F_StringDefaulted = String("hello, \"world!\"\n")
- pb.F_BytesDefaulted = []byte("Bignose")
- pb.F_Sint32Defaulted = Int32(-32)
- pb.F_Sint64Defaulted = Int64(-64)
-
- overify(t, pb,
- "0807"+ // field 1, encoding 0, value 7
- "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField)
- "5001"+ // field 10, encoding 0, value 1
- "5803"+ // field 11, encoding 0, value 3
- "6006"+ // field 12, encoding 0, value 6
- "6d20000000"+ // field 13, encoding 5, value 32
- "714000000000000000"+ // field 14, encoding 1, value 64
- "78a019"+ // field 15, encoding 0, value 3232
- "8001c032"+ // field 16, encoding 0, value 6464
- "8d0100004a45"+ // field 17, encoding 5, value 3232.0
- "9101000000000040b940"+ // field 18, encoding 1, value 6464.0
- "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string"
- "c00201"+ // field 40, encoding 0, value 1
- "c80220"+ // field 41, encoding 0, value 32
- "d00240"+ // field 42, encoding 0, value 64
- "dd0240010000"+ // field 43, encoding 5, value 320
- "e1028002000000000000"+ // field 44, encoding 1, value 640
- "e8028019"+ // field 45, encoding 0, value 3200
- "f0028032"+ // field 46, encoding 0, value 6400
- "fd02e0659948"+ // field 47, encoding 5, value 314159.0
- "81030000000050971041"+ // field 48, encoding 1, value 271828.0
- "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n"
- "b304"+ // start group field 70 level 1
- "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required"
- "b404"+ // end group field 70 level 1
- "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes"
- "b0063f"+ // field 102, encoding 0, 0x3f zigzag32
- "b8067f"+ // field 103, encoding 0, 0x7f zigzag64
- "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose"
- "90193f"+ // field 402, encoding 0, value 63
- "98197f") // field 403, encoding 0, value 127
-
-}
-
-// All required fields set, defaults provided, all non-defaulted optional fields have values.
-func TestEncodeDecode4(t *testing.T) {
- pb := initGoTest(true)
- pb.Table = String("hello")
- pb.Param = Int32(7)
- pb.OptionalField = initGoTestField()
- pb.F_BoolOptional = Bool(true)
- pb.F_Int32Optional = Int32(32)
- pb.F_Int64Optional = Int64(64)
- pb.F_Fixed32Optional = Uint32(3232)
- pb.F_Fixed64Optional = Uint64(6464)
- pb.F_Uint32Optional = Uint32(323232)
- pb.F_Uint64Optional = Uint64(646464)
- pb.F_FloatOptional = Float32(32.)
- pb.F_DoubleOptional = Float64(64.)
- pb.F_StringOptional = String("hello")
- pb.F_BytesOptional = []byte("Bignose")
- pb.F_Sint32Optional = Int32(-32)
- pb.F_Sint64Optional = Int64(-64)
- pb.Optionalgroup = initGoTest_OptionalGroup()
-
- overify(t, pb,
- "0807"+ // field 1, encoding 0, value 7
- "1205"+"68656c6c6f"+ // field 2, encoding 2, string "hello"
- "1807"+ // field 3, encoding 0, value 7
- "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField)
- "320d"+"0a056c6162656c120474797065"+ // field 6, encoding 2 (GoTestField)
- "5001"+ // field 10, encoding 0, value 1
- "5803"+ // field 11, encoding 0, value 3
- "6006"+ // field 12, encoding 0, value 6
- "6d20000000"+ // field 13, encoding 5, value 32
- "714000000000000000"+ // field 14, encoding 1, value 64
- "78a019"+ // field 15, encoding 0, value 3232
- "8001c032"+ // field 16, encoding 0, value 6464
- "8d0100004a45"+ // field 17, encoding 5, value 3232.0
- "9101000000000040b940"+ // field 18, encoding 1, value 6464.0
- "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string"
- "f00101"+ // field 30, encoding 0, value 1
- "f80120"+ // field 31, encoding 0, value 32
- "800240"+ // field 32, encoding 0, value 64
- "8d02a00c0000"+ // field 33, encoding 5, value 3232
- "91024019000000000000"+ // field 34, encoding 1, value 6464
- "9802a0dd13"+ // field 35, encoding 0, value 323232
- "a002c0ba27"+ // field 36, encoding 0, value 646464
- "ad0200000042"+ // field 37, encoding 5, value 32.0
- "b1020000000000005040"+ // field 38, encoding 1, value 64.0
- "ba0205"+"68656c6c6f"+ // field 39, encoding 2, string "hello"
- "c00201"+ // field 40, encoding 0, value 1
- "c80220"+ // field 41, encoding 0, value 32
- "d00240"+ // field 42, encoding 0, value 64
- "dd0240010000"+ // field 43, encoding 5, value 320
- "e1028002000000000000"+ // field 44, encoding 1, value 640
- "e8028019"+ // field 45, encoding 0, value 3200
- "f0028032"+ // field 46, encoding 0, value 6400
- "fd02e0659948"+ // field 47, encoding 5, value 314159.0
- "81030000000050971041"+ // field 48, encoding 1, value 271828.0
- "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n"
- "b304"+ // start group field 70 level 1
- "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required"
- "b404"+ // end group field 70 level 1
- "d305"+ // start group field 90 level 1
- "da0508"+"6f7074696f6e616c"+ // field 91, encoding 2, string "optional"
- "d405"+ // end group field 90 level 1
- "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes"
- "b0063f"+ // field 102, encoding 0, 0x3f zigzag32
- "b8067f"+ // field 103, encoding 0, 0x7f zigzag64
- "ea1207"+"4269676e6f7365"+ // field 301, encoding 2, string "Bignose"
- "f0123f"+ // field 302, encoding 0, value 63
- "f8127f"+ // field 303, encoding 0, value 127
- "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose"
- "90193f"+ // field 402, encoding 0, value 63
- "98197f") // field 403, encoding 0, value 127
-
-}
-
-// All required fields set, defaults provided, all repeated fields given two values.
-func TestEncodeDecode5(t *testing.T) {
- pb := initGoTest(true)
- pb.RepeatedField = []*GoTestField{initGoTestField(), initGoTestField()}
- pb.F_BoolRepeated = []bool{false, true}
- pb.F_Int32Repeated = []int32{32, 33}
- pb.F_Int64Repeated = []int64{64, 65}
- pb.F_Fixed32Repeated = []uint32{3232, 3333}
- pb.F_Fixed64Repeated = []uint64{6464, 6565}
- pb.F_Uint32Repeated = []uint32{323232, 333333}
- pb.F_Uint64Repeated = []uint64{646464, 656565}
- pb.F_FloatRepeated = []float32{32., 33.}
- pb.F_DoubleRepeated = []float64{64., 65.}
- pb.F_StringRepeated = []string{"hello", "sailor"}
- pb.F_BytesRepeated = [][]byte{[]byte("big"), []byte("nose")}
- pb.F_Sint32Repeated = []int32{32, -32}
- pb.F_Sint64Repeated = []int64{64, -64}
- pb.Repeatedgroup = []*GoTest_RepeatedGroup{initGoTest_RepeatedGroup(), initGoTest_RepeatedGroup()}
-
- overify(t, pb,
- "0807"+ // field 1, encoding 0, value 7
- "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField)
- "2a0d"+"0a056c6162656c120474797065"+ // field 5, encoding 2 (GoTestField)
- "2a0d"+"0a056c6162656c120474797065"+ // field 5, encoding 2 (GoTestField)
- "5001"+ // field 10, encoding 0, value 1
- "5803"+ // field 11, encoding 0, value 3
- "6006"+ // field 12, encoding 0, value 6
- "6d20000000"+ // field 13, encoding 5, value 32
- "714000000000000000"+ // field 14, encoding 1, value 64
- "78a019"+ // field 15, encoding 0, value 3232
- "8001c032"+ // field 16, encoding 0, value 6464
- "8d0100004a45"+ // field 17, encoding 5, value 3232.0
- "9101000000000040b940"+ // field 18, encoding 1, value 6464.0
- "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string"
- "a00100"+ // field 20, encoding 0, value 0
- "a00101"+ // field 20, encoding 0, value 1
- "a80120"+ // field 21, encoding 0, value 32
- "a80121"+ // field 21, encoding 0, value 33
- "b00140"+ // field 22, encoding 0, value 64
- "b00141"+ // field 22, encoding 0, value 65
- "bd01a00c0000"+ // field 23, encoding 5, value 3232
- "bd01050d0000"+ // field 23, encoding 5, value 3333
- "c1014019000000000000"+ // field 24, encoding 1, value 6464
- "c101a519000000000000"+ // field 24, encoding 1, value 6565
- "c801a0dd13"+ // field 25, encoding 0, value 323232
- "c80195ac14"+ // field 25, encoding 0, value 333333
- "d001c0ba27"+ // field 26, encoding 0, value 646464
- "d001b58928"+ // field 26, encoding 0, value 656565
- "dd0100000042"+ // field 27, encoding 5, value 32.0
- "dd0100000442"+ // field 27, encoding 5, value 33.0
- "e1010000000000005040"+ // field 28, encoding 1, value 64.0
- "e1010000000000405040"+ // field 28, encoding 1, value 65.0
- "ea0105"+"68656c6c6f"+ // field 29, encoding 2, string "hello"
- "ea0106"+"7361696c6f72"+ // field 29, encoding 2, string "sailor"
- "c00201"+ // field 40, encoding 0, value 1
- "c80220"+ // field 41, encoding 0, value 32
- "d00240"+ // field 42, encoding 0, value 64
- "dd0240010000"+ // field 43, encoding 5, value 320
- "e1028002000000000000"+ // field 44, encoding 1, value 640
- "e8028019"+ // field 45, encoding 0, value 3200
- "f0028032"+ // field 46, encoding 0, value 6400
- "fd02e0659948"+ // field 47, encoding 5, value 314159.0
- "81030000000050971041"+ // field 48, encoding 1, value 271828.0
- "8a0310"+"68656c6c6f2c2022776f726c6421220a"+ // field 49, encoding 2 string "hello, \"world!\"\n"
- "b304"+ // start group field 70 level 1
- "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required"
- "b404"+ // end group field 70 level 1
- "8305"+ // start group field 80 level 1
- "8a0508"+"7265706561746564"+ // field 81, encoding 2, string "repeated"
- "8405"+ // end group field 80 level 1
- "8305"+ // start group field 80 level 1
- "8a0508"+"7265706561746564"+ // field 81, encoding 2, string "repeated"
- "8405"+ // end group field 80 level 1
- "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes"
- "b0063f"+ // field 102, encoding 0, 0x3f zigzag32
- "b8067f"+ // field 103, encoding 0, 0x7f zigzag64
- "ca0c03"+"626967"+ // field 201, encoding 2, string "big"
- "ca0c04"+"6e6f7365"+ // field 201, encoding 2, string "nose"
- "d00c40"+ // field 202, encoding 0, value 32
- "d00c3f"+ // field 202, encoding 0, value -32
- "d80c8001"+ // field 203, encoding 0, value 64
- "d80c7f"+ // field 203, encoding 0, value -64
- "8a1907"+"4269676e6f7365"+ // field 401, encoding 2, string "Bignose"
- "90193f"+ // field 402, encoding 0, value 63
- "98197f") // field 403, encoding 0, value 127
-
-}
-
-// All required fields set, all packed repeated fields given two values.
-func TestEncodeDecode6(t *testing.T) {
- pb := initGoTest(false)
- pb.F_BoolRepeatedPacked = []bool{false, true}
- pb.F_Int32RepeatedPacked = []int32{32, 33}
- pb.F_Int64RepeatedPacked = []int64{64, 65}
- pb.F_Fixed32RepeatedPacked = []uint32{3232, 3333}
- pb.F_Fixed64RepeatedPacked = []uint64{6464, 6565}
- pb.F_Uint32RepeatedPacked = []uint32{323232, 333333}
- pb.F_Uint64RepeatedPacked = []uint64{646464, 656565}
- pb.F_FloatRepeatedPacked = []float32{32., 33.}
- pb.F_DoubleRepeatedPacked = []float64{64., 65.}
- pb.F_Sint32RepeatedPacked = []int32{32, -32}
- pb.F_Sint64RepeatedPacked = []int64{64, -64}
-
- overify(t, pb,
- "0807"+ // field 1, encoding 0, value 7
- "220d"+"0a056c6162656c120474797065"+ // field 4, encoding 2 (GoTestField)
- "5001"+ // field 10, encoding 0, value 1
- "5803"+ // field 11, encoding 0, value 3
- "6006"+ // field 12, encoding 0, value 6
- "6d20000000"+ // field 13, encoding 5, value 32
- "714000000000000000"+ // field 14, encoding 1, value 64
- "78a019"+ // field 15, encoding 0, value 3232
- "8001c032"+ // field 16, encoding 0, value 6464
- "8d0100004a45"+ // field 17, encoding 5, value 3232.0
- "9101000000000040b940"+ // field 18, encoding 1, value 6464.0
- "9a0106"+"737472696e67"+ // field 19, encoding 2 string "string"
- "9203020001"+ // field 50, encoding 2, 2 bytes, value 0, value 1
- "9a03022021"+ // field 51, encoding 2, 2 bytes, value 32, value 33
- "a203024041"+ // field 52, encoding 2, 2 bytes, value 64, value 65
- "aa0308"+ // field 53, encoding 2, 8 bytes
- "a00c0000050d0000"+ // value 3232, value 3333
- "b20310"+ // field 54, encoding 2, 16 bytes
- "4019000000000000a519000000000000"+ // value 6464, value 6565
- "ba0306"+ // field 55, encoding 2, 6 bytes
- "a0dd1395ac14"+ // value 323232, value 333333
- "c20306"+ // field 56, encoding 2, 6 bytes
- "c0ba27b58928"+ // value 646464, value 656565
- "ca0308"+ // field 57, encoding 2, 8 bytes
- "0000004200000442"+ // value 32.0, value 33.0
- "d20310"+ // field 58, encoding 2, 16 bytes
- "00000000000050400000000000405040"+ // value 64.0, value 65.0
- "b304"+ // start group field 70 level 1
- "ba0408"+"7265717569726564"+ // field 71, encoding 2, string "required"
- "b404"+ // end group field 70 level 1
- "aa0605"+"6279746573"+ // field 101, encoding 2 string "bytes"
- "b0063f"+ // field 102, encoding 0, 0x3f zigzag32
- "b8067f"+ // field 103, encoding 0, 0x7f zigzag64
- "b21f02"+ // field 502, encoding 2, 2 bytes
- "403f"+ // value 32, value -32
- "ba1f03"+ // field 503, encoding 2, 3 bytes
- "80017f") // value 64, value -64
-}
-
-// Test that we can encode empty bytes fields.
-func TestEncodeDecodeBytes1(t *testing.T) {
- pb := initGoTest(false)
-
- // Create our bytes
- pb.F_BytesRequired = []byte{}
- pb.F_BytesRepeated = [][]byte{{}}
- pb.F_BytesOptional = []byte{}
-
- d, err := Marshal(pb)
- if err != nil {
- t.Error(err)
- }
-
- pbd := new(GoTest)
- if err := Unmarshal(d, pbd); err != nil {
- t.Error(err)
- }
-
- if pbd.F_BytesRequired == nil || len(pbd.F_BytesRequired) != 0 {
- t.Error("required empty bytes field is incorrect")
- }
- if pbd.F_BytesRepeated == nil || len(pbd.F_BytesRepeated) == 1 && pbd.F_BytesRepeated[0] == nil {
- t.Error("repeated empty bytes field is incorrect")
- }
- if pbd.F_BytesOptional == nil || len(pbd.F_BytesOptional) != 0 {
- t.Error("optional empty bytes field is incorrect")
- }
-}
-
-// Test that we encode nil-valued fields of a repeated bytes field correctly.
-// Since entries in a repeated field cannot be nil, nil must mean empty value.
-func TestEncodeDecodeBytes2(t *testing.T) {
- pb := initGoTest(false)
-
- // Create our bytes
- pb.F_BytesRepeated = [][]byte{nil}
-
- d, err := Marshal(pb)
- if err != nil {
- t.Error(err)
- }
-
- pbd := new(GoTest)
- if err := Unmarshal(d, pbd); err != nil {
- t.Error(err)
- }
-
- if len(pbd.F_BytesRepeated) != 1 || pbd.F_BytesRepeated[0] == nil {
- t.Error("Unexpected value for repeated bytes field")
- }
-}
-
-// All required fields set, defaults provided, all repeated fields given two values.
-func TestSkippingUnrecognizedFields(t *testing.T) {
- o := old()
- pb := initGoTestField()
-
- // Marshal it normally.
- o.Marshal(pb)
-
- // Now new a GoSkipTest record.
- skip := &GoSkipTest{
- SkipInt32: Int32(32),
- SkipFixed32: Uint32(3232),
- SkipFixed64: Uint64(6464),
- SkipString: String("skipper"),
- Skipgroup: &GoSkipTest_SkipGroup{
- GroupInt32: Int32(75),
- GroupString: String("wxyz"),
- },
- }
-
- // Marshal it into same buffer.
- o.Marshal(skip)
-
- pbd := new(GoTestField)
- o.Unmarshal(pbd)
-
- // The __unrecognized field should be a marshaling of GoSkipTest
- skipd := new(GoSkipTest)
-
- o.SetBuf(pbd.XXX_unrecognized)
- o.Unmarshal(skipd)
-
- if *skipd.SkipInt32 != *skip.SkipInt32 {
- t.Error("skip int32", skipd.SkipInt32)
- }
- if *skipd.SkipFixed32 != *skip.SkipFixed32 {
- t.Error("skip fixed32", skipd.SkipFixed32)
- }
- if *skipd.SkipFixed64 != *skip.SkipFixed64 {
- t.Error("skip fixed64", skipd.SkipFixed64)
- }
- if *skipd.SkipString != *skip.SkipString {
- t.Error("skip string", *skipd.SkipString)
- }
- if *skipd.Skipgroup.GroupInt32 != *skip.Skipgroup.GroupInt32 {
- t.Error("skip group int32", skipd.Skipgroup.GroupInt32)
- }
- if *skipd.Skipgroup.GroupString != *skip.Skipgroup.GroupString {
- t.Error("skip group string", *skipd.Skipgroup.GroupString)
- }
-}
-
-// Check that unrecognized fields of a submessage are preserved.
-func TestSubmessageUnrecognizedFields(t *testing.T) {
- nm := &NewMessage{
- Nested: &NewMessage_Nested{
- Name: String("Nigel"),
- FoodGroup: String("carbs"),
- },
- }
- b, err := Marshal(nm)
- if err != nil {
- t.Fatalf("Marshal of NewMessage: %v", err)
- }
-
- // Unmarshal into an OldMessage.
- om := new(OldMessage)
- if err := Unmarshal(b, om); err != nil {
- t.Fatalf("Unmarshal to OldMessage: %v", err)
- }
- exp := &OldMessage{
- Nested: &OldMessage_Nested{
- Name: String("Nigel"),
- // normal protocol buffer users should not do this
- XXX_unrecognized: []byte("\x12\x05carbs"),
- },
- }
- if !Equal(om, exp) {
- t.Errorf("om = %v, want %v", om, exp)
- }
-
- // Clone the OldMessage.
- om = Clone(om).(*OldMessage)
- if !Equal(om, exp) {
- t.Errorf("Clone(om) = %v, want %v", om, exp)
- }
-
- // Marshal the OldMessage, then unmarshal it into an empty NewMessage.
- if b, err = Marshal(om); err != nil {
- t.Fatalf("Marshal of OldMessage: %v", err)
- }
- t.Logf("Marshal(%v) -> %q", om, b)
- nm2 := new(NewMessage)
- if err := Unmarshal(b, nm2); err != nil {
- t.Fatalf("Unmarshal to NewMessage: %v", err)
- }
- if !Equal(nm, nm2) {
- t.Errorf("NewMessage round-trip: %v => %v", nm, nm2)
- }
-}
-
-// Check that an int32 field can be upgraded to an int64 field.
-func TestNegativeInt32(t *testing.T) {
- om := &OldMessage{
- Num: Int32(-1),
- }
- b, err := Marshal(om)
- if err != nil {
- t.Fatalf("Marshal of OldMessage: %v", err)
- }
-
- // Check the size. It should be 11 bytes;
- // 1 for the field/wire type, and 10 for the negative number.
- if len(b) != 11 {
- t.Errorf("%v marshaled as %q, wanted 11 bytes", om, b)
- }
-
- // Unmarshal into a NewMessage.
- nm := new(NewMessage)
- if err := Unmarshal(b, nm); err != nil {
- t.Fatalf("Unmarshal to NewMessage: %v", err)
- }
- want := &NewMessage{
- Num: Int64(-1),
- }
- if !Equal(nm, want) {
- t.Errorf("nm = %v, want %v", nm, want)
- }
-}
-
-// Check that we can grow an array (repeated field) to have many elements.
-// This test doesn't depend only on our encoding; for variety, it makes sure
-// we create, encode, and decode the correct contents explicitly. It's therefore
-// a bit messier.
-// This test also uses (and hence tests) the Marshal/Unmarshal functions
-// instead of the methods.
-func TestBigRepeated(t *testing.T) {
- pb := initGoTest(true)
-
- // Create the arrays
- const N = 50 // Internally the library starts much smaller.
- pb.Repeatedgroup = make([]*GoTest_RepeatedGroup, N)
- pb.F_Sint64Repeated = make([]int64, N)
- pb.F_Sint32Repeated = make([]int32, N)
- pb.F_BytesRepeated = make([][]byte, N)
- pb.F_StringRepeated = make([]string, N)
- pb.F_DoubleRepeated = make([]float64, N)
- pb.F_FloatRepeated = make([]float32, N)
- pb.F_Uint64Repeated = make([]uint64, N)
- pb.F_Uint32Repeated = make([]uint32, N)
- pb.F_Fixed64Repeated = make([]uint64, N)
- pb.F_Fixed32Repeated = make([]uint32, N)
- pb.F_Int64Repeated = make([]int64, N)
- pb.F_Int32Repeated = make([]int32, N)
- pb.F_BoolRepeated = make([]bool, N)
- pb.RepeatedField = make([]*GoTestField, N)
-
- // Fill in the arrays with checkable values.
- igtf := initGoTestField()
- igtrg := initGoTest_RepeatedGroup()
- for i := 0; i < N; i++ {
- pb.Repeatedgroup[i] = igtrg
- pb.F_Sint64Repeated[i] = int64(i)
- pb.F_Sint32Repeated[i] = int32(i)
- s := fmt.Sprint(i)
- pb.F_BytesRepeated[i] = []byte(s)
- pb.F_StringRepeated[i] = s
- pb.F_DoubleRepeated[i] = float64(i)
- pb.F_FloatRepeated[i] = float32(i)
- pb.F_Uint64Repeated[i] = uint64(i)
- pb.F_Uint32Repeated[i] = uint32(i)
- pb.F_Fixed64Repeated[i] = uint64(i)
- pb.F_Fixed32Repeated[i] = uint32(i)
- pb.F_Int64Repeated[i] = int64(i)
- pb.F_Int32Repeated[i] = int32(i)
- pb.F_BoolRepeated[i] = i%2 == 0
- pb.RepeatedField[i] = igtf
- }
-
- // Marshal.
- buf, _ := Marshal(pb)
-
- // Now test Unmarshal by recreating the original buffer.
- pbd := new(GoTest)
- Unmarshal(buf, pbd)
-
- // Check the checkable values
- for i := uint64(0); i < N; i++ {
- if pbd.Repeatedgroup[i] == nil { // TODO: more checking?
- t.Error("pbd.Repeatedgroup bad")
- }
- var x uint64
- x = uint64(pbd.F_Sint64Repeated[i])
- if x != i {
- t.Error("pbd.F_Sint64Repeated bad", x, i)
- }
- x = uint64(pbd.F_Sint32Repeated[i])
- if x != i {
- t.Error("pbd.F_Sint32Repeated bad", x, i)
- }
- s := fmt.Sprint(i)
- equalbytes(pbd.F_BytesRepeated[i], []byte(s), t)
- if pbd.F_StringRepeated[i] != s {
- t.Error("pbd.F_Sint32Repeated bad", pbd.F_StringRepeated[i], i)
- }
- x = uint64(pbd.F_DoubleRepeated[i])
- if x != i {
- t.Error("pbd.F_DoubleRepeated bad", x, i)
- }
- x = uint64(pbd.F_FloatRepeated[i])
- if x != i {
- t.Error("pbd.F_FloatRepeated bad", x, i)
- }
- x = pbd.F_Uint64Repeated[i]
- if x != i {
- t.Error("pbd.F_Uint64Repeated bad", x, i)
- }
- x = uint64(pbd.F_Uint32Repeated[i])
- if x != i {
- t.Error("pbd.F_Uint32Repeated bad", x, i)
- }
- x = pbd.F_Fixed64Repeated[i]
- if x != i {
- t.Error("pbd.F_Fixed64Repeated bad", x, i)
- }
- x = uint64(pbd.F_Fixed32Repeated[i])
- if x != i {
- t.Error("pbd.F_Fixed32Repeated bad", x, i)
- }
- x = uint64(pbd.F_Int64Repeated[i])
- if x != i {
- t.Error("pbd.F_Int64Repeated bad", x, i)
- }
- x = uint64(pbd.F_Int32Repeated[i])
- if x != i {
- t.Error("pbd.F_Int32Repeated bad", x, i)
- }
- if pbd.F_BoolRepeated[i] != (i%2 == 0) {
- t.Error("pbd.F_BoolRepeated bad", x, i)
- }
- if pbd.RepeatedField[i] == nil { // TODO: more checking?
- t.Error("pbd.RepeatedField bad")
- }
- }
-}
-
-// Verify we give a useful message when decoding to the wrong structure type.
-func TestTypeMismatch(t *testing.T) {
- pb1 := initGoTest(true)
-
- // Marshal
- o := old()
- o.Marshal(pb1)
-
- // Now Unmarshal it to the wrong type.
- pb2 := initGoTestField()
- err := o.Unmarshal(pb2)
- if err == nil {
- t.Error("expected error, got no error")
- } else if !strings.Contains(err.Error(), "bad wiretype") {
- t.Error("expected bad wiretype error, got", err)
- }
-}
-
-func encodeDecode(t *testing.T, in, out Message, msg string) {
- buf, err := Marshal(in)
- if err != nil {
- t.Fatalf("failed marshaling %v: %v", msg, err)
- }
- if err := Unmarshal(buf, out); err != nil {
- t.Fatalf("failed unmarshaling %v: %v", msg, err)
- }
-}
-
-func TestPackedNonPackedDecoderSwitching(t *testing.T) {
- np, p := new(NonPackedTest), new(PackedTest)
-
- // non-packed -> packed
- np.A = []int32{0, 1, 1, 2, 3, 5}
- encodeDecode(t, np, p, "non-packed -> packed")
- if !reflect.DeepEqual(np.A, p.B) {
- t.Errorf("failed non-packed -> packed; np.A=%+v, p.B=%+v", np.A, p.B)
- }
-
- // packed -> non-packed
- np.Reset()
- p.B = []int32{3, 1, 4, 1, 5, 9}
- encodeDecode(t, p, np, "packed -> non-packed")
- if !reflect.DeepEqual(p.B, np.A) {
- t.Errorf("failed packed -> non-packed; p.B=%+v, np.A=%+v", p.B, np.A)
- }
-}
-
-func TestProto1RepeatedGroup(t *testing.T) {
- pb := &MessageList{
- Message: []*MessageList_Message{
- {
- Name: String("blah"),
- Count: Int32(7),
- },
- // NOTE: pb.Message[1] is a nil
- nil,
- },
- }
-
- o := old()
- err := o.Marshal(pb)
- if err == nil || !strings.Contains(err.Error(), "repeated field Message has nil") {
- t.Fatalf("unexpected or no error when marshaling: %v", err)
- }
-}
-
-// Test that enums work. Checks for a bug introduced by making enums
-// named types instead of int32: newInt32FromUint64 would crash with
-// a type mismatch in reflect.PointTo.
-func TestEnum(t *testing.T) {
- pb := new(GoEnum)
- pb.Foo = FOO_FOO1.Enum()
- o := old()
- if err := o.Marshal(pb); err != nil {
- t.Fatal("error encoding enum:", err)
- }
- pb1 := new(GoEnum)
- if err := o.Unmarshal(pb1); err != nil {
- t.Fatal("error decoding enum:", err)
- }
- if *pb1.Foo != FOO_FOO1 {
- t.Error("expected 7 but got ", *pb1.Foo)
- }
-}
-
-// Enum types have String methods. Check that enum fields can be printed.
-// We don't care what the value actually is, just as long as it doesn't crash.
-func TestPrintingNilEnumFields(t *testing.T) {
- pb := new(GoEnum)
- fmt.Sprintf("%+v", pb)
-}
-
-// Verify that absent required fields cause Marshal/Unmarshal to return errors.
-func TestRequiredFieldEnforcement(t *testing.T) {
- pb := new(GoTestField)
- _, err := Marshal(pb)
- if err == nil {
- t.Error("marshal: expected error, got nil")
- } else if strings.Index(err.Error(), "Label") < 0 {
- t.Errorf("marshal: bad error type: %v", err)
- }
-
- // A slightly sneaky, yet valid, proto. It encodes the same required field twice,
- // so simply counting the required fields is insufficient.
- // field 1, encoding 2, value "hi"
- buf := []byte("\x0A\x02hi\x0A\x02hi")
- err = Unmarshal(buf, pb)
- if err == nil {
- t.Error("unmarshal: expected error, got nil")
- } else if strings.Index(err.Error(), "{Unknown}") < 0 {
- t.Errorf("unmarshal: bad error type: %v", err)
- }
-}
-
-func TestTypedNilMarshal(t *testing.T) {
- // A typed nil should return ErrNil and not crash.
- _, err := Marshal((*GoEnum)(nil))
- if err != ErrNil {
- t.Errorf("Marshal: got err %v, want ErrNil", err)
- }
-}
-
-// A type that implements the Marshaler interface, but is not nillable.
-type nonNillableInt uint64
-
-func (nni nonNillableInt) Marshal() ([]byte, error) {
- return EncodeVarint(uint64(nni)), nil
-}
-
-type NNIMessage struct {
- nni nonNillableInt
-}
-
-func (*NNIMessage) Reset() {}
-func (*NNIMessage) String() string { return "" }
-func (*NNIMessage) ProtoMessage() {}
-
-// A type that implements the Marshaler interface and is nillable.
-type nillableMessage struct {
- x uint64
-}
-
-func (nm *nillableMessage) Marshal() ([]byte, error) {
- return EncodeVarint(nm.x), nil
-}
-
-type NMMessage struct {
- nm *nillableMessage
-}
-
-func (*NMMessage) Reset() {}
-func (*NMMessage) String() string { return "" }
-func (*NMMessage) ProtoMessage() {}
-
-// Verify a type that uses the Marshaler interface, but has a nil pointer.
-func TestNilMarshaler(t *testing.T) {
- // Try a struct with a Marshaler field that is nil.
- // It should be directly marshable.
- nmm := new(NMMessage)
- if _, err := Marshal(nmm); err != nil {
- t.Error("unexpected error marshaling nmm: ", err)
- }
-
- // Try a struct with a Marshaler field that is not nillable.
- nnim := new(NNIMessage)
- nnim.nni = 7
- var _ Marshaler = nnim.nni // verify it is truly a Marshaler
- if _, err := Marshal(nnim); err != nil {
- t.Error("unexpected error marshaling nnim: ", err)
- }
-}
-
-func TestAllSetDefaults(t *testing.T) {
- // Exercise SetDefaults with all scalar field types.
- m := &Defaults{
- // NaN != NaN, so override that here.
- F_Nan: Float32(1.7),
- }
- expected := &Defaults{
- F_Bool: Bool(true),
- F_Int32: Int32(32),
- F_Int64: Int64(64),
- F_Fixed32: Uint32(320),
- F_Fixed64: Uint64(640),
- F_Uint32: Uint32(3200),
- F_Uint64: Uint64(6400),
- F_Float: Float32(314159),
- F_Double: Float64(271828),
- F_String: String(`hello, "world!"` + "\n"),
- F_Bytes: []byte("Bignose"),
- F_Sint32: Int32(-32),
- F_Sint64: Int64(-64),
- F_Enum: Defaults_GREEN.Enum(),
- F_Pinf: Float32(float32(math.Inf(1))),
- F_Ninf: Float32(float32(math.Inf(-1))),
- F_Nan: Float32(1.7),
- StrZero: String(""),
- }
- SetDefaults(m)
- if !Equal(m, expected) {
- t.Errorf("SetDefaults failed\n got %v\nwant %v", m, expected)
- }
-}
-
-func TestSetDefaultsWithSetField(t *testing.T) {
- // Check that a set value is not overridden.
- m := &Defaults{
- F_Int32: Int32(12),
- }
- SetDefaults(m)
- if v := m.GetF_Int32(); v != 12 {
- t.Errorf("m.FInt32 = %v, want 12", v)
- }
-}
-
-func TestSetDefaultsWithSubMessage(t *testing.T) {
- m := &OtherMessage{
- Key: Int64(123),
- Inner: &InnerMessage{
- Host: String("gopher"),
- },
- }
- expected := &OtherMessage{
- Key: Int64(123),
- Inner: &InnerMessage{
- Host: String("gopher"),
- Port: Int32(4000),
- },
- }
- SetDefaults(m)
- if !Equal(m, expected) {
- t.Errorf("\n got %v\nwant %v", m, expected)
- }
-}
-
-func TestSetDefaultsWithRepeatedSubMessage(t *testing.T) {
- m := &MyMessage{
- RepInner: []*InnerMessage{{}},
- }
- expected := &MyMessage{
- RepInner: []*InnerMessage{{
- Port: Int32(4000),
- }},
- }
- SetDefaults(m)
- if !Equal(m, expected) {
- t.Errorf("\n got %v\nwant %v", m, expected)
- }
-}
-
-func TestSetDefaultWithRepeatedNonMessage(t *testing.T) {
- m := &MyMessage{
- Pet: []string{"turtle", "wombat"},
- }
- expected := Clone(m)
- SetDefaults(m)
- if !Equal(m, expected) {
- t.Errorf("\n got %v\nwant %v", m, expected)
- }
-}
-
-func TestMaximumTagNumber(t *testing.T) {
- m := &MaxTag{
- LastField: String("natural goat essence"),
- }
- buf, err := Marshal(m)
- if err != nil {
- t.Fatalf("proto.Marshal failed: %v", err)
- }
- m2 := new(MaxTag)
- if err := Unmarshal(buf, m2); err != nil {
- t.Fatalf("proto.Unmarshal failed: %v", err)
- }
- if got, want := m2.GetLastField(), *m.LastField; got != want {
- t.Errorf("got %q, want %q", got, want)
- }
-}
-
-func TestJSON(t *testing.T) {
- m := &MyMessage{
- Count: Int32(4),
- Pet: []string{"bunny", "kitty"},
- Inner: &InnerMessage{
- Host: String("cauchy"),
- },
- Bikeshed: MyMessage_GREEN.Enum(),
- }
- const expected = `{"count":4,"pet":["bunny","kitty"],"inner":{"host":"cauchy"},"bikeshed":1}`
-
- b, err := json.Marshal(m)
- if err != nil {
- t.Fatalf("json.Marshal failed: %v", err)
- }
- s := string(b)
- if s != expected {
- t.Errorf("got %s\nwant %s", s, expected)
- }
-
- received := new(MyMessage)
- if err := json.Unmarshal(b, received); err != nil {
- t.Fatalf("json.Unmarshal failed: %v", err)
- }
- if !Equal(received, m) {
- t.Fatalf("got %s, want %s", received, m)
- }
-
- // Test unmarshalling of JSON with symbolic enum name.
- const old = `{"count":4,"pet":["bunny","kitty"],"inner":{"host":"cauchy"},"bikeshed":"GREEN"}`
- received.Reset()
- if err := json.Unmarshal([]byte(old), received); err != nil {
- t.Fatalf("json.Unmarshal failed: %v", err)
- }
- if !Equal(received, m) {
- t.Fatalf("got %s, want %s", received, m)
- }
-}
-
-func TestBadWireType(t *testing.T) {
- b := []byte{7<<3 | 6} // field 7, wire type 6
- pb := new(OtherMessage)
- if err := Unmarshal(b, pb); err == nil {
- t.Errorf("Unmarshal did not fail")
- } else if !strings.Contains(err.Error(), "unknown wire type") {
- t.Errorf("wrong error: %v", err)
- }
-}
-
-func TestBytesWithInvalidLength(t *testing.T) {
- // If a byte sequence has an invalid (negative) length, Unmarshal should not panic.
- b := []byte{2<<3 | WireBytes, 0xff, 0xff, 0xff, 0xff, 0xff, 0}
- Unmarshal(b, new(MyMessage))
-}
-
-func TestLengthOverflow(t *testing.T) {
- // Overflowing a length should not panic.
- b := []byte{2<<3 | WireBytes, 1, 1, 3<<3 | WireBytes, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x7f, 0x01}
- Unmarshal(b, new(MyMessage))
-}
-
-func TestVarintOverflow(t *testing.T) {
- // Overflowing a 64-bit length should not be allowed.
- b := []byte{1<<3 | WireVarint, 0x01, 3<<3 | WireBytes, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x01}
- if err := Unmarshal(b, new(MyMessage)); err == nil {
- t.Fatalf("Overflowed uint64 length without error")
- }
-}
-
-func TestUnmarshalFuzz(t *testing.T) {
- const N = 1000
- seed := time.Now().UnixNano()
- t.Logf("RNG seed is %d", seed)
- rng := rand.New(rand.NewSource(seed))
- buf := make([]byte, 20)
- for i := 0; i < N; i++ {
- for j := range buf {
- buf[j] = byte(rng.Intn(256))
- }
- fuzzUnmarshal(t, buf)
- }
-}
-
-func TestMergeMessages(t *testing.T) {
- pb := &MessageList{Message: []*MessageList_Message{{Name: String("x"), Count: Int32(1)}}}
- data, err := Marshal(pb)
- if err != nil {
- t.Fatalf("Marshal: %v", err)
- }
-
- pb1 := new(MessageList)
- if err := Unmarshal(data, pb1); err != nil {
- t.Fatalf("first Unmarshal: %v", err)
- }
- if err := Unmarshal(data, pb1); err != nil {
- t.Fatalf("second Unmarshal: %v", err)
- }
- if len(pb1.Message) != 1 {
- t.Errorf("two Unmarshals produced %d Messages, want 1", len(pb1.Message))
- }
-
- pb2 := new(MessageList)
- if err := UnmarshalMerge(data, pb2); err != nil {
- t.Fatalf("first UnmarshalMerge: %v", err)
- }
- if err := UnmarshalMerge(data, pb2); err != nil {
- t.Fatalf("second UnmarshalMerge: %v", err)
- }
- if len(pb2.Message) != 2 {
- t.Errorf("two UnmarshalMerges produced %d Messages, want 2", len(pb2.Message))
- }
-}
-
-func TestExtensionMarshalOrder(t *testing.T) {
- m := &MyMessage{Count: Int(123)}
- if err := SetExtension(m, E_Ext_More, &Ext{Data: String("alpha")}); err != nil {
- t.Fatalf("SetExtension: %v", err)
- }
- if err := SetExtension(m, E_Ext_Text, String("aleph")); err != nil {
- t.Fatalf("SetExtension: %v", err)
- }
- if err := SetExtension(m, E_Ext_Number, Int32(1)); err != nil {
- t.Fatalf("SetExtension: %v", err)
- }
-
- // Serialize m several times, and check we get the same bytes each time.
- var orig []byte
- for i := 0; i < 100; i++ {
- b, err := Marshal(m)
- if err != nil {
- t.Fatalf("Marshal: %v", err)
- }
- if i == 0 {
- orig = b
- continue
- }
- if !bytes.Equal(b, orig) {
- t.Errorf("Bytes differ on attempt #%d", i)
- }
- }
-}
-
-// Many extensions, because small maps might not iterate differently on each iteration.
-var exts = []*ExtensionDesc{
- E_X201,
- E_X202,
- E_X203,
- E_X204,
- E_X205,
- E_X206,
- E_X207,
- E_X208,
- E_X209,
- E_X210,
- E_X211,
- E_X212,
- E_X213,
- E_X214,
- E_X215,
- E_X216,
- E_X217,
- E_X218,
- E_X219,
- E_X220,
- E_X221,
- E_X222,
- E_X223,
- E_X224,
- E_X225,
- E_X226,
- E_X227,
- E_X228,
- E_X229,
- E_X230,
- E_X231,
- E_X232,
- E_X233,
- E_X234,
- E_X235,
- E_X236,
- E_X237,
- E_X238,
- E_X239,
- E_X240,
- E_X241,
- E_X242,
- E_X243,
- E_X244,
- E_X245,
- E_X246,
- E_X247,
- E_X248,
- E_X249,
- E_X250,
-}
-
-func TestMessageSetMarshalOrder(t *testing.T) {
- m := &MyMessageSet{}
- for _, x := range exts {
- if err := SetExtension(m, x, &Empty{}); err != nil {
- t.Fatalf("SetExtension: %v", err)
- }
- }
-
- buf, err := Marshal(m)
- if err != nil {
- t.Fatalf("Marshal: %v", err)
- }
-
- // Serialize m several times, and check we get the same bytes each time.
- for i := 0; i < 10; i++ {
- b1, err := Marshal(m)
- if err != nil {
- t.Fatalf("Marshal: %v", err)
- }
- if !bytes.Equal(b1, buf) {
- t.Errorf("Bytes differ on re-Marshal #%d", i)
- }
-
- m2 := &MyMessageSet{}
- if err := Unmarshal(buf, m2); err != nil {
- t.Errorf("Unmarshal: %v", err)
- }
- b2, err := Marshal(m2)
- if err != nil {
- t.Errorf("re-Marshal: %v", err)
- }
- if !bytes.Equal(b2, buf) {
- t.Errorf("Bytes differ on round-trip #%d", i)
- }
- }
-}
-
-func TestUnmarshalMergesMessages(t *testing.T) {
- // If a nested message occurs twice in the input,
- // the fields should be merged when decoding.
- a := &OtherMessage{
- Key: Int64(123),
- Inner: &InnerMessage{
- Host: String("polhode"),
- Port: Int32(1234),
- },
- }
- aData, err := Marshal(a)
- if err != nil {
- t.Fatalf("Marshal(a): %v", err)
- }
- b := &OtherMessage{
- Weight: Float32(1.2),
- Inner: &InnerMessage{
- Host: String("herpolhode"),
- Connected: Bool(true),
- },
- }
- bData, err := Marshal(b)
- if err != nil {
- t.Fatalf("Marshal(b): %v", err)
- }
- want := &OtherMessage{
- Key: Int64(123),
- Weight: Float32(1.2),
- Inner: &InnerMessage{
- Host: String("herpolhode"),
- Port: Int32(1234),
- Connected: Bool(true),
- },
- }
- got := new(OtherMessage)
- if err := Unmarshal(append(aData, bData...), got); err != nil {
- t.Fatalf("Unmarshal: %v", err)
- }
- if !Equal(got, want) {
- t.Errorf("\n got %v\nwant %v", got, want)
- }
-}
-
-func TestEncodingSizes(t *testing.T) {
- tests := []struct {
- m Message
- n int
- }{
- {&Defaults{F_Int32: Int32(math.MaxInt32)}, 6},
- {&Defaults{F_Int32: Int32(math.MinInt32)}, 11},
- {&Defaults{F_Uint32: Uint32(uint32(math.MaxInt32) + 1)}, 6},
- {&Defaults{F_Uint32: Uint32(math.MaxUint32)}, 6},
- }
- for _, test := range tests {
- b, err := Marshal(test.m)
- if err != nil {
- t.Errorf("Marshal(%v): %v", test.m, err)
- continue
- }
- if len(b) != test.n {
- t.Errorf("Marshal(%v) yielded %d bytes, want %d bytes", test.m, len(b), test.n)
- }
- }
-}
-
-func TestRequiredNotSetError(t *testing.T) {
- pb := initGoTest(false)
- pb.RequiredField.Label = nil
- pb.F_Int32Required = nil
- pb.F_Int64Required = nil
-
- expected := "0807" + // field 1, encoding 0, value 7
- "2206" + "120474797065" + // field 4, encoding 2 (GoTestField)
- "5001" + // field 10, encoding 0, value 1
- "6d20000000" + // field 13, encoding 5, value 0x20
- "714000000000000000" + // field 14, encoding 1, value 0x40
- "78a019" + // field 15, encoding 0, value 0xca0 = 3232
- "8001c032" + // field 16, encoding 0, value 0x1940 = 6464
- "8d0100004a45" + // field 17, encoding 5, value 3232.0
- "9101000000000040b940" + // field 18, encoding 1, value 6464.0
- "9a0106" + "737472696e67" + // field 19, encoding 2, string "string"
- "b304" + // field 70, encoding 3, start group
- "ba0408" + "7265717569726564" + // field 71, encoding 2, string "required"
- "b404" + // field 70, encoding 4, end group
- "aa0605" + "6279746573" + // field 101, encoding 2, string "bytes"
- "b0063f" + // field 102, encoding 0, 0x3f zigzag32
- "b8067f" // field 103, encoding 0, 0x7f zigzag64
-
- o := old()
- bytes, err := Marshal(pb)
- if _, ok := err.(*RequiredNotSetError); !ok {
- fmt.Printf("marshal-1 err = %v, want *RequiredNotSetError", err)
- o.DebugPrint("", bytes)
- t.Fatalf("expected = %s", expected)
- }
- if strings.Index(err.Error(), "RequiredField.Label") < 0 {
- t.Errorf("marshal-1 wrong err msg: %v", err)
- }
- if !equal(bytes, expected, t) {
- o.DebugPrint("neq 1", bytes)
- t.Fatalf("expected = %s", expected)
- }
-
- // Now test Unmarshal by recreating the original buffer.
- pbd := new(GoTest)
- err = Unmarshal(bytes, pbd)
- if _, ok := err.(*RequiredNotSetError); !ok {
- t.Fatalf("unmarshal err = %v, want *RequiredNotSetError", err)
- o.DebugPrint("", bytes)
- t.Fatalf("string = %s", expected)
- }
- if strings.Index(err.Error(), "RequiredField.{Unknown}") < 0 {
- t.Errorf("unmarshal wrong err msg: %v", err)
- }
- bytes, err = Marshal(pbd)
- if _, ok := err.(*RequiredNotSetError); !ok {
- t.Errorf("marshal-2 err = %v, want *RequiredNotSetError", err)
- o.DebugPrint("", bytes)
- t.Fatalf("string = %s", expected)
- }
- if strings.Index(err.Error(), "RequiredField.Label") < 0 {
- t.Errorf("marshal-2 wrong err msg: %v", err)
- }
- if !equal(bytes, expected, t) {
- o.DebugPrint("neq 2", bytes)
- t.Fatalf("string = %s", expected)
- }
-}
-
-func fuzzUnmarshal(t *testing.T, data []byte) {
- defer func() {
- if e := recover(); e != nil {
- t.Errorf("These bytes caused a panic: %+v", data)
- t.Logf("Stack:\n%s", debug.Stack())
- t.FailNow()
- }
- }()
-
- pb := new(MyMessage)
- Unmarshal(data, pb)
-}
-
-func TestMapFieldMarshal(t *testing.T) {
- m := &MessageWithMap{
- NameMapping: map[int32]string{
- 1: "Rob",
- 4: "Ian",
- 8: "Dave",
- },
- }
- b, err := Marshal(m)
- if err != nil {
- t.Fatalf("Marshal: %v", err)
- }
-
- // b should be the concatenation of these three byte sequences in some order.
- parts := []string{
- "\n\a\b\x01\x12\x03Rob",
- "\n\a\b\x04\x12\x03Ian",
- "\n\b\b\x08\x12\x04Dave",
- }
- ok := false
- for i := range parts {
- for j := range parts {
- if j == i {
- continue
- }
- for k := range parts {
- if k == i || k == j {
- continue
- }
- try := parts[i] + parts[j] + parts[k]
- if bytes.Equal(b, []byte(try)) {
- ok = true
- break
- }
- }
- }
- }
- if !ok {
- t.Fatalf("Incorrect Marshal output.\n got %q\nwant %q (or a permutation of that)", b, parts[0]+parts[1]+parts[2])
- }
- t.Logf("FYI b: %q", b)
-
- (new(Buffer)).DebugPrint("Dump of b", b)
-}
-
-func TestMapFieldRoundTrips(t *testing.T) {
- m := &MessageWithMap{
- NameMapping: map[int32]string{
- 1: "Rob",
- 4: "Ian",
- 8: "Dave",
- },
- MsgMapping: map[int64]*FloatingPoint{
- 0x7001: &FloatingPoint{F: Float64(2.0)},
- },
- ByteMapping: map[bool][]byte{
- false: []byte("that's not right!"),
- true: []byte("aye, 'tis true!"),
- },
- }
- b, err := Marshal(m)
- if err != nil {
- t.Fatalf("Marshal: %v", err)
- }
- t.Logf("FYI b: %q", b)
- m2 := new(MessageWithMap)
- if err := Unmarshal(b, m2); err != nil {
- t.Fatalf("Unmarshal: %v", err)
- }
- for _, pair := range [][2]interface{}{
- {m.NameMapping, m2.NameMapping},
- {m.MsgMapping, m2.MsgMapping},
- {m.ByteMapping, m2.ByteMapping},
- } {
- if !reflect.DeepEqual(pair[0], pair[1]) {
- t.Errorf("Map did not survive a round trip.\ninitial: %v\n final: %v", pair[0], pair[1])
- }
- }
-}
-
-func TestMapFieldWithNil(t *testing.T) {
- m := &MessageWithMap{
- MsgMapping: map[int64]*FloatingPoint{
- 1: nil,
- },
- }
- b, err := Marshal(m)
- if err == nil {
- t.Fatalf("Marshal of bad map should have failed, got these bytes: %v", b)
- }
-}
-
-// Benchmarks
-
-func testMsg() *GoTest {
- pb := initGoTest(true)
- const N = 1000 // Internally the library starts much smaller.
- pb.F_Int32Repeated = make([]int32, N)
- pb.F_DoubleRepeated = make([]float64, N)
- for i := 0; i < N; i++ {
- pb.F_Int32Repeated[i] = int32(i)
- pb.F_DoubleRepeated[i] = float64(i)
- }
- return pb
-}
-
-func bytesMsg() *GoTest {
- pb := initGoTest(true)
- buf := make([]byte, 4000)
- for i := range buf {
- buf[i] = byte(i)
- }
- pb.F_BytesDefaulted = buf
- return pb
-}
-
-func benchmarkMarshal(b *testing.B, pb Message, marshal func(Message) ([]byte, error)) {
- d, _ := marshal(pb)
- b.SetBytes(int64(len(d)))
- b.ResetTimer()
- for i := 0; i < b.N; i++ {
- marshal(pb)
- }
-}
-
-func benchmarkBufferMarshal(b *testing.B, pb Message) {
- p := NewBuffer(nil)
- benchmarkMarshal(b, pb, func(pb0 Message) ([]byte, error) {
- p.Reset()
- err := p.Marshal(pb0)
- return p.Bytes(), err
- })
-}
-
-func benchmarkSize(b *testing.B, pb Message) {
- benchmarkMarshal(b, pb, func(pb0 Message) ([]byte, error) {
- Size(pb)
- return nil, nil
- })
-}
-
-func newOf(pb Message) Message {
- in := reflect.ValueOf(pb)
- if in.IsNil() {
- return pb
- }
- return reflect.New(in.Type().Elem()).Interface().(Message)
-}
-
-func benchmarkUnmarshal(b *testing.B, pb Message, unmarshal func([]byte, Message) error) {
- d, _ := Marshal(pb)
- b.SetBytes(int64(len(d)))
- pbd := newOf(pb)
-
- b.ResetTimer()
- for i := 0; i < b.N; i++ {
- unmarshal(d, pbd)
- }
-}
-
-func benchmarkBufferUnmarshal(b *testing.B, pb Message) {
- p := NewBuffer(nil)
- benchmarkUnmarshal(b, pb, func(d []byte, pb0 Message) error {
- p.SetBuf(d)
- return p.Unmarshal(pb0)
- })
-}
-
-// Benchmark{Marshal,BufferMarshal,Size,Unmarshal,BufferUnmarshal}{,Bytes}
-
-func BenchmarkMarshal(b *testing.B) {
- benchmarkMarshal(b, testMsg(), Marshal)
-}
-
-func BenchmarkBufferMarshal(b *testing.B) {
- benchmarkBufferMarshal(b, testMsg())
-}
-
-func BenchmarkSize(b *testing.B) {
- benchmarkSize(b, testMsg())
-}
-
-func BenchmarkUnmarshal(b *testing.B) {
- benchmarkUnmarshal(b, testMsg(), Unmarshal)
-}
-
-func BenchmarkBufferUnmarshal(b *testing.B) {
- benchmarkBufferUnmarshal(b, testMsg())
-}
-
-func BenchmarkMarshalBytes(b *testing.B) {
- benchmarkMarshal(b, bytesMsg(), Marshal)
-}
-
-func BenchmarkBufferMarshalBytes(b *testing.B) {
- benchmarkBufferMarshal(b, bytesMsg())
-}
-
-func BenchmarkSizeBytes(b *testing.B) {
- benchmarkSize(b, bytesMsg())
-}
-
-func BenchmarkUnmarshalBytes(b *testing.B) {
- benchmarkUnmarshal(b, bytesMsg(), Unmarshal)
-}
-
-func BenchmarkBufferUnmarshalBytes(b *testing.B) {
- benchmarkBufferUnmarshal(b, bytesMsg())
-}
-
-func BenchmarkUnmarshalUnrecognizedFields(b *testing.B) {
- b.StopTimer()
- pb := initGoTestField()
- skip := &GoSkipTest{
- SkipInt32: Int32(32),
- SkipFixed32: Uint32(3232),
- SkipFixed64: Uint64(6464),
- SkipString: String("skipper"),
- Skipgroup: &GoSkipTest_SkipGroup{
- GroupInt32: Int32(75),
- GroupString: String("wxyz"),
- },
- }
-
- pbd := new(GoTestField)
- p := NewBuffer(nil)
- p.Marshal(pb)
- p.Marshal(skip)
- p2 := NewBuffer(nil)
-
- b.StartTimer()
- for i := 0; i < b.N; i++ {
- p2.SetBuf(p.Bytes())
- p2.Unmarshal(pbd)
- }
-}
diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/clone.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/clone.go
deleted file mode 100644
index 915a68b8ec..0000000000
--- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/clone.go
+++ /dev/null
@@ -1,212 +0,0 @@
-// 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: MessageSet and 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 := in.Addr().Interface().(extendableProto); ok {
- emOut := out.Addr().Interface().(extendableProto)
- mergeExtension(emOut.ExtensionMap(), emIn.ExtensionMap())
- }
-
- 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.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
- }
-}
diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/clone_test.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/clone_test.go
deleted file mode 100644
index a1c697bc84..0000000000
--- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/clone_test.go
+++ /dev/null
@@ -1,245 +0,0 @@
-// 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.
-
-package proto_test
-
-import (
- "testing"
-
- "github.com/golang/protobuf/proto"
-
- proto3pb "github.com/golang/protobuf/proto/proto3_proto"
- pb "github.com/golang/protobuf/proto/testdata"
-)
-
-var cloneTestMessage = &pb.MyMessage{
- Count: proto.Int32(42),
- Name: proto.String("Dave"),
- Pet: []string{"bunny", "kitty", "horsey"},
- Inner: &pb.InnerMessage{
- Host: proto.String("niles"),
- Port: proto.Int32(9099),
- Connected: proto.Bool(true),
- },
- Others: []*pb.OtherMessage{
- {
- Value: []byte("some bytes"),
- },
- },
- Somegroup: &pb.MyMessage_SomeGroup{
- GroupField: proto.Int32(6),
- },
- RepBytes: [][]byte{[]byte("sham"), []byte("wow")},
-}
-
-func init() {
- ext := &pb.Ext{
- Data: proto.String("extension"),
- }
- if err := proto.SetExtension(cloneTestMessage, pb.E_Ext_More, ext); err != nil {
- panic("SetExtension: " + err.Error())
- }
-}
-
-func TestClone(t *testing.T) {
- m := proto.Clone(cloneTestMessage).(*pb.MyMessage)
- if !proto.Equal(m, cloneTestMessage) {
- t.Errorf("Clone(%v) = %v", cloneTestMessage, m)
- }
-
- // Verify it was a deep copy.
- *m.Inner.Port++
- if proto.Equal(m, cloneTestMessage) {
- t.Error("Mutating clone changed the original")
- }
- // Byte fields and repeated fields should be copied.
- if &m.Pet[0] == &cloneTestMessage.Pet[0] {
- t.Error("Pet: repeated field not copied")
- }
- if &m.Others[0] == &cloneTestMessage.Others[0] {
- t.Error("Others: repeated field not copied")
- }
- if &m.Others[0].Value[0] == &cloneTestMessage.Others[0].Value[0] {
- t.Error("Others[0].Value: bytes field not copied")
- }
- if &m.RepBytes[0] == &cloneTestMessage.RepBytes[0] {
- t.Error("RepBytes: repeated field not copied")
- }
- if &m.RepBytes[0][0] == &cloneTestMessage.RepBytes[0][0] {
- t.Error("RepBytes[0]: bytes field not copied")
- }
-}
-
-func TestCloneNil(t *testing.T) {
- var m *pb.MyMessage
- if c := proto.Clone(m); !proto.Equal(m, c) {
- t.Errorf("Clone(%v) = %v", m, c)
- }
-}
-
-var mergeTests = []struct {
- src, dst, want proto.Message
-}{
- {
- src: &pb.MyMessage{
- Count: proto.Int32(42),
- },
- dst: &pb.MyMessage{
- Name: proto.String("Dave"),
- },
- want: &pb.MyMessage{
- Count: proto.Int32(42),
- Name: proto.String("Dave"),
- },
- },
- {
- src: &pb.MyMessage{
- Inner: &pb.InnerMessage{
- Host: proto.String("hey"),
- Connected: proto.Bool(true),
- },
- Pet: []string{"horsey"},
- Others: []*pb.OtherMessage{
- {
- Value: []byte("some bytes"),
- },
- },
- },
- dst: &pb.MyMessage{
- Inner: &pb.InnerMessage{
- Host: proto.String("niles"),
- Port: proto.Int32(9099),
- },
- Pet: []string{"bunny", "kitty"},
- Others: []*pb.OtherMessage{
- {
- Key: proto.Int64(31415926535),
- },
- {
- // Explicitly test a src=nil field
- Inner: nil,
- },
- },
- },
- want: &pb.MyMessage{
- Inner: &pb.InnerMessage{
- Host: proto.String("hey"),
- Connected: proto.Bool(true),
- Port: proto.Int32(9099),
- },
- Pet: []string{"bunny", "kitty", "horsey"},
- Others: []*pb.OtherMessage{
- {
- Key: proto.Int64(31415926535),
- },
- {},
- {
- Value: []byte("some bytes"),
- },
- },
- },
- },
- {
- src: &pb.MyMessage{
- RepBytes: [][]byte{[]byte("wow")},
- },
- dst: &pb.MyMessage{
- Somegroup: &pb.MyMessage_SomeGroup{
- GroupField: proto.Int32(6),
- },
- RepBytes: [][]byte{[]byte("sham")},
- },
- want: &pb.MyMessage{
- Somegroup: &pb.MyMessage_SomeGroup{
- GroupField: proto.Int32(6),
- },
- RepBytes: [][]byte{[]byte("sham"), []byte("wow")},
- },
- },
- // Check that a scalar bytes field replaces rather than appends.
- {
- src: &pb.OtherMessage{Value: []byte("foo")},
- dst: &pb.OtherMessage{Value: []byte("bar")},
- want: &pb.OtherMessage{Value: []byte("foo")},
- },
- {
- src: &pb.MessageWithMap{
- NameMapping: map[int32]string{6: "Nigel"},
- MsgMapping: map[int64]*pb.FloatingPoint{
- 0x4001: &pb.FloatingPoint{F: proto.Float64(2.0)},
- },
- ByteMapping: map[bool][]byte{true: []byte("wowsa")},
- },
- dst: &pb.MessageWithMap{
- NameMapping: map[int32]string{
- 6: "Bruce", // should be overwritten
- 7: "Andrew",
- },
- },
- want: &pb.MessageWithMap{
- NameMapping: map[int32]string{
- 6: "Nigel",
- 7: "Andrew",
- },
- MsgMapping: map[int64]*pb.FloatingPoint{
- 0x4001: &pb.FloatingPoint{F: proto.Float64(2.0)},
- },
- ByteMapping: map[bool][]byte{true: []byte("wowsa")},
- },
- },
- // proto3 shouldn't merge zero values,
- // in the same way that proto2 shouldn't merge nils.
- {
- src: &proto3pb.Message{
- Name: "Aaron",
- Data: []byte(""), // zero value, but not nil
- },
- dst: &proto3pb.Message{
- HeightInCm: 176,
- Data: []byte("texas!"),
- },
- want: &proto3pb.Message{
- Name: "Aaron",
- HeightInCm: 176,
- Data: []byte("texas!"),
- },
- },
-}
-
-func TestMerge(t *testing.T) {
- for _, m := range mergeTests {
- got := proto.Clone(m.dst)
- proto.Merge(got, m.src)
- if !proto.Equal(got, m.want) {
- t.Errorf("Merge(%v, %v)\n got %v\nwant %v\n", m.dst, m.src, got, m.want)
- }
- }
-}
diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/decode.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/decode.go
deleted file mode 100644
index bf71dcad10..0000000000
--- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/decode.go
+++ /dev/null
@@ -1,827 +0,0 @@
-// 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")
-
-// 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) {
- // x, n already 0
- 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
-}
-
-// 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) {
- // x, err already 0
-
- 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
-}
-
-// 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)
-}
-
-// 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.
-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 {
- 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 := structPointer_Interface(base, st).(extendableProto); isExtensionField(e, int32(tag)) {
- if err = o.skip(st, tag, wire); err == nil {
- ext := e.ExtensionMap()[int32(tag)] // may be missing
- ext.enc = append(ext.enc, o.buf[oi:o.index]...)
- e.ExtensionMap()[int32(tag)] = ext
- }
- 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
-
- y := *v
- for i := 0; i < nb; i++ {
- 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() || !valelem.IsValid() {
- // We did not decode the key or the value in the map entry.
- // Either way, it's an invalid map entry.
- return fmt.Errorf("proto: bad map data: missing key/val")
- }
-
- 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
-}
diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/encode.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/encode.go
deleted file mode 100644
index 72c780b915..0000000000
--- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/encode.go
+++ /dev/null
@@ -1,1293 +0,0 @@
-// 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")
-
- // ErrNil is the error returned if Marshal is called with nil.
- ErrNil = errors.New("proto: Marshal called with nil")
-)
-
-// 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
-
-// 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
-}
-
-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(uint64((x << 1) ^ uint64((int64(x) >> 63))))
-}
-
-func sizeZigzag64(x uint64) int {
- return sizeVarint(uint64((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)
- var state errorState
- if err != nil && !state.shouldContinue(err, nil) {
- return nil, err
- }
- if p.buf == nil && err == nil {
- // Return a non-nil slice on success.
- return []byte{}, nil
- }
- return p.buf, 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()
- if err != nil {
- return err
- }
- p.buf = append(p.buf, data...)
- return nil
- }
-
- 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++
- }
-
- 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++
- }
-
- 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 {
- 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 {
- 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 {
- 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 {
- 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 == "" {
- 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 nil
- }
-
- 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 {
- 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 {
- 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 += len(p.tagcode)
- 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 {
- v := *structPointer_ExtMap(base, p.field)
- if err := encodeExtensionMap(v); err != nil {
- return err
- }
- // 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 sizeExtensionMap(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 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 {
- return err
- }
- return nil
- }
-
- keys := v.MapKeys()
- sort.Sort(mapKeys(keys))
- for _, key := range keys {
- val := v.MapIndex(key)
-
- // The only illegal map entry values are nil message pointers.
- if val.Kind() == reflect.Ptr && val.IsNil() {
- return errors.New("proto: map has nil element")
- }
-
- 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
- }
- }
- }
- }
-
- // Add unrecognized fields at the end.
- if prop.unrecField.IsValid() {
- v := *structPointer_Bytes(base, prop.unrecField)
- 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)
- }
-
- 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
-}
diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/equal.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/equal.go
deleted file mode 100644
index d8673a3e97..0000000000
--- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/equal.go
+++ /dev/null
@@ -1,256 +0,0 @@
-// 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.
-// TODO: MessageSet.
-
-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.
- - Two repeated fields are equal iff their lengths are the same,
- and their corresponding elements are equal (a "bytes" field,
- although represented by []byte, is not a repeated field)
- - 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.
- - 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 {
- 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) {
- return false
- }
- }
-
- if em1 := v1.FieldByName("XXX_extensions"); em1.IsValid() {
- em2 := v2.FieldByName("XXX_extensions")
- if !equalExtensions(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.
-func equalAny(v1, v2 reflect.Value) 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.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) {
- return false
- }
- }
- return true
- case reflect.Ptr:
- return equalAny(v1.Elem(), v2.Elem())
- case reflect.Slice:
- if v1.Type().Elem().Kind() == reflect.Uint8 {
- // short circuit: []byte
- 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)) {
- 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.
-// em1 and em2 are extension maps.
-func equalExtensions(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)) {
- 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)) {
- return false
- }
- }
-
- return true
-}
diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/equal_test.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/equal_test.go
deleted file mode 100644
index b322f65ab6..0000000000
--- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/equal_test.go
+++ /dev/null
@@ -1,191 +0,0 @@
-// 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.
-
-package proto_test
-
-import (
- "testing"
-
- . "github.com/golang/protobuf/proto"
- pb "github.com/golang/protobuf/proto/testdata"
-)
-
-// Four identical base messages.
-// The init function adds extensions to some of them.
-var messageWithoutExtension = &pb.MyMessage{Count: Int32(7)}
-var messageWithExtension1a = &pb.MyMessage{Count: Int32(7)}
-var messageWithExtension1b = &pb.MyMessage{Count: Int32(7)}
-var messageWithExtension2 = &pb.MyMessage{Count: Int32(7)}
-
-// Two messages with non-message extensions.
-var messageWithInt32Extension1 = &pb.MyMessage{Count: Int32(8)}
-var messageWithInt32Extension2 = &pb.MyMessage{Count: Int32(8)}
-
-func init() {
- ext1 := &pb.Ext{Data: String("Kirk")}
- ext2 := &pb.Ext{Data: String("Picard")}
-
- // messageWithExtension1a has ext1, but never marshals it.
- if err := SetExtension(messageWithExtension1a, pb.E_Ext_More, ext1); err != nil {
- panic("SetExtension on 1a failed: " + err.Error())
- }
-
- // messageWithExtension1b is the unmarshaled form of messageWithExtension1a.
- if err := SetExtension(messageWithExtension1b, pb.E_Ext_More, ext1); err != nil {
- panic("SetExtension on 1b failed: " + err.Error())
- }
- buf, err := Marshal(messageWithExtension1b)
- if err != nil {
- panic("Marshal of 1b failed: " + err.Error())
- }
- messageWithExtension1b.Reset()
- if err := Unmarshal(buf, messageWithExtension1b); err != nil {
- panic("Unmarshal of 1b failed: " + err.Error())
- }
-
- // messageWithExtension2 has ext2.
- if err := SetExtension(messageWithExtension2, pb.E_Ext_More, ext2); err != nil {
- panic("SetExtension on 2 failed: " + err.Error())
- }
-
- if err := SetExtension(messageWithInt32Extension1, pb.E_Ext_Number, Int32(23)); err != nil {
- panic("SetExtension on Int32-1 failed: " + err.Error())
- }
- if err := SetExtension(messageWithInt32Extension1, pb.E_Ext_Number, Int32(24)); err != nil {
- panic("SetExtension on Int32-2 failed: " + err.Error())
- }
-}
-
-var EqualTests = []struct {
- desc string
- a, b Message
- exp bool
-}{
- {"different types", &pb.GoEnum{}, &pb.GoTestField{}, false},
- {"equal empty", &pb.GoEnum{}, &pb.GoEnum{}, true},
- {"nil vs nil", nil, nil, true},
- {"typed nil vs typed nil", (*pb.GoEnum)(nil), (*pb.GoEnum)(nil), true},
- {"typed nil vs empty", (*pb.GoEnum)(nil), &pb.GoEnum{}, false},
- {"different typed nil", (*pb.GoEnum)(nil), (*pb.GoTestField)(nil), false},
-
- {"one set field, one unset field", &pb.GoTestField{Label: String("foo")}, &pb.GoTestField{}, false},
- {"one set field zero, one unset field", &pb.GoTest{Param: Int32(0)}, &pb.GoTest{}, false},
- {"different set fields", &pb.GoTestField{Label: String("foo")}, &pb.GoTestField{Label: String("bar")}, false},
- {"equal set", &pb.GoTestField{Label: String("foo")}, &pb.GoTestField{Label: String("foo")}, true},
-
- {"repeated, one set", &pb.GoTest{F_Int32Repeated: []int32{2, 3}}, &pb.GoTest{}, false},
- {"repeated, different length", &pb.GoTest{F_Int32Repeated: []int32{2, 3}}, &pb.GoTest{F_Int32Repeated: []int32{2}}, false},
- {"repeated, different value", &pb.GoTest{F_Int32Repeated: []int32{2}}, &pb.GoTest{F_Int32Repeated: []int32{3}}, false},
- {"repeated, equal", &pb.GoTest{F_Int32Repeated: []int32{2, 4}}, &pb.GoTest{F_Int32Repeated: []int32{2, 4}}, true},
- {"repeated, nil equal nil", &pb.GoTest{F_Int32Repeated: nil}, &pb.GoTest{F_Int32Repeated: nil}, true},
- {"repeated, nil equal empty", &pb.GoTest{F_Int32Repeated: nil}, &pb.GoTest{F_Int32Repeated: []int32{}}, true},
- {"repeated, empty equal nil", &pb.GoTest{F_Int32Repeated: []int32{}}, &pb.GoTest{F_Int32Repeated: nil}, true},
-
- {
- "nested, different",
- &pb.GoTest{RequiredField: &pb.GoTestField{Label: String("foo")}},
- &pb.GoTest{RequiredField: &pb.GoTestField{Label: String("bar")}},
- false,
- },
- {
- "nested, equal",
- &pb.GoTest{RequiredField: &pb.GoTestField{Label: String("wow")}},
- &pb.GoTest{RequiredField: &pb.GoTestField{Label: String("wow")}},
- true,
- },
-
- {"bytes", &pb.OtherMessage{Value: []byte("foo")}, &pb.OtherMessage{Value: []byte("foo")}, true},
- {"bytes, empty", &pb.OtherMessage{Value: []byte{}}, &pb.OtherMessage{Value: []byte{}}, true},
- {"bytes, empty vs nil", &pb.OtherMessage{Value: []byte{}}, &pb.OtherMessage{Value: nil}, false},
- {
- "repeated bytes",
- &pb.MyMessage{RepBytes: [][]byte{[]byte("sham"), []byte("wow")}},
- &pb.MyMessage{RepBytes: [][]byte{[]byte("sham"), []byte("wow")}},
- true,
- },
-
- {"extension vs. no extension", messageWithoutExtension, messageWithExtension1a, false},
- {"extension vs. same extension", messageWithExtension1a, messageWithExtension1b, true},
- {"extension vs. different extension", messageWithExtension1a, messageWithExtension2, false},
-
- {"int32 extension vs. itself", messageWithInt32Extension1, messageWithInt32Extension1, true},
- {"int32 extension vs. a different int32", messageWithInt32Extension1, messageWithInt32Extension2, false},
-
- {
- "message with group",
- &pb.MyMessage{
- Count: Int32(1),
- Somegroup: &pb.MyMessage_SomeGroup{
- GroupField: Int32(5),
- },
- },
- &pb.MyMessage{
- Count: Int32(1),
- Somegroup: &pb.MyMessage_SomeGroup{
- GroupField: Int32(5),
- },
- },
- true,
- },
-
- {
- "map same",
- &pb.MessageWithMap{NameMapping: map[int32]string{1: "Ken"}},
- &pb.MessageWithMap{NameMapping: map[int32]string{1: "Ken"}},
- true,
- },
- {
- "map different entry",
- &pb.MessageWithMap{NameMapping: map[int32]string{1: "Ken"}},
- &pb.MessageWithMap{NameMapping: map[int32]string{2: "Rob"}},
- false,
- },
- {
- "map different key only",
- &pb.MessageWithMap{NameMapping: map[int32]string{1: "Ken"}},
- &pb.MessageWithMap{NameMapping: map[int32]string{2: "Ken"}},
- false,
- },
- {
- "map different value only",
- &pb.MessageWithMap{NameMapping: map[int32]string{1: "Ken"}},
- &pb.MessageWithMap{NameMapping: map[int32]string{1: "Rob"}},
- false,
- },
-}
-
-func TestEqual(t *testing.T) {
- for _, tc := range EqualTests {
- if res := Equal(tc.a, tc.b); res != tc.exp {
- t.Errorf("%v: Equal(%v, %v) = %v, want %v", tc.desc, tc.a, tc.b, res, tc.exp)
- }
- }
-}
diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/extensions.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/extensions.go
deleted file mode 100644
index e591ccef79..0000000000
--- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/extensions.go
+++ /dev/null
@@ -1,400 +0,0 @@
-// 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 that may be extended.
-type extendableProto interface {
- Message
- ExtensionRangeArray() []ExtensionRange
- ExtensionMap() map[int32]Extension
-}
-
-var extendableProtoType = reflect.TypeOf((*extendableProto)(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
-}
-
-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 extendableProto, id int32, b []byte) {
- base.ExtensionMap()[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 {
- // Check the extended type.
- if a, b := reflect.TypeOf(pb), 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
-}
-
-// encodeExtensionMap encodes any unmarshaled (unencoded) extensions in m.
-func encodeExtensionMap(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 sizeExtensionMap(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 extendableProto, extension *ExtensionDesc) bool {
- // TODO: Check types, field numbers, etc.?
- _, ok := pb.ExtensionMap()[extension.Field]
- return ok
-}
-
-// ClearExtension removes the given extension from pb.
-func ClearExtension(pb extendableProto, extension *ExtensionDesc) {
- // TODO: Check types, field numbers, etc.?
- delete(pb.ExtensionMap(), 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 extendableProto, extension *ExtensionDesc) (interface{}, error) {
- if err := checkExtensionTypes(pb, extension); err != nil {
- return nil, err
- }
-
- emap := pb.ExtensionMap()
- 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)
- rep := extension.repeated()
-
- 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 !rep || 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 := pb.(extendableProto)
- if !ok {
- err = errors.New("proto: not an extendable proto")
- return
- }
- 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
-}
-
-// SetExtension sets the specified extension of pb to the specified value.
-func SetExtension(pb extendableProto, extension *ExtensionDesc, value interface{}) error {
- if err := checkExtensionTypes(pb, 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)
- }
-
- pb.ExtensionMap()[extension.Field] = Extension{desc: extension, value: value}
- return nil
-}
-
-// 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()]
-}
diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/extensions_test.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/extensions_test.go
deleted file mode 100644
index 72552767d8..0000000000
--- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/extensions_test.go
+++ /dev/null
@@ -1,292 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2014 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_test
-
-import (
- "fmt"
- "reflect"
- "testing"
-
- "github.com/golang/protobuf/proto"
- pb "github.com/golang/protobuf/proto/testdata"
-)
-
-func TestGetExtensionsWithMissingExtensions(t *testing.T) {
- msg := &pb.MyMessage{}
- ext1 := &pb.Ext{}
- if err := proto.SetExtension(msg, pb.E_Ext_More, ext1); err != nil {
- t.Fatalf("Could not set ext1: %s", ext1)
- }
- exts, err := proto.GetExtensions(msg, []*proto.ExtensionDesc{
- pb.E_Ext_More,
- pb.E_Ext_Text,
- })
- if err != nil {
- t.Fatalf("GetExtensions() failed: %s", err)
- }
- if exts[0] != ext1 {
- t.Errorf("ext1 not in returned extensions: %T %v", exts[0], exts[0])
- }
- if exts[1] != nil {
- t.Errorf("ext2 in returned extensions: %T %v", exts[1], exts[1])
- }
-}
-
-func TestGetExtensionStability(t *testing.T) {
- check := func(m *pb.MyMessage) bool {
- ext1, err := proto.GetExtension(m, pb.E_Ext_More)
- if err != nil {
- t.Fatalf("GetExtension() failed: %s", err)
- }
- ext2, err := proto.GetExtension(m, pb.E_Ext_More)
- if err != nil {
- t.Fatalf("GetExtension() failed: %s", err)
- }
- return ext1 == ext2
- }
- msg := &pb.MyMessage{Count: proto.Int32(4)}
- ext0 := &pb.Ext{}
- if err := proto.SetExtension(msg, pb.E_Ext_More, ext0); err != nil {
- t.Fatalf("Could not set ext1: %s", ext0)
- }
- if !check(msg) {
- t.Errorf("GetExtension() not stable before marshaling")
- }
- bb, err := proto.Marshal(msg)
- if err != nil {
- t.Fatalf("Marshal() failed: %s", err)
- }
- msg1 := &pb.MyMessage{}
- err = proto.Unmarshal(bb, msg1)
- if err != nil {
- t.Fatalf("Unmarshal() failed: %s", err)
- }
- if !check(msg1) {
- t.Errorf("GetExtension() not stable after unmarshaling")
- }
-}
-
-func TestGetExtensionDefaults(t *testing.T) {
- var setFloat64 float64 = 1
- var setFloat32 float32 = 2
- var setInt32 int32 = 3
- var setInt64 int64 = 4
- var setUint32 uint32 = 5
- var setUint64 uint64 = 6
- var setBool = true
- var setBool2 = false
- var setString = "Goodnight string"
- var setBytes = []byte("Goodnight bytes")
- var setEnum = pb.DefaultsMessage_TWO
-
- type testcase struct {
- ext *proto.ExtensionDesc // Extension we are testing.
- want interface{} // Expected value of extension, or nil (meaning that GetExtension will fail).
- def interface{} // Expected value of extension after ClearExtension().
- }
- tests := []testcase{
- {pb.E_NoDefaultDouble, setFloat64, nil},
- {pb.E_NoDefaultFloat, setFloat32, nil},
- {pb.E_NoDefaultInt32, setInt32, nil},
- {pb.E_NoDefaultInt64, setInt64, nil},
- {pb.E_NoDefaultUint32, setUint32, nil},
- {pb.E_NoDefaultUint64, setUint64, nil},
- {pb.E_NoDefaultSint32, setInt32, nil},
- {pb.E_NoDefaultSint64, setInt64, nil},
- {pb.E_NoDefaultFixed32, setUint32, nil},
- {pb.E_NoDefaultFixed64, setUint64, nil},
- {pb.E_NoDefaultSfixed32, setInt32, nil},
- {pb.E_NoDefaultSfixed64, setInt64, nil},
- {pb.E_NoDefaultBool, setBool, nil},
- {pb.E_NoDefaultBool, setBool2, nil},
- {pb.E_NoDefaultString, setString, nil},
- {pb.E_NoDefaultBytes, setBytes, nil},
- {pb.E_NoDefaultEnum, setEnum, nil},
- {pb.E_DefaultDouble, setFloat64, float64(3.1415)},
- {pb.E_DefaultFloat, setFloat32, float32(3.14)},
- {pb.E_DefaultInt32, setInt32, int32(42)},
- {pb.E_DefaultInt64, setInt64, int64(43)},
- {pb.E_DefaultUint32, setUint32, uint32(44)},
- {pb.E_DefaultUint64, setUint64, uint64(45)},
- {pb.E_DefaultSint32, setInt32, int32(46)},
- {pb.E_DefaultSint64, setInt64, int64(47)},
- {pb.E_DefaultFixed32, setUint32, uint32(48)},
- {pb.E_DefaultFixed64, setUint64, uint64(49)},
- {pb.E_DefaultSfixed32, setInt32, int32(50)},
- {pb.E_DefaultSfixed64, setInt64, int64(51)},
- {pb.E_DefaultBool, setBool, true},
- {pb.E_DefaultBool, setBool2, true},
- {pb.E_DefaultString, setString, "Hello, string"},
- {pb.E_DefaultBytes, setBytes, []byte("Hello, bytes")},
- {pb.E_DefaultEnum, setEnum, pb.DefaultsMessage_ONE},
- }
-
- checkVal := func(test testcase, msg *pb.DefaultsMessage, valWant interface{}) error {
- val, err := proto.GetExtension(msg, test.ext)
- if err != nil {
- if valWant != nil {
- return fmt.Errorf("GetExtension(): %s", err)
- }
- if want := proto.ErrMissingExtension; err != want {
- return fmt.Errorf("Unexpected error: got %v, want %v", err, want)
- }
- return nil
- }
-
- // All proto2 extension values are either a pointer to a value or a slice of values.
- ty := reflect.TypeOf(val)
- tyWant := reflect.TypeOf(test.ext.ExtensionType)
- if got, want := ty, tyWant; got != want {
- return fmt.Errorf("unexpected reflect.TypeOf(): got %v want %v", got, want)
- }
- tye := ty.Elem()
- tyeWant := tyWant.Elem()
- if got, want := tye, tyeWant; got != want {
- return fmt.Errorf("unexpected reflect.TypeOf().Elem(): got %v want %v", got, want)
- }
-
- // Check the name of the type of the value.
- // If it is an enum it will be type int32 with the name of the enum.
- if got, want := tye.Name(), tye.Name(); got != want {
- return fmt.Errorf("unexpected reflect.TypeOf().Elem().Name(): got %v want %v", got, want)
- }
-
- // Check that value is what we expect.
- // If we have a pointer in val, get the value it points to.
- valExp := val
- if ty.Kind() == reflect.Ptr {
- valExp = reflect.ValueOf(val).Elem().Interface()
- }
- if got, want := valExp, valWant; !reflect.DeepEqual(got, want) {
- return fmt.Errorf("unexpected reflect.DeepEqual(): got %v want %v", got, want)
- }
-
- return nil
- }
-
- setTo := func(test testcase) interface{} {
- setTo := reflect.ValueOf(test.want)
- if typ := reflect.TypeOf(test.ext.ExtensionType); typ.Kind() == reflect.Ptr {
- setTo = reflect.New(typ).Elem()
- setTo.Set(reflect.New(setTo.Type().Elem()))
- setTo.Elem().Set(reflect.ValueOf(test.want))
- }
- return setTo.Interface()
- }
-
- for _, test := range tests {
- msg := &pb.DefaultsMessage{}
- name := test.ext.Name
-
- // Check the initial value.
- if err := checkVal(test, msg, test.def); err != nil {
- t.Errorf("%s: %v", name, err)
- }
-
- // Set the per-type value and check value.
- name = fmt.Sprintf("%s (set to %T %v)", name, test.want, test.want)
- if err := proto.SetExtension(msg, test.ext, setTo(test)); err != nil {
- t.Errorf("%s: SetExtension(): %v", name, err)
- continue
- }
- if err := checkVal(test, msg, test.want); err != nil {
- t.Errorf("%s: %v", name, err)
- continue
- }
-
- // Set and check the value.
- name += " (cleared)"
- proto.ClearExtension(msg, test.ext)
- if err := checkVal(test, msg, test.def); err != nil {
- t.Errorf("%s: %v", name, err)
- }
- }
-}
-
-func TestExtensionsRoundTrip(t *testing.T) {
- msg := &pb.MyMessage{}
- ext1 := &pb.Ext{
- Data: proto.String("hi"),
- }
- ext2 := &pb.Ext{
- Data: proto.String("there"),
- }
- exists := proto.HasExtension(msg, pb.E_Ext_More)
- if exists {
- t.Error("Extension More present unexpectedly")
- }
- if err := proto.SetExtension(msg, pb.E_Ext_More, ext1); err != nil {
- t.Error(err)
- }
- if err := proto.SetExtension(msg, pb.E_Ext_More, ext2); err != nil {
- t.Error(err)
- }
- e, err := proto.GetExtension(msg, pb.E_Ext_More)
- if err != nil {
- t.Error(err)
- }
- x, ok := e.(*pb.Ext)
- if !ok {
- t.Errorf("e has type %T, expected testdata.Ext", e)
- } else if *x.Data != "there" {
- t.Errorf("SetExtension failed to overwrite, got %+v, not 'there'", x)
- }
- proto.ClearExtension(msg, pb.E_Ext_More)
- if _, err = proto.GetExtension(msg, pb.E_Ext_More); err != proto.ErrMissingExtension {
- t.Errorf("got %v, expected ErrMissingExtension", e)
- }
- if _, err := proto.GetExtension(msg, pb.E_X215); err == nil {
- t.Error("expected bad extension error, got nil")
- }
- if err := proto.SetExtension(msg, pb.E_X215, 12); err == nil {
- t.Error("expected extension err")
- }
- if err := proto.SetExtension(msg, pb.E_Ext_More, 12); err == nil {
- t.Error("expected some sort of type mismatch error, got nil")
- }
-}
-
-func TestNilExtension(t *testing.T) {
- msg := &pb.MyMessage{
- Count: proto.Int32(1),
- }
- if err := proto.SetExtension(msg, pb.E_Ext_Text, proto.String("hello")); err != nil {
- t.Fatal(err)
- }
- if err := proto.SetExtension(msg, pb.E_Ext_More, (*pb.Ext)(nil)); err == nil {
- t.Error("expected SetExtension to fail due to a nil extension")
- } else if want := "proto: SetExtension called with nil value of type *testdata.Ext"; err.Error() != want {
- t.Errorf("expected error %v, got %v", want, err)
- }
- // Note: if the behavior of Marshal is ever changed to ignore nil extensions, update
- // this test to verify that E_Ext_Text is properly propagated through marshal->unmarshal.
-}
diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/lib.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/lib.go
deleted file mode 100644
index 0b28b08643..0000000000
--- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/lib.go
+++ /dev/null
@@ -1,813 +0,0 @@
-// 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.
- - Marshal and Unmarshal are functions to encode and decode the wire format.
-
-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;
- }
- }
-
-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"`
- XXX_unrecognized []byte `json:"-"`
- }
- func (m *Test) Reset() { *m = Test{} }
- func (m *Test) String() string { return proto.CompactTextString(m) }
- func (*Test) ProtoMessage() {}
- 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 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),
- Optionalgroup: &pb.Test_OptionalGroup{
- RequiredField: proto.String("good bye"),
- },
- }
- 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())
- }
- // etc.
- }
-*/
-package proto
-
-import (
- "encoding/json"
- "fmt"
- "log"
- "reflect"
- "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 // write 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)
- break
-
- 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:
- if err != nil {
- fmt.Printf("%3d: t=%3d start err %v\n", index, tag, err)
- break out
- }
- fmt.Printf("%3d: t=%3d start\n", index, tag)
- depth++
-
- case WireEndGroup:
- depth--
- if err != nil {
- fmt.Printf("%3d: t=%3d end err %v\n", index, tag, err)
- break out
- }
- 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.
-
-type mapKeys []reflect.Value
-
-func (s mapKeys) Len() int { return len(s) }
-func (s mapKeys) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
-func (s mapKeys) Less(i, j int) bool {
- return fmt.Sprint(s[i].Interface()) < fmt.Sprint(s[j].Interface())
-}
-
-// 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
-}
diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/message_set.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/message_set.go
deleted file mode 100644
index 9d912bce19..0000000000
--- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/message_set.go
+++ /dev/null
@@ -1,287 +0,0 @@
-// 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.
-//
-// When a proto1 proto has a field that looks like:
-// optional message info = 3;
-// the protocol compiler produces a field in the generated struct that looks like:
-// Info *_proto_.MessageSet `protobuf:"bytes,3,opt,name=info"`
-// The package is automatically inserted so there is no need for that proto file to
-// import 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(m map[int32]Extension) ([]byte, error) {
- if err := encodeExtensionMap(m); err != nil {
- return nil, err
- }
-
- // 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, m map[int32]Extension) error {
- 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(m map[int32]Extension) ([]byte, error) {
- 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, m map[int32]Extension) 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,
- }
-}
diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/message_set_test.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/message_set_test.go
deleted file mode 100644
index 7c29bccf4b..0000000000
--- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/message_set_test.go
+++ /dev/null
@@ -1,66 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2014 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 (
- "bytes"
- "testing"
-)
-
-func TestUnmarshalMessageSetWithDuplicate(t *testing.T) {
- // Check that a repeated message set entry will be concatenated.
- in := &MessageSet{
- Item: []*_MessageSet_Item{
- {TypeId: Int32(12345), Message: []byte("hoo")},
- {TypeId: Int32(12345), Message: []byte("hah")},
- },
- }
- b, err := Marshal(in)
- if err != nil {
- t.Fatalf("Marshal: %v", err)
- }
- t.Logf("Marshaled bytes: %q", b)
-
- m := make(map[int32]Extension)
- if err := UnmarshalMessageSet(b, m); err != nil {
- t.Fatalf("UnmarshalMessageSet: %v", err)
- }
- ext, ok := m[12345]
- if !ok {
- t.Fatalf("Didn't retrieve extension 12345; map is %v", m)
- }
- // Skip wire type/field number and length varints.
- got := skipVarint(skipVarint(ext.enc))
- if want := []byte("hoohah"); !bytes.Equal(got, want) {
- t.Errorf("Combined extension is %q, want %q", got, want)
- }
-}
diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/pointer_reflect.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/pointer_reflect.go
deleted file mode 100644
index 749919d250..0000000000
--- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/pointer_reflect.go
+++ /dev/null
@@ -1,479 +0,0 @@
-// 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
-
-// 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)
-}
-
-// 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)}
-}
diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/pointer_unsafe.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/pointer_unsafe.go
deleted file mode 100644
index e9be0fe92e..0000000000
--- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/pointer_unsafe.go
+++ /dev/null
@@ -1,266 +0,0 @@
-// 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
-
-// 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_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)))
-}
diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/properties.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/properties.go
deleted file mode 100644
index d74844ab2a..0000000000
--- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/properties.go
+++ /dev/null
@@ -1,742 +0,0 @@
-// 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"
- "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)
-
-// 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
-}
-
-// 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)
- 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
-
- 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"
- }
- if p.OrigName != p.Name {
- s += ",name=" + p.OrigName
- }
- if p.proto3 {
- s += ",proto3"
- }
- 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, "enum="):
- p.Enum = f[5:]
- case f == "proto3":
- p.proto3 = 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.enc = (*Buffer).enc_slice_byte
- p.dec = (*Buffer).dec_slice_byte
- p.size = size_slice_byte
- // This is a []byte, which is either a bytes field,
- // or the value of a map field. In the latter case,
- // we always encode an empty []byte, so we should not
- // use the proto3 enc/size funcs.
- // f == nil iff this is the key/value of a map field.
- if p.proto3 && f != nil {
- p.enc = (*Buffer).enc_proto3_slice_byte
- p.size = size_proto3_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)
- 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_extensions" { // special case
- p.enc = (*Buffer).enc_map
- p.dec = nil // not needed
- p.size = size_map
- }
- if f.Name == "XXX_unrecognized" { // special case
- prop.unrecField = toField(&f)
- }
- 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_") {
- fmt.Fprintln(os.Stderr, "proto: no encoder for", f.Name, f.Type.String(), "[GetProperties]")
- }
- }
-
- // Re-order prop.order.
- sort.Sort(prop)
-
- // 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
-}
diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/proto3_proto/proto3.pb.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/proto3_proto/proto3.pb.go
deleted file mode 100644
index 37c7782092..0000000000
--- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/proto3_proto/proto3.pb.go
+++ /dev/null
@@ -1,122 +0,0 @@
-// Code generated by protoc-gen-go.
-// source: proto3_proto/proto3.proto
-// DO NOT EDIT!
-
-/*
-Package proto3_proto is a generated protocol buffer package.
-
-It is generated from these files:
- proto3_proto/proto3.proto
-
-It has these top-level messages:
- Message
- Nested
- MessageWithMap
-*/
-package proto3_proto
-
-import proto "github.com/golang/protobuf/proto"
-import testdata "github.com/golang/protobuf/proto/testdata"
-
-// Reference imports to suppress errors if they are not otherwise used.
-var _ = proto.Marshal
-
-type Message_Humour int32
-
-const (
- Message_UNKNOWN Message_Humour = 0
- Message_PUNS Message_Humour = 1
- Message_SLAPSTICK Message_Humour = 2
- Message_BILL_BAILEY Message_Humour = 3
-)
-
-var Message_Humour_name = map[int32]string{
- 0: "UNKNOWN",
- 1: "PUNS",
- 2: "SLAPSTICK",
- 3: "BILL_BAILEY",
-}
-var Message_Humour_value = map[string]int32{
- "UNKNOWN": 0,
- "PUNS": 1,
- "SLAPSTICK": 2,
- "BILL_BAILEY": 3,
-}
-
-func (x Message_Humour) String() string {
- return proto.EnumName(Message_Humour_name, int32(x))
-}
-
-type Message struct {
- Name string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
- Hilarity Message_Humour `protobuf:"varint,2,opt,name=hilarity,enum=proto3_proto.Message_Humour" json:"hilarity,omitempty"`
- HeightInCm uint32 `protobuf:"varint,3,opt,name=height_in_cm" json:"height_in_cm,omitempty"`
- Data []byte `protobuf:"bytes,4,opt,name=data,proto3" json:"data,omitempty"`
- ResultCount int64 `protobuf:"varint,7,opt,name=result_count" json:"result_count,omitempty"`
- TrueScotsman bool `protobuf:"varint,8,opt,name=true_scotsman" json:"true_scotsman,omitempty"`
- Score float32 `protobuf:"fixed32,9,opt,name=score" json:"score,omitempty"`
- Key []uint64 `protobuf:"varint,5,rep,name=key" json:"key,omitempty"`
- Nested *Nested `protobuf:"bytes,6,opt,name=nested" json:"nested,omitempty"`
- Terrain map[string]*Nested `protobuf:"bytes,10,rep,name=terrain" json:"terrain,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
- Proto2Field *testdata.SubDefaults `protobuf:"bytes,11,opt,name=proto2_field" json:"proto2_field,omitempty"`
- Proto2Value map[string]*testdata.SubDefaults `protobuf:"bytes,13,rep,name=proto2_value" json:"proto2_value,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
-}
-
-func (m *Message) Reset() { *m = Message{} }
-func (m *Message) String() string { return proto.CompactTextString(m) }
-func (*Message) ProtoMessage() {}
-
-func (m *Message) GetNested() *Nested {
- if m != nil {
- return m.Nested
- }
- return nil
-}
-
-func (m *Message) GetTerrain() map[string]*Nested {
- if m != nil {
- return m.Terrain
- }
- return nil
-}
-
-func (m *Message) GetProto2Field() *testdata.SubDefaults {
- if m != nil {
- return m.Proto2Field
- }
- return nil
-}
-
-func (m *Message) GetProto2Value() map[string]*testdata.SubDefaults {
- if m != nil {
- return m.Proto2Value
- }
- return nil
-}
-
-type Nested struct {
- Bunny string `protobuf:"bytes,1,opt,name=bunny" json:"bunny,omitempty"`
-}
-
-func (m *Nested) Reset() { *m = Nested{} }
-func (m *Nested) String() string { return proto.CompactTextString(m) }
-func (*Nested) ProtoMessage() {}
-
-type MessageWithMap struct {
- ByteMapping map[bool][]byte `protobuf:"bytes,1,rep,name=byte_mapping" json:"byte_mapping,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value,proto3"`
-}
-
-func (m *MessageWithMap) Reset() { *m = MessageWithMap{} }
-func (m *MessageWithMap) String() string { return proto.CompactTextString(m) }
-func (*MessageWithMap) ProtoMessage() {}
-
-func (m *MessageWithMap) GetByteMapping() map[bool][]byte {
- if m != nil {
- return m.ByteMapping
- }
- return nil
-}
-
-func init() {
- proto.RegisterEnum("proto3_proto.Message_Humour", Message_Humour_name, Message_Humour_value)
-}
diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/proto3_proto/proto3.proto b/Godeps/_workspace/src/github.com/golang/protobuf/proto/proto3_proto/proto3.proto
deleted file mode 100644
index e2311d9294..0000000000
--- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/proto3_proto/proto3.proto
+++ /dev/null
@@ -1,68 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2014 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.
-
-syntax = "proto3";
-
-import "testdata/test.proto";
-
-package proto3_proto;
-
-message Message {
- enum Humour {
- UNKNOWN = 0;
- PUNS = 1;
- SLAPSTICK = 2;
- BILL_BAILEY = 3;
- }
-
- string name = 1;
- Humour hilarity = 2;
- uint32 height_in_cm = 3;
- bytes data = 4;
- int64 result_count = 7;
- bool true_scotsman = 8;
- float score = 9;
-
- repeated uint64 key = 5;
- Nested nested = 6;
-
- map terrain = 10;
- testdata.SubDefaults proto2_field = 11;
- map proto2_value = 13;
-}
-
-message Nested {
- string bunny = 1;
-}
-
-message MessageWithMap {
- map byte_mapping = 1;
-}
diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/proto3_test.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/proto3_test.go
deleted file mode 100644
index 462f8055c3..0000000000
--- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/proto3_test.go
+++ /dev/null
@@ -1,125 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2014 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_test
-
-import (
- "testing"
-
- "github.com/golang/protobuf/proto"
- pb "github.com/golang/protobuf/proto/proto3_proto"
- tpb "github.com/golang/protobuf/proto/testdata"
-)
-
-func TestProto3ZeroValues(t *testing.T) {
- tests := []struct {
- desc string
- m proto.Message
- }{
- {"zero message", &pb.Message{}},
- {"empty bytes field", &pb.Message{Data: []byte{}}},
- }
- for _, test := range tests {
- b, err := proto.Marshal(test.m)
- if err != nil {
- t.Errorf("%s: proto.Marshal: %v", test.desc, err)
- continue
- }
- if len(b) > 0 {
- t.Errorf("%s: Encoding is non-empty: %q", test.desc, b)
- }
- }
-}
-
-func TestRoundTripProto3(t *testing.T) {
- m := &pb.Message{
- Name: "David", // (2 | 1<<3): 0x0a 0x05 "David"
- Hilarity: pb.Message_PUNS, // (0 | 2<<3): 0x10 0x01
- HeightInCm: 178, // (0 | 3<<3): 0x18 0xb2 0x01
- Data: []byte("roboto"), // (2 | 4<<3): 0x20 0x06 "roboto"
- ResultCount: 47, // (0 | 7<<3): 0x38 0x2f
- TrueScotsman: true, // (0 | 8<<3): 0x40 0x01
- Score: 8.1, // (5 | 9<<3): 0x4d <8.1>
-
- Key: []uint64{1, 0xdeadbeef},
- Nested: &pb.Nested{
- Bunny: "Monty",
- },
- }
- t.Logf(" m: %v", m)
-
- b, err := proto.Marshal(m)
- if err != nil {
- t.Fatalf("proto.Marshal: %v", err)
- }
- t.Logf(" b: %q", b)
-
- m2 := new(pb.Message)
- if err := proto.Unmarshal(b, m2); err != nil {
- t.Fatalf("proto.Unmarshal: %v", err)
- }
- t.Logf("m2: %v", m2)
-
- if !proto.Equal(m, m2) {
- t.Errorf("proto.Equal returned false:\n m: %v\nm2: %v", m, m2)
- }
-}
-
-func TestProto3SetDefaults(t *testing.T) {
- in := &pb.Message{
- Terrain: map[string]*pb.Nested{
- "meadow": new(pb.Nested),
- },
- Proto2Field: new(tpb.SubDefaults),
- Proto2Value: map[string]*tpb.SubDefaults{
- "badlands": new(tpb.SubDefaults),
- },
- }
-
- got := proto.Clone(in).(*pb.Message)
- proto.SetDefaults(got)
-
- // There are no defaults in proto3. Everything should be the zero value, but
- // we need to remember to set defaults for nested proto2 messages.
- want := &pb.Message{
- Terrain: map[string]*pb.Nested{
- "meadow": new(pb.Nested),
- },
- Proto2Field: &tpb.SubDefaults{N: proto.Int64(7)},
- Proto2Value: map[string]*tpb.SubDefaults{
- "badlands": &tpb.SubDefaults{N: proto.Int64(7)},
- },
- }
-
- if !proto.Equal(got, want) {
- t.Errorf("with in = %v\nproto.SetDefaults(in) =>\ngot %v\nwant %v", in, got, want)
- }
-}
diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/size2_test.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/size2_test.go
deleted file mode 100644
index a2729c39a1..0000000000
--- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/size2_test.go
+++ /dev/null
@@ -1,63 +0,0 @@
-// 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.
-
-package proto
-
-import (
- "testing"
-)
-
-// This is a separate file and package from size_test.go because that one uses
-// generated messages and thus may not be in package proto without having a circular
-// dependency, whereas this file tests unexported details of size.go.
-
-func TestVarintSize(t *testing.T) {
- // Check the edge cases carefully.
- testCases := []struct {
- n uint64
- size int
- }{
- {0, 1},
- {1, 1},
- {127, 1},
- {128, 2},
- {16383, 2},
- {16384, 3},
- {1<<63 - 1, 9},
- {1 << 63, 10},
- }
- for _, tc := range testCases {
- size := sizeVarint(tc.n)
- if size != tc.size {
- t.Errorf("sizeVarint(%d) = %d, want %d", tc.n, size, tc.size)
- }
- }
-}
diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/size_test.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/size_test.go
deleted file mode 100644
index db5614fd1d..0000000000
--- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/size_test.go
+++ /dev/null
@@ -1,142 +0,0 @@
-// 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.
-
-package proto_test
-
-import (
- "log"
- "strings"
- "testing"
-
- . "github.com/golang/protobuf/proto"
- proto3pb "github.com/golang/protobuf/proto/proto3_proto"
- pb "github.com/golang/protobuf/proto/testdata"
-)
-
-var messageWithExtension1 = &pb.MyMessage{Count: Int32(7)}
-
-// messageWithExtension2 is in equal_test.go.
-var messageWithExtension3 = &pb.MyMessage{Count: Int32(8)}
-
-func init() {
- if err := SetExtension(messageWithExtension1, pb.E_Ext_More, &pb.Ext{Data: String("Abbott")}); err != nil {
- log.Panicf("SetExtension: %v", err)
- }
- if err := SetExtension(messageWithExtension3, pb.E_Ext_More, &pb.Ext{Data: String("Costello")}); err != nil {
- log.Panicf("SetExtension: %v", err)
- }
-
- // Force messageWithExtension3 to have the extension encoded.
- Marshal(messageWithExtension3)
-
-}
-
-var SizeTests = []struct {
- desc string
- pb Message
-}{
- {"empty", &pb.OtherMessage{}},
- // Basic types.
- {"bool", &pb.Defaults{F_Bool: Bool(true)}},
- {"int32", &pb.Defaults{F_Int32: Int32(12)}},
- {"negative int32", &pb.Defaults{F_Int32: Int32(-1)}},
- {"small int64", &pb.Defaults{F_Int64: Int64(1)}},
- {"big int64", &pb.Defaults{F_Int64: Int64(1 << 20)}},
- {"negative int64", &pb.Defaults{F_Int64: Int64(-1)}},
- {"fixed32", &pb.Defaults{F_Fixed32: Uint32(71)}},
- {"fixed64", &pb.Defaults{F_Fixed64: Uint64(72)}},
- {"uint32", &pb.Defaults{F_Uint32: Uint32(123)}},
- {"uint64", &pb.Defaults{F_Uint64: Uint64(124)}},
- {"float", &pb.Defaults{F_Float: Float32(12.6)}},
- {"double", &pb.Defaults{F_Double: Float64(13.9)}},
- {"string", &pb.Defaults{F_String: String("niles")}},
- {"bytes", &pb.Defaults{F_Bytes: []byte("wowsa")}},
- {"bytes, empty", &pb.Defaults{F_Bytes: []byte{}}},
- {"sint32", &pb.Defaults{F_Sint32: Int32(65)}},
- {"sint64", &pb.Defaults{F_Sint64: Int64(67)}},
- {"enum", &pb.Defaults{F_Enum: pb.Defaults_BLUE.Enum()}},
- // Repeated.
- {"empty repeated bool", &pb.MoreRepeated{Bools: []bool{}}},
- {"repeated bool", &pb.MoreRepeated{Bools: []bool{false, true, true, false}}},
- {"packed repeated bool", &pb.MoreRepeated{BoolsPacked: []bool{false, true, true, false, true, true, true}}},
- {"repeated int32", &pb.MoreRepeated{Ints: []int32{1, 12203, 1729, -1}}},
- {"repeated int32 packed", &pb.MoreRepeated{IntsPacked: []int32{1, 12203, 1729}}},
- {"repeated int64 packed", &pb.MoreRepeated{Int64SPacked: []int64{
- // Need enough large numbers to verify that the header is counting the number of bytes
- // for the field, not the number of elements.
- 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62,
- 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62, 1 << 62,
- }}},
- {"repeated string", &pb.MoreRepeated{Strings: []string{"r", "ken", "gri"}}},
- {"repeated fixed", &pb.MoreRepeated{Fixeds: []uint32{1, 2, 3, 4}}},
- // Nested.
- {"nested", &pb.OldMessage{Nested: &pb.OldMessage_Nested{Name: String("whatever")}}},
- {"group", &pb.GroupOld{G: &pb.GroupOld_G{X: Int32(12345)}}},
- // Other things.
- {"unrecognized", &pb.MoreRepeated{XXX_unrecognized: []byte{13<<3 | 0, 4}}},
- {"extension (unencoded)", messageWithExtension1},
- {"extension (encoded)", messageWithExtension3},
- // proto3 message
- {"proto3 empty", &proto3pb.Message{}},
- {"proto3 bool", &proto3pb.Message{TrueScotsman: true}},
- {"proto3 int64", &proto3pb.Message{ResultCount: 1}},
- {"proto3 uint32", &proto3pb.Message{HeightInCm: 123}},
- {"proto3 float", &proto3pb.Message{Score: 12.6}},
- {"proto3 string", &proto3pb.Message{Name: "Snezana"}},
- {"proto3 bytes", &proto3pb.Message{Data: []byte("wowsa")}},
- {"proto3 bytes, empty", &proto3pb.Message{Data: []byte{}}},
- {"proto3 enum", &proto3pb.Message{Hilarity: proto3pb.Message_PUNS}},
- {"proto3 map field with empty bytes", &proto3pb.MessageWithMap{ByteMapping: map[bool][]byte{false: []byte{}}}},
-
- {"map field", &pb.MessageWithMap{NameMapping: map[int32]string{1: "Rob", 7: "Andrew"}}},
- {"map field with message", &pb.MessageWithMap{MsgMapping: map[int64]*pb.FloatingPoint{0x7001: &pb.FloatingPoint{F: Float64(2.0)}}}},
- {"map field with bytes", &pb.MessageWithMap{ByteMapping: map[bool][]byte{true: []byte("this time for sure")}}},
- {"map field with empty bytes", &pb.MessageWithMap{ByteMapping: map[bool][]byte{true: []byte{}}}},
-
- {"map field with big entry", &pb.MessageWithMap{NameMapping: map[int32]string{8: strings.Repeat("x", 125)}}},
- {"map field with big key and val", &pb.MessageWithMap{StrToStr: map[string]string{strings.Repeat("x", 70): strings.Repeat("y", 70)}}},
- {"map field with big numeric key", &pb.MessageWithMap{NameMapping: map[int32]string{0xf00d: "om nom nom"}}},
-}
-
-func TestSize(t *testing.T) {
- for _, tc := range SizeTests {
- size := Size(tc.pb)
- b, err := Marshal(tc.pb)
- if err != nil {
- t.Errorf("%v: Marshal failed: %v", tc.desc, err)
- continue
- }
- if size != len(b) {
- t.Errorf("%v: Size(%v) = %d, want %d", tc.desc, tc.pb, size, len(b))
- t.Logf("%v: bytes: %#v", tc.desc, b)
- }
- }
-}
diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/testdata/Makefile b/Godeps/_workspace/src/github.com/golang/protobuf/proto/testdata/Makefile
deleted file mode 100644
index fc288628a7..0000000000
--- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/testdata/Makefile
+++ /dev/null
@@ -1,50 +0,0 @@
-# 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.
-
-
-include ../../Make.protobuf
-
-all: regenerate
-
-regenerate:
- rm -f test.pb.go
- make test.pb.go
-
-# The following rules are just aids to development. Not needed for typical testing.
-
-diff: regenerate
- git diff test.pb.go
-
-restore:
- cp test.pb.go.golden test.pb.go
-
-preserve:
- cp test.pb.go test.pb.go.golden
diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/testdata/golden_test.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/testdata/golden_test.go
deleted file mode 100644
index 7172d0e969..0000000000
--- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/testdata/golden_test.go
+++ /dev/null
@@ -1,86 +0,0 @@
-// 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.
-
-// Verify that the compiler output for test.proto is unchanged.
-
-package testdata
-
-import (
- "crypto/sha1"
- "fmt"
- "io/ioutil"
- "os"
- "os/exec"
- "path/filepath"
- "testing"
-)
-
-// sum returns in string form (for easy comparison) the SHA-1 hash of the named file.
-func sum(t *testing.T, name string) string {
- data, err := ioutil.ReadFile(name)
- if err != nil {
- t.Fatal(err)
- }
- t.Logf("sum(%q): length is %d", name, len(data))
- hash := sha1.New()
- _, err = hash.Write(data)
- if err != nil {
- t.Fatal(err)
- }
- return fmt.Sprintf("% x", hash.Sum(nil))
-}
-
-func run(t *testing.T, name string, args ...string) {
- cmd := exec.Command(name, args...)
- cmd.Stdin = os.Stdin
- cmd.Stdout = os.Stdout
- cmd.Stderr = os.Stderr
- err := cmd.Run()
- if err != nil {
- t.Fatal(err)
- }
-}
-
-func TestGolden(t *testing.T) {
- // Compute the original checksum.
- goldenSum := sum(t, "test.pb.go")
- // Run the proto compiler.
- run(t, "protoc", "--go_out="+os.TempDir(), "test.proto")
- newFile := filepath.Join(os.TempDir(), "test.pb.go")
- defer os.Remove(newFile)
- // Compute the new checksum.
- newSum := sum(t, newFile)
- // Verify
- if newSum != goldenSum {
- run(t, "diff", "-u", "test.pb.go", newFile)
- t.Fatal("Code generated by protoc-gen-go has changed; update test.pb.go")
- }
-}
diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/testdata/test.pb.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/testdata/test.pb.go
deleted file mode 100644
index 13674a4491..0000000000
--- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/testdata/test.pb.go
+++ /dev/null
@@ -1,2746 +0,0 @@
-// Code generated by protoc-gen-go.
-// source: test.proto
-// DO NOT EDIT!
-
-/*
-Package testdata is a generated protocol buffer package.
-
-It is generated from these files:
- test.proto
-
-It has these top-level messages:
- GoEnum
- GoTestField
- GoTest
- GoSkipTest
- NonPackedTest
- PackedTest
- MaxTag
- OldMessage
- NewMessage
- InnerMessage
- OtherMessage
- MyMessage
- Ext
- DefaultsMessage
- MyMessageSet
- Empty
- MessageList
- Strings
- Defaults
- SubDefaults
- RepeatedEnum
- MoreRepeated
- GroupOld
- GroupNew
- FloatingPoint
- MessageWithMap
-*/
-package testdata
-
-import proto "github.com/golang/protobuf/proto"
-import math "math"
-
-// Reference imports to suppress errors if they are not otherwise used.
-var _ = proto.Marshal
-var _ = math.Inf
-
-type FOO int32
-
-const (
- FOO_FOO1 FOO = 1
-)
-
-var FOO_name = map[int32]string{
- 1: "FOO1",
-}
-var FOO_value = map[string]int32{
- "FOO1": 1,
-}
-
-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, "FOO")
- if err != nil {
- return err
- }
- *x = FOO(value)
- return nil
-}
-
-// An enum, for completeness.
-type GoTest_KIND int32
-
-const (
- GoTest_VOID GoTest_KIND = 0
- // Basic types
- GoTest_BOOL GoTest_KIND = 1
- GoTest_BYTES GoTest_KIND = 2
- GoTest_FINGERPRINT GoTest_KIND = 3
- GoTest_FLOAT GoTest_KIND = 4
- GoTest_INT GoTest_KIND = 5
- GoTest_STRING GoTest_KIND = 6
- GoTest_TIME GoTest_KIND = 7
- // Groupings
- GoTest_TUPLE GoTest_KIND = 8
- GoTest_ARRAY GoTest_KIND = 9
- GoTest_MAP GoTest_KIND = 10
- // Table types
- GoTest_TABLE GoTest_KIND = 11
- // Functions
- GoTest_FUNCTION GoTest_KIND = 12
-)
-
-var GoTest_KIND_name = map[int32]string{
- 0: "VOID",
- 1: "BOOL",
- 2: "BYTES",
- 3: "FINGERPRINT",
- 4: "FLOAT",
- 5: "INT",
- 6: "STRING",
- 7: "TIME",
- 8: "TUPLE",
- 9: "ARRAY",
- 10: "MAP",
- 11: "TABLE",
- 12: "FUNCTION",
-}
-var GoTest_KIND_value = map[string]int32{
- "VOID": 0,
- "BOOL": 1,
- "BYTES": 2,
- "FINGERPRINT": 3,
- "FLOAT": 4,
- "INT": 5,
- "STRING": 6,
- "TIME": 7,
- "TUPLE": 8,
- "ARRAY": 9,
- "MAP": 10,
- "TABLE": 11,
- "FUNCTION": 12,
-}
-
-func (x GoTest_KIND) Enum() *GoTest_KIND {
- p := new(GoTest_KIND)
- *p = x
- return p
-}
-func (x GoTest_KIND) String() string {
- return proto.EnumName(GoTest_KIND_name, int32(x))
-}
-func (x *GoTest_KIND) UnmarshalJSON(data []byte) error {
- value, err := proto.UnmarshalJSONEnum(GoTest_KIND_value, data, "GoTest_KIND")
- if err != nil {
- return err
- }
- *x = GoTest_KIND(value)
- return nil
-}
-
-type MyMessage_Color int32
-
-const (
- MyMessage_RED MyMessage_Color = 0
- MyMessage_GREEN MyMessage_Color = 1
- MyMessage_BLUE MyMessage_Color = 2
-)
-
-var MyMessage_Color_name = map[int32]string{
- 0: "RED",
- 1: "GREEN",
- 2: "BLUE",
-}
-var MyMessage_Color_value = map[string]int32{
- "RED": 0,
- "GREEN": 1,
- "BLUE": 2,
-}
-
-func (x MyMessage_Color) Enum() *MyMessage_Color {
- p := new(MyMessage_Color)
- *p = x
- return p
-}
-func (x MyMessage_Color) String() string {
- return proto.EnumName(MyMessage_Color_name, int32(x))
-}
-func (x *MyMessage_Color) UnmarshalJSON(data []byte) error {
- value, err := proto.UnmarshalJSONEnum(MyMessage_Color_value, data, "MyMessage_Color")
- if err != nil {
- return err
- }
- *x = MyMessage_Color(value)
- return nil
-}
-
-type DefaultsMessage_DefaultsEnum int32
-
-const (
- DefaultsMessage_ZERO DefaultsMessage_DefaultsEnum = 0
- DefaultsMessage_ONE DefaultsMessage_DefaultsEnum = 1
- DefaultsMessage_TWO DefaultsMessage_DefaultsEnum = 2
-)
-
-var DefaultsMessage_DefaultsEnum_name = map[int32]string{
- 0: "ZERO",
- 1: "ONE",
- 2: "TWO",
-}
-var DefaultsMessage_DefaultsEnum_value = map[string]int32{
- "ZERO": 0,
- "ONE": 1,
- "TWO": 2,
-}
-
-func (x DefaultsMessage_DefaultsEnum) Enum() *DefaultsMessage_DefaultsEnum {
- p := new(DefaultsMessage_DefaultsEnum)
- *p = x
- return p
-}
-func (x DefaultsMessage_DefaultsEnum) String() string {
- return proto.EnumName(DefaultsMessage_DefaultsEnum_name, int32(x))
-}
-func (x *DefaultsMessage_DefaultsEnum) UnmarshalJSON(data []byte) error {
- value, err := proto.UnmarshalJSONEnum(DefaultsMessage_DefaultsEnum_value, data, "DefaultsMessage_DefaultsEnum")
- if err != nil {
- return err
- }
- *x = DefaultsMessage_DefaultsEnum(value)
- return nil
-}
-
-type Defaults_Color int32
-
-const (
- Defaults_RED Defaults_Color = 0
- Defaults_GREEN Defaults_Color = 1
- Defaults_BLUE Defaults_Color = 2
-)
-
-var Defaults_Color_name = map[int32]string{
- 0: "RED",
- 1: "GREEN",
- 2: "BLUE",
-}
-var Defaults_Color_value = map[string]int32{
- "RED": 0,
- "GREEN": 1,
- "BLUE": 2,
-}
-
-func (x Defaults_Color) Enum() *Defaults_Color {
- p := new(Defaults_Color)
- *p = x
- return p
-}
-func (x Defaults_Color) String() string {
- return proto.EnumName(Defaults_Color_name, int32(x))
-}
-func (x *Defaults_Color) UnmarshalJSON(data []byte) error {
- value, err := proto.UnmarshalJSONEnum(Defaults_Color_value, data, "Defaults_Color")
- if err != nil {
- return err
- }
- *x = Defaults_Color(value)
- return nil
-}
-
-type RepeatedEnum_Color int32
-
-const (
- RepeatedEnum_RED RepeatedEnum_Color = 1
-)
-
-var RepeatedEnum_Color_name = map[int32]string{
- 1: "RED",
-}
-var RepeatedEnum_Color_value = map[string]int32{
- "RED": 1,
-}
-
-func (x RepeatedEnum_Color) Enum() *RepeatedEnum_Color {
- p := new(RepeatedEnum_Color)
- *p = x
- return p
-}
-func (x RepeatedEnum_Color) String() string {
- return proto.EnumName(RepeatedEnum_Color_name, int32(x))
-}
-func (x *RepeatedEnum_Color) UnmarshalJSON(data []byte) error {
- value, err := proto.UnmarshalJSONEnum(RepeatedEnum_Color_value, data, "RepeatedEnum_Color")
- if err != nil {
- return err
- }
- *x = RepeatedEnum_Color(value)
- return nil
-}
-
-type GoEnum struct {
- Foo *FOO `protobuf:"varint,1,req,name=foo,enum=testdata.FOO" json:"foo,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *GoEnum) Reset() { *m = GoEnum{} }
-func (m *GoEnum) String() string { return proto.CompactTextString(m) }
-func (*GoEnum) ProtoMessage() {}
-
-func (m *GoEnum) GetFoo() FOO {
- if m != nil && m.Foo != nil {
- return *m.Foo
- }
- return FOO_FOO1
-}
-
-type GoTestField struct {
- Label *string `protobuf:"bytes,1,req" json:"Label,omitempty"`
- Type *string `protobuf:"bytes,2,req" json:"Type,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *GoTestField) Reset() { *m = GoTestField{} }
-func (m *GoTestField) String() string { return proto.CompactTextString(m) }
-func (*GoTestField) ProtoMessage() {}
-
-func (m *GoTestField) GetLabel() string {
- if m != nil && m.Label != nil {
- return *m.Label
- }
- return ""
-}
-
-func (m *GoTestField) GetType() string {
- if m != nil && m.Type != nil {
- return *m.Type
- }
- return ""
-}
-
-type GoTest struct {
- // Some typical parameters
- Kind *GoTest_KIND `protobuf:"varint,1,req,enum=testdata.GoTest_KIND" json:"Kind,omitempty"`
- Table *string `protobuf:"bytes,2,opt" json:"Table,omitempty"`
- Param *int32 `protobuf:"varint,3,opt" json:"Param,omitempty"`
- // Required, repeated and optional foreign fields.
- RequiredField *GoTestField `protobuf:"bytes,4,req" json:"RequiredField,omitempty"`
- RepeatedField []*GoTestField `protobuf:"bytes,5,rep" json:"RepeatedField,omitempty"`
- OptionalField *GoTestField `protobuf:"bytes,6,opt" json:"OptionalField,omitempty"`
- // Required fields of all basic types
- F_BoolRequired *bool `protobuf:"varint,10,req,name=F_Bool_required" json:"F_Bool_required,omitempty"`
- F_Int32Required *int32 `protobuf:"varint,11,req,name=F_Int32_required" json:"F_Int32_required,omitempty"`
- F_Int64Required *int64 `protobuf:"varint,12,req,name=F_Int64_required" json:"F_Int64_required,omitempty"`
- F_Fixed32Required *uint32 `protobuf:"fixed32,13,req,name=F_Fixed32_required" json:"F_Fixed32_required,omitempty"`
- F_Fixed64Required *uint64 `protobuf:"fixed64,14,req,name=F_Fixed64_required" json:"F_Fixed64_required,omitempty"`
- F_Uint32Required *uint32 `protobuf:"varint,15,req,name=F_Uint32_required" json:"F_Uint32_required,omitempty"`
- F_Uint64Required *uint64 `protobuf:"varint,16,req,name=F_Uint64_required" json:"F_Uint64_required,omitempty"`
- F_FloatRequired *float32 `protobuf:"fixed32,17,req,name=F_Float_required" json:"F_Float_required,omitempty"`
- F_DoubleRequired *float64 `protobuf:"fixed64,18,req,name=F_Double_required" json:"F_Double_required,omitempty"`
- F_StringRequired *string `protobuf:"bytes,19,req,name=F_String_required" json:"F_String_required,omitempty"`
- F_BytesRequired []byte `protobuf:"bytes,101,req,name=F_Bytes_required" json:"F_Bytes_required,omitempty"`
- F_Sint32Required *int32 `protobuf:"zigzag32,102,req,name=F_Sint32_required" json:"F_Sint32_required,omitempty"`
- F_Sint64Required *int64 `protobuf:"zigzag64,103,req,name=F_Sint64_required" json:"F_Sint64_required,omitempty"`
- // Repeated fields of all basic types
- F_BoolRepeated []bool `protobuf:"varint,20,rep,name=F_Bool_repeated" json:"F_Bool_repeated,omitempty"`
- F_Int32Repeated []int32 `protobuf:"varint,21,rep,name=F_Int32_repeated" json:"F_Int32_repeated,omitempty"`
- F_Int64Repeated []int64 `protobuf:"varint,22,rep,name=F_Int64_repeated" json:"F_Int64_repeated,omitempty"`
- F_Fixed32Repeated []uint32 `protobuf:"fixed32,23,rep,name=F_Fixed32_repeated" json:"F_Fixed32_repeated,omitempty"`
- F_Fixed64Repeated []uint64 `protobuf:"fixed64,24,rep,name=F_Fixed64_repeated" json:"F_Fixed64_repeated,omitempty"`
- F_Uint32Repeated []uint32 `protobuf:"varint,25,rep,name=F_Uint32_repeated" json:"F_Uint32_repeated,omitempty"`
- F_Uint64Repeated []uint64 `protobuf:"varint,26,rep,name=F_Uint64_repeated" json:"F_Uint64_repeated,omitempty"`
- F_FloatRepeated []float32 `protobuf:"fixed32,27,rep,name=F_Float_repeated" json:"F_Float_repeated,omitempty"`
- F_DoubleRepeated []float64 `protobuf:"fixed64,28,rep,name=F_Double_repeated" json:"F_Double_repeated,omitempty"`
- F_StringRepeated []string `protobuf:"bytes,29,rep,name=F_String_repeated" json:"F_String_repeated,omitempty"`
- F_BytesRepeated [][]byte `protobuf:"bytes,201,rep,name=F_Bytes_repeated" json:"F_Bytes_repeated,omitempty"`
- F_Sint32Repeated []int32 `protobuf:"zigzag32,202,rep,name=F_Sint32_repeated" json:"F_Sint32_repeated,omitempty"`
- F_Sint64Repeated []int64 `protobuf:"zigzag64,203,rep,name=F_Sint64_repeated" json:"F_Sint64_repeated,omitempty"`
- // Optional fields of all basic types
- F_BoolOptional *bool `protobuf:"varint,30,opt,name=F_Bool_optional" json:"F_Bool_optional,omitempty"`
- F_Int32Optional *int32 `protobuf:"varint,31,opt,name=F_Int32_optional" json:"F_Int32_optional,omitempty"`
- F_Int64Optional *int64 `protobuf:"varint,32,opt,name=F_Int64_optional" json:"F_Int64_optional,omitempty"`
- F_Fixed32Optional *uint32 `protobuf:"fixed32,33,opt,name=F_Fixed32_optional" json:"F_Fixed32_optional,omitempty"`
- F_Fixed64Optional *uint64 `protobuf:"fixed64,34,opt,name=F_Fixed64_optional" json:"F_Fixed64_optional,omitempty"`
- F_Uint32Optional *uint32 `protobuf:"varint,35,opt,name=F_Uint32_optional" json:"F_Uint32_optional,omitempty"`
- F_Uint64Optional *uint64 `protobuf:"varint,36,opt,name=F_Uint64_optional" json:"F_Uint64_optional,omitempty"`
- F_FloatOptional *float32 `protobuf:"fixed32,37,opt,name=F_Float_optional" json:"F_Float_optional,omitempty"`
- F_DoubleOptional *float64 `protobuf:"fixed64,38,opt,name=F_Double_optional" json:"F_Double_optional,omitempty"`
- F_StringOptional *string `protobuf:"bytes,39,opt,name=F_String_optional" json:"F_String_optional,omitempty"`
- F_BytesOptional []byte `protobuf:"bytes,301,opt,name=F_Bytes_optional" json:"F_Bytes_optional,omitempty"`
- F_Sint32Optional *int32 `protobuf:"zigzag32,302,opt,name=F_Sint32_optional" json:"F_Sint32_optional,omitempty"`
- F_Sint64Optional *int64 `protobuf:"zigzag64,303,opt,name=F_Sint64_optional" json:"F_Sint64_optional,omitempty"`
- // Default-valued fields of all basic types
- F_BoolDefaulted *bool `protobuf:"varint,40,opt,name=F_Bool_defaulted,def=1" json:"F_Bool_defaulted,omitempty"`
- F_Int32Defaulted *int32 `protobuf:"varint,41,opt,name=F_Int32_defaulted,def=32" json:"F_Int32_defaulted,omitempty"`
- F_Int64Defaulted *int64 `protobuf:"varint,42,opt,name=F_Int64_defaulted,def=64" json:"F_Int64_defaulted,omitempty"`
- F_Fixed32Defaulted *uint32 `protobuf:"fixed32,43,opt,name=F_Fixed32_defaulted,def=320" json:"F_Fixed32_defaulted,omitempty"`
- F_Fixed64Defaulted *uint64 `protobuf:"fixed64,44,opt,name=F_Fixed64_defaulted,def=640" json:"F_Fixed64_defaulted,omitempty"`
- F_Uint32Defaulted *uint32 `protobuf:"varint,45,opt,name=F_Uint32_defaulted,def=3200" json:"F_Uint32_defaulted,omitempty"`
- F_Uint64Defaulted *uint64 `protobuf:"varint,46,opt,name=F_Uint64_defaulted,def=6400" json:"F_Uint64_defaulted,omitempty"`
- F_FloatDefaulted *float32 `protobuf:"fixed32,47,opt,name=F_Float_defaulted,def=314159" json:"F_Float_defaulted,omitempty"`
- F_DoubleDefaulted *float64 `protobuf:"fixed64,48,opt,name=F_Double_defaulted,def=271828" json:"F_Double_defaulted,omitempty"`
- F_StringDefaulted *string `protobuf:"bytes,49,opt,name=F_String_defaulted,def=hello, \"world!\"\n" json:"F_String_defaulted,omitempty"`
- F_BytesDefaulted []byte `protobuf:"bytes,401,opt,name=F_Bytes_defaulted,def=Bignose" json:"F_Bytes_defaulted,omitempty"`
- F_Sint32Defaulted *int32 `protobuf:"zigzag32,402,opt,name=F_Sint32_defaulted,def=-32" json:"F_Sint32_defaulted,omitempty"`
- F_Sint64Defaulted *int64 `protobuf:"zigzag64,403,opt,name=F_Sint64_defaulted,def=-64" json:"F_Sint64_defaulted,omitempty"`
- // Packed repeated fields (no string or bytes).
- F_BoolRepeatedPacked []bool `protobuf:"varint,50,rep,packed,name=F_Bool_repeated_packed" json:"F_Bool_repeated_packed,omitempty"`
- F_Int32RepeatedPacked []int32 `protobuf:"varint,51,rep,packed,name=F_Int32_repeated_packed" json:"F_Int32_repeated_packed,omitempty"`
- F_Int64RepeatedPacked []int64 `protobuf:"varint,52,rep,packed,name=F_Int64_repeated_packed" json:"F_Int64_repeated_packed,omitempty"`
- F_Fixed32RepeatedPacked []uint32 `protobuf:"fixed32,53,rep,packed,name=F_Fixed32_repeated_packed" json:"F_Fixed32_repeated_packed,omitempty"`
- F_Fixed64RepeatedPacked []uint64 `protobuf:"fixed64,54,rep,packed,name=F_Fixed64_repeated_packed" json:"F_Fixed64_repeated_packed,omitempty"`
- F_Uint32RepeatedPacked []uint32 `protobuf:"varint,55,rep,packed,name=F_Uint32_repeated_packed" json:"F_Uint32_repeated_packed,omitempty"`
- F_Uint64RepeatedPacked []uint64 `protobuf:"varint,56,rep,packed,name=F_Uint64_repeated_packed" json:"F_Uint64_repeated_packed,omitempty"`
- F_FloatRepeatedPacked []float32 `protobuf:"fixed32,57,rep,packed,name=F_Float_repeated_packed" json:"F_Float_repeated_packed,omitempty"`
- F_DoubleRepeatedPacked []float64 `protobuf:"fixed64,58,rep,packed,name=F_Double_repeated_packed" json:"F_Double_repeated_packed,omitempty"`
- F_Sint32RepeatedPacked []int32 `protobuf:"zigzag32,502,rep,packed,name=F_Sint32_repeated_packed" json:"F_Sint32_repeated_packed,omitempty"`
- F_Sint64RepeatedPacked []int64 `protobuf:"zigzag64,503,rep,packed,name=F_Sint64_repeated_packed" json:"F_Sint64_repeated_packed,omitempty"`
- Requiredgroup *GoTest_RequiredGroup `protobuf:"group,70,req,name=RequiredGroup" json:"requiredgroup,omitempty"`
- Repeatedgroup []*GoTest_RepeatedGroup `protobuf:"group,80,rep,name=RepeatedGroup" json:"repeatedgroup,omitempty"`
- Optionalgroup *GoTest_OptionalGroup `protobuf:"group,90,opt,name=OptionalGroup" json:"optionalgroup,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *GoTest) Reset() { *m = GoTest{} }
-func (m *GoTest) String() string { return proto.CompactTextString(m) }
-func (*GoTest) ProtoMessage() {}
-
-const Default_GoTest_F_BoolDefaulted bool = true
-const Default_GoTest_F_Int32Defaulted int32 = 32
-const Default_GoTest_F_Int64Defaulted int64 = 64
-const Default_GoTest_F_Fixed32Defaulted uint32 = 320
-const Default_GoTest_F_Fixed64Defaulted uint64 = 640
-const Default_GoTest_F_Uint32Defaulted uint32 = 3200
-const Default_GoTest_F_Uint64Defaulted uint64 = 6400
-const Default_GoTest_F_FloatDefaulted float32 = 314159
-const Default_GoTest_F_DoubleDefaulted float64 = 271828
-const Default_GoTest_F_StringDefaulted string = "hello, \"world!\"\n"
-
-var Default_GoTest_F_BytesDefaulted []byte = []byte("Bignose")
-
-const Default_GoTest_F_Sint32Defaulted int32 = -32
-const Default_GoTest_F_Sint64Defaulted int64 = -64
-
-func (m *GoTest) GetKind() GoTest_KIND {
- if m != nil && m.Kind != nil {
- return *m.Kind
- }
- return GoTest_VOID
-}
-
-func (m *GoTest) GetTable() string {
- if m != nil && m.Table != nil {
- return *m.Table
- }
- return ""
-}
-
-func (m *GoTest) GetParam() int32 {
- if m != nil && m.Param != nil {
- return *m.Param
- }
- return 0
-}
-
-func (m *GoTest) GetRequiredField() *GoTestField {
- if m != nil {
- return m.RequiredField
- }
- return nil
-}
-
-func (m *GoTest) GetRepeatedField() []*GoTestField {
- if m != nil {
- return m.RepeatedField
- }
- return nil
-}
-
-func (m *GoTest) GetOptionalField() *GoTestField {
- if m != nil {
- return m.OptionalField
- }
- return nil
-}
-
-func (m *GoTest) GetF_BoolRequired() bool {
- if m != nil && m.F_BoolRequired != nil {
- return *m.F_BoolRequired
- }
- return false
-}
-
-func (m *GoTest) GetF_Int32Required() int32 {
- if m != nil && m.F_Int32Required != nil {
- return *m.F_Int32Required
- }
- return 0
-}
-
-func (m *GoTest) GetF_Int64Required() int64 {
- if m != nil && m.F_Int64Required != nil {
- return *m.F_Int64Required
- }
- return 0
-}
-
-func (m *GoTest) GetF_Fixed32Required() uint32 {
- if m != nil && m.F_Fixed32Required != nil {
- return *m.F_Fixed32Required
- }
- return 0
-}
-
-func (m *GoTest) GetF_Fixed64Required() uint64 {
- if m != nil && m.F_Fixed64Required != nil {
- return *m.F_Fixed64Required
- }
- return 0
-}
-
-func (m *GoTest) GetF_Uint32Required() uint32 {
- if m != nil && m.F_Uint32Required != nil {
- return *m.F_Uint32Required
- }
- return 0
-}
-
-func (m *GoTest) GetF_Uint64Required() uint64 {
- if m != nil && m.F_Uint64Required != nil {
- return *m.F_Uint64Required
- }
- return 0
-}
-
-func (m *GoTest) GetF_FloatRequired() float32 {
- if m != nil && m.F_FloatRequired != nil {
- return *m.F_FloatRequired
- }
- return 0
-}
-
-func (m *GoTest) GetF_DoubleRequired() float64 {
- if m != nil && m.F_DoubleRequired != nil {
- return *m.F_DoubleRequired
- }
- return 0
-}
-
-func (m *GoTest) GetF_StringRequired() string {
- if m != nil && m.F_StringRequired != nil {
- return *m.F_StringRequired
- }
- return ""
-}
-
-func (m *GoTest) GetF_BytesRequired() []byte {
- if m != nil {
- return m.F_BytesRequired
- }
- return nil
-}
-
-func (m *GoTest) GetF_Sint32Required() int32 {
- if m != nil && m.F_Sint32Required != nil {
- return *m.F_Sint32Required
- }
- return 0
-}
-
-func (m *GoTest) GetF_Sint64Required() int64 {
- if m != nil && m.F_Sint64Required != nil {
- return *m.F_Sint64Required
- }
- return 0
-}
-
-func (m *GoTest) GetF_BoolRepeated() []bool {
- if m != nil {
- return m.F_BoolRepeated
- }
- return nil
-}
-
-func (m *GoTest) GetF_Int32Repeated() []int32 {
- if m != nil {
- return m.F_Int32Repeated
- }
- return nil
-}
-
-func (m *GoTest) GetF_Int64Repeated() []int64 {
- if m != nil {
- return m.F_Int64Repeated
- }
- return nil
-}
-
-func (m *GoTest) GetF_Fixed32Repeated() []uint32 {
- if m != nil {
- return m.F_Fixed32Repeated
- }
- return nil
-}
-
-func (m *GoTest) GetF_Fixed64Repeated() []uint64 {
- if m != nil {
- return m.F_Fixed64Repeated
- }
- return nil
-}
-
-func (m *GoTest) GetF_Uint32Repeated() []uint32 {
- if m != nil {
- return m.F_Uint32Repeated
- }
- return nil
-}
-
-func (m *GoTest) GetF_Uint64Repeated() []uint64 {
- if m != nil {
- return m.F_Uint64Repeated
- }
- return nil
-}
-
-func (m *GoTest) GetF_FloatRepeated() []float32 {
- if m != nil {
- return m.F_FloatRepeated
- }
- return nil
-}
-
-func (m *GoTest) GetF_DoubleRepeated() []float64 {
- if m != nil {
- return m.F_DoubleRepeated
- }
- return nil
-}
-
-func (m *GoTest) GetF_StringRepeated() []string {
- if m != nil {
- return m.F_StringRepeated
- }
- return nil
-}
-
-func (m *GoTest) GetF_BytesRepeated() [][]byte {
- if m != nil {
- return m.F_BytesRepeated
- }
- return nil
-}
-
-func (m *GoTest) GetF_Sint32Repeated() []int32 {
- if m != nil {
- return m.F_Sint32Repeated
- }
- return nil
-}
-
-func (m *GoTest) GetF_Sint64Repeated() []int64 {
- if m != nil {
- return m.F_Sint64Repeated
- }
- return nil
-}
-
-func (m *GoTest) GetF_BoolOptional() bool {
- if m != nil && m.F_BoolOptional != nil {
- return *m.F_BoolOptional
- }
- return false
-}
-
-func (m *GoTest) GetF_Int32Optional() int32 {
- if m != nil && m.F_Int32Optional != nil {
- return *m.F_Int32Optional
- }
- return 0
-}
-
-func (m *GoTest) GetF_Int64Optional() int64 {
- if m != nil && m.F_Int64Optional != nil {
- return *m.F_Int64Optional
- }
- return 0
-}
-
-func (m *GoTest) GetF_Fixed32Optional() uint32 {
- if m != nil && m.F_Fixed32Optional != nil {
- return *m.F_Fixed32Optional
- }
- return 0
-}
-
-func (m *GoTest) GetF_Fixed64Optional() uint64 {
- if m != nil && m.F_Fixed64Optional != nil {
- return *m.F_Fixed64Optional
- }
- return 0
-}
-
-func (m *GoTest) GetF_Uint32Optional() uint32 {
- if m != nil && m.F_Uint32Optional != nil {
- return *m.F_Uint32Optional
- }
- return 0
-}
-
-func (m *GoTest) GetF_Uint64Optional() uint64 {
- if m != nil && m.F_Uint64Optional != nil {
- return *m.F_Uint64Optional
- }
- return 0
-}
-
-func (m *GoTest) GetF_FloatOptional() float32 {
- if m != nil && m.F_FloatOptional != nil {
- return *m.F_FloatOptional
- }
- return 0
-}
-
-func (m *GoTest) GetF_DoubleOptional() float64 {
- if m != nil && m.F_DoubleOptional != nil {
- return *m.F_DoubleOptional
- }
- return 0
-}
-
-func (m *GoTest) GetF_StringOptional() string {
- if m != nil && m.F_StringOptional != nil {
- return *m.F_StringOptional
- }
- return ""
-}
-
-func (m *GoTest) GetF_BytesOptional() []byte {
- if m != nil {
- return m.F_BytesOptional
- }
- return nil
-}
-
-func (m *GoTest) GetF_Sint32Optional() int32 {
- if m != nil && m.F_Sint32Optional != nil {
- return *m.F_Sint32Optional
- }
- return 0
-}
-
-func (m *GoTest) GetF_Sint64Optional() int64 {
- if m != nil && m.F_Sint64Optional != nil {
- return *m.F_Sint64Optional
- }
- return 0
-}
-
-func (m *GoTest) GetF_BoolDefaulted() bool {
- if m != nil && m.F_BoolDefaulted != nil {
- return *m.F_BoolDefaulted
- }
- return Default_GoTest_F_BoolDefaulted
-}
-
-func (m *GoTest) GetF_Int32Defaulted() int32 {
- if m != nil && m.F_Int32Defaulted != nil {
- return *m.F_Int32Defaulted
- }
- return Default_GoTest_F_Int32Defaulted
-}
-
-func (m *GoTest) GetF_Int64Defaulted() int64 {
- if m != nil && m.F_Int64Defaulted != nil {
- return *m.F_Int64Defaulted
- }
- return Default_GoTest_F_Int64Defaulted
-}
-
-func (m *GoTest) GetF_Fixed32Defaulted() uint32 {
- if m != nil && m.F_Fixed32Defaulted != nil {
- return *m.F_Fixed32Defaulted
- }
- return Default_GoTest_F_Fixed32Defaulted
-}
-
-func (m *GoTest) GetF_Fixed64Defaulted() uint64 {
- if m != nil && m.F_Fixed64Defaulted != nil {
- return *m.F_Fixed64Defaulted
- }
- return Default_GoTest_F_Fixed64Defaulted
-}
-
-func (m *GoTest) GetF_Uint32Defaulted() uint32 {
- if m != nil && m.F_Uint32Defaulted != nil {
- return *m.F_Uint32Defaulted
- }
- return Default_GoTest_F_Uint32Defaulted
-}
-
-func (m *GoTest) GetF_Uint64Defaulted() uint64 {
- if m != nil && m.F_Uint64Defaulted != nil {
- return *m.F_Uint64Defaulted
- }
- return Default_GoTest_F_Uint64Defaulted
-}
-
-func (m *GoTest) GetF_FloatDefaulted() float32 {
- if m != nil && m.F_FloatDefaulted != nil {
- return *m.F_FloatDefaulted
- }
- return Default_GoTest_F_FloatDefaulted
-}
-
-func (m *GoTest) GetF_DoubleDefaulted() float64 {
- if m != nil && m.F_DoubleDefaulted != nil {
- return *m.F_DoubleDefaulted
- }
- return Default_GoTest_F_DoubleDefaulted
-}
-
-func (m *GoTest) GetF_StringDefaulted() string {
- if m != nil && m.F_StringDefaulted != nil {
- return *m.F_StringDefaulted
- }
- return Default_GoTest_F_StringDefaulted
-}
-
-func (m *GoTest) GetF_BytesDefaulted() []byte {
- if m != nil && m.F_BytesDefaulted != nil {
- return m.F_BytesDefaulted
- }
- return append([]byte(nil), Default_GoTest_F_BytesDefaulted...)
-}
-
-func (m *GoTest) GetF_Sint32Defaulted() int32 {
- if m != nil && m.F_Sint32Defaulted != nil {
- return *m.F_Sint32Defaulted
- }
- return Default_GoTest_F_Sint32Defaulted
-}
-
-func (m *GoTest) GetF_Sint64Defaulted() int64 {
- if m != nil && m.F_Sint64Defaulted != nil {
- return *m.F_Sint64Defaulted
- }
- return Default_GoTest_F_Sint64Defaulted
-}
-
-func (m *GoTest) GetF_BoolRepeatedPacked() []bool {
- if m != nil {
- return m.F_BoolRepeatedPacked
- }
- return nil
-}
-
-func (m *GoTest) GetF_Int32RepeatedPacked() []int32 {
- if m != nil {
- return m.F_Int32RepeatedPacked
- }
- return nil
-}
-
-func (m *GoTest) GetF_Int64RepeatedPacked() []int64 {
- if m != nil {
- return m.F_Int64RepeatedPacked
- }
- return nil
-}
-
-func (m *GoTest) GetF_Fixed32RepeatedPacked() []uint32 {
- if m != nil {
- return m.F_Fixed32RepeatedPacked
- }
- return nil
-}
-
-func (m *GoTest) GetF_Fixed64RepeatedPacked() []uint64 {
- if m != nil {
- return m.F_Fixed64RepeatedPacked
- }
- return nil
-}
-
-func (m *GoTest) GetF_Uint32RepeatedPacked() []uint32 {
- if m != nil {
- return m.F_Uint32RepeatedPacked
- }
- return nil
-}
-
-func (m *GoTest) GetF_Uint64RepeatedPacked() []uint64 {
- if m != nil {
- return m.F_Uint64RepeatedPacked
- }
- return nil
-}
-
-func (m *GoTest) GetF_FloatRepeatedPacked() []float32 {
- if m != nil {
- return m.F_FloatRepeatedPacked
- }
- return nil
-}
-
-func (m *GoTest) GetF_DoubleRepeatedPacked() []float64 {
- if m != nil {
- return m.F_DoubleRepeatedPacked
- }
- return nil
-}
-
-func (m *GoTest) GetF_Sint32RepeatedPacked() []int32 {
- if m != nil {
- return m.F_Sint32RepeatedPacked
- }
- return nil
-}
-
-func (m *GoTest) GetF_Sint64RepeatedPacked() []int64 {
- if m != nil {
- return m.F_Sint64RepeatedPacked
- }
- return nil
-}
-
-func (m *GoTest) GetRequiredgroup() *GoTest_RequiredGroup {
- if m != nil {
- return m.Requiredgroup
- }
- return nil
-}
-
-func (m *GoTest) GetRepeatedgroup() []*GoTest_RepeatedGroup {
- if m != nil {
- return m.Repeatedgroup
- }
- return nil
-}
-
-func (m *GoTest) GetOptionalgroup() *GoTest_OptionalGroup {
- if m != nil {
- return m.Optionalgroup
- }
- return nil
-}
-
-// Required, repeated, and optional groups.
-type GoTest_RequiredGroup struct {
- RequiredField *string `protobuf:"bytes,71,req" json:"RequiredField,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *GoTest_RequiredGroup) Reset() { *m = GoTest_RequiredGroup{} }
-func (m *GoTest_RequiredGroup) String() string { return proto.CompactTextString(m) }
-func (*GoTest_RequiredGroup) ProtoMessage() {}
-
-func (m *GoTest_RequiredGroup) GetRequiredField() string {
- if m != nil && m.RequiredField != nil {
- return *m.RequiredField
- }
- return ""
-}
-
-type GoTest_RepeatedGroup struct {
- RequiredField *string `protobuf:"bytes,81,req" json:"RequiredField,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *GoTest_RepeatedGroup) Reset() { *m = GoTest_RepeatedGroup{} }
-func (m *GoTest_RepeatedGroup) String() string { return proto.CompactTextString(m) }
-func (*GoTest_RepeatedGroup) ProtoMessage() {}
-
-func (m *GoTest_RepeatedGroup) GetRequiredField() string {
- if m != nil && m.RequiredField != nil {
- return *m.RequiredField
- }
- return ""
-}
-
-type GoTest_OptionalGroup struct {
- RequiredField *string `protobuf:"bytes,91,req" json:"RequiredField,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *GoTest_OptionalGroup) Reset() { *m = GoTest_OptionalGroup{} }
-func (m *GoTest_OptionalGroup) String() string { return proto.CompactTextString(m) }
-func (*GoTest_OptionalGroup) ProtoMessage() {}
-
-func (m *GoTest_OptionalGroup) GetRequiredField() string {
- if m != nil && m.RequiredField != nil {
- return *m.RequiredField
- }
- return ""
-}
-
-// For testing skipping of unrecognized fields.
-// Numbers are all big, larger than tag numbers in GoTestField,
-// the message used in the corresponding test.
-type GoSkipTest struct {
- SkipInt32 *int32 `protobuf:"varint,11,req,name=skip_int32" json:"skip_int32,omitempty"`
- SkipFixed32 *uint32 `protobuf:"fixed32,12,req,name=skip_fixed32" json:"skip_fixed32,omitempty"`
- SkipFixed64 *uint64 `protobuf:"fixed64,13,req,name=skip_fixed64" json:"skip_fixed64,omitempty"`
- SkipString *string `protobuf:"bytes,14,req,name=skip_string" json:"skip_string,omitempty"`
- Skipgroup *GoSkipTest_SkipGroup `protobuf:"group,15,req,name=SkipGroup" json:"skipgroup,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *GoSkipTest) Reset() { *m = GoSkipTest{} }
-func (m *GoSkipTest) String() string { return proto.CompactTextString(m) }
-func (*GoSkipTest) ProtoMessage() {}
-
-func (m *GoSkipTest) GetSkipInt32() int32 {
- if m != nil && m.SkipInt32 != nil {
- return *m.SkipInt32
- }
- return 0
-}
-
-func (m *GoSkipTest) GetSkipFixed32() uint32 {
- if m != nil && m.SkipFixed32 != nil {
- return *m.SkipFixed32
- }
- return 0
-}
-
-func (m *GoSkipTest) GetSkipFixed64() uint64 {
- if m != nil && m.SkipFixed64 != nil {
- return *m.SkipFixed64
- }
- return 0
-}
-
-func (m *GoSkipTest) GetSkipString() string {
- if m != nil && m.SkipString != nil {
- return *m.SkipString
- }
- return ""
-}
-
-func (m *GoSkipTest) GetSkipgroup() *GoSkipTest_SkipGroup {
- if m != nil {
- return m.Skipgroup
- }
- return nil
-}
-
-type GoSkipTest_SkipGroup struct {
- GroupInt32 *int32 `protobuf:"varint,16,req,name=group_int32" json:"group_int32,omitempty"`
- GroupString *string `protobuf:"bytes,17,req,name=group_string" json:"group_string,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *GoSkipTest_SkipGroup) Reset() { *m = GoSkipTest_SkipGroup{} }
-func (m *GoSkipTest_SkipGroup) String() string { return proto.CompactTextString(m) }
-func (*GoSkipTest_SkipGroup) ProtoMessage() {}
-
-func (m *GoSkipTest_SkipGroup) GetGroupInt32() int32 {
- if m != nil && m.GroupInt32 != nil {
- return *m.GroupInt32
- }
- return 0
-}
-
-func (m *GoSkipTest_SkipGroup) GetGroupString() string {
- if m != nil && m.GroupString != nil {
- return *m.GroupString
- }
- return ""
-}
-
-// For testing packed/non-packed decoder switching.
-// A serialized instance of one should be deserializable as the other.
-type NonPackedTest struct {
- A []int32 `protobuf:"varint,1,rep,name=a" json:"a,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *NonPackedTest) Reset() { *m = NonPackedTest{} }
-func (m *NonPackedTest) String() string { return proto.CompactTextString(m) }
-func (*NonPackedTest) ProtoMessage() {}
-
-func (m *NonPackedTest) GetA() []int32 {
- if m != nil {
- return m.A
- }
- return nil
-}
-
-type PackedTest struct {
- B []int32 `protobuf:"varint,1,rep,packed,name=b" json:"b,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *PackedTest) Reset() { *m = PackedTest{} }
-func (m *PackedTest) String() string { return proto.CompactTextString(m) }
-func (*PackedTest) ProtoMessage() {}
-
-func (m *PackedTest) GetB() []int32 {
- if m != nil {
- return m.B
- }
- return nil
-}
-
-type MaxTag struct {
- // Maximum possible tag number.
- LastField *string `protobuf:"bytes,536870911,opt,name=last_field" json:"last_field,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *MaxTag) Reset() { *m = MaxTag{} }
-func (m *MaxTag) String() string { return proto.CompactTextString(m) }
-func (*MaxTag) ProtoMessage() {}
-
-func (m *MaxTag) GetLastField() string {
- if m != nil && m.LastField != nil {
- return *m.LastField
- }
- return ""
-}
-
-type OldMessage struct {
- Nested *OldMessage_Nested `protobuf:"bytes,1,opt,name=nested" json:"nested,omitempty"`
- Num *int32 `protobuf:"varint,2,opt,name=num" json:"num,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *OldMessage) Reset() { *m = OldMessage{} }
-func (m *OldMessage) String() string { return proto.CompactTextString(m) }
-func (*OldMessage) ProtoMessage() {}
-
-func (m *OldMessage) GetNested() *OldMessage_Nested {
- if m != nil {
- return m.Nested
- }
- return nil
-}
-
-func (m *OldMessage) GetNum() int32 {
- if m != nil && m.Num != nil {
- return *m.Num
- }
- return 0
-}
-
-type OldMessage_Nested struct {
- Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *OldMessage_Nested) Reset() { *m = OldMessage_Nested{} }
-func (m *OldMessage_Nested) String() string { return proto.CompactTextString(m) }
-func (*OldMessage_Nested) ProtoMessage() {}
-
-func (m *OldMessage_Nested) GetName() string {
- if m != nil && m.Name != nil {
- return *m.Name
- }
- return ""
-}
-
-// NewMessage is wire compatible with OldMessage;
-// imagine it as a future version.
-type NewMessage struct {
- Nested *NewMessage_Nested `protobuf:"bytes,1,opt,name=nested" json:"nested,omitempty"`
- // This is an int32 in OldMessage.
- Num *int64 `protobuf:"varint,2,opt,name=num" json:"num,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *NewMessage) Reset() { *m = NewMessage{} }
-func (m *NewMessage) String() string { return proto.CompactTextString(m) }
-func (*NewMessage) ProtoMessage() {}
-
-func (m *NewMessage) GetNested() *NewMessage_Nested {
- if m != nil {
- return m.Nested
- }
- return nil
-}
-
-func (m *NewMessage) GetNum() int64 {
- if m != nil && m.Num != nil {
- return *m.Num
- }
- return 0
-}
-
-type NewMessage_Nested struct {
- Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
- FoodGroup *string `protobuf:"bytes,2,opt,name=food_group" json:"food_group,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *NewMessage_Nested) Reset() { *m = NewMessage_Nested{} }
-func (m *NewMessage_Nested) String() string { return proto.CompactTextString(m) }
-func (*NewMessage_Nested) ProtoMessage() {}
-
-func (m *NewMessage_Nested) GetName() string {
- if m != nil && m.Name != nil {
- return *m.Name
- }
- return ""
-}
-
-func (m *NewMessage_Nested) GetFoodGroup() string {
- if m != nil && m.FoodGroup != nil {
- return *m.FoodGroup
- }
- return ""
-}
-
-type InnerMessage struct {
- Host *string `protobuf:"bytes,1,req,name=host" json:"host,omitempty"`
- Port *int32 `protobuf:"varint,2,opt,name=port,def=4000" json:"port,omitempty"`
- Connected *bool `protobuf:"varint,3,opt,name=connected" json:"connected,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *InnerMessage) Reset() { *m = InnerMessage{} }
-func (m *InnerMessage) String() string { return proto.CompactTextString(m) }
-func (*InnerMessage) ProtoMessage() {}
-
-const Default_InnerMessage_Port int32 = 4000
-
-func (m *InnerMessage) GetHost() string {
- if m != nil && m.Host != nil {
- return *m.Host
- }
- return ""
-}
-
-func (m *InnerMessage) GetPort() int32 {
- if m != nil && m.Port != nil {
- return *m.Port
- }
- return Default_InnerMessage_Port
-}
-
-func (m *InnerMessage) GetConnected() bool {
- if m != nil && m.Connected != nil {
- return *m.Connected
- }
- return false
-}
-
-type OtherMessage struct {
- Key *int64 `protobuf:"varint,1,opt,name=key" json:"key,omitempty"`
- Value []byte `protobuf:"bytes,2,opt,name=value" json:"value,omitempty"`
- Weight *float32 `protobuf:"fixed32,3,opt,name=weight" json:"weight,omitempty"`
- Inner *InnerMessage `protobuf:"bytes,4,opt,name=inner" json:"inner,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *OtherMessage) Reset() { *m = OtherMessage{} }
-func (m *OtherMessage) String() string { return proto.CompactTextString(m) }
-func (*OtherMessage) ProtoMessage() {}
-
-func (m *OtherMessage) GetKey() int64 {
- if m != nil && m.Key != nil {
- return *m.Key
- }
- return 0
-}
-
-func (m *OtherMessage) GetValue() []byte {
- if m != nil {
- return m.Value
- }
- return nil
-}
-
-func (m *OtherMessage) GetWeight() float32 {
- if m != nil && m.Weight != nil {
- return *m.Weight
- }
- return 0
-}
-
-func (m *OtherMessage) GetInner() *InnerMessage {
- if m != nil {
- return m.Inner
- }
- return nil
-}
-
-type MyMessage struct {
- Count *int32 `protobuf:"varint,1,req,name=count" json:"count,omitempty"`
- Name *string `protobuf:"bytes,2,opt,name=name" json:"name,omitempty"`
- Quote *string `protobuf:"bytes,3,opt,name=quote" json:"quote,omitempty"`
- Pet []string `protobuf:"bytes,4,rep,name=pet" json:"pet,omitempty"`
- Inner *InnerMessage `protobuf:"bytes,5,opt,name=inner" json:"inner,omitempty"`
- Others []*OtherMessage `protobuf:"bytes,6,rep,name=others" json:"others,omitempty"`
- RepInner []*InnerMessage `protobuf:"bytes,12,rep,name=rep_inner" json:"rep_inner,omitempty"`
- Bikeshed *MyMessage_Color `protobuf:"varint,7,opt,name=bikeshed,enum=testdata.MyMessage_Color" json:"bikeshed,omitempty"`
- Somegroup *MyMessage_SomeGroup `protobuf:"group,8,opt,name=SomeGroup" json:"somegroup,omitempty"`
- // This field becomes [][]byte in the generated code.
- RepBytes [][]byte `protobuf:"bytes,10,rep,name=rep_bytes" json:"rep_bytes,omitempty"`
- Bigfloat *float64 `protobuf:"fixed64,11,opt,name=bigfloat" json:"bigfloat,omitempty"`
- XXX_extensions map[int32]proto.Extension `json:"-"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *MyMessage) Reset() { *m = MyMessage{} }
-func (m *MyMessage) String() string { return proto.CompactTextString(m) }
-func (*MyMessage) ProtoMessage() {}
-
-var extRange_MyMessage = []proto.ExtensionRange{
- {100, 536870911},
-}
-
-func (*MyMessage) ExtensionRangeArray() []proto.ExtensionRange {
- return extRange_MyMessage
-}
-func (m *MyMessage) ExtensionMap() map[int32]proto.Extension {
- if m.XXX_extensions == nil {
- m.XXX_extensions = make(map[int32]proto.Extension)
- }
- return m.XXX_extensions
-}
-
-func (m *MyMessage) GetCount() int32 {
- if m != nil && m.Count != nil {
- return *m.Count
- }
- return 0
-}
-
-func (m *MyMessage) GetName() string {
- if m != nil && m.Name != nil {
- return *m.Name
- }
- return ""
-}
-
-func (m *MyMessage) GetQuote() string {
- if m != nil && m.Quote != nil {
- return *m.Quote
- }
- return ""
-}
-
-func (m *MyMessage) GetPet() []string {
- if m != nil {
- return m.Pet
- }
- return nil
-}
-
-func (m *MyMessage) GetInner() *InnerMessage {
- if m != nil {
- return m.Inner
- }
- return nil
-}
-
-func (m *MyMessage) GetOthers() []*OtherMessage {
- if m != nil {
- return m.Others
- }
- return nil
-}
-
-func (m *MyMessage) GetRepInner() []*InnerMessage {
- if m != nil {
- return m.RepInner
- }
- return nil
-}
-
-func (m *MyMessage) GetBikeshed() MyMessage_Color {
- if m != nil && m.Bikeshed != nil {
- return *m.Bikeshed
- }
- return MyMessage_RED
-}
-
-func (m *MyMessage) GetSomegroup() *MyMessage_SomeGroup {
- if m != nil {
- return m.Somegroup
- }
- return nil
-}
-
-func (m *MyMessage) GetRepBytes() [][]byte {
- if m != nil {
- return m.RepBytes
- }
- return nil
-}
-
-func (m *MyMessage) GetBigfloat() float64 {
- if m != nil && m.Bigfloat != nil {
- return *m.Bigfloat
- }
- return 0
-}
-
-type MyMessage_SomeGroup struct {
- GroupField *int32 `protobuf:"varint,9,opt,name=group_field" json:"group_field,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *MyMessage_SomeGroup) Reset() { *m = MyMessage_SomeGroup{} }
-func (m *MyMessage_SomeGroup) String() string { return proto.CompactTextString(m) }
-func (*MyMessage_SomeGroup) ProtoMessage() {}
-
-func (m *MyMessage_SomeGroup) GetGroupField() int32 {
- if m != nil && m.GroupField != nil {
- return *m.GroupField
- }
- return 0
-}
-
-type Ext struct {
- Data *string `protobuf:"bytes,1,opt,name=data" json:"data,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *Ext) Reset() { *m = Ext{} }
-func (m *Ext) String() string { return proto.CompactTextString(m) }
-func (*Ext) ProtoMessage() {}
-
-func (m *Ext) GetData() string {
- if m != nil && m.Data != nil {
- return *m.Data
- }
- return ""
-}
-
-var E_Ext_More = &proto.ExtensionDesc{
- ExtendedType: (*MyMessage)(nil),
- ExtensionType: (*Ext)(nil),
- Field: 103,
- Name: "testdata.Ext.more",
- Tag: "bytes,103,opt,name=more",
-}
-
-var E_Ext_Text = &proto.ExtensionDesc{
- ExtendedType: (*MyMessage)(nil),
- ExtensionType: (*string)(nil),
- Field: 104,
- Name: "testdata.Ext.text",
- Tag: "bytes,104,opt,name=text",
-}
-
-var E_Ext_Number = &proto.ExtensionDesc{
- ExtendedType: (*MyMessage)(nil),
- ExtensionType: (*int32)(nil),
- Field: 105,
- Name: "testdata.Ext.number",
- Tag: "varint,105,opt,name=number",
-}
-
-type DefaultsMessage struct {
- XXX_extensions map[int32]proto.Extension `json:"-"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *DefaultsMessage) Reset() { *m = DefaultsMessage{} }
-func (m *DefaultsMessage) String() string { return proto.CompactTextString(m) }
-func (*DefaultsMessage) ProtoMessage() {}
-
-var extRange_DefaultsMessage = []proto.ExtensionRange{
- {100, 536870911},
-}
-
-func (*DefaultsMessage) ExtensionRangeArray() []proto.ExtensionRange {
- return extRange_DefaultsMessage
-}
-func (m *DefaultsMessage) ExtensionMap() map[int32]proto.Extension {
- if m.XXX_extensions == nil {
- m.XXX_extensions = make(map[int32]proto.Extension)
- }
- return m.XXX_extensions
-}
-
-type MyMessageSet struct {
- XXX_extensions map[int32]proto.Extension `json:"-"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *MyMessageSet) Reset() { *m = MyMessageSet{} }
-func (m *MyMessageSet) String() string { return proto.CompactTextString(m) }
-func (*MyMessageSet) ProtoMessage() {}
-
-func (m *MyMessageSet) Marshal() ([]byte, error) {
- return proto.MarshalMessageSet(m.ExtensionMap())
-}
-func (m *MyMessageSet) Unmarshal(buf []byte) error {
- return proto.UnmarshalMessageSet(buf, m.ExtensionMap())
-}
-func (m *MyMessageSet) MarshalJSON() ([]byte, error) {
- return proto.MarshalMessageSetJSON(m.XXX_extensions)
-}
-func (m *MyMessageSet) UnmarshalJSON(buf []byte) error {
- return proto.UnmarshalMessageSetJSON(buf, m.XXX_extensions)
-}
-
-// ensure MyMessageSet satisfies proto.Marshaler and proto.Unmarshaler
-var _ proto.Marshaler = (*MyMessageSet)(nil)
-var _ proto.Unmarshaler = (*MyMessageSet)(nil)
-
-var extRange_MyMessageSet = []proto.ExtensionRange{
- {100, 2147483646},
-}
-
-func (*MyMessageSet) ExtensionRangeArray() []proto.ExtensionRange {
- return extRange_MyMessageSet
-}
-func (m *MyMessageSet) ExtensionMap() map[int32]proto.Extension {
- if m.XXX_extensions == nil {
- m.XXX_extensions = make(map[int32]proto.Extension)
- }
- return m.XXX_extensions
-}
-
-type Empty struct {
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *Empty) Reset() { *m = Empty{} }
-func (m *Empty) String() string { return proto.CompactTextString(m) }
-func (*Empty) ProtoMessage() {}
-
-type MessageList struct {
- Message []*MessageList_Message `protobuf:"group,1,rep" json:"message,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *MessageList) Reset() { *m = MessageList{} }
-func (m *MessageList) String() string { return proto.CompactTextString(m) }
-func (*MessageList) ProtoMessage() {}
-
-func (m *MessageList) GetMessage() []*MessageList_Message {
- if m != nil {
- return m.Message
- }
- return nil
-}
-
-type MessageList_Message struct {
- Name *string `protobuf:"bytes,2,req,name=name" json:"name,omitempty"`
- Count *int32 `protobuf:"varint,3,req,name=count" json:"count,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *MessageList_Message) Reset() { *m = MessageList_Message{} }
-func (m *MessageList_Message) String() string { return proto.CompactTextString(m) }
-func (*MessageList_Message) ProtoMessage() {}
-
-func (m *MessageList_Message) GetName() string {
- if m != nil && m.Name != nil {
- return *m.Name
- }
- return ""
-}
-
-func (m *MessageList_Message) GetCount() int32 {
- if m != nil && m.Count != nil {
- return *m.Count
- }
- return 0
-}
-
-type Strings struct {
- StringField *string `protobuf:"bytes,1,opt,name=string_field" json:"string_field,omitempty"`
- BytesField []byte `protobuf:"bytes,2,opt,name=bytes_field" json:"bytes_field,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *Strings) Reset() { *m = Strings{} }
-func (m *Strings) String() string { return proto.CompactTextString(m) }
-func (*Strings) ProtoMessage() {}
-
-func (m *Strings) GetStringField() string {
- if m != nil && m.StringField != nil {
- return *m.StringField
- }
- return ""
-}
-
-func (m *Strings) GetBytesField() []byte {
- if m != nil {
- return m.BytesField
- }
- return nil
-}
-
-type Defaults struct {
- // Default-valued fields of all basic types.
- // Same as GoTest, but copied here to make testing easier.
- F_Bool *bool `protobuf:"varint,1,opt,def=1" json:"F_Bool,omitempty"`
- F_Int32 *int32 `protobuf:"varint,2,opt,def=32" json:"F_Int32,omitempty"`
- F_Int64 *int64 `protobuf:"varint,3,opt,def=64" json:"F_Int64,omitempty"`
- F_Fixed32 *uint32 `protobuf:"fixed32,4,opt,def=320" json:"F_Fixed32,omitempty"`
- F_Fixed64 *uint64 `protobuf:"fixed64,5,opt,def=640" json:"F_Fixed64,omitempty"`
- F_Uint32 *uint32 `protobuf:"varint,6,opt,def=3200" json:"F_Uint32,omitempty"`
- F_Uint64 *uint64 `protobuf:"varint,7,opt,def=6400" json:"F_Uint64,omitempty"`
- F_Float *float32 `protobuf:"fixed32,8,opt,def=314159" json:"F_Float,omitempty"`
- F_Double *float64 `protobuf:"fixed64,9,opt,def=271828" json:"F_Double,omitempty"`
- F_String *string `protobuf:"bytes,10,opt,def=hello, \"world!\"\n" json:"F_String,omitempty"`
- F_Bytes []byte `protobuf:"bytes,11,opt,def=Bignose" json:"F_Bytes,omitempty"`
- F_Sint32 *int32 `protobuf:"zigzag32,12,opt,def=-32" json:"F_Sint32,omitempty"`
- F_Sint64 *int64 `protobuf:"zigzag64,13,opt,def=-64" json:"F_Sint64,omitempty"`
- F_Enum *Defaults_Color `protobuf:"varint,14,opt,enum=testdata.Defaults_Color,def=1" json:"F_Enum,omitempty"`
- // More fields with crazy defaults.
- F_Pinf *float32 `protobuf:"fixed32,15,opt,def=inf" json:"F_Pinf,omitempty"`
- F_Ninf *float32 `protobuf:"fixed32,16,opt,def=-inf" json:"F_Ninf,omitempty"`
- F_Nan *float32 `protobuf:"fixed32,17,opt,def=nan" json:"F_Nan,omitempty"`
- // Sub-message.
- Sub *SubDefaults `protobuf:"bytes,18,opt,name=sub" json:"sub,omitempty"`
- // Redundant but explicit defaults.
- StrZero *string `protobuf:"bytes,19,opt,name=str_zero,def=" json:"str_zero,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *Defaults) Reset() { *m = Defaults{} }
-func (m *Defaults) String() string { return proto.CompactTextString(m) }
-func (*Defaults) ProtoMessage() {}
-
-const Default_Defaults_F_Bool bool = true
-const Default_Defaults_F_Int32 int32 = 32
-const Default_Defaults_F_Int64 int64 = 64
-const Default_Defaults_F_Fixed32 uint32 = 320
-const Default_Defaults_F_Fixed64 uint64 = 640
-const Default_Defaults_F_Uint32 uint32 = 3200
-const Default_Defaults_F_Uint64 uint64 = 6400
-const Default_Defaults_F_Float float32 = 314159
-const Default_Defaults_F_Double float64 = 271828
-const Default_Defaults_F_String string = "hello, \"world!\"\n"
-
-var Default_Defaults_F_Bytes []byte = []byte("Bignose")
-
-const Default_Defaults_F_Sint32 int32 = -32
-const Default_Defaults_F_Sint64 int64 = -64
-const Default_Defaults_F_Enum Defaults_Color = Defaults_GREEN
-
-var Default_Defaults_F_Pinf float32 = float32(math.Inf(1))
-var Default_Defaults_F_Ninf float32 = float32(math.Inf(-1))
-var Default_Defaults_F_Nan float32 = float32(math.NaN())
-
-func (m *Defaults) GetF_Bool() bool {
- if m != nil && m.F_Bool != nil {
- return *m.F_Bool
- }
- return Default_Defaults_F_Bool
-}
-
-func (m *Defaults) GetF_Int32() int32 {
- if m != nil && m.F_Int32 != nil {
- return *m.F_Int32
- }
- return Default_Defaults_F_Int32
-}
-
-func (m *Defaults) GetF_Int64() int64 {
- if m != nil && m.F_Int64 != nil {
- return *m.F_Int64
- }
- return Default_Defaults_F_Int64
-}
-
-func (m *Defaults) GetF_Fixed32() uint32 {
- if m != nil && m.F_Fixed32 != nil {
- return *m.F_Fixed32
- }
- return Default_Defaults_F_Fixed32
-}
-
-func (m *Defaults) GetF_Fixed64() uint64 {
- if m != nil && m.F_Fixed64 != nil {
- return *m.F_Fixed64
- }
- return Default_Defaults_F_Fixed64
-}
-
-func (m *Defaults) GetF_Uint32() uint32 {
- if m != nil && m.F_Uint32 != nil {
- return *m.F_Uint32
- }
- return Default_Defaults_F_Uint32
-}
-
-func (m *Defaults) GetF_Uint64() uint64 {
- if m != nil && m.F_Uint64 != nil {
- return *m.F_Uint64
- }
- return Default_Defaults_F_Uint64
-}
-
-func (m *Defaults) GetF_Float() float32 {
- if m != nil && m.F_Float != nil {
- return *m.F_Float
- }
- return Default_Defaults_F_Float
-}
-
-func (m *Defaults) GetF_Double() float64 {
- if m != nil && m.F_Double != nil {
- return *m.F_Double
- }
- return Default_Defaults_F_Double
-}
-
-func (m *Defaults) GetF_String() string {
- if m != nil && m.F_String != nil {
- return *m.F_String
- }
- return Default_Defaults_F_String
-}
-
-func (m *Defaults) GetF_Bytes() []byte {
- if m != nil && m.F_Bytes != nil {
- return m.F_Bytes
- }
- return append([]byte(nil), Default_Defaults_F_Bytes...)
-}
-
-func (m *Defaults) GetF_Sint32() int32 {
- if m != nil && m.F_Sint32 != nil {
- return *m.F_Sint32
- }
- return Default_Defaults_F_Sint32
-}
-
-func (m *Defaults) GetF_Sint64() int64 {
- if m != nil && m.F_Sint64 != nil {
- return *m.F_Sint64
- }
- return Default_Defaults_F_Sint64
-}
-
-func (m *Defaults) GetF_Enum() Defaults_Color {
- if m != nil && m.F_Enum != nil {
- return *m.F_Enum
- }
- return Default_Defaults_F_Enum
-}
-
-func (m *Defaults) GetF_Pinf() float32 {
- if m != nil && m.F_Pinf != nil {
- return *m.F_Pinf
- }
- return Default_Defaults_F_Pinf
-}
-
-func (m *Defaults) GetF_Ninf() float32 {
- if m != nil && m.F_Ninf != nil {
- return *m.F_Ninf
- }
- return Default_Defaults_F_Ninf
-}
-
-func (m *Defaults) GetF_Nan() float32 {
- if m != nil && m.F_Nan != nil {
- return *m.F_Nan
- }
- return Default_Defaults_F_Nan
-}
-
-func (m *Defaults) GetSub() *SubDefaults {
- if m != nil {
- return m.Sub
- }
- return nil
-}
-
-func (m *Defaults) GetStrZero() string {
- if m != nil && m.StrZero != nil {
- return *m.StrZero
- }
- return ""
-}
-
-type SubDefaults struct {
- N *int64 `protobuf:"varint,1,opt,name=n,def=7" json:"n,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *SubDefaults) Reset() { *m = SubDefaults{} }
-func (m *SubDefaults) String() string { return proto.CompactTextString(m) }
-func (*SubDefaults) ProtoMessage() {}
-
-const Default_SubDefaults_N int64 = 7
-
-func (m *SubDefaults) GetN() int64 {
- if m != nil && m.N != nil {
- return *m.N
- }
- return Default_SubDefaults_N
-}
-
-type RepeatedEnum struct {
- Color []RepeatedEnum_Color `protobuf:"varint,1,rep,name=color,enum=testdata.RepeatedEnum_Color" json:"color,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *RepeatedEnum) Reset() { *m = RepeatedEnum{} }
-func (m *RepeatedEnum) String() string { return proto.CompactTextString(m) }
-func (*RepeatedEnum) ProtoMessage() {}
-
-func (m *RepeatedEnum) GetColor() []RepeatedEnum_Color {
- if m != nil {
- return m.Color
- }
- return nil
-}
-
-type MoreRepeated struct {
- Bools []bool `protobuf:"varint,1,rep,name=bools" json:"bools,omitempty"`
- BoolsPacked []bool `protobuf:"varint,2,rep,packed,name=bools_packed" json:"bools_packed,omitempty"`
- Ints []int32 `protobuf:"varint,3,rep,name=ints" json:"ints,omitempty"`
- IntsPacked []int32 `protobuf:"varint,4,rep,packed,name=ints_packed" json:"ints_packed,omitempty"`
- Int64SPacked []int64 `protobuf:"varint,7,rep,packed,name=int64s_packed" json:"int64s_packed,omitempty"`
- Strings []string `protobuf:"bytes,5,rep,name=strings" json:"strings,omitempty"`
- Fixeds []uint32 `protobuf:"fixed32,6,rep,name=fixeds" json:"fixeds,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *MoreRepeated) Reset() { *m = MoreRepeated{} }
-func (m *MoreRepeated) String() string { return proto.CompactTextString(m) }
-func (*MoreRepeated) ProtoMessage() {}
-
-func (m *MoreRepeated) GetBools() []bool {
- if m != nil {
- return m.Bools
- }
- return nil
-}
-
-func (m *MoreRepeated) GetBoolsPacked() []bool {
- if m != nil {
- return m.BoolsPacked
- }
- return nil
-}
-
-func (m *MoreRepeated) GetInts() []int32 {
- if m != nil {
- return m.Ints
- }
- return nil
-}
-
-func (m *MoreRepeated) GetIntsPacked() []int32 {
- if m != nil {
- return m.IntsPacked
- }
- return nil
-}
-
-func (m *MoreRepeated) GetInt64SPacked() []int64 {
- if m != nil {
- return m.Int64SPacked
- }
- return nil
-}
-
-func (m *MoreRepeated) GetStrings() []string {
- if m != nil {
- return m.Strings
- }
- return nil
-}
-
-func (m *MoreRepeated) GetFixeds() []uint32 {
- if m != nil {
- return m.Fixeds
- }
- return nil
-}
-
-type GroupOld struct {
- G *GroupOld_G `protobuf:"group,101,opt" json:"g,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *GroupOld) Reset() { *m = GroupOld{} }
-func (m *GroupOld) String() string { return proto.CompactTextString(m) }
-func (*GroupOld) ProtoMessage() {}
-
-func (m *GroupOld) GetG() *GroupOld_G {
- if m != nil {
- return m.G
- }
- return nil
-}
-
-type GroupOld_G struct {
- X *int32 `protobuf:"varint,2,opt,name=x" json:"x,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *GroupOld_G) Reset() { *m = GroupOld_G{} }
-func (m *GroupOld_G) String() string { return proto.CompactTextString(m) }
-func (*GroupOld_G) ProtoMessage() {}
-
-func (m *GroupOld_G) GetX() int32 {
- if m != nil && m.X != nil {
- return *m.X
- }
- return 0
-}
-
-type GroupNew struct {
- G *GroupNew_G `protobuf:"group,101,opt" json:"g,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *GroupNew) Reset() { *m = GroupNew{} }
-func (m *GroupNew) String() string { return proto.CompactTextString(m) }
-func (*GroupNew) ProtoMessage() {}
-
-func (m *GroupNew) GetG() *GroupNew_G {
- if m != nil {
- return m.G
- }
- return nil
-}
-
-type GroupNew_G struct {
- X *int32 `protobuf:"varint,2,opt,name=x" json:"x,omitempty"`
- Y *int32 `protobuf:"varint,3,opt,name=y" json:"y,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *GroupNew_G) Reset() { *m = GroupNew_G{} }
-func (m *GroupNew_G) String() string { return proto.CompactTextString(m) }
-func (*GroupNew_G) ProtoMessage() {}
-
-func (m *GroupNew_G) GetX() int32 {
- if m != nil && m.X != nil {
- return *m.X
- }
- return 0
-}
-
-func (m *GroupNew_G) GetY() int32 {
- if m != nil && m.Y != nil {
- return *m.Y
- }
- return 0
-}
-
-type FloatingPoint struct {
- F *float64 `protobuf:"fixed64,1,req,name=f" json:"f,omitempty"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *FloatingPoint) Reset() { *m = FloatingPoint{} }
-func (m *FloatingPoint) String() string { return proto.CompactTextString(m) }
-func (*FloatingPoint) ProtoMessage() {}
-
-func (m *FloatingPoint) GetF() float64 {
- if m != nil && m.F != nil {
- return *m.F
- }
- return 0
-}
-
-type MessageWithMap struct {
- NameMapping map[int32]string `protobuf:"bytes,1,rep,name=name_mapping" json:"name_mapping,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
- MsgMapping map[int64]*FloatingPoint `protobuf:"bytes,2,rep,name=msg_mapping" json:"msg_mapping,omitempty" protobuf_key:"zigzag64,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
- ByteMapping map[bool][]byte `protobuf:"bytes,3,rep,name=byte_mapping" json:"byte_mapping,omitempty" protobuf_key:"varint,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
- StrToStr map[string]string `protobuf:"bytes,4,rep,name=str_to_str" json:"str_to_str,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
- XXX_unrecognized []byte `json:"-"`
-}
-
-func (m *MessageWithMap) Reset() { *m = MessageWithMap{} }
-func (m *MessageWithMap) String() string { return proto.CompactTextString(m) }
-func (*MessageWithMap) ProtoMessage() {}
-
-func (m *MessageWithMap) GetNameMapping() map[int32]string {
- if m != nil {
- return m.NameMapping
- }
- return nil
-}
-
-func (m *MessageWithMap) GetMsgMapping() map[int64]*FloatingPoint {
- if m != nil {
- return m.MsgMapping
- }
- return nil
-}
-
-func (m *MessageWithMap) GetByteMapping() map[bool][]byte {
- if m != nil {
- return m.ByteMapping
- }
- return nil
-}
-
-func (m *MessageWithMap) GetStrToStr() map[string]string {
- if m != nil {
- return m.StrToStr
- }
- return nil
-}
-
-var E_Greeting = &proto.ExtensionDesc{
- ExtendedType: (*MyMessage)(nil),
- ExtensionType: ([]string)(nil),
- Field: 106,
- Name: "testdata.greeting",
- Tag: "bytes,106,rep,name=greeting",
-}
-
-var E_NoDefaultDouble = &proto.ExtensionDesc{
- ExtendedType: (*DefaultsMessage)(nil),
- ExtensionType: (*float64)(nil),
- Field: 101,
- Name: "testdata.no_default_double",
- Tag: "fixed64,101,opt,name=no_default_double",
-}
-
-var E_NoDefaultFloat = &proto.ExtensionDesc{
- ExtendedType: (*DefaultsMessage)(nil),
- ExtensionType: (*float32)(nil),
- Field: 102,
- Name: "testdata.no_default_float",
- Tag: "fixed32,102,opt,name=no_default_float",
-}
-
-var E_NoDefaultInt32 = &proto.ExtensionDesc{
- ExtendedType: (*DefaultsMessage)(nil),
- ExtensionType: (*int32)(nil),
- Field: 103,
- Name: "testdata.no_default_int32",
- Tag: "varint,103,opt,name=no_default_int32",
-}
-
-var E_NoDefaultInt64 = &proto.ExtensionDesc{
- ExtendedType: (*DefaultsMessage)(nil),
- ExtensionType: (*int64)(nil),
- Field: 104,
- Name: "testdata.no_default_int64",
- Tag: "varint,104,opt,name=no_default_int64",
-}
-
-var E_NoDefaultUint32 = &proto.ExtensionDesc{
- ExtendedType: (*DefaultsMessage)(nil),
- ExtensionType: (*uint32)(nil),
- Field: 105,
- Name: "testdata.no_default_uint32",
- Tag: "varint,105,opt,name=no_default_uint32",
-}
-
-var E_NoDefaultUint64 = &proto.ExtensionDesc{
- ExtendedType: (*DefaultsMessage)(nil),
- ExtensionType: (*uint64)(nil),
- Field: 106,
- Name: "testdata.no_default_uint64",
- Tag: "varint,106,opt,name=no_default_uint64",
-}
-
-var E_NoDefaultSint32 = &proto.ExtensionDesc{
- ExtendedType: (*DefaultsMessage)(nil),
- ExtensionType: (*int32)(nil),
- Field: 107,
- Name: "testdata.no_default_sint32",
- Tag: "zigzag32,107,opt,name=no_default_sint32",
-}
-
-var E_NoDefaultSint64 = &proto.ExtensionDesc{
- ExtendedType: (*DefaultsMessage)(nil),
- ExtensionType: (*int64)(nil),
- Field: 108,
- Name: "testdata.no_default_sint64",
- Tag: "zigzag64,108,opt,name=no_default_sint64",
-}
-
-var E_NoDefaultFixed32 = &proto.ExtensionDesc{
- ExtendedType: (*DefaultsMessage)(nil),
- ExtensionType: (*uint32)(nil),
- Field: 109,
- Name: "testdata.no_default_fixed32",
- Tag: "fixed32,109,opt,name=no_default_fixed32",
-}
-
-var E_NoDefaultFixed64 = &proto.ExtensionDesc{
- ExtendedType: (*DefaultsMessage)(nil),
- ExtensionType: (*uint64)(nil),
- Field: 110,
- Name: "testdata.no_default_fixed64",
- Tag: "fixed64,110,opt,name=no_default_fixed64",
-}
-
-var E_NoDefaultSfixed32 = &proto.ExtensionDesc{
- ExtendedType: (*DefaultsMessage)(nil),
- ExtensionType: (*int32)(nil),
- Field: 111,
- Name: "testdata.no_default_sfixed32",
- Tag: "fixed32,111,opt,name=no_default_sfixed32",
-}
-
-var E_NoDefaultSfixed64 = &proto.ExtensionDesc{
- ExtendedType: (*DefaultsMessage)(nil),
- ExtensionType: (*int64)(nil),
- Field: 112,
- Name: "testdata.no_default_sfixed64",
- Tag: "fixed64,112,opt,name=no_default_sfixed64",
-}
-
-var E_NoDefaultBool = &proto.ExtensionDesc{
- ExtendedType: (*DefaultsMessage)(nil),
- ExtensionType: (*bool)(nil),
- Field: 113,
- Name: "testdata.no_default_bool",
- Tag: "varint,113,opt,name=no_default_bool",
-}
-
-var E_NoDefaultString = &proto.ExtensionDesc{
- ExtendedType: (*DefaultsMessage)(nil),
- ExtensionType: (*string)(nil),
- Field: 114,
- Name: "testdata.no_default_string",
- Tag: "bytes,114,opt,name=no_default_string",
-}
-
-var E_NoDefaultBytes = &proto.ExtensionDesc{
- ExtendedType: (*DefaultsMessage)(nil),
- ExtensionType: ([]byte)(nil),
- Field: 115,
- Name: "testdata.no_default_bytes",
- Tag: "bytes,115,opt,name=no_default_bytes",
-}
-
-var E_NoDefaultEnum = &proto.ExtensionDesc{
- ExtendedType: (*DefaultsMessage)(nil),
- ExtensionType: (*DefaultsMessage_DefaultsEnum)(nil),
- Field: 116,
- Name: "testdata.no_default_enum",
- Tag: "varint,116,opt,name=no_default_enum,enum=testdata.DefaultsMessage_DefaultsEnum",
-}
-
-var E_DefaultDouble = &proto.ExtensionDesc{
- ExtendedType: (*DefaultsMessage)(nil),
- ExtensionType: (*float64)(nil),
- Field: 201,
- Name: "testdata.default_double",
- Tag: "fixed64,201,opt,name=default_double,def=3.1415",
-}
-
-var E_DefaultFloat = &proto.ExtensionDesc{
- ExtendedType: (*DefaultsMessage)(nil),
- ExtensionType: (*float32)(nil),
- Field: 202,
- Name: "testdata.default_float",
- Tag: "fixed32,202,opt,name=default_float,def=3.14",
-}
-
-var E_DefaultInt32 = &proto.ExtensionDesc{
- ExtendedType: (*DefaultsMessage)(nil),
- ExtensionType: (*int32)(nil),
- Field: 203,
- Name: "testdata.default_int32",
- Tag: "varint,203,opt,name=default_int32,def=42",
-}
-
-var E_DefaultInt64 = &proto.ExtensionDesc{
- ExtendedType: (*DefaultsMessage)(nil),
- ExtensionType: (*int64)(nil),
- Field: 204,
- Name: "testdata.default_int64",
- Tag: "varint,204,opt,name=default_int64,def=43",
-}
-
-var E_DefaultUint32 = &proto.ExtensionDesc{
- ExtendedType: (*DefaultsMessage)(nil),
- ExtensionType: (*uint32)(nil),
- Field: 205,
- Name: "testdata.default_uint32",
- Tag: "varint,205,opt,name=default_uint32,def=44",
-}
-
-var E_DefaultUint64 = &proto.ExtensionDesc{
- ExtendedType: (*DefaultsMessage)(nil),
- ExtensionType: (*uint64)(nil),
- Field: 206,
- Name: "testdata.default_uint64",
- Tag: "varint,206,opt,name=default_uint64,def=45",
-}
-
-var E_DefaultSint32 = &proto.ExtensionDesc{
- ExtendedType: (*DefaultsMessage)(nil),
- ExtensionType: (*int32)(nil),
- Field: 207,
- Name: "testdata.default_sint32",
- Tag: "zigzag32,207,opt,name=default_sint32,def=46",
-}
-
-var E_DefaultSint64 = &proto.ExtensionDesc{
- ExtendedType: (*DefaultsMessage)(nil),
- ExtensionType: (*int64)(nil),
- Field: 208,
- Name: "testdata.default_sint64",
- Tag: "zigzag64,208,opt,name=default_sint64,def=47",
-}
-
-var E_DefaultFixed32 = &proto.ExtensionDesc{
- ExtendedType: (*DefaultsMessage)(nil),
- ExtensionType: (*uint32)(nil),
- Field: 209,
- Name: "testdata.default_fixed32",
- Tag: "fixed32,209,opt,name=default_fixed32,def=48",
-}
-
-var E_DefaultFixed64 = &proto.ExtensionDesc{
- ExtendedType: (*DefaultsMessage)(nil),
- ExtensionType: (*uint64)(nil),
- Field: 210,
- Name: "testdata.default_fixed64",
- Tag: "fixed64,210,opt,name=default_fixed64,def=49",
-}
-
-var E_DefaultSfixed32 = &proto.ExtensionDesc{
- ExtendedType: (*DefaultsMessage)(nil),
- ExtensionType: (*int32)(nil),
- Field: 211,
- Name: "testdata.default_sfixed32",
- Tag: "fixed32,211,opt,name=default_sfixed32,def=50",
-}
-
-var E_DefaultSfixed64 = &proto.ExtensionDesc{
- ExtendedType: (*DefaultsMessage)(nil),
- ExtensionType: (*int64)(nil),
- Field: 212,
- Name: "testdata.default_sfixed64",
- Tag: "fixed64,212,opt,name=default_sfixed64,def=51",
-}
-
-var E_DefaultBool = &proto.ExtensionDesc{
- ExtendedType: (*DefaultsMessage)(nil),
- ExtensionType: (*bool)(nil),
- Field: 213,
- Name: "testdata.default_bool",
- Tag: "varint,213,opt,name=default_bool,def=1",
-}
-
-var E_DefaultString = &proto.ExtensionDesc{
- ExtendedType: (*DefaultsMessage)(nil),
- ExtensionType: (*string)(nil),
- Field: 214,
- Name: "testdata.default_string",
- Tag: "bytes,214,opt,name=default_string,def=Hello, string",
-}
-
-var E_DefaultBytes = &proto.ExtensionDesc{
- ExtendedType: (*DefaultsMessage)(nil),
- ExtensionType: ([]byte)(nil),
- Field: 215,
- Name: "testdata.default_bytes",
- Tag: "bytes,215,opt,name=default_bytes,def=Hello, bytes",
-}
-
-var E_DefaultEnum = &proto.ExtensionDesc{
- ExtendedType: (*DefaultsMessage)(nil),
- ExtensionType: (*DefaultsMessage_DefaultsEnum)(nil),
- Field: 216,
- Name: "testdata.default_enum",
- Tag: "varint,216,opt,name=default_enum,enum=testdata.DefaultsMessage_DefaultsEnum,def=1",
-}
-
-var E_X201 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 201,
- Name: "testdata.x201",
- Tag: "bytes,201,opt,name=x201",
-}
-
-var E_X202 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 202,
- Name: "testdata.x202",
- Tag: "bytes,202,opt,name=x202",
-}
-
-var E_X203 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 203,
- Name: "testdata.x203",
- Tag: "bytes,203,opt,name=x203",
-}
-
-var E_X204 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 204,
- Name: "testdata.x204",
- Tag: "bytes,204,opt,name=x204",
-}
-
-var E_X205 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 205,
- Name: "testdata.x205",
- Tag: "bytes,205,opt,name=x205",
-}
-
-var E_X206 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 206,
- Name: "testdata.x206",
- Tag: "bytes,206,opt,name=x206",
-}
-
-var E_X207 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 207,
- Name: "testdata.x207",
- Tag: "bytes,207,opt,name=x207",
-}
-
-var E_X208 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 208,
- Name: "testdata.x208",
- Tag: "bytes,208,opt,name=x208",
-}
-
-var E_X209 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 209,
- Name: "testdata.x209",
- Tag: "bytes,209,opt,name=x209",
-}
-
-var E_X210 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 210,
- Name: "testdata.x210",
- Tag: "bytes,210,opt,name=x210",
-}
-
-var E_X211 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 211,
- Name: "testdata.x211",
- Tag: "bytes,211,opt,name=x211",
-}
-
-var E_X212 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 212,
- Name: "testdata.x212",
- Tag: "bytes,212,opt,name=x212",
-}
-
-var E_X213 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 213,
- Name: "testdata.x213",
- Tag: "bytes,213,opt,name=x213",
-}
-
-var E_X214 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 214,
- Name: "testdata.x214",
- Tag: "bytes,214,opt,name=x214",
-}
-
-var E_X215 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 215,
- Name: "testdata.x215",
- Tag: "bytes,215,opt,name=x215",
-}
-
-var E_X216 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 216,
- Name: "testdata.x216",
- Tag: "bytes,216,opt,name=x216",
-}
-
-var E_X217 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 217,
- Name: "testdata.x217",
- Tag: "bytes,217,opt,name=x217",
-}
-
-var E_X218 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 218,
- Name: "testdata.x218",
- Tag: "bytes,218,opt,name=x218",
-}
-
-var E_X219 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 219,
- Name: "testdata.x219",
- Tag: "bytes,219,opt,name=x219",
-}
-
-var E_X220 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 220,
- Name: "testdata.x220",
- Tag: "bytes,220,opt,name=x220",
-}
-
-var E_X221 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 221,
- Name: "testdata.x221",
- Tag: "bytes,221,opt,name=x221",
-}
-
-var E_X222 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 222,
- Name: "testdata.x222",
- Tag: "bytes,222,opt,name=x222",
-}
-
-var E_X223 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 223,
- Name: "testdata.x223",
- Tag: "bytes,223,opt,name=x223",
-}
-
-var E_X224 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 224,
- Name: "testdata.x224",
- Tag: "bytes,224,opt,name=x224",
-}
-
-var E_X225 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 225,
- Name: "testdata.x225",
- Tag: "bytes,225,opt,name=x225",
-}
-
-var E_X226 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 226,
- Name: "testdata.x226",
- Tag: "bytes,226,opt,name=x226",
-}
-
-var E_X227 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 227,
- Name: "testdata.x227",
- Tag: "bytes,227,opt,name=x227",
-}
-
-var E_X228 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 228,
- Name: "testdata.x228",
- Tag: "bytes,228,opt,name=x228",
-}
-
-var E_X229 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 229,
- Name: "testdata.x229",
- Tag: "bytes,229,opt,name=x229",
-}
-
-var E_X230 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 230,
- Name: "testdata.x230",
- Tag: "bytes,230,opt,name=x230",
-}
-
-var E_X231 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 231,
- Name: "testdata.x231",
- Tag: "bytes,231,opt,name=x231",
-}
-
-var E_X232 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 232,
- Name: "testdata.x232",
- Tag: "bytes,232,opt,name=x232",
-}
-
-var E_X233 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 233,
- Name: "testdata.x233",
- Tag: "bytes,233,opt,name=x233",
-}
-
-var E_X234 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 234,
- Name: "testdata.x234",
- Tag: "bytes,234,opt,name=x234",
-}
-
-var E_X235 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 235,
- Name: "testdata.x235",
- Tag: "bytes,235,opt,name=x235",
-}
-
-var E_X236 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 236,
- Name: "testdata.x236",
- Tag: "bytes,236,opt,name=x236",
-}
-
-var E_X237 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 237,
- Name: "testdata.x237",
- Tag: "bytes,237,opt,name=x237",
-}
-
-var E_X238 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 238,
- Name: "testdata.x238",
- Tag: "bytes,238,opt,name=x238",
-}
-
-var E_X239 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 239,
- Name: "testdata.x239",
- Tag: "bytes,239,opt,name=x239",
-}
-
-var E_X240 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 240,
- Name: "testdata.x240",
- Tag: "bytes,240,opt,name=x240",
-}
-
-var E_X241 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 241,
- Name: "testdata.x241",
- Tag: "bytes,241,opt,name=x241",
-}
-
-var E_X242 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 242,
- Name: "testdata.x242",
- Tag: "bytes,242,opt,name=x242",
-}
-
-var E_X243 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 243,
- Name: "testdata.x243",
- Tag: "bytes,243,opt,name=x243",
-}
-
-var E_X244 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 244,
- Name: "testdata.x244",
- Tag: "bytes,244,opt,name=x244",
-}
-
-var E_X245 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 245,
- Name: "testdata.x245",
- Tag: "bytes,245,opt,name=x245",
-}
-
-var E_X246 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 246,
- Name: "testdata.x246",
- Tag: "bytes,246,opt,name=x246",
-}
-
-var E_X247 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 247,
- Name: "testdata.x247",
- Tag: "bytes,247,opt,name=x247",
-}
-
-var E_X248 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 248,
- Name: "testdata.x248",
- Tag: "bytes,248,opt,name=x248",
-}
-
-var E_X249 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 249,
- Name: "testdata.x249",
- Tag: "bytes,249,opt,name=x249",
-}
-
-var E_X250 = &proto.ExtensionDesc{
- ExtendedType: (*MyMessageSet)(nil),
- ExtensionType: (*Empty)(nil),
- Field: 250,
- Name: "testdata.x250",
- Tag: "bytes,250,opt,name=x250",
-}
-
-func init() {
- proto.RegisterEnum("testdata.FOO", FOO_name, FOO_value)
- proto.RegisterEnum("testdata.GoTest_KIND", GoTest_KIND_name, GoTest_KIND_value)
- proto.RegisterEnum("testdata.MyMessage_Color", MyMessage_Color_name, MyMessage_Color_value)
- proto.RegisterEnum("testdata.DefaultsMessage_DefaultsEnum", DefaultsMessage_DefaultsEnum_name, DefaultsMessage_DefaultsEnum_value)
- proto.RegisterEnum("testdata.Defaults_Color", Defaults_Color_name, Defaults_Color_value)
- proto.RegisterEnum("testdata.RepeatedEnum_Color", RepeatedEnum_Color_name, RepeatedEnum_Color_value)
- proto.RegisterExtension(E_Ext_More)
- proto.RegisterExtension(E_Ext_Text)
- proto.RegisterExtension(E_Ext_Number)
- proto.RegisterExtension(E_Greeting)
- proto.RegisterExtension(E_NoDefaultDouble)
- proto.RegisterExtension(E_NoDefaultFloat)
- proto.RegisterExtension(E_NoDefaultInt32)
- proto.RegisterExtension(E_NoDefaultInt64)
- proto.RegisterExtension(E_NoDefaultUint32)
- proto.RegisterExtension(E_NoDefaultUint64)
- proto.RegisterExtension(E_NoDefaultSint32)
- proto.RegisterExtension(E_NoDefaultSint64)
- proto.RegisterExtension(E_NoDefaultFixed32)
- proto.RegisterExtension(E_NoDefaultFixed64)
- proto.RegisterExtension(E_NoDefaultSfixed32)
- proto.RegisterExtension(E_NoDefaultSfixed64)
- proto.RegisterExtension(E_NoDefaultBool)
- proto.RegisterExtension(E_NoDefaultString)
- proto.RegisterExtension(E_NoDefaultBytes)
- proto.RegisterExtension(E_NoDefaultEnum)
- proto.RegisterExtension(E_DefaultDouble)
- proto.RegisterExtension(E_DefaultFloat)
- proto.RegisterExtension(E_DefaultInt32)
- proto.RegisterExtension(E_DefaultInt64)
- proto.RegisterExtension(E_DefaultUint32)
- proto.RegisterExtension(E_DefaultUint64)
- proto.RegisterExtension(E_DefaultSint32)
- proto.RegisterExtension(E_DefaultSint64)
- proto.RegisterExtension(E_DefaultFixed32)
- proto.RegisterExtension(E_DefaultFixed64)
- proto.RegisterExtension(E_DefaultSfixed32)
- proto.RegisterExtension(E_DefaultSfixed64)
- proto.RegisterExtension(E_DefaultBool)
- proto.RegisterExtension(E_DefaultString)
- proto.RegisterExtension(E_DefaultBytes)
- proto.RegisterExtension(E_DefaultEnum)
- proto.RegisterExtension(E_X201)
- proto.RegisterExtension(E_X202)
- proto.RegisterExtension(E_X203)
- proto.RegisterExtension(E_X204)
- proto.RegisterExtension(E_X205)
- proto.RegisterExtension(E_X206)
- proto.RegisterExtension(E_X207)
- proto.RegisterExtension(E_X208)
- proto.RegisterExtension(E_X209)
- proto.RegisterExtension(E_X210)
- proto.RegisterExtension(E_X211)
- proto.RegisterExtension(E_X212)
- proto.RegisterExtension(E_X213)
- proto.RegisterExtension(E_X214)
- proto.RegisterExtension(E_X215)
- proto.RegisterExtension(E_X216)
- proto.RegisterExtension(E_X217)
- proto.RegisterExtension(E_X218)
- proto.RegisterExtension(E_X219)
- proto.RegisterExtension(E_X220)
- proto.RegisterExtension(E_X221)
- proto.RegisterExtension(E_X222)
- proto.RegisterExtension(E_X223)
- proto.RegisterExtension(E_X224)
- proto.RegisterExtension(E_X225)
- proto.RegisterExtension(E_X226)
- proto.RegisterExtension(E_X227)
- proto.RegisterExtension(E_X228)
- proto.RegisterExtension(E_X229)
- proto.RegisterExtension(E_X230)
- proto.RegisterExtension(E_X231)
- proto.RegisterExtension(E_X232)
- proto.RegisterExtension(E_X233)
- proto.RegisterExtension(E_X234)
- proto.RegisterExtension(E_X235)
- proto.RegisterExtension(E_X236)
- proto.RegisterExtension(E_X237)
- proto.RegisterExtension(E_X238)
- proto.RegisterExtension(E_X239)
- proto.RegisterExtension(E_X240)
- proto.RegisterExtension(E_X241)
- proto.RegisterExtension(E_X242)
- proto.RegisterExtension(E_X243)
- proto.RegisterExtension(E_X244)
- proto.RegisterExtension(E_X245)
- proto.RegisterExtension(E_X246)
- proto.RegisterExtension(E_X247)
- proto.RegisterExtension(E_X248)
- proto.RegisterExtension(E_X249)
- proto.RegisterExtension(E_X250)
-}
diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/testdata/test.proto b/Godeps/_workspace/src/github.com/golang/protobuf/proto/testdata/test.proto
deleted file mode 100644
index 440dba38dd..0000000000
--- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/testdata/test.proto
+++ /dev/null
@@ -1,480 +0,0 @@
-// 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.
-
-// A feature-rich test file for the protocol compiler and libraries.
-
-syntax = "proto2";
-
-package testdata;
-
-enum FOO { FOO1 = 1; };
-
-message GoEnum {
- required FOO foo = 1;
-}
-
-message GoTestField {
- required string Label = 1;
- required string Type = 2;
-}
-
-message GoTest {
- // An enum, for completeness.
- enum KIND {
- VOID = 0;
-
- // Basic types
- BOOL = 1;
- BYTES = 2;
- FINGERPRINT = 3;
- FLOAT = 4;
- INT = 5;
- STRING = 6;
- TIME = 7;
-
- // Groupings
- TUPLE = 8;
- ARRAY = 9;
- MAP = 10;
-
- // Table types
- TABLE = 11;
-
- // Functions
- FUNCTION = 12; // last tag
- };
-
- // Some typical parameters
- required KIND Kind = 1;
- optional string Table = 2;
- optional int32 Param = 3;
-
- // Required, repeated and optional foreign fields.
- required GoTestField RequiredField = 4;
- repeated GoTestField RepeatedField = 5;
- optional GoTestField OptionalField = 6;
-
- // Required fields of all basic types
- required bool F_Bool_required = 10;
- required int32 F_Int32_required = 11;
- required int64 F_Int64_required = 12;
- required fixed32 F_Fixed32_required = 13;
- required fixed64 F_Fixed64_required = 14;
- required uint32 F_Uint32_required = 15;
- required uint64 F_Uint64_required = 16;
- required float F_Float_required = 17;
- required double F_Double_required = 18;
- required string F_String_required = 19;
- required bytes F_Bytes_required = 101;
- required sint32 F_Sint32_required = 102;
- required sint64 F_Sint64_required = 103;
-
- // Repeated fields of all basic types
- repeated bool F_Bool_repeated = 20;
- repeated int32 F_Int32_repeated = 21;
- repeated int64 F_Int64_repeated = 22;
- repeated fixed32 F_Fixed32_repeated = 23;
- repeated fixed64 F_Fixed64_repeated = 24;
- repeated uint32 F_Uint32_repeated = 25;
- repeated uint64 F_Uint64_repeated = 26;
- repeated float F_Float_repeated = 27;
- repeated double F_Double_repeated = 28;
- repeated string F_String_repeated = 29;
- repeated bytes F_Bytes_repeated = 201;
- repeated sint32 F_Sint32_repeated = 202;
- repeated sint64 F_Sint64_repeated = 203;
-
- // Optional fields of all basic types
- optional bool F_Bool_optional = 30;
- optional int32 F_Int32_optional = 31;
- optional int64 F_Int64_optional = 32;
- optional fixed32 F_Fixed32_optional = 33;
- optional fixed64 F_Fixed64_optional = 34;
- optional uint32 F_Uint32_optional = 35;
- optional uint64 F_Uint64_optional = 36;
- optional float F_Float_optional = 37;
- optional double F_Double_optional = 38;
- optional string F_String_optional = 39;
- optional bytes F_Bytes_optional = 301;
- optional sint32 F_Sint32_optional = 302;
- optional sint64 F_Sint64_optional = 303;
-
- // Default-valued fields of all basic types
- optional bool F_Bool_defaulted = 40 [default=true];
- optional int32 F_Int32_defaulted = 41 [default=32];
- optional int64 F_Int64_defaulted = 42 [default=64];
- optional fixed32 F_Fixed32_defaulted = 43 [default=320];
- optional fixed64 F_Fixed64_defaulted = 44 [default=640];
- optional uint32 F_Uint32_defaulted = 45 [default=3200];
- optional uint64 F_Uint64_defaulted = 46 [default=6400];
- optional float F_Float_defaulted = 47 [default=314159.];
- optional double F_Double_defaulted = 48 [default=271828.];
- optional string F_String_defaulted = 49 [default="hello, \"world!\"\n"];
- optional bytes F_Bytes_defaulted = 401 [default="Bignose"];
- optional sint32 F_Sint32_defaulted = 402 [default = -32];
- optional sint64 F_Sint64_defaulted = 403 [default = -64];
-
- // Packed repeated fields (no string or bytes).
- repeated bool F_Bool_repeated_packed = 50 [packed=true];
- repeated int32 F_Int32_repeated_packed = 51 [packed=true];
- repeated int64 F_Int64_repeated_packed = 52 [packed=true];
- repeated fixed32 F_Fixed32_repeated_packed = 53 [packed=true];
- repeated fixed64 F_Fixed64_repeated_packed = 54 [packed=true];
- repeated uint32 F_Uint32_repeated_packed = 55 [packed=true];
- repeated uint64 F_Uint64_repeated_packed = 56 [packed=true];
- repeated float F_Float_repeated_packed = 57 [packed=true];
- repeated double F_Double_repeated_packed = 58 [packed=true];
- repeated sint32 F_Sint32_repeated_packed = 502 [packed=true];
- repeated sint64 F_Sint64_repeated_packed = 503 [packed=true];
-
- // Required, repeated, and optional groups.
- required group RequiredGroup = 70 {
- required string RequiredField = 71;
- };
-
- repeated group RepeatedGroup = 80 {
- required string RequiredField = 81;
- };
-
- optional group OptionalGroup = 90 {
- required string RequiredField = 91;
- };
-}
-
-// For testing skipping of unrecognized fields.
-// Numbers are all big, larger than tag numbers in GoTestField,
-// the message used in the corresponding test.
-message GoSkipTest {
- required int32 skip_int32 = 11;
- required fixed32 skip_fixed32 = 12;
- required fixed64 skip_fixed64 = 13;
- required string skip_string = 14;
- required group SkipGroup = 15 {
- required int32 group_int32 = 16;
- required string group_string = 17;
- }
-}
-
-// For testing packed/non-packed decoder switching.
-// A serialized instance of one should be deserializable as the other.
-message NonPackedTest {
- repeated int32 a = 1;
-}
-
-message PackedTest {
- repeated int32 b = 1 [packed=true];
-}
-
-message MaxTag {
- // Maximum possible tag number.
- optional string last_field = 536870911;
-}
-
-message OldMessage {
- message Nested {
- optional string name = 1;
- }
- optional Nested nested = 1;
-
- optional int32 num = 2;
-}
-
-// NewMessage is wire compatible with OldMessage;
-// imagine it as a future version.
-message NewMessage {
- message Nested {
- optional string name = 1;
- optional string food_group = 2;
- }
- optional Nested nested = 1;
-
- // This is an int32 in OldMessage.
- optional int64 num = 2;
-}
-
-// Smaller tests for ASCII formatting.
-
-message InnerMessage {
- required string host = 1;
- optional int32 port = 2 [default=4000];
- optional bool connected = 3;
-}
-
-message OtherMessage {
- optional int64 key = 1;
- optional bytes value = 2;
- optional float weight = 3;
- optional InnerMessage inner = 4;
-}
-
-message MyMessage {
- required int32 count = 1;
- optional string name = 2;
- optional string quote = 3;
- repeated string pet = 4;
- optional InnerMessage inner = 5;
- repeated OtherMessage others = 6;
- repeated InnerMessage rep_inner = 12;
-
- enum Color {
- RED = 0;
- GREEN = 1;
- BLUE = 2;
- };
- optional Color bikeshed = 7;
-
- optional group SomeGroup = 8 {
- optional int32 group_field = 9;
- }
-
- // This field becomes [][]byte in the generated code.
- repeated bytes rep_bytes = 10;
-
- optional double bigfloat = 11;
-
- extensions 100 to max;
-}
-
-message Ext {
- extend MyMessage {
- optional Ext more = 103;
- optional string text = 104;
- optional int32 number = 105;
- }
-
- optional string data = 1;
-}
-
-extend MyMessage {
- repeated string greeting = 106;
-}
-
-message DefaultsMessage {
- enum DefaultsEnum {
- ZERO = 0;
- ONE = 1;
- TWO = 2;
- };
- extensions 100 to max;
-}
-
-extend DefaultsMessage {
- optional double no_default_double = 101;
- optional float no_default_float = 102;
- optional int32 no_default_int32 = 103;
- optional int64 no_default_int64 = 104;
- optional uint32 no_default_uint32 = 105;
- optional uint64 no_default_uint64 = 106;
- optional sint32 no_default_sint32 = 107;
- optional sint64 no_default_sint64 = 108;
- optional fixed32 no_default_fixed32 = 109;
- optional fixed64 no_default_fixed64 = 110;
- optional sfixed32 no_default_sfixed32 = 111;
- optional sfixed64 no_default_sfixed64 = 112;
- optional bool no_default_bool = 113;
- optional string no_default_string = 114;
- optional bytes no_default_bytes = 115;
- optional DefaultsMessage.DefaultsEnum no_default_enum = 116;
-
- optional double default_double = 201 [default = 3.1415];
- optional float default_float = 202 [default = 3.14];
- optional int32 default_int32 = 203 [default = 42];
- optional int64 default_int64 = 204 [default = 43];
- optional uint32 default_uint32 = 205 [default = 44];
- optional uint64 default_uint64 = 206 [default = 45];
- optional sint32 default_sint32 = 207 [default = 46];
- optional sint64 default_sint64 = 208 [default = 47];
- optional fixed32 default_fixed32 = 209 [default = 48];
- optional fixed64 default_fixed64 = 210 [default = 49];
- optional sfixed32 default_sfixed32 = 211 [default = 50];
- optional sfixed64 default_sfixed64 = 212 [default = 51];
- optional bool default_bool = 213 [default = true];
- optional string default_string = 214 [default = "Hello, string"];
- optional bytes default_bytes = 215 [default = "Hello, bytes"];
- optional DefaultsMessage.DefaultsEnum default_enum = 216 [default = ONE];
-}
-
-message MyMessageSet {
- option message_set_wire_format = true;
- extensions 100 to max;
-}
-
-message Empty {
-}
-
-extend MyMessageSet {
- optional Empty x201 = 201;
- optional Empty x202 = 202;
- optional Empty x203 = 203;
- optional Empty x204 = 204;
- optional Empty x205 = 205;
- optional Empty x206 = 206;
- optional Empty x207 = 207;
- optional Empty x208 = 208;
- optional Empty x209 = 209;
- optional Empty x210 = 210;
- optional Empty x211 = 211;
- optional Empty x212 = 212;
- optional Empty x213 = 213;
- optional Empty x214 = 214;
- optional Empty x215 = 215;
- optional Empty x216 = 216;
- optional Empty x217 = 217;
- optional Empty x218 = 218;
- optional Empty x219 = 219;
- optional Empty x220 = 220;
- optional Empty x221 = 221;
- optional Empty x222 = 222;
- optional Empty x223 = 223;
- optional Empty x224 = 224;
- optional Empty x225 = 225;
- optional Empty x226 = 226;
- optional Empty x227 = 227;
- optional Empty x228 = 228;
- optional Empty x229 = 229;
- optional Empty x230 = 230;
- optional Empty x231 = 231;
- optional Empty x232 = 232;
- optional Empty x233 = 233;
- optional Empty x234 = 234;
- optional Empty x235 = 235;
- optional Empty x236 = 236;
- optional Empty x237 = 237;
- optional Empty x238 = 238;
- optional Empty x239 = 239;
- optional Empty x240 = 240;
- optional Empty x241 = 241;
- optional Empty x242 = 242;
- optional Empty x243 = 243;
- optional Empty x244 = 244;
- optional Empty x245 = 245;
- optional Empty x246 = 246;
- optional Empty x247 = 247;
- optional Empty x248 = 248;
- optional Empty x249 = 249;
- optional Empty x250 = 250;
-}
-
-message MessageList {
- repeated group Message = 1 {
- required string name = 2;
- required int32 count = 3;
- }
-}
-
-message Strings {
- optional string string_field = 1;
- optional bytes bytes_field = 2;
-}
-
-message Defaults {
- enum Color {
- RED = 0;
- GREEN = 1;
- BLUE = 2;
- }
-
- // Default-valued fields of all basic types.
- // Same as GoTest, but copied here to make testing easier.
- optional bool F_Bool = 1 [default=true];
- optional int32 F_Int32 = 2 [default=32];
- optional int64 F_Int64 = 3 [default=64];
- optional fixed32 F_Fixed32 = 4 [default=320];
- optional fixed64 F_Fixed64 = 5 [default=640];
- optional uint32 F_Uint32 = 6 [default=3200];
- optional uint64 F_Uint64 = 7 [default=6400];
- optional float F_Float = 8 [default=314159.];
- optional double F_Double = 9 [default=271828.];
- optional string F_String = 10 [default="hello, \"world!\"\n"];
- optional bytes F_Bytes = 11 [default="Bignose"];
- optional sint32 F_Sint32 = 12 [default=-32];
- optional sint64 F_Sint64 = 13 [default=-64];
- optional Color F_Enum = 14 [default=GREEN];
-
- // More fields with crazy defaults.
- optional float F_Pinf = 15 [default=inf];
- optional float F_Ninf = 16 [default=-inf];
- optional float F_Nan = 17 [default=nan];
-
- // Sub-message.
- optional SubDefaults sub = 18;
-
- // Redundant but explicit defaults.
- optional string str_zero = 19 [default=""];
-}
-
-message SubDefaults {
- optional int64 n = 1 [default=7];
-}
-
-message RepeatedEnum {
- enum Color {
- RED = 1;
- }
- repeated Color color = 1;
-}
-
-message MoreRepeated {
- repeated bool bools = 1;
- repeated bool bools_packed = 2 [packed=true];
- repeated int32 ints = 3;
- repeated int32 ints_packed = 4 [packed=true];
- repeated int64 int64s_packed = 7 [packed=true];
- repeated string strings = 5;
- repeated fixed32 fixeds = 6;
-}
-
-// GroupOld and GroupNew have the same wire format.
-// GroupNew has a new field inside a group.
-
-message GroupOld {
- optional group G = 101 {
- optional int32 x = 2;
- }
-}
-
-message GroupNew {
- optional group G = 101 {
- optional int32 x = 2;
- optional int32 y = 3;
- }
-}
-
-message FloatingPoint {
- required double f = 1;
-}
-
-message MessageWithMap {
- map name_mapping = 1;
- map msg_mapping = 2;
- map byte_mapping = 3;
- map str_to_str = 4;
-}
diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/text.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/text.go
deleted file mode 100644
index f7dc58a3e6..0000000000
--- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/text.go
+++ /dev/null
@@ -1,769 +0,0 @@
-// 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"
- "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.Printf("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
-}
-
-var (
- messageSetType = reflect.TypeOf((*MessageSet)(nil)).Elem()
-)
-
-// raw is the interface satisfied by RawMessage.
-type raw interface {
- Bytes() []byte
-}
-
-func writeStruct(w *textWriter, sv reflect.Value) error {
- if sv.Type() == messageSetType {
- return writeMessageSet(w, sv.Addr().Interface().(*MessageSet))
- }
-
- 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("\n")); err != nil {
- return err
- }
- continue
- }
- if err := 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() // TODO: should we sort these for deterministic output?
- 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 := 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 := 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 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 := 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 pv.Type().Implements(extendableProtoType) {
- if err := 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 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.Interface().([]byte))); 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 tm, ok := v.Interface().(encoding.TextMarshaler); ok {
- text, err := tm.MarshalText()
- if err != nil {
- return err
- }
- if _, err = w.Write(text); err != nil {
- return err
- }
- } else if err := 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 writeMessageSet(w *textWriter, ms *MessageSet) error {
- for _, item := range ms.Item {
- id := *item.TypeId
- if msd, ok := messageSetMap[id]; ok {
- // Known message set type.
- if _, err := fmt.Fprintf(w, "[%s]: <\n", msd.name); err != nil {
- return err
- }
- w.indent()
-
- pb := reflect.New(msd.t.Elem())
- if err := Unmarshal(item.Message, pb.Interface().(Message)); err != nil {
- if _, err := fmt.Fprintf(w, "/* bad message: %v */\n", err); err != nil {
- return err
- }
- } else {
- if err := writeStruct(w, pb.Elem()); err != nil {
- return err
- }
- }
- } else {
- // Unknown type.
- if _, err := fmt.Fprintf(w, "[%d]: <\n", id); err != nil {
- return err
- }
- w.indent()
- if err := writeUnknownStruct(w, item.Message); err != nil {
- return err
- }
- }
- w.unindent()
- if _, err := w.Write(gtNewline); err != nil {
- return err
- }
- }
- return nil
-}
-
-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 writeExtensions(w *textWriter, pv reflect.Value) error {
- emap := extensionMaps[pv.Type().Elem()]
- ep := pv.Interface().(extendableProto)
-
- // Order the extensions by ID.
- // This isn't strictly necessary, but it will give us
- // canonical output, which will also make testing easier.
- m := ep.ExtensionMap()
- ids := make([]int32, 0, len(m))
- for id := range m {
- ids = append(ids, id)
- }
- sort.Sort(int32Slice(ids))
-
- 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 := writeExtension(w, desc.Name, pb); err != nil {
- return err
- }
- } else {
- v := reflect.ValueOf(pb)
- for i := 0; i < v.Len(); i++ {
- if err := writeExtension(w, desc.Name, v.Index(i).Interface()); err != nil {
- return err
- }
- }
- }
- }
- return nil
-}
-
-func 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 := 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
-}
-
-func marshalText(w io.Writer, pb Message, compact bool) error {
- val := reflect.ValueOf(pb)
- if pb == nil || val.IsNil() {
- w.Write([]byte(""))
- 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: compact,
- }
-
- if tm, ok := pb.(encoding.TextMarshaler); ok {
- text, err := tm.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 := writeStruct(aw, v); err != nil {
- return err
- }
- if bw != nil {
- return bw.Flush()
- }
- return nil
-}
-
-// 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 marshalText(w, pb, false)
-}
-
-// MarshalTextString is the same as MarshalText, but returns the string directly.
-func MarshalTextString(pb Message) string {
- var buf bytes.Buffer
- marshalText(&buf, pb, false)
- return buf.String()
-}
-
-// CompactText writes a given protocol buffer in compact text format (one line).
-func CompactText(w io.Writer, pb Message) error { return marshalText(w, pb, true) }
-
-// CompactTextString is the same as CompactText, but returns the string directly.
-func CompactTextString(pb Message) string {
- var buf bytes.Buffer
- marshalText(&buf, pb, true)
- return buf.String()
-}
diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/text_parser.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/text_parser.go
deleted file mode 100644
index 7d0c757198..0000000000
--- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/text_parser.go
+++ /dev/null
@@ -1,772 +0,0 @@
-// 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"
-)
-
-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 (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 && p.cur.value[0] == '"' {
- // Look for multiple quoted strings separated by whitespace,
- // and concatenate them.
- cat := p.cur
- for {
- p.skipWhitespace()
- if p.done || 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.", st)} // should not happen
-}
-
-// Returns the index in the struct for the named field, as well as the parsed tag properties.
-func structFieldByName(st reflect.Type, name string) (int, *Properties, bool) {
- sprops := GetProperties(st)
- 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()
- reqCount := GetProperties(st).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]".
- for {
- tok := p.next()
- if tok.err != nil {
- return tok.err
- }
- if tok.value == terminator {
- break
- }
- if tok.value == "[" {
- // Looks like an extension.
- //
- // TODO: Check whether we need to handle
- // namespace rooted names (e.g. ".something.Foo").
- tok = p.next()
- if tok.err != nil {
- return tok.err
- }
- 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 == tok.value {
- desc = d
- break
- }
- }
- if desc == nil {
- return p.errorf("unrecognized extension %q", tok.value)
- }
- // Check the extension terminator.
- tok = p.next()
- if tok.err != nil {
- return tok.err
- }
- if tok.value != "]" {
- return p.errorf("unrecognized extension terminator %q", tok.value)
- }
-
- 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().(extendableProto)
- 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())
- }
- } else {
- // This is a normal, non-extension field.
- name := tok.value
- fi, props, ok := structFieldByName(st, name)
- if !ok {
- return p.errorf("unknown field name %q in %v", name, st)
- }
-
- dst := sv.Field(fi)
-
- 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 >
- // Technically the "key" and "value" could come in any order,
- // but in practice they won't.
-
- tok := p.next()
- var terminator string
- switch tok.value {
- case "<":
- terminator = ">"
- case "{":
- terminator = "}"
- default:
- return p.errorf("expected '{' or '<', found %q", tok.value)
- }
- if err := p.consumeToken("key"); err != nil {
- return err
- }
- 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
- }
- if err := p.consumeToken("value"); err != nil {
- return err
- }
- 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
- }
- if err := p.consumeToken(terminator); err != nil {
- return err
- }
-
- 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, st.Field(fi).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
- } else if props.Required {
- reqCount--
- }
- }
-
- if err := p.consumeOptionalSeparator(); err != nil {
- return err
- }
-
- }
-
- if reqCount > 0 {
- return p.missingRequiredFieldError(sv)
- }
- return reqFieldErr
-}
-
-// 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. May already exist.
- flen := fv.Len()
- if flen == fv.Cap() {
- nav := reflect.MakeSlice(at, flen, 2*flen+1)
- reflect.Copy(nav, fv)
- fv.Set(nav)
- }
- fv.SetLen(flen + 1)
-
- // Read one.
- p.back()
- return p.readAny(fv.Index(flen), props)
- case reflect.Bool:
- // Either "true", "false", 1 or 0.
- switch tok.value {
- case "true", "1":
- fv.SetBool(true)
- return nil
- case "false", "0":
- 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(uint64(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
-}
diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/text_parser_test.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/text_parser_test.go
deleted file mode 100644
index 0754b2626c..0000000000
--- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/text_parser_test.go
+++ /dev/null
@@ -1,511 +0,0 @@
-// 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_test
-
-import (
- "math"
- "reflect"
- "testing"
-
- . "github.com/golang/protobuf/proto"
- proto3pb "github.com/golang/protobuf/proto/proto3_proto"
- . "github.com/golang/protobuf/proto/testdata"
-)
-
-type UnmarshalTextTest struct {
- in string
- err string // if "", no error expected
- out *MyMessage
-}
-
-func buildExtStructTest(text string) UnmarshalTextTest {
- msg := &MyMessage{
- Count: Int32(42),
- }
- SetExtension(msg, E_Ext_More, &Ext{
- Data: String("Hello, world!"),
- })
- return UnmarshalTextTest{in: text, out: msg}
-}
-
-func buildExtDataTest(text string) UnmarshalTextTest {
- msg := &MyMessage{
- Count: Int32(42),
- }
- SetExtension(msg, E_Ext_Text, String("Hello, world!"))
- SetExtension(msg, E_Ext_Number, Int32(1729))
- return UnmarshalTextTest{in: text, out: msg}
-}
-
-func buildExtRepStringTest(text string) UnmarshalTextTest {
- msg := &MyMessage{
- Count: Int32(42),
- }
- if err := SetExtension(msg, E_Greeting, []string{"bula", "hola"}); err != nil {
- panic(err)
- }
- return UnmarshalTextTest{in: text, out: msg}
-}
-
-var unMarshalTextTests = []UnmarshalTextTest{
- // Basic
- {
- in: " count:42\n name:\"Dave\" ",
- out: &MyMessage{
- Count: Int32(42),
- Name: String("Dave"),
- },
- },
-
- // Empty quoted string
- {
- in: `count:42 name:""`,
- out: &MyMessage{
- Count: Int32(42),
- Name: String(""),
- },
- },
-
- // Quoted string concatenation
- {
- in: `count:42 name: "My name is "` + "\n" + `"elsewhere"`,
- out: &MyMessage{
- Count: Int32(42),
- Name: String("My name is elsewhere"),
- },
- },
-
- // Quoted string with escaped apostrophe
- {
- in: `count:42 name: "HOLIDAY - New Year\'s Day"`,
- out: &MyMessage{
- Count: Int32(42),
- Name: String("HOLIDAY - New Year's Day"),
- },
- },
-
- // Quoted string with single quote
- {
- in: `count:42 name: 'Roger "The Ramster" Ramjet'`,
- out: &MyMessage{
- Count: Int32(42),
- Name: String(`Roger "The Ramster" Ramjet`),
- },
- },
-
- // Quoted string with all the accepted special characters from the C++ test
- {
- in: `count:42 name: ` + "\"\\\"A string with \\' characters \\n and \\r newlines and \\t tabs and \\001 slashes \\\\ and multiple spaces\"",
- out: &MyMessage{
- Count: Int32(42),
- Name: String("\"A string with ' characters \n and \r newlines and \t tabs and \001 slashes \\ and multiple spaces"),
- },
- },
-
- // Quoted string with quoted backslash
- {
- in: `count:42 name: "\\'xyz"`,
- out: &MyMessage{
- Count: Int32(42),
- Name: String(`\'xyz`),
- },
- },
-
- // Quoted string with UTF-8 bytes.
- {
- in: "count:42 name: '\303\277\302\201\xAB'",
- out: &MyMessage{
- Count: Int32(42),
- Name: String("\303\277\302\201\xAB"),
- },
- },
-
- // Bad quoted string
- {
- in: `inner: < host: "\0" >` + "\n",
- err: `line 1.15: invalid quoted string "\0": \0 requires 2 following digits`,
- },
-
- // Number too large for int64
- {
- in: "count: 1 others { key: 123456789012345678901 }",
- err: "line 1.23: invalid int64: 123456789012345678901",
- },
-
- // Number too large for int32
- {
- in: "count: 1234567890123",
- err: "line 1.7: invalid int32: 1234567890123",
- },
-
- // Number in hexadecimal
- {
- in: "count: 0x2beef",
- out: &MyMessage{
- Count: Int32(0x2beef),
- },
- },
-
- // Number in octal
- {
- in: "count: 024601",
- out: &MyMessage{
- Count: Int32(024601),
- },
- },
-
- // Floating point number with "f" suffix
- {
- in: "count: 4 others:< weight: 17.0f >",
- out: &MyMessage{
- Count: Int32(4),
- Others: []*OtherMessage{
- {
- Weight: Float32(17),
- },
- },
- },
- },
-
- // Floating point positive infinity
- {
- in: "count: 4 bigfloat: inf",
- out: &MyMessage{
- Count: Int32(4),
- Bigfloat: Float64(math.Inf(1)),
- },
- },
-
- // Floating point negative infinity
- {
- in: "count: 4 bigfloat: -inf",
- out: &MyMessage{
- Count: Int32(4),
- Bigfloat: Float64(math.Inf(-1)),
- },
- },
-
- // Number too large for float32
- {
- in: "others:< weight: 12345678901234567890123456789012345678901234567890 >",
- err: "line 1.17: invalid float32: 12345678901234567890123456789012345678901234567890",
- },
-
- // Number posing as a quoted string
- {
- in: `inner: < host: 12 >` + "\n",
- err: `line 1.15: invalid string: 12`,
- },
-
- // Quoted string posing as int32
- {
- in: `count: "12"`,
- err: `line 1.7: invalid int32: "12"`,
- },
-
- // Quoted string posing a float32
- {
- in: `others:< weight: "17.4" >`,
- err: `line 1.17: invalid float32: "17.4"`,
- },
-
- // Enum
- {
- in: `count:42 bikeshed: BLUE`,
- out: &MyMessage{
- Count: Int32(42),
- Bikeshed: MyMessage_BLUE.Enum(),
- },
- },
-
- // Repeated field
- {
- in: `count:42 pet: "horsey" pet:"bunny"`,
- out: &MyMessage{
- Count: Int32(42),
- Pet: []string{"horsey", "bunny"},
- },
- },
-
- // Repeated message with/without colon and <>/{}
- {
- in: `count:42 others:{} others{} others:<> others:{}`,
- out: &MyMessage{
- Count: Int32(42),
- Others: []*OtherMessage{
- {},
- {},
- {},
- {},
- },
- },
- },
-
- // Missing colon for inner message
- {
- in: `count:42 inner < host: "cauchy.syd" >`,
- out: &MyMessage{
- Count: Int32(42),
- Inner: &InnerMessage{
- Host: String("cauchy.syd"),
- },
- },
- },
-
- // Missing colon for string field
- {
- in: `name "Dave"`,
- err: `line 1.5: expected ':', found "\"Dave\""`,
- },
-
- // Missing colon for int32 field
- {
- in: `count 42`,
- err: `line 1.6: expected ':', found "42"`,
- },
-
- // Missing required field
- {
- in: `name: "Pawel"`,
- err: `proto: required field "testdata.MyMessage.count" not set`,
- out: &MyMessage{
- Name: String("Pawel"),
- },
- },
-
- // Repeated non-repeated field
- {
- in: `name: "Rob" name: "Russ"`,
- err: `line 1.12: non-repeated field "name" was repeated`,
- },
-
- // Group
- {
- in: `count: 17 SomeGroup { group_field: 12 }`,
- out: &MyMessage{
- Count: Int32(17),
- Somegroup: &MyMessage_SomeGroup{
- GroupField: Int32(12),
- },
- },
- },
-
- // Semicolon between fields
- {
- in: `count:3;name:"Calvin"`,
- out: &MyMessage{
- Count: Int32(3),
- Name: String("Calvin"),
- },
- },
- // Comma between fields
- {
- in: `count:4,name:"Ezekiel"`,
- out: &MyMessage{
- Count: Int32(4),
- Name: String("Ezekiel"),
- },
- },
-
- // Extension
- buildExtStructTest(`count: 42 [testdata.Ext.more]:`),
- buildExtStructTest(`count: 42 [testdata.Ext.more] {data:"Hello, world!"}`),
- buildExtDataTest(`count: 42 [testdata.Ext.text]:"Hello, world!" [testdata.Ext.number]:1729`),
- buildExtRepStringTest(`count: 42 [testdata.greeting]:"bula" [testdata.greeting]:"hola"`),
-
- // Big all-in-one
- {
- in: "count:42 # Meaning\n" +
- `name:"Dave" ` +
- `quote:"\"I didn't want to go.\"" ` +
- `pet:"bunny" ` +
- `pet:"kitty" ` +
- `pet:"horsey" ` +
- `inner:<` +
- ` host:"footrest.syd" ` +
- ` port:7001 ` +
- ` connected:true ` +
- `> ` +
- `others:<` +
- ` key:3735928559 ` +
- ` value:"\x01A\a\f" ` +
- `> ` +
- `others:<` +
- " weight:58.9 # Atomic weight of Co\n" +
- ` inner:<` +
- ` host:"lesha.mtv" ` +
- ` port:8002 ` +
- ` >` +
- `>`,
- out: &MyMessage{
- Count: Int32(42),
- Name: String("Dave"),
- Quote: String(`"I didn't want to go."`),
- Pet: []string{"bunny", "kitty", "horsey"},
- Inner: &InnerMessage{
- Host: String("footrest.syd"),
- Port: Int32(7001),
- Connected: Bool(true),
- },
- Others: []*OtherMessage{
- {
- Key: Int64(3735928559),
- Value: []byte{0x1, 'A', '\a', '\f'},
- },
- {
- Weight: Float32(58.9),
- Inner: &InnerMessage{
- Host: String("lesha.mtv"),
- Port: Int32(8002),
- },
- },
- },
- },
- },
-}
-
-func TestUnmarshalText(t *testing.T) {
- for i, test := range unMarshalTextTests {
- pb := new(MyMessage)
- err := UnmarshalText(test.in, pb)
- if test.err == "" {
- // We don't expect failure.
- if err != nil {
- t.Errorf("Test %d: Unexpected error: %v", i, err)
- } else if !reflect.DeepEqual(pb, test.out) {
- t.Errorf("Test %d: Incorrect populated \nHave: %v\nWant: %v",
- i, pb, test.out)
- }
- } else {
- // We do expect failure.
- if err == nil {
- t.Errorf("Test %d: Didn't get expected error: %v", i, test.err)
- } else if err.Error() != test.err {
- t.Errorf("Test %d: Incorrect error.\nHave: %v\nWant: %v",
- i, err.Error(), test.err)
- } else if _, ok := err.(*RequiredNotSetError); ok && test.out != nil && !reflect.DeepEqual(pb, test.out) {
- t.Errorf("Test %d: Incorrect populated \nHave: %v\nWant: %v",
- i, pb, test.out)
- }
- }
- }
-}
-
-func TestUnmarshalTextCustomMessage(t *testing.T) {
- msg := &textMessage{}
- if err := UnmarshalText("custom", msg); err != nil {
- t.Errorf("Unexpected error from custom unmarshal: %v", err)
- }
- if UnmarshalText("not custom", msg) == nil {
- t.Errorf("Didn't get expected error from custom unmarshal")
- }
-}
-
-// Regression test; this caused a panic.
-func TestRepeatedEnum(t *testing.T) {
- pb := new(RepeatedEnum)
- if err := UnmarshalText("color: RED", pb); err != nil {
- t.Fatal(err)
- }
- exp := &RepeatedEnum{
- Color: []RepeatedEnum_Color{RepeatedEnum_RED},
- }
- if !Equal(pb, exp) {
- t.Errorf("Incorrect populated \nHave: %v\nWant: %v", pb, exp)
- }
-}
-
-func TestProto3TextParsing(t *testing.T) {
- m := new(proto3pb.Message)
- const in = `name: "Wallace" true_scotsman: true`
- want := &proto3pb.Message{
- Name: "Wallace",
- TrueScotsman: true,
- }
- if err := UnmarshalText(in, m); err != nil {
- t.Fatal(err)
- }
- if !Equal(m, want) {
- t.Errorf("\n got %v\nwant %v", m, want)
- }
-}
-
-func TestMapParsing(t *testing.T) {
- m := new(MessageWithMap)
- const in = `name_mapping: name_mapping:` +
- `msg_mapping:,>` + // separating commas are okay
- `msg_mapping>` + // no colon after "value"
- `byte_mapping:`
- want := &MessageWithMap{
- NameMapping: map[int32]string{
- 1: "Beatles",
- 1234: "Feist",
- },
- MsgMapping: map[int64]*FloatingPoint{
- -4: {F: Float64(2.0)},
- -2: {F: Float64(4.0)},
- },
- ByteMapping: map[bool][]byte{
- true: []byte("so be it"),
- },
- }
- if err := UnmarshalText(in, m); err != nil {
- t.Fatal(err)
- }
- if !Equal(m, want) {
- t.Errorf("\n got %v\nwant %v", m, want)
- }
-}
-
-var benchInput string
-
-func init() {
- benchInput = "count: 4\n"
- for i := 0; i < 1000; i++ {
- benchInput += "pet: \"fido\"\n"
- }
-
- // Check it is valid input.
- pb := new(MyMessage)
- err := UnmarshalText(benchInput, pb)
- if err != nil {
- panic("Bad benchmark input: " + err.Error())
- }
-}
-
-func BenchmarkUnmarshalText(b *testing.B) {
- pb := new(MyMessage)
- for i := 0; i < b.N; i++ {
- UnmarshalText(benchInput, pb)
- }
- b.SetBytes(int64(len(benchInput)))
-}
diff --git a/Godeps/_workspace/src/github.com/golang/protobuf/proto/text_test.go b/Godeps/_workspace/src/github.com/golang/protobuf/proto/text_test.go
deleted file mode 100644
index 39861d1ca8..0000000000
--- a/Godeps/_workspace/src/github.com/golang/protobuf/proto/text_test.go
+++ /dev/null
@@ -1,441 +0,0 @@
-// 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_test
-
-import (
- "bytes"
- "errors"
- "io/ioutil"
- "math"
- "strings"
- "testing"
-
- "github.com/golang/protobuf/proto"
-
- proto3pb "github.com/golang/protobuf/proto/proto3_proto"
- pb "github.com/golang/protobuf/proto/testdata"
-)
-
-// textMessage implements the methods that allow it to marshal and unmarshal
-// itself as text.
-type textMessage struct {
-}
-
-func (*textMessage) MarshalText() ([]byte, error) {
- return []byte("custom"), nil
-}
-
-func (*textMessage) UnmarshalText(bytes []byte) error {
- if string(bytes) != "custom" {
- return errors.New("expected 'custom'")
- }
- return nil
-}
-
-func (*textMessage) Reset() {}
-func (*textMessage) String() string { return "" }
-func (*textMessage) ProtoMessage() {}
-
-func newTestMessage() *pb.MyMessage {
- msg := &pb.MyMessage{
- Count: proto.Int32(42),
- Name: proto.String("Dave"),
- Quote: proto.String(`"I didn't want to go."`),
- Pet: []string{"bunny", "kitty", "horsey"},
- Inner: &pb.InnerMessage{
- Host: proto.String("footrest.syd"),
- Port: proto.Int32(7001),
- Connected: proto.Bool(true),
- },
- Others: []*pb.OtherMessage{
- {
- Key: proto.Int64(0xdeadbeef),
- Value: []byte{1, 65, 7, 12},
- },
- {
- Weight: proto.Float32(6.022),
- Inner: &pb.InnerMessage{
- Host: proto.String("lesha.mtv"),
- Port: proto.Int32(8002),
- },
- },
- },
- Bikeshed: pb.MyMessage_BLUE.Enum(),
- Somegroup: &pb.MyMessage_SomeGroup{
- GroupField: proto.Int32(8),
- },
- // One normally wouldn't do this.
- // This is an undeclared tag 13, as a varint (wire type 0) with value 4.
- XXX_unrecognized: []byte{13<<3 | 0, 4},
- }
- ext := &pb.Ext{
- Data: proto.String("Big gobs for big rats"),
- }
- if err := proto.SetExtension(msg, pb.E_Ext_More, ext); err != nil {
- panic(err)
- }
- greetings := []string{"adg", "easy", "cow"}
- if err := proto.SetExtension(msg, pb.E_Greeting, greetings); err != nil {
- panic(err)
- }
-
- // Add an unknown extension. We marshal a pb.Ext, and fake the ID.
- b, err := proto.Marshal(&pb.Ext{Data: proto.String("3G skiing")})
- if err != nil {
- panic(err)
- }
- b = append(proto.EncodeVarint(201<<3|proto.WireBytes), b...)
- proto.SetRawExtension(msg, 201, b)
-
- // Extensions can be plain fields, too, so let's test that.
- b = append(proto.EncodeVarint(202<<3|proto.WireVarint), 19)
- proto.SetRawExtension(msg, 202, b)
-
- return msg
-}
-
-const text = `count: 42
-name: "Dave"
-quote: "\"I didn't want to go.\""
-pet: "bunny"
-pet: "kitty"
-pet: "horsey"
-inner: <
- host: "footrest.syd"
- port: 7001
- connected: true
->
-others: <
- key: 3735928559
- value: "\001A\007\014"
->
-others: <
- weight: 6.022
- inner: <
- host: "lesha.mtv"
- port: 8002
- >
->
-bikeshed: BLUE
-SomeGroup {
- group_field: 8
-}
-/* 2 unknown bytes */
-13: 4
-[testdata.Ext.more]: <
- data: "Big gobs for big rats"
->
-[testdata.greeting]: "adg"
-[testdata.greeting]: "easy"
-[testdata.greeting]: "cow"
-/* 13 unknown bytes */
-201: "\t3G skiing"
-/* 3 unknown bytes */
-202: 19
-`
-
-func TestMarshalText(t *testing.T) {
- buf := new(bytes.Buffer)
- if err := proto.MarshalText(buf, newTestMessage()); err != nil {
- t.Fatalf("proto.MarshalText: %v", err)
- }
- s := buf.String()
- if s != text {
- t.Errorf("Got:\n===\n%v===\nExpected:\n===\n%v===\n", s, text)
- }
-}
-
-func TestMarshalTextCustomMessage(t *testing.T) {
- buf := new(bytes.Buffer)
- if err := proto.MarshalText(buf, &textMessage{}); err != nil {
- t.Fatalf("proto.MarshalText: %v", err)
- }
- s := buf.String()
- if s != "custom" {
- t.Errorf("Got %q, expected %q", s, "custom")
- }
-}
-func TestMarshalTextNil(t *testing.T) {
- want := ""
- tests := []proto.Message{nil, (*pb.MyMessage)(nil)}
- for i, test := range tests {
- buf := new(bytes.Buffer)
- if err := proto.MarshalText(buf, test); err != nil {
- t.Fatal(err)
- }
- if got := buf.String(); got != want {
- t.Errorf("%d: got %q want %q", i, got, want)
- }
- }
-}
-
-func TestMarshalTextUnknownEnum(t *testing.T) {
- // The Color enum only specifies values 0-2.
- m := &pb.MyMessage{Bikeshed: pb.MyMessage_Color(3).Enum()}
- got := m.String()
- const want = `bikeshed:3 `
- if got != want {
- t.Errorf("\n got %q\nwant %q", got, want)
- }
-}
-
-func BenchmarkMarshalTextBuffered(b *testing.B) {
- buf := new(bytes.Buffer)
- m := newTestMessage()
- for i := 0; i < b.N; i++ {
- buf.Reset()
- proto.MarshalText(buf, m)
- }
-}
-
-func BenchmarkMarshalTextUnbuffered(b *testing.B) {
- w := ioutil.Discard
- m := newTestMessage()
- for i := 0; i < b.N; i++ {
- proto.MarshalText(w, m)
- }
-}
-
-func compact(src string) string {
- // s/[ \n]+/ /g; s/ $//;
- dst := make([]byte, len(src))
- space, comment := false, false
- j := 0
- for i := 0; i < len(src); i++ {
- if strings.HasPrefix(src[i:], "/*") {
- comment = true
- i++
- continue
- }
- if comment && strings.HasPrefix(src[i:], "*/") {
- comment = false
- i++
- continue
- }
- if comment {
- continue
- }
- c := src[i]
- if c == ' ' || c == '\n' {
- space = true
- continue
- }
- if j > 0 && (dst[j-1] == ':' || dst[j-1] == '<' || dst[j-1] == '{') {
- space = false
- }
- if c == '{' {
- space = false
- }
- if space {
- dst[j] = ' '
- j++
- space = false
- }
- dst[j] = c
- j++
- }
- if space {
- dst[j] = ' '
- j++
- }
- return string(dst[0:j])
-}
-
-var compactText = compact(text)
-
-func TestCompactText(t *testing.T) {
- s := proto.CompactTextString(newTestMessage())
- if s != compactText {
- t.Errorf("Got:\n===\n%v===\nExpected:\n===\n%v\n===\n", s, compactText)
- }
-}
-
-func TestStringEscaping(t *testing.T) {
- testCases := []struct {
- in *pb.Strings
- out string
- }{
- {
- // Test data from C++ test (TextFormatTest.StringEscape).
- // Single divergence: we don't escape apostrophes.
- &pb.Strings{StringField: proto.String("\"A string with ' characters \n and \r newlines and \t tabs and \001 slashes \\ and multiple spaces")},
- "string_field: \"\\\"A string with ' characters \\n and \\r newlines and \\t tabs and \\001 slashes \\\\ and multiple spaces\"\n",
- },
- {
- // Test data from the same C++ test.
- &pb.Strings{StringField: proto.String("\350\260\267\346\255\214")},
- "string_field: \"\\350\\260\\267\\346\\255\\214\"\n",
- },
- {
- // Some UTF-8.
- &pb.Strings{StringField: proto.String("\x00\x01\xff\x81")},
- `string_field: "\000\001\377\201"` + "\n",
- },
- }
-
- for i, tc := range testCases {
- var buf bytes.Buffer
- if err := proto.MarshalText(&buf, tc.in); err != nil {
- t.Errorf("proto.MarsalText: %v", err)
- continue
- }
- s := buf.String()
- if s != tc.out {
- t.Errorf("#%d: Got:\n%s\nExpected:\n%s\n", i, s, tc.out)
- continue
- }
-
- // Check round-trip.
- pb := new(pb.Strings)
- if err := proto.UnmarshalText(s, pb); err != nil {
- t.Errorf("#%d: UnmarshalText: %v", i, err)
- continue
- }
- if !proto.Equal(pb, tc.in) {
- t.Errorf("#%d: Round-trip failed:\nstart: %v\n end: %v", i, tc.in, pb)
- }
- }
-}
-
-// A limitedWriter accepts some output before it fails.
-// This is a proxy for something like a nearly-full or imminently-failing disk,
-// or a network connection that is about to die.
-type limitedWriter struct {
- b bytes.Buffer
- limit int
-}
-
-var outOfSpace = errors.New("proto: insufficient space")
-
-func (w *limitedWriter) Write(p []byte) (n int, err error) {
- var avail = w.limit - w.b.Len()
- if avail <= 0 {
- return 0, outOfSpace
- }
- if len(p) <= avail {
- return w.b.Write(p)
- }
- n, _ = w.b.Write(p[:avail])
- return n, outOfSpace
-}
-
-func TestMarshalTextFailing(t *testing.T) {
- // Try lots of different sizes to exercise more error code-paths.
- for lim := 0; lim < len(text); lim++ {
- buf := new(limitedWriter)
- buf.limit = lim
- err := proto.MarshalText(buf, newTestMessage())
- // We expect a certain error, but also some partial results in the buffer.
- if err != outOfSpace {
- t.Errorf("Got:\n===\n%v===\nExpected:\n===\n%v===\n", err, outOfSpace)
- }
- s := buf.b.String()
- x := text[:buf.limit]
- if s != x {
- t.Errorf("Got:\n===\n%v===\nExpected:\n===\n%v===\n", s, x)
- }
- }
-}
-
-func TestFloats(t *testing.T) {
- tests := []struct {
- f float64
- want string
- }{
- {0, "0"},
- {4.7, "4.7"},
- {math.Inf(1), "inf"},
- {math.Inf(-1), "-inf"},
- {math.NaN(), "nan"},
- }
- for _, test := range tests {
- msg := &pb.FloatingPoint{F: &test.f}
- got := strings.TrimSpace(msg.String())
- want := `f:` + test.want
- if got != want {
- t.Errorf("f=%f: got %q, want %q", test.f, got, want)
- }
- }
-}
-
-func TestRepeatedNilText(t *testing.T) {
- m := &pb.MessageList{
- Message: []*pb.MessageList_Message{
- nil,
- &pb.MessageList_Message{
- Name: proto.String("Horse"),
- },
- nil,
- },
- }
- want := `Message
-Message {
- name: "Horse"
-}
-Message
-`
- if s := proto.MarshalTextString(m); s != want {
- t.Errorf(" got: %s\nwant: %s", s, want)
- }
-}
-
-func TestProto3Text(t *testing.T) {
- tests := []struct {
- m proto.Message
- want string
- }{
- // zero message
- {&proto3pb.Message{}, ``},
- // zero message except for an empty byte slice
- {&proto3pb.Message{Data: []byte{}}, ``},
- // trivial case
- {&proto3pb.Message{Name: "Rob", HeightInCm: 175}, `name:"Rob" height_in_cm:175`},
- // empty map
- {&pb.MessageWithMap{}, ``},
- // non-empty map; current map format is the same as a repeated struct
- {
- &pb.MessageWithMap{NameMapping: map[int32]string{1234: "Feist"}},
- `name_mapping:`,
- },
- // map with nil value; not well-defined, but we shouldn't crash
- {
- &pb.MessageWithMap{MsgMapping: map[int64]*pb.FloatingPoint{7: nil}},
- `msg_mapping:`,
- },
- }
- for _, test := range tests {
- got := strings.TrimSpace(test.m.String())
- if got != test.want {
- t.Errorf("\n got %s\nwant %s", got, test.want)
- }
- }
-}
diff --git a/Godeps/_workspace/src/github.com/golang/snappy/AUTHORS b/Godeps/_workspace/src/github.com/golang/snappy/AUTHORS
deleted file mode 100644
index 824bf2e148..0000000000
--- a/Godeps/_workspace/src/github.com/golang/snappy/AUTHORS
+++ /dev/null
@@ -1,14 +0,0 @@
-# This is the official list of Snappy-Go authors for copyright purposes.
-# This file is distinct from the CONTRIBUTORS files.
-# See the latter for an explanation.
-
-# Names should be added to this file as
-# Name or Organization
-# The email address is not required for organizations.
-
-# Please keep the list sorted.
-
-Damian Gryski
-Google Inc.
-Jan Mercl <0xjnml@gmail.com>
-Sebastien Binet
diff --git a/Godeps/_workspace/src/github.com/golang/snappy/CONTRIBUTORS b/Godeps/_workspace/src/github.com/golang/snappy/CONTRIBUTORS
deleted file mode 100644
index 9f54f21ff7..0000000000
--- a/Godeps/_workspace/src/github.com/golang/snappy/CONTRIBUTORS
+++ /dev/null
@@ -1,36 +0,0 @@
-# This is the official list of people who can contribute
-# (and typically have contributed) code to the Snappy-Go repository.
-# The AUTHORS file lists the copyright holders; this file
-# lists people. For example, Google employees are listed here
-# but not in AUTHORS, because Google holds the copyright.
-#
-# The submission process automatically checks to make sure
-# that people submitting code are listed in this file (by email address).
-#
-# Names should be added to this file only after verifying that
-# the individual or the individual's organization has agreed to
-# the appropriate Contributor License Agreement, found here:
-#
-# http://code.google.com/legal/individual-cla-v1.0.html
-# http://code.google.com/legal/corporate-cla-v1.0.html
-#
-# The agreement for individuals can be filled out on the web.
-#
-# When adding J Random Contributor's name to this file,
-# either J's name or J's organization's name should be
-# added to the AUTHORS file, depending on whether the
-# individual or corporate CLA was used.
-
-# Names should be added to this file like so:
-# Name
-
-# Please keep the list sorted.
-
-Damian Gryski
-Jan Mercl <0xjnml@gmail.com>
-Kai Backman
-Marc-Antoine Ruel
-Nigel Tao
-Rob Pike
-Russ Cox
-Sebastien Binet
diff --git a/Godeps/_workspace/src/github.com/golang/snappy/LICENSE b/Godeps/_workspace/src/github.com/golang/snappy/LICENSE
deleted file mode 100644
index 6050c10f4c..0000000000
--- a/Godeps/_workspace/src/github.com/golang/snappy/LICENSE
+++ /dev/null
@@ -1,27 +0,0 @@
-Copyright (c) 2011 The Snappy-Go Authors. All rights reserved.
-
-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.
diff --git a/Godeps/_workspace/src/github.com/golang/snappy/README b/Godeps/_workspace/src/github.com/golang/snappy/README
deleted file mode 100644
index 5074bbab8d..0000000000
--- a/Godeps/_workspace/src/github.com/golang/snappy/README
+++ /dev/null
@@ -1,7 +0,0 @@
-The Snappy compression format in the Go programming language.
-
-To download and install from source:
-$ go get github.com/golang/snappy
-
-Unless otherwise noted, the Snappy-Go source files are distributed
-under the BSD-style license found in the LICENSE file.
diff --git a/Godeps/_workspace/src/github.com/golang/snappy/decode.go b/Godeps/_workspace/src/github.com/golang/snappy/decode.go
deleted file mode 100644
index a72edf0d0f..0000000000
--- a/Godeps/_workspace/src/github.com/golang/snappy/decode.go
+++ /dev/null
@@ -1,290 +0,0 @@
-// Copyright 2011 The Snappy-Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package snappy
-
-import (
- "encoding/binary"
- "errors"
- "io"
-)
-
-var (
- // ErrCorrupt reports that the input is invalid.
- ErrCorrupt = errors.New("snappy: corrupt input")
- // ErrUnsupported reports that the input isn't supported.
- ErrUnsupported = errors.New("snappy: unsupported input")
-)
-
-// DecodedLen returns the length of the decoded block.
-func DecodedLen(src []byte) (int, error) {
- v, _, err := decodedLen(src)
- return v, err
-}
-
-// decodedLen returns the length of the decoded block and the number of bytes
-// that the length header occupied.
-func decodedLen(src []byte) (blockLen, headerLen int, err error) {
- v, n := binary.Uvarint(src)
- if n <= 0 {
- return 0, 0, ErrCorrupt
- }
- if uint64(int(v)) != v {
- return 0, 0, errors.New("snappy: decoded block is too large")
- }
- return int(v), n, nil
-}
-
-// Decode returns the decoded form of src. The returned slice may be a sub-
-// slice of dst if dst was large enough to hold the entire decoded block.
-// Otherwise, a newly allocated slice will be returned.
-// It is valid to pass a nil dst.
-func Decode(dst, src []byte) ([]byte, error) {
- dLen, s, err := decodedLen(src)
- if err != nil {
- return nil, err
- }
- if len(dst) < dLen {
- dst = make([]byte, dLen)
- }
-
- var d, offset, length int
- for s < len(src) {
- switch src[s] & 0x03 {
- case tagLiteral:
- x := uint(src[s] >> 2)
- switch {
- case x < 60:
- s++
- case x == 60:
- s += 2
- if s > len(src) {
- return nil, ErrCorrupt
- }
- x = uint(src[s-1])
- case x == 61:
- s += 3
- if s > len(src) {
- return nil, ErrCorrupt
- }
- x = uint(src[s-2]) | uint(src[s-1])<<8
- case x == 62:
- s += 4
- if s > len(src) {
- return nil, ErrCorrupt
- }
- x = uint(src[s-3]) | uint(src[s-2])<<8 | uint(src[s-1])<<16
- case x == 63:
- s += 5
- if s > len(src) {
- return nil, ErrCorrupt
- }
- x = uint(src[s-4]) | uint(src[s-3])<<8 | uint(src[s-2])<<16 | uint(src[s-1])<<24
- }
- length = int(x + 1)
- if length <= 0 {
- return nil, errors.New("snappy: unsupported literal length")
- }
- if length > len(dst)-d || length > len(src)-s {
- return nil, ErrCorrupt
- }
- copy(dst[d:], src[s:s+length])
- d += length
- s += length
- continue
-
- case tagCopy1:
- s += 2
- if s > len(src) {
- return nil, ErrCorrupt
- }
- length = 4 + int(src[s-2])>>2&0x7
- offset = int(src[s-2])&0xe0<<3 | int(src[s-1])
-
- case tagCopy2:
- s += 3
- if s > len(src) {
- return nil, ErrCorrupt
- }
- length = 1 + int(src[s-3])>>2
- offset = int(src[s-2]) | int(src[s-1])<<8
-
- case tagCopy4:
- return nil, errors.New("snappy: unsupported COPY_4 tag")
- }
-
- end := d + length
- if offset > d || end > len(dst) {
- return nil, ErrCorrupt
- }
- for ; d < end; d++ {
- dst[d] = dst[d-offset]
- }
- }
- if d != dLen {
- return nil, ErrCorrupt
- }
- return dst[:d], nil
-}
-
-// NewReader returns a new Reader that decompresses from r, using the framing
-// format described at
-// https://github.com/google/snappy/blob/master/framing_format.txt
-func NewReader(r io.Reader) *Reader {
- return &Reader{
- r: r,
- decoded: make([]byte, maxUncompressedChunkLen),
- buf: make([]byte, MaxEncodedLen(maxUncompressedChunkLen)+checksumSize),
- }
-}
-
-// Reader is an io.Reader than can read Snappy-compressed bytes.
-type Reader struct {
- r io.Reader
- err error
- decoded []byte
- buf []byte
- // decoded[i:j] contains decoded bytes that have not yet been passed on.
- i, j int
- readHeader bool
-}
-
-// Reset discards any buffered data, resets all state, and switches the Snappy
-// reader to read from r. This permits reusing a Reader rather than allocating
-// a new one.
-func (r *Reader) Reset(reader io.Reader) {
- r.r = reader
- r.err = nil
- r.i = 0
- r.j = 0
- r.readHeader = false
-}
-
-func (r *Reader) readFull(p []byte) (ok bool) {
- if _, r.err = io.ReadFull(r.r, p); r.err != nil {
- if r.err == io.ErrUnexpectedEOF {
- r.err = ErrCorrupt
- }
- return false
- }
- return true
-}
-
-// Read satisfies the io.Reader interface.
-func (r *Reader) Read(p []byte) (int, error) {
- if r.err != nil {
- return 0, r.err
- }
- for {
- if r.i < r.j {
- n := copy(p, r.decoded[r.i:r.j])
- r.i += n
- return n, nil
- }
- if !r.readFull(r.buf[:4]) {
- return 0, r.err
- }
- chunkType := r.buf[0]
- if !r.readHeader {
- if chunkType != chunkTypeStreamIdentifier {
- r.err = ErrCorrupt
- return 0, r.err
- }
- r.readHeader = true
- }
- chunkLen := int(r.buf[1]) | int(r.buf[2])<<8 | int(r.buf[3])<<16
- if chunkLen > len(r.buf) {
- r.err = ErrUnsupported
- return 0, r.err
- }
-
- // The chunk types are specified at
- // https://github.com/google/snappy/blob/master/framing_format.txt
- switch chunkType {
- case chunkTypeCompressedData:
- // Section 4.2. Compressed data (chunk type 0x00).
- if chunkLen < checksumSize {
- r.err = ErrCorrupt
- return 0, r.err
- }
- buf := r.buf[:chunkLen]
- if !r.readFull(buf) {
- return 0, r.err
- }
- checksum := uint32(buf[0]) | uint32(buf[1])<<8 | uint32(buf[2])<<16 | uint32(buf[3])<<24
- buf = buf[checksumSize:]
-
- n, err := DecodedLen(buf)
- if err != nil {
- r.err = err
- return 0, r.err
- }
- if n > len(r.decoded) {
- r.err = ErrCorrupt
- return 0, r.err
- }
- if _, err := Decode(r.decoded, buf); err != nil {
- r.err = err
- return 0, r.err
- }
- if crc(r.decoded[:n]) != checksum {
- r.err = ErrCorrupt
- return 0, r.err
- }
- r.i, r.j = 0, n
- continue
-
- case chunkTypeUncompressedData:
- // Section 4.3. Uncompressed data (chunk type 0x01).
- if chunkLen < checksumSize {
- r.err = ErrCorrupt
- return 0, r.err
- }
- buf := r.buf[:checksumSize]
- if !r.readFull(buf) {
- return 0, r.err
- }
- checksum := uint32(buf[0]) | uint32(buf[1])<<8 | uint32(buf[2])<<16 | uint32(buf[3])<<24
- // Read directly into r.decoded instead of via r.buf.
- n := chunkLen - checksumSize
- if !r.readFull(r.decoded[:n]) {
- return 0, r.err
- }
- if crc(r.decoded[:n]) != checksum {
- r.err = ErrCorrupt
- return 0, r.err
- }
- r.i, r.j = 0, n
- continue
-
- case chunkTypeStreamIdentifier:
- // Section 4.1. Stream identifier (chunk type 0xff).
- if chunkLen != len(magicBody) {
- r.err = ErrCorrupt
- return 0, r.err
- }
- if !r.readFull(r.buf[:len(magicBody)]) {
- return 0, r.err
- }
- for i := 0; i < len(magicBody); i++ {
- if r.buf[i] != magicBody[i] {
- r.err = ErrCorrupt
- return 0, r.err
- }
- }
- continue
- }
-
- if chunkType <= 0x7f {
- // Section 4.5. Reserved unskippable chunks (chunk types 0x02-0x7f).
- r.err = ErrUnsupported
- return 0, r.err
- }
- // Section 4.4 Padding (chunk type 0xfe).
- // Section 4.6. Reserved skippable chunks (chunk types 0x80-0xfd).
- if !r.readFull(r.buf[:chunkLen]) {
- return 0, r.err
- }
- }
-}
diff --git a/Godeps/_workspace/src/github.com/golang/snappy/encode.go b/Godeps/_workspace/src/github.com/golang/snappy/encode.go
deleted file mode 100644
index f3b5484bc7..0000000000
--- a/Godeps/_workspace/src/github.com/golang/snappy/encode.go
+++ /dev/null
@@ -1,254 +0,0 @@
-// Copyright 2011 The Snappy-Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package snappy
-
-import (
- "encoding/binary"
- "io"
-)
-
-// We limit how far copy back-references can go, the same as the C++ code.
-const maxOffset = 1 << 15
-
-// emitLiteral writes a literal chunk and returns the number of bytes written.
-func emitLiteral(dst, lit []byte) int {
- i, n := 0, uint(len(lit)-1)
- switch {
- case n < 60:
- dst[0] = uint8(n)<<2 | tagLiteral
- i = 1
- case n < 1<<8:
- dst[0] = 60<<2 | tagLiteral
- dst[1] = uint8(n)
- i = 2
- case n < 1<<16:
- dst[0] = 61<<2 | tagLiteral
- dst[1] = uint8(n)
- dst[2] = uint8(n >> 8)
- i = 3
- case n < 1<<24:
- dst[0] = 62<<2 | tagLiteral
- dst[1] = uint8(n)
- dst[2] = uint8(n >> 8)
- dst[3] = uint8(n >> 16)
- i = 4
- case int64(n) < 1<<32:
- dst[0] = 63<<2 | tagLiteral
- dst[1] = uint8(n)
- dst[2] = uint8(n >> 8)
- dst[3] = uint8(n >> 16)
- dst[4] = uint8(n >> 24)
- i = 5
- default:
- panic("snappy: source buffer is too long")
- }
- if copy(dst[i:], lit) != len(lit) {
- panic("snappy: destination buffer is too short")
- }
- return i + len(lit)
-}
-
-// emitCopy writes a copy chunk and returns the number of bytes written.
-func emitCopy(dst []byte, offset, length int) int {
- i := 0
- for length > 0 {
- x := length - 4
- if 0 <= x && x < 1<<3 && offset < 1<<11 {
- dst[i+0] = uint8(offset>>8)&0x07<<5 | uint8(x)<<2 | tagCopy1
- dst[i+1] = uint8(offset)
- i += 2
- break
- }
-
- x = length
- if x > 1<<6 {
- x = 1 << 6
- }
- dst[i+0] = uint8(x-1)<<2 | tagCopy2
- dst[i+1] = uint8(offset)
- dst[i+2] = uint8(offset >> 8)
- i += 3
- length -= x
- }
- return i
-}
-
-// Encode returns the encoded form of src. The returned slice may be a sub-
-// slice of dst if dst was large enough to hold the entire encoded block.
-// Otherwise, a newly allocated slice will be returned.
-// It is valid to pass a nil dst.
-func Encode(dst, src []byte) []byte {
- if n := MaxEncodedLen(len(src)); len(dst) < n {
- dst = make([]byte, n)
- }
-
- // The block starts with the varint-encoded length of the decompressed bytes.
- d := binary.PutUvarint(dst, uint64(len(src)))
-
- // Return early if src is short.
- if len(src) <= 4 {
- if len(src) != 0 {
- d += emitLiteral(dst[d:], src)
- }
- return dst[:d]
- }
-
- // Initialize the hash table. Its size ranges from 1<<8 to 1<<14 inclusive.
- const maxTableSize = 1 << 14
- shift, tableSize := uint(32-8), 1<<8
- for tableSize < maxTableSize && tableSize < len(src) {
- shift--
- tableSize *= 2
- }
- var table [maxTableSize]int
-
- // Iterate over the source bytes.
- var (
- s int // The iterator position.
- t int // The last position with the same hash as s.
- lit int // The start position of any pending literal bytes.
- )
- for s+3 < len(src) {
- // Update the hash table.
- b0, b1, b2, b3 := src[s], src[s+1], src[s+2], src[s+3]
- h := uint32(b0) | uint32(b1)<<8 | uint32(b2)<<16 | uint32(b3)<<24
- p := &table[(h*0x1e35a7bd)>>shift]
- // We need to to store values in [-1, inf) in table. To save
- // some initialization time, (re)use the table's zero value
- // and shift the values against this zero: add 1 on writes,
- // subtract 1 on reads.
- t, *p = *p-1, s+1
- // If t is invalid or src[s:s+4] differs from src[t:t+4], accumulate a literal byte.
- if t < 0 || s-t >= maxOffset || b0 != src[t] || b1 != src[t+1] || b2 != src[t+2] || b3 != src[t+3] {
- s++
- continue
- }
- // Otherwise, we have a match. First, emit any pending literal bytes.
- if lit != s {
- d += emitLiteral(dst[d:], src[lit:s])
- }
- // Extend the match to be as long as possible.
- s0 := s
- s, t = s+4, t+4
- for s < len(src) && src[s] == src[t] {
- s++
- t++
- }
- // Emit the copied bytes.
- d += emitCopy(dst[d:], s-t, s-s0)
- lit = s
- }
-
- // Emit any final pending literal bytes and return.
- if lit != len(src) {
- d += emitLiteral(dst[d:], src[lit:])
- }
- return dst[:d]
-}
-
-// MaxEncodedLen returns the maximum length of a snappy block, given its
-// uncompressed length.
-func MaxEncodedLen(srcLen int) int {
- // Compressed data can be defined as:
- // compressed := item* literal*
- // item := literal* copy
- //
- // The trailing literal sequence has a space blowup of at most 62/60
- // since a literal of length 60 needs one tag byte + one extra byte
- // for length information.
- //
- // Item blowup is trickier to measure. Suppose the "copy" op copies
- // 4 bytes of data. Because of a special check in the encoding code,
- // we produce a 4-byte copy only if the offset is < 65536. Therefore
- // the copy op takes 3 bytes to encode, and this type of item leads
- // to at most the 62/60 blowup for representing literals.
- //
- // Suppose the "copy" op copies 5 bytes of data. If the offset is big
- // enough, it will take 5 bytes to encode the copy op. Therefore the
- // worst case here is a one-byte literal followed by a five-byte copy.
- // That is, 6 bytes of input turn into 7 bytes of "compressed" data.
- //
- // This last factor dominates the blowup, so the final estimate is:
- return 32 + srcLen + srcLen/6
-}
-
-// NewWriter returns a new Writer that compresses to w, using the framing
-// format described at
-// https://github.com/google/snappy/blob/master/framing_format.txt
-func NewWriter(w io.Writer) *Writer {
- return &Writer{
- w: w,
- enc: make([]byte, MaxEncodedLen(maxUncompressedChunkLen)),
- }
-}
-
-// Writer is an io.Writer than can write Snappy-compressed bytes.
-type Writer struct {
- w io.Writer
- err error
- enc []byte
- buf [checksumSize + chunkHeaderSize]byte
- wroteHeader bool
-}
-
-// Reset discards the writer's state and switches the Snappy writer to write to
-// w. This permits reusing a Writer rather than allocating a new one.
-func (w *Writer) Reset(writer io.Writer) {
- w.w = writer
- w.err = nil
- w.wroteHeader = false
-}
-
-// Write satisfies the io.Writer interface.
-func (w *Writer) Write(p []byte) (n int, errRet error) {
- if w.err != nil {
- return 0, w.err
- }
- if !w.wroteHeader {
- copy(w.enc, magicChunk)
- if _, err := w.w.Write(w.enc[:len(magicChunk)]); err != nil {
- w.err = err
- return n, err
- }
- w.wroteHeader = true
- }
- for len(p) > 0 {
- var uncompressed []byte
- if len(p) > maxUncompressedChunkLen {
- uncompressed, p = p[:maxUncompressedChunkLen], p[maxUncompressedChunkLen:]
- } else {
- uncompressed, p = p, nil
- }
- checksum := crc(uncompressed)
-
- // Compress the buffer, discarding the result if the improvement
- // isn't at least 12.5%.
- chunkType := uint8(chunkTypeCompressedData)
- chunkBody := Encode(w.enc, uncompressed)
- if len(chunkBody) >= len(uncompressed)-len(uncompressed)/8 {
- chunkType, chunkBody = chunkTypeUncompressedData, uncompressed
- }
-
- chunkLen := 4 + len(chunkBody)
- w.buf[0] = chunkType
- w.buf[1] = uint8(chunkLen >> 0)
- w.buf[2] = uint8(chunkLen >> 8)
- w.buf[3] = uint8(chunkLen >> 16)
- w.buf[4] = uint8(checksum >> 0)
- w.buf[5] = uint8(checksum >> 8)
- w.buf[6] = uint8(checksum >> 16)
- w.buf[7] = uint8(checksum >> 24)
- if _, err := w.w.Write(w.buf[:]); err != nil {
- w.err = err
- return n, err
- }
- if _, err := w.w.Write(chunkBody); err != nil {
- w.err = err
- return n, err
- }
- n += len(uncompressed)
- }
- return n, nil
-}
diff --git a/Godeps/_workspace/src/github.com/golang/snappy/snappy.go b/Godeps/_workspace/src/github.com/golang/snappy/snappy.go
deleted file mode 100644
index e98653acff..0000000000
--- a/Godeps/_workspace/src/github.com/golang/snappy/snappy.go
+++ /dev/null
@@ -1,68 +0,0 @@
-// Copyright 2011 The Snappy-Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// Package snappy implements the snappy block-based compression format.
-// It aims for very high speeds and reasonable compression.
-//
-// The C++ snappy implementation is at https://github.com/google/snappy
-package snappy
-
-import (
- "hash/crc32"
-)
-
-/*
-Each encoded block begins with the varint-encoded length of the decoded data,
-followed by a sequence of chunks. Chunks begin and end on byte boundaries. The
-first byte of each chunk is broken into its 2 least and 6 most significant bits
-called l and m: l ranges in [0, 4) and m ranges in [0, 64). l is the chunk tag.
-Zero means a literal tag. All other values mean a copy tag.
-
-For literal tags:
- - If m < 60, the next 1 + m bytes are literal bytes.
- - Otherwise, let n be the little-endian unsigned integer denoted by the next
- m - 59 bytes. The next 1 + n bytes after that are literal bytes.
-
-For copy tags, length bytes are copied from offset bytes ago, in the style of
-Lempel-Ziv compression algorithms. In particular:
- - For l == 1, the offset ranges in [0, 1<<11) and the length in [4, 12).
- The length is 4 + the low 3 bits of m. The high 3 bits of m form bits 8-10
- of the offset. The next byte is bits 0-7 of the offset.
- - For l == 2, the offset ranges in [0, 1<<16) and the length in [1, 65).
- The length is 1 + m. The offset is the little-endian unsigned integer
- denoted by the next 2 bytes.
- - For l == 3, this tag is a legacy format that is no longer supported.
-*/
-const (
- tagLiteral = 0x00
- tagCopy1 = 0x01
- tagCopy2 = 0x02
- tagCopy4 = 0x03
-)
-
-const (
- checksumSize = 4
- chunkHeaderSize = 4
- magicChunk = "\xff\x06\x00\x00" + magicBody
- magicBody = "sNaPpY"
- // https://github.com/google/snappy/blob/master/framing_format.txt says
- // that "the uncompressed data in a chunk must be no longer than 65536 bytes".
- maxUncompressedChunkLen = 65536
-)
-
-const (
- chunkTypeCompressedData = 0x00
- chunkTypeUncompressedData = 0x01
- chunkTypePadding = 0xfe
- chunkTypeStreamIdentifier = 0xff
-)
-
-var crcTable = crc32.MakeTable(crc32.Castagnoli)
-
-// crc implements the checksum specified in section 3 of
-// https://github.com/google/snappy/blob/master/framing_format.txt
-func crc(b []byte) uint32 {
- c := crc32.Update(0, crcTable, b)
- return uint32(c>>15|c<<17) + 0xa282ead8
-}
diff --git a/Godeps/_workspace/src/github.com/golang/snappy/snappy_test.go b/Godeps/_workspace/src/github.com/golang/snappy/snappy_test.go
deleted file mode 100644
index d6a03973b3..0000000000
--- a/Godeps/_workspace/src/github.com/golang/snappy/snappy_test.go
+++ /dev/null
@@ -1,367 +0,0 @@
-// Copyright 2011 The Snappy-Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package snappy
-
-import (
- "bytes"
- "flag"
- "fmt"
- "io"
- "io/ioutil"
- "math/rand"
- "net/http"
- "os"
- "path/filepath"
- "strings"
- "testing"
-)
-
-var (
- download = flag.Bool("download", false, "If true, download any missing files before running benchmarks")
- testdata = flag.String("testdata", "testdata", "Directory containing the test data")
-)
-
-func roundtrip(b, ebuf, dbuf []byte) error {
- d, err := Decode(dbuf, Encode(ebuf, b))
- if err != nil {
- return fmt.Errorf("decoding error: %v", err)
- }
- if !bytes.Equal(b, d) {
- return fmt.Errorf("roundtrip mismatch:\n\twant %v\n\tgot %v", b, d)
- }
- return nil
-}
-
-func TestEmpty(t *testing.T) {
- if err := roundtrip(nil, nil, nil); err != nil {
- t.Fatal(err)
- }
-}
-
-func TestSmallCopy(t *testing.T) {
- for _, ebuf := range [][]byte{nil, make([]byte, 20), make([]byte, 64)} {
- for _, dbuf := range [][]byte{nil, make([]byte, 20), make([]byte, 64)} {
- for i := 0; i < 32; i++ {
- s := "aaaa" + strings.Repeat("b", i) + "aaaabbbb"
- if err := roundtrip([]byte(s), ebuf, dbuf); err != nil {
- t.Errorf("len(ebuf)=%d, len(dbuf)=%d, i=%d: %v", len(ebuf), len(dbuf), i, err)
- }
- }
- }
- }
-}
-
-func TestSmallRand(t *testing.T) {
- rng := rand.New(rand.NewSource(27354294))
- for n := 1; n < 20000; n += 23 {
- b := make([]byte, n)
- for i := range b {
- b[i] = uint8(rng.Uint32())
- }
- if err := roundtrip(b, nil, nil); err != nil {
- t.Fatal(err)
- }
- }
-}
-
-func TestSmallRegular(t *testing.T) {
- for n := 1; n < 20000; n += 23 {
- b := make([]byte, n)
- for i := range b {
- b[i] = uint8(i%10 + 'a')
- }
- if err := roundtrip(b, nil, nil); err != nil {
- t.Fatal(err)
- }
- }
-}
-
-func TestInvalidVarint(t *testing.T) {
- data := []byte("\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\x00")
- if _, err := DecodedLen(data); err != ErrCorrupt {
- t.Errorf("DecodedLen: got %v, want ErrCorrupt", err)
- }
- if _, err := Decode(nil, data); err != ErrCorrupt {
- t.Errorf("Decode: got %v, want ErrCorrupt", err)
- }
-}
-
-func cmp(a, b []byte) error {
- if len(a) != len(b) {
- return fmt.Errorf("got %d bytes, want %d", len(a), len(b))
- }
- for i := range a {
- if a[i] != b[i] {
- return fmt.Errorf("byte #%d: got 0x%02x, want 0x%02x", i, a[i], b[i])
- }
- }
- return nil
-}
-
-func TestFramingFormat(t *testing.T) {
- // src is comprised of alternating 1e5-sized sequences of random
- // (incompressible) bytes and repeated (compressible) bytes. 1e5 was chosen
- // because it is larger than maxUncompressedChunkLen (64k).
- src := make([]byte, 1e6)
- rng := rand.New(rand.NewSource(1))
- for i := 0; i < 10; i++ {
- if i%2 == 0 {
- for j := 0; j < 1e5; j++ {
- src[1e5*i+j] = uint8(rng.Intn(256))
- }
- } else {
- for j := 0; j < 1e5; j++ {
- src[1e5*i+j] = uint8(i)
- }
- }
- }
-
- buf := new(bytes.Buffer)
- if _, err := NewWriter(buf).Write(src); err != nil {
- t.Fatalf("Write: encoding: %v", err)
- }
- dst, err := ioutil.ReadAll(NewReader(buf))
- if err != nil {
- t.Fatalf("ReadAll: decoding: %v", err)
- }
- if err := cmp(dst, src); err != nil {
- t.Fatal(err)
- }
-}
-
-func TestReaderReset(t *testing.T) {
- gold := bytes.Repeat([]byte("All that is gold does not glitter,\n"), 10000)
- buf := new(bytes.Buffer)
- if _, err := NewWriter(buf).Write(gold); err != nil {
- t.Fatalf("Write: %v", err)
- }
- encoded, invalid, partial := buf.String(), "invalid", "partial"
- r := NewReader(nil)
- for i, s := range []string{encoded, invalid, partial, encoded, partial, invalid, encoded, encoded} {
- if s == partial {
- r.Reset(strings.NewReader(encoded))
- if _, err := r.Read(make([]byte, 101)); err != nil {
- t.Errorf("#%d: %v", i, err)
- continue
- }
- continue
- }
- r.Reset(strings.NewReader(s))
- got, err := ioutil.ReadAll(r)
- switch s {
- case encoded:
- if err != nil {
- t.Errorf("#%d: %v", i, err)
- continue
- }
- if err := cmp(got, gold); err != nil {
- t.Errorf("#%d: %v", i, err)
- continue
- }
- case invalid:
- if err == nil {
- t.Errorf("#%d: got nil error, want non-nil", i)
- continue
- }
- }
- }
-}
-
-func TestWriterReset(t *testing.T) {
- gold := bytes.Repeat([]byte("Not all those who wander are lost;\n"), 10000)
- var gots, wants [][]byte
- const n = 20
- w, failed := NewWriter(nil), false
- for i := 0; i <= n; i++ {
- buf := new(bytes.Buffer)
- w.Reset(buf)
- want := gold[:len(gold)*i/n]
- if _, err := w.Write(want); err != nil {
- t.Errorf("#%d: Write: %v", i, err)
- failed = true
- continue
- }
- got, err := ioutil.ReadAll(NewReader(buf))
- if err != nil {
- t.Errorf("#%d: ReadAll: %v", i, err)
- failed = true
- continue
- }
- gots = append(gots, got)
- wants = append(wants, want)
- }
- if failed {
- return
- }
- for i := range gots {
- if err := cmp(gots[i], wants[i]); err != nil {
- t.Errorf("#%d: %v", i, err)
- }
- }
-}
-
-func benchDecode(b *testing.B, src []byte) {
- encoded := Encode(nil, src)
- // Bandwidth is in amount of uncompressed data.
- b.SetBytes(int64(len(src)))
- b.ResetTimer()
- for i := 0; i < b.N; i++ {
- Decode(src, encoded)
- }
-}
-
-func benchEncode(b *testing.B, src []byte) {
- // Bandwidth is in amount of uncompressed data.
- b.SetBytes(int64(len(src)))
- dst := make([]byte, MaxEncodedLen(len(src)))
- b.ResetTimer()
- for i := 0; i < b.N; i++ {
- Encode(dst, src)
- }
-}
-
-func readFile(b testing.TB, filename string) []byte {
- src, err := ioutil.ReadFile(filename)
- if err != nil {
- b.Skipf("skipping benchmark: %v", err)
- }
- if len(src) == 0 {
- b.Fatalf("%s has zero length", filename)
- }
- return src
-}
-
-// expand returns a slice of length n containing repeated copies of src.
-func expand(src []byte, n int) []byte {
- dst := make([]byte, n)
- for x := dst; len(x) > 0; {
- i := copy(x, src)
- x = x[i:]
- }
- return dst
-}
-
-func benchWords(b *testing.B, n int, decode bool) {
- // Note: the file is OS-language dependent so the resulting values are not
- // directly comparable for non-US-English OS installations.
- data := expand(readFile(b, "/usr/share/dict/words"), n)
- if decode {
- benchDecode(b, data)
- } else {
- benchEncode(b, data)
- }
-}
-
-func BenchmarkWordsDecode1e3(b *testing.B) { benchWords(b, 1e3, true) }
-func BenchmarkWordsDecode1e4(b *testing.B) { benchWords(b, 1e4, true) }
-func BenchmarkWordsDecode1e5(b *testing.B) { benchWords(b, 1e5, true) }
-func BenchmarkWordsDecode1e6(b *testing.B) { benchWords(b, 1e6, true) }
-func BenchmarkWordsEncode1e3(b *testing.B) { benchWords(b, 1e3, false) }
-func BenchmarkWordsEncode1e4(b *testing.B) { benchWords(b, 1e4, false) }
-func BenchmarkWordsEncode1e5(b *testing.B) { benchWords(b, 1e5, false) }
-func BenchmarkWordsEncode1e6(b *testing.B) { benchWords(b, 1e6, false) }
-
-// testFiles' values are copied directly from
-// https://raw.githubusercontent.com/google/snappy/master/snappy_unittest.cc
-// The label field is unused in snappy-go.
-var testFiles = []struct {
- label string
- filename string
-}{
- {"html", "html"},
- {"urls", "urls.10K"},
- {"jpg", "fireworks.jpeg"},
- {"jpg_200", "fireworks.jpeg"},
- {"pdf", "paper-100k.pdf"},
- {"html4", "html_x_4"},
- {"txt1", "alice29.txt"},
- {"txt2", "asyoulik.txt"},
- {"txt3", "lcet10.txt"},
- {"txt4", "plrabn12.txt"},
- {"pb", "geo.protodata"},
- {"gaviota", "kppkn.gtb"},
-}
-
-// The test data files are present at this canonical URL.
-const baseURL = "https://raw.githubusercontent.com/google/snappy/master/testdata/"
-
-func downloadTestdata(b *testing.B, basename string) (errRet error) {
- filename := filepath.Join(*testdata, basename)
- if stat, err := os.Stat(filename); err == nil && stat.Size() != 0 {
- return nil
- }
-
- if !*download {
- b.Skipf("test data not found; skipping benchmark without the -download flag")
- }
- // Download the official snappy C++ implementation reference test data
- // files for benchmarking.
- if err := os.Mkdir(*testdata, 0777); err != nil && !os.IsExist(err) {
- return fmt.Errorf("failed to create testdata: %s", err)
- }
-
- f, err := os.Create(filename)
- if err != nil {
- return fmt.Errorf("failed to create %s: %s", filename, err)
- }
- defer f.Close()
- defer func() {
- if errRet != nil {
- os.Remove(filename)
- }
- }()
- url := baseURL + basename
- resp, err := http.Get(url)
- if err != nil {
- return fmt.Errorf("failed to download %s: %s", url, err)
- }
- defer resp.Body.Close()
- if s := resp.StatusCode; s != http.StatusOK {
- return fmt.Errorf("downloading %s: HTTP status code %d (%s)", url, s, http.StatusText(s))
- }
- _, err = io.Copy(f, resp.Body)
- if err != nil {
- return fmt.Errorf("failed to download %s to %s: %s", url, filename, err)
- }
- return nil
-}
-
-func benchFile(b *testing.B, n int, decode bool) {
- if err := downloadTestdata(b, testFiles[n].filename); err != nil {
- b.Fatalf("failed to download testdata: %s", err)
- }
- data := readFile(b, filepath.Join(*testdata, testFiles[n].filename))
- if decode {
- benchDecode(b, data)
- } else {
- benchEncode(b, data)
- }
-}
-
-// Naming convention is kept similar to what snappy's C++ implementation uses.
-func Benchmark_UFlat0(b *testing.B) { benchFile(b, 0, true) }
-func Benchmark_UFlat1(b *testing.B) { benchFile(b, 1, true) }
-func Benchmark_UFlat2(b *testing.B) { benchFile(b, 2, true) }
-func Benchmark_UFlat3(b *testing.B) { benchFile(b, 3, true) }
-func Benchmark_UFlat4(b *testing.B) { benchFile(b, 4, true) }
-func Benchmark_UFlat5(b *testing.B) { benchFile(b, 5, true) }
-func Benchmark_UFlat6(b *testing.B) { benchFile(b, 6, true) }
-func Benchmark_UFlat7(b *testing.B) { benchFile(b, 7, true) }
-func Benchmark_UFlat8(b *testing.B) { benchFile(b, 8, true) }
-func Benchmark_UFlat9(b *testing.B) { benchFile(b, 9, true) }
-func Benchmark_UFlat10(b *testing.B) { benchFile(b, 10, true) }
-func Benchmark_UFlat11(b *testing.B) { benchFile(b, 11, true) }
-func Benchmark_ZFlat0(b *testing.B) { benchFile(b, 0, false) }
-func Benchmark_ZFlat1(b *testing.B) { benchFile(b, 1, false) }
-func Benchmark_ZFlat2(b *testing.B) { benchFile(b, 2, false) }
-func Benchmark_ZFlat3(b *testing.B) { benchFile(b, 3, false) }
-func Benchmark_ZFlat4(b *testing.B) { benchFile(b, 4, false) }
-func Benchmark_ZFlat5(b *testing.B) { benchFile(b, 5, false) }
-func Benchmark_ZFlat6(b *testing.B) { benchFile(b, 6, false) }
-func Benchmark_ZFlat7(b *testing.B) { benchFile(b, 7, false) }
-func Benchmark_ZFlat8(b *testing.B) { benchFile(b, 8, false) }
-func Benchmark_ZFlat9(b *testing.B) { benchFile(b, 9, false) }
-func Benchmark_ZFlat10(b *testing.B) { benchFile(b, 10, false) }
-func Benchmark_ZFlat11(b *testing.B) { benchFile(b, 11, false) }
diff --git a/Godeps/_workspace/src/github.com/hashicorp/consul/api/README.md b/Godeps/_workspace/src/github.com/hashicorp/consul/api/README.md
deleted file mode 100644
index bce2ebb516..0000000000
--- a/Godeps/_workspace/src/github.com/hashicorp/consul/api/README.md
+++ /dev/null
@@ -1,39 +0,0 @@
-Consul API client
-=================
-
-This package provides the `api` package which attempts to
-provide programmatic access to the full Consul API.
-
-Currently, all of the Consul APIs included in version 0.3 are supported.
-
-Documentation
-=============
-
-The full documentation is available on [Godoc](http://godoc.org/github.com/hashicorp/consul/api)
-
-Usage
-=====
-
-Below is an example of using the Consul client:
-
-```go
-// Get a new client, with KV endpoints
-client, _ := api.NewClient(api.DefaultConfig())
-kv := client.KV()
-
-// PUT a new KV pair
-p := &api.KVPair{Key: "foo", Value: []byte("test")}
-_, err := kv.Put(p, nil)
-if err != nil {
- panic(err)
-}
-
-// Lookup the pair
-pair, _, err := kv.Get("foo", nil)
-if err != nil {
- panic(err)
-}
-fmt.Printf("KV: %v", pair)
-
-```
-
diff --git a/Godeps/_workspace/src/github.com/hashicorp/consul/api/acl.go b/Godeps/_workspace/src/github.com/hashicorp/consul/api/acl.go
deleted file mode 100644
index c3fb0d53aa..0000000000
--- a/Godeps/_workspace/src/github.com/hashicorp/consul/api/acl.go
+++ /dev/null
@@ -1,140 +0,0 @@
-package api
-
-const (
- // ACLCLientType is the client type token
- ACLClientType = "client"
-
- // ACLManagementType is the management type token
- ACLManagementType = "management"
-)
-
-// ACLEntry is used to represent an ACL entry
-type ACLEntry struct {
- CreateIndex uint64
- ModifyIndex uint64
- ID string
- Name string
- Type string
- Rules string
-}
-
-// ACL can be used to query the ACL endpoints
-type ACL struct {
- c *Client
-}
-
-// ACL returns a handle to the ACL endpoints
-func (c *Client) ACL() *ACL {
- return &ACL{c}
-}
-
-// Create is used to generate a new token with the given parameters
-func (a *ACL) Create(acl *ACLEntry, q *WriteOptions) (string, *WriteMeta, error) {
- r := a.c.newRequest("PUT", "/v1/acl/create")
- r.setWriteOptions(q)
- r.obj = acl
- rtt, resp, err := requireOK(a.c.doRequest(r))
- if err != nil {
- return "", nil, err
- }
- defer resp.Body.Close()
-
- wm := &WriteMeta{RequestTime: rtt}
- var out struct{ ID string }
- if err := decodeBody(resp, &out); err != nil {
- return "", nil, err
- }
- return out.ID, wm, nil
-}
-
-// Update is used to update the rules of an existing token
-func (a *ACL) Update(acl *ACLEntry, q *WriteOptions) (*WriteMeta, error) {
- r := a.c.newRequest("PUT", "/v1/acl/update")
- r.setWriteOptions(q)
- r.obj = acl
- rtt, resp, err := requireOK(a.c.doRequest(r))
- if err != nil {
- return nil, err
- }
- defer resp.Body.Close()
-
- wm := &WriteMeta{RequestTime: rtt}
- return wm, nil
-}
-
-// Destroy is used to destroy a given ACL token ID
-func (a *ACL) Destroy(id string, q *WriteOptions) (*WriteMeta, error) {
- r := a.c.newRequest("PUT", "/v1/acl/destroy/"+id)
- r.setWriteOptions(q)
- rtt, resp, err := requireOK(a.c.doRequest(r))
- if err != nil {
- return nil, err
- }
- resp.Body.Close()
-
- wm := &WriteMeta{RequestTime: rtt}
- return wm, nil
-}
-
-// Clone is used to return a new token cloned from an existing one
-func (a *ACL) Clone(id string, q *WriteOptions) (string, *WriteMeta, error) {
- r := a.c.newRequest("PUT", "/v1/acl/clone/"+id)
- r.setWriteOptions(q)
- rtt, resp, err := requireOK(a.c.doRequest(r))
- if err != nil {
- return "", nil, err
- }
- defer resp.Body.Close()
-
- wm := &WriteMeta{RequestTime: rtt}
- var out struct{ ID string }
- if err := decodeBody(resp, &out); err != nil {
- return "", nil, err
- }
- return out.ID, wm, nil
-}
-
-// Info is used to query for information about an ACL token
-func (a *ACL) Info(id string, q *QueryOptions) (*ACLEntry, *QueryMeta, error) {
- r := a.c.newRequest("GET", "/v1/acl/info/"+id)
- r.setQueryOptions(q)
- rtt, resp, err := requireOK(a.c.doRequest(r))
- if err != nil {
- return nil, nil, err
- }
- defer resp.Body.Close()
-
- qm := &QueryMeta{}
- parseQueryMeta(resp, qm)
- qm.RequestTime = rtt
-
- var entries []*ACLEntry
- if err := decodeBody(resp, &entries); err != nil {
- return nil, nil, err
- }
- if len(entries) > 0 {
- return entries[0], qm, nil
- }
- return nil, qm, nil
-}
-
-// List is used to get all the ACL tokens
-func (a *ACL) List(q *QueryOptions) ([]*ACLEntry, *QueryMeta, error) {
- r := a.c.newRequest("GET", "/v1/acl/list")
- r.setQueryOptions(q)
- rtt, resp, err := requireOK(a.c.doRequest(r))
- if err != nil {
- return nil, nil, err
- }
- defer resp.Body.Close()
-
- qm := &QueryMeta{}
- parseQueryMeta(resp, qm)
- qm.RequestTime = rtt
-
- var entries []*ACLEntry
- if err := decodeBody(resp, &entries); err != nil {
- return nil, nil, err
- }
- return entries, qm, nil
-}
diff --git a/Godeps/_workspace/src/github.com/hashicorp/consul/api/acl_test.go b/Godeps/_workspace/src/github.com/hashicorp/consul/api/acl_test.go
deleted file mode 100644
index 2a5207a6ee..0000000000
--- a/Godeps/_workspace/src/github.com/hashicorp/consul/api/acl_test.go
+++ /dev/null
@@ -1,128 +0,0 @@
-package api
-
-import (
- "testing"
-)
-
-func TestACL_CreateDestroy(t *testing.T) {
- t.Parallel()
- c, s := makeACLClient(t)
- defer s.Stop()
-
- acl := c.ACL()
-
- ae := ACLEntry{
- Name: "API test",
- Type: ACLClientType,
- Rules: `key "" { policy = "deny" }`,
- }
-
- id, wm, err := acl.Create(&ae, nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- if wm.RequestTime == 0 {
- t.Fatalf("bad: %v", wm)
- }
-
- if id == "" {
- t.Fatalf("invalid: %v", id)
- }
-
- ae2, _, err := acl.Info(id, nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- if ae2.Name != ae.Name || ae2.Type != ae.Type || ae2.Rules != ae.Rules {
- t.Fatalf("Bad: %#v", ae2)
- }
-
- wm, err = acl.Destroy(id, nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- if wm.RequestTime == 0 {
- t.Fatalf("bad: %v", wm)
- }
-}
-
-func TestACL_CloneDestroy(t *testing.T) {
- t.Parallel()
- c, s := makeACLClient(t)
- defer s.Stop()
-
- acl := c.ACL()
-
- id, wm, err := acl.Clone(c.config.Token, nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- if wm.RequestTime == 0 {
- t.Fatalf("bad: %v", wm)
- }
-
- if id == "" {
- t.Fatalf("invalid: %v", id)
- }
-
- wm, err = acl.Destroy(id, nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- if wm.RequestTime == 0 {
- t.Fatalf("bad: %v", wm)
- }
-}
-
-func TestACL_Info(t *testing.T) {
- t.Parallel()
- c, s := makeACLClient(t)
- defer s.Stop()
-
- acl := c.ACL()
-
- ae, qm, err := acl.Info(c.config.Token, nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- if qm.LastIndex == 0 {
- t.Fatalf("bad: %v", qm)
- }
- if !qm.KnownLeader {
- t.Fatalf("bad: %v", qm)
- }
-
- if ae == nil || ae.ID != c.config.Token || ae.Type != ACLManagementType {
- t.Fatalf("bad: %#v", ae)
- }
-}
-
-func TestACL_List(t *testing.T) {
- t.Parallel()
- c, s := makeACLClient(t)
- defer s.Stop()
-
- acl := c.ACL()
-
- acls, qm, err := acl.List(nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- if len(acls) < 2 {
- t.Fatalf("bad: %v", acls)
- }
-
- if qm.LastIndex == 0 {
- t.Fatalf("bad: %v", qm)
- }
- if !qm.KnownLeader {
- t.Fatalf("bad: %v", qm)
- }
-}
diff --git a/Godeps/_workspace/src/github.com/hashicorp/consul/api/agent.go b/Godeps/_workspace/src/github.com/hashicorp/consul/api/agent.go
deleted file mode 100644
index e56a18dcd2..0000000000
--- a/Godeps/_workspace/src/github.com/hashicorp/consul/api/agent.go
+++ /dev/null
@@ -1,334 +0,0 @@
-package api
-
-import (
- "fmt"
-)
-
-// AgentCheck represents a check known to the agent
-type AgentCheck struct {
- Node string
- CheckID string
- Name string
- Status string
- Notes string
- Output string
- ServiceID string
- ServiceName string
-}
-
-// AgentService represents a service known to the agent
-type AgentService struct {
- ID string
- Service string
- Tags []string
- Port int
- Address string
-}
-
-// AgentMember represents a cluster member known to the agent
-type AgentMember struct {
- Name string
- Addr string
- Port uint16
- Tags map[string]string
- Status int
- ProtocolMin uint8
- ProtocolMax uint8
- ProtocolCur uint8
- DelegateMin uint8
- DelegateMax uint8
- DelegateCur uint8
-}
-
-// AgentServiceRegistration is used to register a new service
-type AgentServiceRegistration struct {
- ID string `json:",omitempty"`
- Name string `json:",omitempty"`
- Tags []string `json:",omitempty"`
- Port int `json:",omitempty"`
- Address string `json:",omitempty"`
- Check *AgentServiceCheck
- Checks AgentServiceChecks
-}
-
-// AgentCheckRegistration is used to register a new check
-type AgentCheckRegistration struct {
- ID string `json:",omitempty"`
- Name string `json:",omitempty"`
- Notes string `json:",omitempty"`
- ServiceID string `json:",omitempty"`
- AgentServiceCheck
-}
-
-// AgentServiceCheck is used to create an associated
-// check for a service
-type AgentServiceCheck struct {
- Script string `json:",omitempty"`
- Interval string `json:",omitempty"`
- Timeout string `json:",omitempty"`
- TTL string `json:",omitempty"`
- HTTP string `json:",omitempty"`
- Status string `json:",omitempty"`
-}
-type AgentServiceChecks []*AgentServiceCheck
-
-// Agent can be used to query the Agent endpoints
-type Agent struct {
- c *Client
-
- // cache the node name
- nodeName string
-}
-
-// Agent returns a handle to the agent endpoints
-func (c *Client) Agent() *Agent {
- return &Agent{c: c}
-}
-
-// Self is used to query the agent we are speaking to for
-// information about itself
-func (a *Agent) Self() (map[string]map[string]interface{}, error) {
- r := a.c.newRequest("GET", "/v1/agent/self")
- _, resp, err := requireOK(a.c.doRequest(r))
- if err != nil {
- return nil, err
- }
- defer resp.Body.Close()
-
- var out map[string]map[string]interface{}
- if err := decodeBody(resp, &out); err != nil {
- return nil, err
- }
- return out, nil
-}
-
-// NodeName is used to get the node name of the agent
-func (a *Agent) NodeName() (string, error) {
- if a.nodeName != "" {
- return a.nodeName, nil
- }
- info, err := a.Self()
- if err != nil {
- return "", err
- }
- name := info["Config"]["NodeName"].(string)
- a.nodeName = name
- return name, nil
-}
-
-// Checks returns the locally registered checks
-func (a *Agent) Checks() (map[string]*AgentCheck, error) {
- r := a.c.newRequest("GET", "/v1/agent/checks")
- _, resp, err := requireOK(a.c.doRequest(r))
- if err != nil {
- return nil, err
- }
- defer resp.Body.Close()
-
- var out map[string]*AgentCheck
- if err := decodeBody(resp, &out); err != nil {
- return nil, err
- }
- return out, nil
-}
-
-// Services returns the locally registered services
-func (a *Agent) Services() (map[string]*AgentService, error) {
- r := a.c.newRequest("GET", "/v1/agent/services")
- _, resp, err := requireOK(a.c.doRequest(r))
- if err != nil {
- return nil, err
- }
- defer resp.Body.Close()
-
- var out map[string]*AgentService
- if err := decodeBody(resp, &out); err != nil {
- return nil, err
- }
- return out, nil
-}
-
-// Members returns the known gossip members. The WAN
-// flag can be used to query a server for WAN members.
-func (a *Agent) Members(wan bool) ([]*AgentMember, error) {
- r := a.c.newRequest("GET", "/v1/agent/members")
- if wan {
- r.params.Set("wan", "1")
- }
- _, resp, err := requireOK(a.c.doRequest(r))
- if err != nil {
- return nil, err
- }
- defer resp.Body.Close()
-
- var out []*AgentMember
- if err := decodeBody(resp, &out); err != nil {
- return nil, err
- }
- return out, nil
-}
-
-// ServiceRegister is used to register a new service with
-// the local agent
-func (a *Agent) ServiceRegister(service *AgentServiceRegistration) error {
- r := a.c.newRequest("PUT", "/v1/agent/service/register")
- r.obj = service
- _, resp, err := requireOK(a.c.doRequest(r))
- if err != nil {
- return err
- }
- resp.Body.Close()
- return nil
-}
-
-// ServiceDeregister is used to deregister a service with
-// the local agent
-func (a *Agent) ServiceDeregister(serviceID string) error {
- r := a.c.newRequest("PUT", "/v1/agent/service/deregister/"+serviceID)
- _, resp, err := requireOK(a.c.doRequest(r))
- if err != nil {
- return err
- }
- resp.Body.Close()
- return nil
-}
-
-// PassTTL is used to set a TTL check to the passing state
-func (a *Agent) PassTTL(checkID, note string) error {
- return a.UpdateTTL(checkID, note, "pass")
-}
-
-// WarnTTL is used to set a TTL check to the warning state
-func (a *Agent) WarnTTL(checkID, note string) error {
- return a.UpdateTTL(checkID, note, "warn")
-}
-
-// FailTTL is used to set a TTL check to the failing state
-func (a *Agent) FailTTL(checkID, note string) error {
- return a.UpdateTTL(checkID, note, "fail")
-}
-
-// UpdateTTL is used to update the TTL of a check
-func (a *Agent) UpdateTTL(checkID, note, status string) error {
- switch status {
- case "pass":
- case "warn":
- case "fail":
- default:
- return fmt.Errorf("Invalid status: %s", status)
- }
- endpoint := fmt.Sprintf("/v1/agent/check/%s/%s", status, checkID)
- r := a.c.newRequest("PUT", endpoint)
- r.params.Set("note", note)
- _, resp, err := requireOK(a.c.doRequest(r))
- if err != nil {
- return err
- }
- resp.Body.Close()
- return nil
-}
-
-// CheckRegister is used to register a new check with
-// the local agent
-func (a *Agent) CheckRegister(check *AgentCheckRegistration) error {
- r := a.c.newRequest("PUT", "/v1/agent/check/register")
- r.obj = check
- _, resp, err := requireOK(a.c.doRequest(r))
- if err != nil {
- return err
- }
- resp.Body.Close()
- return nil
-}
-
-// CheckDeregister is used to deregister a check with
-// the local agent
-func (a *Agent) CheckDeregister(checkID string) error {
- r := a.c.newRequest("PUT", "/v1/agent/check/deregister/"+checkID)
- _, resp, err := requireOK(a.c.doRequest(r))
- if err != nil {
- return err
- }
- resp.Body.Close()
- return nil
-}
-
-// Join is used to instruct the agent to attempt a join to
-// another cluster member
-func (a *Agent) Join(addr string, wan bool) error {
- r := a.c.newRequest("PUT", "/v1/agent/join/"+addr)
- if wan {
- r.params.Set("wan", "1")
- }
- _, resp, err := requireOK(a.c.doRequest(r))
- if err != nil {
- return err
- }
- resp.Body.Close()
- return nil
-}
-
-// ForceLeave is used to have the agent eject a failed node
-func (a *Agent) ForceLeave(node string) error {
- r := a.c.newRequest("PUT", "/v1/agent/force-leave/"+node)
- _, resp, err := requireOK(a.c.doRequest(r))
- if err != nil {
- return err
- }
- resp.Body.Close()
- return nil
-}
-
-// EnableServiceMaintenance toggles service maintenance mode on
-// for the given service ID.
-func (a *Agent) EnableServiceMaintenance(serviceID, reason string) error {
- r := a.c.newRequest("PUT", "/v1/agent/service/maintenance/"+serviceID)
- r.params.Set("enable", "true")
- r.params.Set("reason", reason)
- _, resp, err := requireOK(a.c.doRequest(r))
- if err != nil {
- return err
- }
- resp.Body.Close()
- return nil
-}
-
-// DisableServiceMaintenance toggles service maintenance mode off
-// for the given service ID.
-func (a *Agent) DisableServiceMaintenance(serviceID string) error {
- r := a.c.newRequest("PUT", "/v1/agent/service/maintenance/"+serviceID)
- r.params.Set("enable", "false")
- _, resp, err := requireOK(a.c.doRequest(r))
- if err != nil {
- return err
- }
- resp.Body.Close()
- return nil
-}
-
-// EnableNodeMaintenance toggles node maintenance mode on for the
-// agent we are connected to.
-func (a *Agent) EnableNodeMaintenance(reason string) error {
- r := a.c.newRequest("PUT", "/v1/agent/maintenance")
- r.params.Set("enable", "true")
- r.params.Set("reason", reason)
- _, resp, err := requireOK(a.c.doRequest(r))
- if err != nil {
- return err
- }
- resp.Body.Close()
- return nil
-}
-
-// DisableNodeMaintenance toggles node maintenance mode off for the
-// agent we are connected to.
-func (a *Agent) DisableNodeMaintenance() error {
- r := a.c.newRequest("PUT", "/v1/agent/maintenance")
- r.params.Set("enable", "false")
- _, resp, err := requireOK(a.c.doRequest(r))
- if err != nil {
- return err
- }
- resp.Body.Close()
- return nil
-}
diff --git a/Godeps/_workspace/src/github.com/hashicorp/consul/api/agent_test.go b/Godeps/_workspace/src/github.com/hashicorp/consul/api/agent_test.go
deleted file mode 100644
index 358c12a6c2..0000000000
--- a/Godeps/_workspace/src/github.com/hashicorp/consul/api/agent_test.go
+++ /dev/null
@@ -1,524 +0,0 @@
-package api
-
-import (
- "strings"
- "testing"
-)
-
-func TestAgent_Self(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- agent := c.Agent()
-
- info, err := agent.Self()
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- name := info["Config"]["NodeName"]
- if name == "" {
- t.Fatalf("bad: %v", info)
- }
-}
-
-func TestAgent_Members(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- agent := c.Agent()
-
- members, err := agent.Members(false)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- if len(members) != 1 {
- t.Fatalf("bad: %v", members)
- }
-}
-
-func TestAgent_Services(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- agent := c.Agent()
-
- reg := &AgentServiceRegistration{
- Name: "foo",
- Tags: []string{"bar", "baz"},
- Port: 8000,
- Check: &AgentServiceCheck{
- TTL: "15s",
- },
- }
- if err := agent.ServiceRegister(reg); err != nil {
- t.Fatalf("err: %v", err)
- }
-
- services, err := agent.Services()
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- if _, ok := services["foo"]; !ok {
- t.Fatalf("missing service: %v", services)
- }
- checks, err := agent.Checks()
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- chk, ok := checks["service:foo"]
- if !ok {
- t.Fatalf("missing check: %v", checks)
- }
-
- // Checks should default to critical
- if chk.Status != "critical" {
- t.Fatalf("Bad: %#v", chk)
- }
-
- if err := agent.ServiceDeregister("foo"); err != nil {
- t.Fatalf("err: %v", err)
- }
-}
-
-func TestAgent_Services_CheckPassing(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- agent := c.Agent()
- reg := &AgentServiceRegistration{
- Name: "foo",
- Tags: []string{"bar", "baz"},
- Port: 8000,
- Check: &AgentServiceCheck{
- TTL: "15s",
- Status: "passing",
- },
- }
- if err := agent.ServiceRegister(reg); err != nil {
- t.Fatalf("err: %v", err)
- }
-
- services, err := agent.Services()
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- if _, ok := services["foo"]; !ok {
- t.Fatalf("missing service: %v", services)
- }
-
- checks, err := agent.Checks()
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- chk, ok := checks["service:foo"]
- if !ok {
- t.Fatalf("missing check: %v", checks)
- }
-
- if chk.Status != "passing" {
- t.Fatalf("Bad: %#v", chk)
- }
- if err := agent.ServiceDeregister("foo"); err != nil {
- t.Fatalf("err: %v", err)
- }
-}
-
-func TestAgent_Services_CheckBadStatus(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- agent := c.Agent()
- reg := &AgentServiceRegistration{
- Name: "foo",
- Tags: []string{"bar", "baz"},
- Port: 8000,
- Check: &AgentServiceCheck{
- TTL: "15s",
- Status: "fluffy",
- },
- }
- if err := agent.ServiceRegister(reg); err == nil {
- t.Fatalf("bad status accepted")
- }
-}
-
-func TestAgent_ServiceAddress(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- agent := c.Agent()
-
- reg1 := &AgentServiceRegistration{
- Name: "foo1",
- Port: 8000,
- Address: "192.168.0.42",
- }
- reg2 := &AgentServiceRegistration{
- Name: "foo2",
- Port: 8000,
- }
- if err := agent.ServiceRegister(reg1); err != nil {
- t.Fatalf("err: %v", err)
- }
- if err := agent.ServiceRegister(reg2); err != nil {
- t.Fatalf("err: %v", err)
- }
-
- services, err := agent.Services()
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- if _, ok := services["foo1"]; !ok {
- t.Fatalf("missing service: %v", services)
- }
- if _, ok := services["foo2"]; !ok {
- t.Fatalf("missing service: %v", services)
- }
-
- if services["foo1"].Address != "192.168.0.42" {
- t.Fatalf("missing Address field in service foo1: %v", services)
- }
- if services["foo2"].Address != "" {
- t.Fatalf("missing Address field in service foo2: %v", services)
- }
-
- if err := agent.ServiceDeregister("foo"); err != nil {
- t.Fatalf("err: %v", err)
- }
-}
-
-func TestAgent_Services_MultipleChecks(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- agent := c.Agent()
-
- reg := &AgentServiceRegistration{
- Name: "foo",
- Tags: []string{"bar", "baz"},
- Port: 8000,
- Checks: AgentServiceChecks{
- &AgentServiceCheck{
- TTL: "15s",
- },
- &AgentServiceCheck{
- TTL: "30s",
- },
- },
- }
- if err := agent.ServiceRegister(reg); err != nil {
- t.Fatalf("err: %v", err)
- }
-
- services, err := agent.Services()
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- if _, ok := services["foo"]; !ok {
- t.Fatalf("missing service: %v", services)
- }
-
- checks, err := agent.Checks()
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- if _, ok := checks["service:foo:1"]; !ok {
- t.Fatalf("missing check: %v", checks)
- }
- if _, ok := checks["service:foo:2"]; !ok {
- t.Fatalf("missing check: %v", checks)
- }
-}
-
-func TestAgent_SetTTLStatus(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- agent := c.Agent()
-
- reg := &AgentServiceRegistration{
- Name: "foo",
- Check: &AgentServiceCheck{
- TTL: "15s",
- },
- }
- if err := agent.ServiceRegister(reg); err != nil {
- t.Fatalf("err: %v", err)
- }
-
- if err := agent.WarnTTL("service:foo", "test"); err != nil {
- t.Fatalf("err: %v", err)
- }
-
- checks, err := agent.Checks()
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- chk, ok := checks["service:foo"]
- if !ok {
- t.Fatalf("missing check: %v", checks)
- }
- if chk.Status != "warning" {
- t.Fatalf("Bad: %#v", chk)
- }
- if chk.Output != "test" {
- t.Fatalf("Bad: %#v", chk)
- }
-
- if err := agent.ServiceDeregister("foo"); err != nil {
- t.Fatalf("err: %v", err)
- }
-}
-
-func TestAgent_Checks(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- agent := c.Agent()
-
- reg := &AgentCheckRegistration{
- Name: "foo",
- }
- reg.TTL = "15s"
- if err := agent.CheckRegister(reg); err != nil {
- t.Fatalf("err: %v", err)
- }
-
- checks, err := agent.Checks()
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- chk, ok := checks["foo"]
- if !ok {
- t.Fatalf("missing check: %v", checks)
- }
- if chk.Status != "critical" {
- t.Fatalf("check not critical: %v", chk)
- }
-
- if err := agent.CheckDeregister("foo"); err != nil {
- t.Fatalf("err: %v", err)
- }
-}
-
-func TestAgent_CheckStartPassing(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- agent := c.Agent()
-
- reg := &AgentCheckRegistration{
- Name: "foo",
- AgentServiceCheck: AgentServiceCheck{
- Status: "passing",
- },
- }
- reg.TTL = "15s"
- if err := agent.CheckRegister(reg); err != nil {
- t.Fatalf("err: %v", err)
- }
-
- checks, err := agent.Checks()
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- chk, ok := checks["foo"]
- if !ok {
- t.Fatalf("missing check: %v", checks)
- }
- if chk.Status != "passing" {
- t.Fatalf("check not passing: %v", chk)
- }
-
- if err := agent.CheckDeregister("foo"); err != nil {
- t.Fatalf("err: %v", err)
- }
-}
-
-func TestAgent_Checks_serviceBound(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- agent := c.Agent()
-
- // First register a service
- serviceReg := &AgentServiceRegistration{
- Name: "redis",
- }
- if err := agent.ServiceRegister(serviceReg); err != nil {
- t.Fatalf("err: %v", err)
- }
-
- // Register a check bound to the service
- reg := &AgentCheckRegistration{
- Name: "redischeck",
- ServiceID: "redis",
- }
- reg.TTL = "15s"
- if err := agent.CheckRegister(reg); err != nil {
- t.Fatalf("err: %v", err)
- }
-
- checks, err := agent.Checks()
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- check, ok := checks["redischeck"]
- if !ok {
- t.Fatalf("missing check: %v", checks)
- }
- if check.ServiceID != "redis" {
- t.Fatalf("missing service association for check: %v", check)
- }
-}
-
-func TestAgent_Join(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- agent := c.Agent()
-
- info, err := agent.Self()
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- // Join ourself
- addr := info["Config"]["AdvertiseAddr"].(string)
- err = agent.Join(addr, false)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-}
-
-func TestAgent_ForceLeave(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- agent := c.Agent()
-
- // Eject somebody
- err := agent.ForceLeave("foo")
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-}
-
-func TestServiceMaintenance(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- agent := c.Agent()
-
- // First register a service
- serviceReg := &AgentServiceRegistration{
- Name: "redis",
- }
- if err := agent.ServiceRegister(serviceReg); err != nil {
- t.Fatalf("err: %v", err)
- }
-
- // Enable maintenance mode
- if err := agent.EnableServiceMaintenance("redis", "broken"); err != nil {
- t.Fatalf("err: %s", err)
- }
-
- // Ensure a critical check was added
- checks, err := agent.Checks()
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- found := false
- for _, check := range checks {
- if strings.Contains(check.CheckID, "maintenance") {
- found = true
- if check.Status != "critical" || check.Notes != "broken" {
- t.Fatalf("bad: %#v", checks)
- }
- }
- }
- if !found {
- t.Fatalf("bad: %#v", checks)
- }
-
- // Disable maintenance mode
- if err := agent.DisableServiceMaintenance("redis"); err != nil {
- t.Fatalf("err: %s", err)
- }
-
- // Ensure the critical health check was removed
- checks, err = agent.Checks()
- if err != nil {
- t.Fatalf("err: %s", err)
- }
- for _, check := range checks {
- if strings.Contains(check.CheckID, "maintenance") {
- t.Fatalf("should have removed health check")
- }
- }
-}
-
-func TestNodeMaintenance(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- agent := c.Agent()
-
- // Enable maintenance mode
- if err := agent.EnableNodeMaintenance("broken"); err != nil {
- t.Fatalf("err: %s", err)
- }
-
- // Check that a critical check was added
- checks, err := agent.Checks()
- if err != nil {
- t.Fatalf("err: %s", err)
- }
- found := false
- for _, check := range checks {
- if strings.Contains(check.CheckID, "maintenance") {
- found = true
- if check.Status != "critical" || check.Notes != "broken" {
- t.Fatalf("bad: %#v", checks)
- }
- }
- }
- if !found {
- t.Fatalf("bad: %#v", checks)
- }
-
- // Disable maintenance mode
- if err := agent.DisableNodeMaintenance(); err != nil {
- t.Fatalf("err: %s", err)
- }
-
- // Ensure the check was removed
- checks, err = agent.Checks()
- if err != nil {
- t.Fatalf("err: %s", err)
- }
- for _, check := range checks {
- if strings.Contains(check.CheckID, "maintenance") {
- t.Fatalf("should have removed health check")
- }
- }
-}
diff --git a/Godeps/_workspace/src/github.com/hashicorp/consul/api/api.go b/Godeps/_workspace/src/github.com/hashicorp/consul/api/api.go
deleted file mode 100644
index 8fe2ead048..0000000000
--- a/Godeps/_workspace/src/github.com/hashicorp/consul/api/api.go
+++ /dev/null
@@ -1,442 +0,0 @@
-package api
-
-import (
- "bytes"
- "crypto/tls"
- "encoding/json"
- "fmt"
- "io"
- "log"
- "net"
- "net/http"
- "net/url"
- "os"
- "strconv"
- "strings"
- "time"
-)
-
-// QueryOptions are used to parameterize a query
-type QueryOptions struct {
- // Providing a datacenter overwrites the DC provided
- // by the Config
- Datacenter string
-
- // AllowStale allows any Consul server (non-leader) to service
- // a read. This allows for lower latency and higher throughput
- AllowStale bool
-
- // RequireConsistent forces the read to be fully consistent.
- // This is more expensive but prevents ever performing a stale
- // read.
- RequireConsistent bool
-
- // WaitIndex is used to enable a blocking query. Waits
- // until the timeout or the next index is reached
- WaitIndex uint64
-
- // WaitTime is used to bound the duration of a wait.
- // Defaults to that of the Config, but can be overriden.
- WaitTime time.Duration
-
- // Token is used to provide a per-request ACL token
- // which overrides the agent's default token.
- Token string
-}
-
-// WriteOptions are used to parameterize a write
-type WriteOptions struct {
- // Providing a datacenter overwrites the DC provided
- // by the Config
- Datacenter string
-
- // Token is used to provide a per-request ACL token
- // which overrides the agent's default token.
- Token string
-}
-
-// QueryMeta is used to return meta data about a query
-type QueryMeta struct {
- // LastIndex. This can be used as a WaitIndex to perform
- // a blocking query
- LastIndex uint64
-
- // Time of last contact from the leader for the
- // server servicing the request
- LastContact time.Duration
-
- // Is there a known leader
- KnownLeader bool
-
- // How long did the request take
- RequestTime time.Duration
-}
-
-// WriteMeta is used to return meta data about a write
-type WriteMeta struct {
- // How long did the request take
- RequestTime time.Duration
-}
-
-// HttpBasicAuth is used to authenticate http client with HTTP Basic Authentication
-type HttpBasicAuth struct {
- // Username to use for HTTP Basic Authentication
- Username string
-
- // Password to use for HTTP Basic Authentication
- Password string
-}
-
-// Config is used to configure the creation of a client
-type Config struct {
- // Address is the address of the Consul server
- Address string
-
- // Scheme is the URI scheme for the Consul server
- Scheme string
-
- // Datacenter to use. If not provided, the default agent datacenter is used.
- Datacenter string
-
- // HttpClient is the client to use. Default will be
- // used if not provided.
- HttpClient *http.Client
-
- // HttpAuth is the auth info to use for http access.
- HttpAuth *HttpBasicAuth
-
- // WaitTime limits how long a Watch will block. If not provided,
- // the agent default values will be used.
- WaitTime time.Duration
-
- // Token is used to provide a per-request ACL token
- // which overrides the agent's default token.
- Token string
-}
-
-// DefaultConfig returns a default configuration for the client
-func DefaultConfig() *Config {
- config := &Config{
- Address: "127.0.0.1:8500",
- Scheme: "http",
- HttpClient: http.DefaultClient,
- }
-
- if addr := os.Getenv("CONSUL_HTTP_ADDR"); addr != "" {
- config.Address = addr
- }
-
- if token := os.Getenv("CONSUL_HTTP_TOKEN"); token != "" {
- config.Token = token
- }
-
- if auth := os.Getenv("CONSUL_HTTP_AUTH"); auth != "" {
- var username, password string
- if strings.Contains(auth, ":") {
- split := strings.SplitN(auth, ":", 2)
- username = split[0]
- password = split[1]
- } else {
- username = auth
- }
-
- config.HttpAuth = &HttpBasicAuth{
- Username: username,
- Password: password,
- }
- }
-
- if ssl := os.Getenv("CONSUL_HTTP_SSL"); ssl != "" {
- enabled, err := strconv.ParseBool(ssl)
- if err != nil {
- log.Printf("[WARN] client: could not parse CONSUL_HTTP_SSL: %s", err)
- }
-
- if enabled {
- config.Scheme = "https"
- }
- }
-
- if verify := os.Getenv("CONSUL_HTTP_SSL_VERIFY"); verify != "" {
- doVerify, err := strconv.ParseBool(verify)
- if err != nil {
- log.Printf("[WARN] client: could not parse CONSUL_HTTP_SSL_VERIFY: %s", err)
- }
-
- if !doVerify {
- config.HttpClient.Transport = &http.Transport{
- TLSClientConfig: &tls.Config{
- InsecureSkipVerify: true,
- },
- }
- }
- }
-
- return config
-}
-
-// Client provides a client to the Consul API
-type Client struct {
- config Config
-}
-
-// NewClient returns a new client
-func NewClient(config *Config) (*Client, error) {
- // bootstrap the config
- defConfig := DefaultConfig()
-
- if len(config.Address) == 0 {
- config.Address = defConfig.Address
- }
-
- if len(config.Scheme) == 0 {
- config.Scheme = defConfig.Scheme
- }
-
- if config.HttpClient == nil {
- config.HttpClient = defConfig.HttpClient
- }
-
- if parts := strings.SplitN(config.Address, "unix://", 2); len(parts) == 2 {
- config.HttpClient = &http.Client{
- Transport: &http.Transport{
- Dial: func(_, _ string) (net.Conn, error) {
- return net.Dial("unix", parts[1])
- },
- },
- }
- config.Address = parts[1]
- }
-
- client := &Client{
- config: *config,
- }
- return client, nil
-}
-
-// request is used to help build up a request
-type request struct {
- config *Config
- method string
- url *url.URL
- params url.Values
- body io.Reader
- obj interface{}
-}
-
-// setQueryOptions is used to annotate the request with
-// additional query options
-func (r *request) setQueryOptions(q *QueryOptions) {
- if q == nil {
- return
- }
- if q.Datacenter != "" {
- r.params.Set("dc", q.Datacenter)
- }
- if q.AllowStale {
- r.params.Set("stale", "")
- }
- if q.RequireConsistent {
- r.params.Set("consistent", "")
- }
- if q.WaitIndex != 0 {
- r.params.Set("index", strconv.FormatUint(q.WaitIndex, 10))
- }
- if q.WaitTime != 0 {
- r.params.Set("wait", durToMsec(q.WaitTime))
- }
- if q.Token != "" {
- r.params.Set("token", q.Token)
- }
-}
-
-// durToMsec converts a duration to a millisecond specified string
-func durToMsec(dur time.Duration) string {
- return fmt.Sprintf("%dms", dur/time.Millisecond)
-}
-
-// setWriteOptions is used to annotate the request with
-// additional write options
-func (r *request) setWriteOptions(q *WriteOptions) {
- if q == nil {
- return
- }
- if q.Datacenter != "" {
- r.params.Set("dc", q.Datacenter)
- }
- if q.Token != "" {
- r.params.Set("token", q.Token)
- }
-}
-
-// toHTTP converts the request to an HTTP request
-func (r *request) toHTTP() (*http.Request, error) {
- // Encode the query parameters
- r.url.RawQuery = r.params.Encode()
-
- // Check if we should encode the body
- if r.body == nil && r.obj != nil {
- if b, err := encodeBody(r.obj); err != nil {
- return nil, err
- } else {
- r.body = b
- }
- }
-
- // Create the HTTP request
- req, err := http.NewRequest(r.method, r.url.RequestURI(), r.body)
- if err != nil {
- return nil, err
- }
-
- req.URL.Host = r.url.Host
- req.URL.Scheme = r.url.Scheme
- req.Host = r.url.Host
-
- // Setup auth
- if r.config.HttpAuth != nil {
- req.SetBasicAuth(r.config.HttpAuth.Username, r.config.HttpAuth.Password)
- }
-
- return req, nil
-}
-
-// newRequest is used to create a new request
-func (c *Client) newRequest(method, path string) *request {
- r := &request{
- config: &c.config,
- method: method,
- url: &url.URL{
- Scheme: c.config.Scheme,
- Host: c.config.Address,
- Path: path,
- },
- params: make(map[string][]string),
- }
- if c.config.Datacenter != "" {
- r.params.Set("dc", c.config.Datacenter)
- }
- if c.config.WaitTime != 0 {
- r.params.Set("wait", durToMsec(r.config.WaitTime))
- }
- if c.config.Token != "" {
- r.params.Set("token", r.config.Token)
- }
- return r
-}
-
-// doRequest runs a request with our client
-func (c *Client) doRequest(r *request) (time.Duration, *http.Response, error) {
- req, err := r.toHTTP()
- if err != nil {
- return 0, nil, err
- }
- start := time.Now()
- resp, err := c.config.HttpClient.Do(req)
- diff := time.Now().Sub(start)
- return diff, resp, err
-}
-
-// Query is used to do a GET request against an endpoint
-// and deserialize the response into an interface using
-// standard Consul conventions.
-func (c *Client) query(endpoint string, out interface{}, q *QueryOptions) (*QueryMeta, error) {
- r := c.newRequest("GET", endpoint)
- r.setQueryOptions(q)
- rtt, resp, err := requireOK(c.doRequest(r))
- if err != nil {
- return nil, err
- }
- defer resp.Body.Close()
-
- qm := &QueryMeta{}
- parseQueryMeta(resp, qm)
- qm.RequestTime = rtt
-
- if err := decodeBody(resp, out); err != nil {
- return nil, err
- }
- return qm, nil
-}
-
-// write is used to do a PUT request against an endpoint
-// and serialize/deserialized using the standard Consul conventions.
-func (c *Client) write(endpoint string, in, out interface{}, q *WriteOptions) (*WriteMeta, error) {
- r := c.newRequest("PUT", endpoint)
- r.setWriteOptions(q)
- r.obj = in
- rtt, resp, err := requireOK(c.doRequest(r))
- if err != nil {
- return nil, err
- }
- defer resp.Body.Close()
-
- wm := &WriteMeta{RequestTime: rtt}
- if out != nil {
- if err := decodeBody(resp, &out); err != nil {
- return nil, err
- }
- }
- return wm, nil
-}
-
-// parseQueryMeta is used to help parse query meta-data
-func parseQueryMeta(resp *http.Response, q *QueryMeta) error {
- header := resp.Header
-
- // Parse the X-Consul-Index
- index, err := strconv.ParseUint(header.Get("X-Consul-Index"), 10, 64)
- if err != nil {
- return fmt.Errorf("Failed to parse X-Consul-Index: %v", err)
- }
- q.LastIndex = index
-
- // Parse the X-Consul-LastContact
- last, err := strconv.ParseUint(header.Get("X-Consul-LastContact"), 10, 64)
- if err != nil {
- return fmt.Errorf("Failed to parse X-Consul-LastContact: %v", err)
- }
- q.LastContact = time.Duration(last) * time.Millisecond
-
- // Parse the X-Consul-KnownLeader
- switch header.Get("X-Consul-KnownLeader") {
- case "true":
- q.KnownLeader = true
- default:
- q.KnownLeader = false
- }
- return nil
-}
-
-// decodeBody is used to JSON decode a body
-func decodeBody(resp *http.Response, out interface{}) error {
- dec := json.NewDecoder(resp.Body)
- return dec.Decode(out)
-}
-
-// encodeBody is used to encode a request body
-func encodeBody(obj interface{}) (io.Reader, error) {
- buf := bytes.NewBuffer(nil)
- enc := json.NewEncoder(buf)
- if err := enc.Encode(obj); err != nil {
- return nil, err
- }
- return buf, nil
-}
-
-// requireOK is used to wrap doRequest and check for a 200
-func requireOK(d time.Duration, resp *http.Response, e error) (time.Duration, *http.Response, error) {
- if e != nil {
- if resp != nil {
- resp.Body.Close()
- }
- return d, nil, e
- }
- if resp.StatusCode != 200 {
- var buf bytes.Buffer
- io.Copy(&buf, resp.Body)
- resp.Body.Close()
- return d, nil, fmt.Errorf("Unexpected response code: %d (%s)", resp.StatusCode, buf.Bytes())
- }
- return d, resp, nil
-}
diff --git a/Godeps/_workspace/src/github.com/hashicorp/consul/api/api_test.go b/Godeps/_workspace/src/github.com/hashicorp/consul/api/api_test.go
deleted file mode 100644
index 56f9494f89..0000000000
--- a/Godeps/_workspace/src/github.com/hashicorp/consul/api/api_test.go
+++ /dev/null
@@ -1,252 +0,0 @@
-package api
-
-import (
- crand "crypto/rand"
- "fmt"
- "io/ioutil"
- "net/http"
- "os"
- "path/filepath"
- "runtime"
- "testing"
- "time"
-
- "github.com/hashicorp/consul/testutil"
-)
-
-type configCallback func(c *Config)
-
-func makeClient(t *testing.T) (*Client, *testutil.TestServer) {
- return makeClientWithConfig(t, nil, nil)
-}
-
-func makeACLClient(t *testing.T) (*Client, *testutil.TestServer) {
- return makeClientWithConfig(t, func(clientConfig *Config) {
- clientConfig.Token = "root"
- }, func(serverConfig *testutil.TestServerConfig) {
- serverConfig.ACLMasterToken = "root"
- serverConfig.ACLDatacenter = "dc1"
- serverConfig.ACLDefaultPolicy = "deny"
- })
-}
-
-func makeClientWithConfig(
- t *testing.T,
- cb1 configCallback,
- cb2 testutil.ServerConfigCallback) (*Client, *testutil.TestServer) {
-
- // Make client config
- conf := DefaultConfig()
- if cb1 != nil {
- cb1(conf)
- }
-
- // Create server
- server := testutil.NewTestServerConfig(t, cb2)
- conf.Address = server.HTTPAddr
-
- // Create client
- client, err := NewClient(conf)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- return client, server
-}
-
-func testKey() string {
- buf := make([]byte, 16)
- if _, err := crand.Read(buf); err != nil {
- panic(fmt.Errorf("Failed to read random bytes: %v", err))
- }
-
- return fmt.Sprintf("%08x-%04x-%04x-%04x-%12x",
- buf[0:4],
- buf[4:6],
- buf[6:8],
- buf[8:10],
- buf[10:16])
-}
-
-func TestDefaultConfig_env(t *testing.T) {
- t.Parallel()
- addr := "1.2.3.4:5678"
- token := "abcd1234"
- auth := "username:password"
-
- os.Setenv("CONSUL_HTTP_ADDR", addr)
- defer os.Setenv("CONSUL_HTTP_ADDR", "")
- os.Setenv("CONSUL_HTTP_TOKEN", token)
- defer os.Setenv("CONSUL_HTTP_TOKEN", "")
- os.Setenv("CONSUL_HTTP_AUTH", auth)
- defer os.Setenv("CONSUL_HTTP_AUTH", "")
- os.Setenv("CONSUL_HTTP_SSL", "1")
- defer os.Setenv("CONSUL_HTTP_SSL", "")
- os.Setenv("CONSUL_HTTP_SSL_VERIFY", "0")
- defer os.Setenv("CONSUL_HTTP_SSL_VERIFY", "")
-
- config := DefaultConfig()
-
- if config.Address != addr {
- t.Errorf("expected %q to be %q", config.Address, addr)
- }
-
- if config.Token != token {
- t.Errorf("expected %q to be %q", config.Token, token)
- }
-
- if config.HttpAuth == nil {
- t.Fatalf("expected HttpAuth to be enabled")
- }
- if config.HttpAuth.Username != "username" {
- t.Errorf("expected %q to be %q", config.HttpAuth.Username, "username")
- }
- if config.HttpAuth.Password != "password" {
- t.Errorf("expected %q to be %q", config.HttpAuth.Password, "password")
- }
-
- if config.Scheme != "https" {
- t.Errorf("expected %q to be %q", config.Scheme, "https")
- }
-
- if !config.HttpClient.Transport.(*http.Transport).TLSClientConfig.InsecureSkipVerify {
- t.Errorf("expected SSL verification to be off")
- }
-}
-
-func TestSetQueryOptions(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- r := c.newRequest("GET", "/v1/kv/foo")
- q := &QueryOptions{
- Datacenter: "foo",
- AllowStale: true,
- RequireConsistent: true,
- WaitIndex: 1000,
- WaitTime: 100 * time.Second,
- Token: "12345",
- }
- r.setQueryOptions(q)
-
- if r.params.Get("dc") != "foo" {
- t.Fatalf("bad: %v", r.params)
- }
- if _, ok := r.params["stale"]; !ok {
- t.Fatalf("bad: %v", r.params)
- }
- if _, ok := r.params["consistent"]; !ok {
- t.Fatalf("bad: %v", r.params)
- }
- if r.params.Get("index") != "1000" {
- t.Fatalf("bad: %v", r.params)
- }
- if r.params.Get("wait") != "100000ms" {
- t.Fatalf("bad: %v", r.params)
- }
- if r.params.Get("token") != "12345" {
- t.Fatalf("bad: %v", r.params)
- }
-}
-
-func TestSetWriteOptions(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- r := c.newRequest("GET", "/v1/kv/foo")
- q := &WriteOptions{
- Datacenter: "foo",
- Token: "23456",
- }
- r.setWriteOptions(q)
-
- if r.params.Get("dc") != "foo" {
- t.Fatalf("bad: %v", r.params)
- }
- if r.params.Get("token") != "23456" {
- t.Fatalf("bad: %v", r.params)
- }
-}
-
-func TestRequestToHTTP(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- r := c.newRequest("DELETE", "/v1/kv/foo")
- q := &QueryOptions{
- Datacenter: "foo",
- }
- r.setQueryOptions(q)
- req, err := r.toHTTP()
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- if req.Method != "DELETE" {
- t.Fatalf("bad: %v", req)
- }
- if req.URL.RequestURI() != "/v1/kv/foo?dc=foo" {
- t.Fatalf("bad: %v", req)
- }
-}
-
-func TestParseQueryMeta(t *testing.T) {
- t.Parallel()
- resp := &http.Response{
- Header: make(map[string][]string),
- }
- resp.Header.Set("X-Consul-Index", "12345")
- resp.Header.Set("X-Consul-LastContact", "80")
- resp.Header.Set("X-Consul-KnownLeader", "true")
-
- qm := &QueryMeta{}
- if err := parseQueryMeta(resp, qm); err != nil {
- t.Fatalf("err: %v", err)
- }
-
- if qm.LastIndex != 12345 {
- t.Fatalf("Bad: %v", qm)
- }
- if qm.LastContact != 80*time.Millisecond {
- t.Fatalf("Bad: %v", qm)
- }
- if !qm.KnownLeader {
- t.Fatalf("Bad: %v", qm)
- }
-}
-
-func TestAPI_UnixSocket(t *testing.T) {
- t.Parallel()
- if runtime.GOOS == "windows" {
- t.SkipNow()
- }
-
- tempDir, err := ioutil.TempDir("", "consul")
- if err != nil {
- t.Fatalf("err: %s", err)
- }
- defer os.RemoveAll(tempDir)
- socket := filepath.Join(tempDir, "test.sock")
-
- c, s := makeClientWithConfig(t, func(c *Config) {
- c.Address = "unix://" + socket
- }, func(c *testutil.TestServerConfig) {
- c.Addresses = &testutil.TestAddressConfig{
- HTTP: "unix://" + socket,
- }
- })
- defer s.Stop()
-
- agent := c.Agent()
-
- info, err := agent.Self()
- if err != nil {
- t.Fatalf("err: %s", err)
- }
- if info["Config"]["NodeName"] == "" {
- t.Fatalf("bad: %v", info)
- }
-}
diff --git a/Godeps/_workspace/src/github.com/hashicorp/consul/api/catalog.go b/Godeps/_workspace/src/github.com/hashicorp/consul/api/catalog.go
deleted file mode 100644
index cf64bd9091..0000000000
--- a/Godeps/_workspace/src/github.com/hashicorp/consul/api/catalog.go
+++ /dev/null
@@ -1,182 +0,0 @@
-package api
-
-type Node struct {
- Node string
- Address string
-}
-
-type CatalogService struct {
- Node string
- Address string
- ServiceID string
- ServiceName string
- ServiceAddress string
- ServiceTags []string
- ServicePort int
-}
-
-type CatalogNode struct {
- Node *Node
- Services map[string]*AgentService
-}
-
-type CatalogRegistration struct {
- Node string
- Address string
- Datacenter string
- Service *AgentService
- Check *AgentCheck
-}
-
-type CatalogDeregistration struct {
- Node string
- Address string
- Datacenter string
- ServiceID string
- CheckID string
-}
-
-// Catalog can be used to query the Catalog endpoints
-type Catalog struct {
- c *Client
-}
-
-// Catalog returns a handle to the catalog endpoints
-func (c *Client) Catalog() *Catalog {
- return &Catalog{c}
-}
-
-func (c *Catalog) Register(reg *CatalogRegistration, q *WriteOptions) (*WriteMeta, error) {
- r := c.c.newRequest("PUT", "/v1/catalog/register")
- r.setWriteOptions(q)
- r.obj = reg
- rtt, resp, err := requireOK(c.c.doRequest(r))
- if err != nil {
- return nil, err
- }
- resp.Body.Close()
-
- wm := &WriteMeta{}
- wm.RequestTime = rtt
-
- return wm, nil
-}
-
-func (c *Catalog) Deregister(dereg *CatalogDeregistration, q *WriteOptions) (*WriteMeta, error) {
- r := c.c.newRequest("PUT", "/v1/catalog/deregister")
- r.setWriteOptions(q)
- r.obj = dereg
- rtt, resp, err := requireOK(c.c.doRequest(r))
- if err != nil {
- return nil, err
- }
- resp.Body.Close()
-
- wm := &WriteMeta{}
- wm.RequestTime = rtt
-
- return wm, nil
-}
-
-// Datacenters is used to query for all the known datacenters
-func (c *Catalog) Datacenters() ([]string, error) {
- r := c.c.newRequest("GET", "/v1/catalog/datacenters")
- _, resp, err := requireOK(c.c.doRequest(r))
- if err != nil {
- return nil, err
- }
- defer resp.Body.Close()
-
- var out []string
- if err := decodeBody(resp, &out); err != nil {
- return nil, err
- }
- return out, nil
-}
-
-// Nodes is used to query all the known nodes
-func (c *Catalog) Nodes(q *QueryOptions) ([]*Node, *QueryMeta, error) {
- r := c.c.newRequest("GET", "/v1/catalog/nodes")
- r.setQueryOptions(q)
- rtt, resp, err := requireOK(c.c.doRequest(r))
- if err != nil {
- return nil, nil, err
- }
- defer resp.Body.Close()
-
- qm := &QueryMeta{}
- parseQueryMeta(resp, qm)
- qm.RequestTime = rtt
-
- var out []*Node
- if err := decodeBody(resp, &out); err != nil {
- return nil, nil, err
- }
- return out, qm, nil
-}
-
-// Services is used to query for all known services
-func (c *Catalog) Services(q *QueryOptions) (map[string][]string, *QueryMeta, error) {
- r := c.c.newRequest("GET", "/v1/catalog/services")
- r.setQueryOptions(q)
- rtt, resp, err := requireOK(c.c.doRequest(r))
- if err != nil {
- return nil, nil, err
- }
- defer resp.Body.Close()
-
- qm := &QueryMeta{}
- parseQueryMeta(resp, qm)
- qm.RequestTime = rtt
-
- var out map[string][]string
- if err := decodeBody(resp, &out); err != nil {
- return nil, nil, err
- }
- return out, qm, nil
-}
-
-// Service is used to query catalog entries for a given service
-func (c *Catalog) Service(service, tag string, q *QueryOptions) ([]*CatalogService, *QueryMeta, error) {
- r := c.c.newRequest("GET", "/v1/catalog/service/"+service)
- r.setQueryOptions(q)
- if tag != "" {
- r.params.Set("tag", tag)
- }
- rtt, resp, err := requireOK(c.c.doRequest(r))
- if err != nil {
- return nil, nil, err
- }
- defer resp.Body.Close()
-
- qm := &QueryMeta{}
- parseQueryMeta(resp, qm)
- qm.RequestTime = rtt
-
- var out []*CatalogService
- if err := decodeBody(resp, &out); err != nil {
- return nil, nil, err
- }
- return out, qm, nil
-}
-
-// Node is used to query for service information about a single node
-func (c *Catalog) Node(node string, q *QueryOptions) (*CatalogNode, *QueryMeta, error) {
- r := c.c.newRequest("GET", "/v1/catalog/node/"+node)
- r.setQueryOptions(q)
- rtt, resp, err := requireOK(c.c.doRequest(r))
- if err != nil {
- return nil, nil, err
- }
- defer resp.Body.Close()
-
- qm := &QueryMeta{}
- parseQueryMeta(resp, qm)
- qm.RequestTime = rtt
-
- var out *CatalogNode
- if err := decodeBody(resp, &out); err != nil {
- return nil, nil, err
- }
- return out, qm, nil
-}
diff --git a/Godeps/_workspace/src/github.com/hashicorp/consul/api/catalog_test.go b/Godeps/_workspace/src/github.com/hashicorp/consul/api/catalog_test.go
deleted file mode 100644
index bb8be25b00..0000000000
--- a/Godeps/_workspace/src/github.com/hashicorp/consul/api/catalog_test.go
+++ /dev/null
@@ -1,279 +0,0 @@
-package api
-
-import (
- "fmt"
- "testing"
-
- "github.com/hashicorp/consul/testutil"
-)
-
-func TestCatalog_Datacenters(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- catalog := c.Catalog()
-
- testutil.WaitForResult(func() (bool, error) {
- datacenters, err := catalog.Datacenters()
- if err != nil {
- return false, err
- }
-
- if len(datacenters) == 0 {
- return false, fmt.Errorf("Bad: %v", datacenters)
- }
-
- return true, nil
- }, func(err error) {
- t.Fatalf("err: %s", err)
- })
-}
-
-func TestCatalog_Nodes(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- catalog := c.Catalog()
-
- testutil.WaitForResult(func() (bool, error) {
- nodes, meta, err := catalog.Nodes(nil)
- if err != nil {
- return false, err
- }
-
- if meta.LastIndex == 0 {
- return false, fmt.Errorf("Bad: %v", meta)
- }
-
- if len(nodes) == 0 {
- return false, fmt.Errorf("Bad: %v", nodes)
- }
-
- return true, nil
- }, func(err error) {
- t.Fatalf("err: %s", err)
- })
-}
-
-func TestCatalog_Services(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- catalog := c.Catalog()
-
- testutil.WaitForResult(func() (bool, error) {
- services, meta, err := catalog.Services(nil)
- if err != nil {
- return false, err
- }
-
- if meta.LastIndex == 0 {
- return false, fmt.Errorf("Bad: %v", meta)
- }
-
- if len(services) == 0 {
- return false, fmt.Errorf("Bad: %v", services)
- }
-
- return true, nil
- }, func(err error) {
- t.Fatalf("err: %s", err)
- })
-}
-
-func TestCatalog_Service(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- catalog := c.Catalog()
-
- testutil.WaitForResult(func() (bool, error) {
- services, meta, err := catalog.Service("consul", "", nil)
- if err != nil {
- return false, err
- }
-
- if meta.LastIndex == 0 {
- return false, fmt.Errorf("Bad: %v", meta)
- }
-
- if len(services) == 0 {
- return false, fmt.Errorf("Bad: %v", services)
- }
-
- return true, nil
- }, func(err error) {
- t.Fatalf("err: %s", err)
- })
-}
-
-func TestCatalog_Node(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- catalog := c.Catalog()
- name, _ := c.Agent().NodeName()
-
- testutil.WaitForResult(func() (bool, error) {
- info, meta, err := catalog.Node(name, nil)
- if err != nil {
- return false, err
- }
-
- if meta.LastIndex == 0 {
- return false, fmt.Errorf("Bad: %v", meta)
- }
- if len(info.Services) == 0 {
- return false, fmt.Errorf("Bad: %v", info)
- }
-
- return true, nil
- }, func(err error) {
- t.Fatalf("err: %s", err)
- })
-}
-
-func TestCatalog_Registration(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- catalog := c.Catalog()
-
- service := &AgentService{
- ID: "redis1",
- Service: "redis",
- Tags: []string{"master", "v1"},
- Port: 8000,
- }
-
- check := &AgentCheck{
- Node: "foobar",
- CheckID: "service:redis1",
- Name: "Redis health check",
- Notes: "Script based health check",
- Status: "passing",
- ServiceID: "redis1",
- }
-
- reg := &CatalogRegistration{
- Datacenter: "dc1",
- Node: "foobar",
- Address: "192.168.10.10",
- Service: service,
- Check: check,
- }
-
- testutil.WaitForResult(func() (bool, error) {
- if _, err := catalog.Register(reg, nil); err != nil {
- return false, err
- }
-
- node, _, err := catalog.Node("foobar", nil)
- if err != nil {
- return false, err
- }
-
- if _, ok := node.Services["redis1"]; !ok {
- return false, fmt.Errorf("missing service: redis1")
- }
-
- health, _, err := c.Health().Node("foobar", nil)
- if err != nil {
- return false, err
- }
-
- if health[0].CheckID != "service:redis1" {
- return false, fmt.Errorf("missing checkid service:redis1")
- }
-
- return true, nil
- }, func(err error) {
- t.Fatalf("err: %s", err)
- })
-
- // Test catalog deregistration of the previously registered service
- dereg := &CatalogDeregistration{
- Datacenter: "dc1",
- Node: "foobar",
- Address: "192.168.10.10",
- ServiceID: "redis1",
- }
-
- if _, err := catalog.Deregister(dereg, nil); err != nil {
- t.Fatalf("err: %v", err)
- }
-
- testutil.WaitForResult(func() (bool, error) {
- node, _, err := catalog.Node("foobar", nil)
- if err != nil {
- return false, err
- }
-
- if _, ok := node.Services["redis1"]; ok {
- return false, fmt.Errorf("ServiceID:redis1 is not deregistered")
- }
-
- return true, nil
- }, func(err error) {
- t.Fatalf("err: %s", err)
- })
-
- // Test deregistration of the previously registered check
- dereg = &CatalogDeregistration{
- Datacenter: "dc1",
- Node: "foobar",
- Address: "192.168.10.10",
- CheckID: "service:redis1",
- }
-
- if _, err := catalog.Deregister(dereg, nil); err != nil {
- t.Fatalf("err: %v", err)
- }
-
- testutil.WaitForResult(func() (bool, error) {
- health, _, err := c.Health().Node("foobar", nil)
- if err != nil {
- return false, err
- }
-
- if len(health) != 0 {
- return false, fmt.Errorf("CheckID:service:redis1 is not deregistered")
- }
-
- return true, nil
- }, func(err error) {
- t.Fatalf("err: %s", err)
- })
-
- // Test node deregistration of the previously registered node
- dereg = &CatalogDeregistration{
- Datacenter: "dc1",
- Node: "foobar",
- Address: "192.168.10.10",
- }
-
- if _, err := catalog.Deregister(dereg, nil); err != nil {
- t.Fatalf("err: %v", err)
- }
-
- testutil.WaitForResult(func() (bool, error) {
- node, _, err := catalog.Node("foobar", nil)
- if err != nil {
- return false, err
- }
-
- if node != nil {
- return false, fmt.Errorf("node is not deregistered: %v", node)
- }
-
- return true, nil
- }, func(err error) {
- t.Fatalf("err: %s", err)
- })
-}
diff --git a/Godeps/_workspace/src/github.com/hashicorp/consul/api/event.go b/Godeps/_workspace/src/github.com/hashicorp/consul/api/event.go
deleted file mode 100644
index 85b5b069b0..0000000000
--- a/Godeps/_workspace/src/github.com/hashicorp/consul/api/event.go
+++ /dev/null
@@ -1,104 +0,0 @@
-package api
-
-import (
- "bytes"
- "strconv"
-)
-
-// Event can be used to query the Event endpoints
-type Event struct {
- c *Client
-}
-
-// UserEvent represents an event that was fired by the user
-type UserEvent struct {
- ID string
- Name string
- Payload []byte
- NodeFilter string
- ServiceFilter string
- TagFilter string
- Version int
- LTime uint64
-}
-
-// Event returns a handle to the event endpoints
-func (c *Client) Event() *Event {
- return &Event{c}
-}
-
-// Fire is used to fire a new user event. Only the Name, Payload and Filters
-// are respected. This returns the ID or an associated error. Cross DC requests
-// are supported.
-func (e *Event) Fire(params *UserEvent, q *WriteOptions) (string, *WriteMeta, error) {
- r := e.c.newRequest("PUT", "/v1/event/fire/"+params.Name)
- r.setWriteOptions(q)
- if params.NodeFilter != "" {
- r.params.Set("node", params.NodeFilter)
- }
- if params.ServiceFilter != "" {
- r.params.Set("service", params.ServiceFilter)
- }
- if params.TagFilter != "" {
- r.params.Set("tag", params.TagFilter)
- }
- if params.Payload != nil {
- r.body = bytes.NewReader(params.Payload)
- }
-
- rtt, resp, err := requireOK(e.c.doRequest(r))
- if err != nil {
- return "", nil, err
- }
- defer resp.Body.Close()
-
- wm := &WriteMeta{RequestTime: rtt}
- var out UserEvent
- if err := decodeBody(resp, &out); err != nil {
- return "", nil, err
- }
- return out.ID, wm, nil
-}
-
-// List is used to get the most recent events an agent has received.
-// This list can be optionally filtered by the name. This endpoint supports
-// quasi-blocking queries. The index is not monotonic, nor does it provide provide
-// LastContact or KnownLeader.
-func (e *Event) List(name string, q *QueryOptions) ([]*UserEvent, *QueryMeta, error) {
- r := e.c.newRequest("GET", "/v1/event/list")
- r.setQueryOptions(q)
- if name != "" {
- r.params.Set("name", name)
- }
- rtt, resp, err := requireOK(e.c.doRequest(r))
- if err != nil {
- return nil, nil, err
- }
- defer resp.Body.Close()
-
- qm := &QueryMeta{}
- parseQueryMeta(resp, qm)
- qm.RequestTime = rtt
-
- var entries []*UserEvent
- if err := decodeBody(resp, &entries); err != nil {
- return nil, nil, err
- }
- return entries, qm, nil
-}
-
-// IDToIndex is a bit of a hack. This simulates the index generation to
-// convert an event ID into a WaitIndex.
-func (e *Event) IDToIndex(uuid string) uint64 {
- lower := uuid[0:8] + uuid[9:13] + uuid[14:18]
- upper := uuid[19:23] + uuid[24:36]
- lowVal, err := strconv.ParseUint(lower, 16, 64)
- if err != nil {
- panic("Failed to convert " + lower)
- }
- highVal, err := strconv.ParseUint(upper, 16, 64)
- if err != nil {
- panic("Failed to convert " + upper)
- }
- return lowVal ^ highVal
-}
diff --git a/Godeps/_workspace/src/github.com/hashicorp/consul/api/event_test.go b/Godeps/_workspace/src/github.com/hashicorp/consul/api/event_test.go
deleted file mode 100644
index 1ca92e2331..0000000000
--- a/Godeps/_workspace/src/github.com/hashicorp/consul/api/event_test.go
+++ /dev/null
@@ -1,49 +0,0 @@
-package api
-
-import (
- "testing"
-
- "github.com/hashicorp/consul/testutil"
-)
-
-func TestEvent_FireList(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- event := c.Event()
-
- params := &UserEvent{Name: "foo"}
- id, meta, err := event.Fire(params, nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- if meta.RequestTime == 0 {
- t.Fatalf("bad: %v", meta)
- }
-
- if id == "" {
- t.Fatalf("invalid: %v", id)
- }
-
- var events []*UserEvent
- var qm *QueryMeta
- testutil.WaitForResult(func() (bool, error) {
- events, qm, err = event.List("", nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- return len(events) > 0, err
- }, func(err error) {
- t.Fatalf("err: %#v", err)
- })
-
- if events[len(events)-1].ID != id {
- t.Fatalf("bad: %#v", events)
- }
-
- if qm.LastIndex != event.IDToIndex(id) {
- t.Fatalf("Bad: %#v", qm)
- }
-}
diff --git a/Godeps/_workspace/src/github.com/hashicorp/consul/api/health.go b/Godeps/_workspace/src/github.com/hashicorp/consul/api/health.go
deleted file mode 100644
index 02b161e28e..0000000000
--- a/Godeps/_workspace/src/github.com/hashicorp/consul/api/health.go
+++ /dev/null
@@ -1,136 +0,0 @@
-package api
-
-import (
- "fmt"
-)
-
-// HealthCheck is used to represent a single check
-type HealthCheck struct {
- Node string
- CheckID string
- Name string
- Status string
- Notes string
- Output string
- ServiceID string
- ServiceName string
-}
-
-// ServiceEntry is used for the health service endpoint
-type ServiceEntry struct {
- Node *Node
- Service *AgentService
- Checks []*HealthCheck
-}
-
-// Health can be used to query the Health endpoints
-type Health struct {
- c *Client
-}
-
-// Health returns a handle to the health endpoints
-func (c *Client) Health() *Health {
- return &Health{c}
-}
-
-// Node is used to query for checks belonging to a given node
-func (h *Health) Node(node string, q *QueryOptions) ([]*HealthCheck, *QueryMeta, error) {
- r := h.c.newRequest("GET", "/v1/health/node/"+node)
- r.setQueryOptions(q)
- rtt, resp, err := requireOK(h.c.doRequest(r))
- if err != nil {
- return nil, nil, err
- }
- defer resp.Body.Close()
-
- qm := &QueryMeta{}
- parseQueryMeta(resp, qm)
- qm.RequestTime = rtt
-
- var out []*HealthCheck
- if err := decodeBody(resp, &out); err != nil {
- return nil, nil, err
- }
- return out, qm, nil
-}
-
-// Checks is used to return the checks associated with a service
-func (h *Health) Checks(service string, q *QueryOptions) ([]*HealthCheck, *QueryMeta, error) {
- r := h.c.newRequest("GET", "/v1/health/checks/"+service)
- r.setQueryOptions(q)
- rtt, resp, err := requireOK(h.c.doRequest(r))
- if err != nil {
- return nil, nil, err
- }
- defer resp.Body.Close()
-
- qm := &QueryMeta{}
- parseQueryMeta(resp, qm)
- qm.RequestTime = rtt
-
- var out []*HealthCheck
- if err := decodeBody(resp, &out); err != nil {
- return nil, nil, err
- }
- return out, qm, nil
-}
-
-// Service is used to query health information along with service info
-// for a given service. It can optionally do server-side filtering on a tag
-// or nodes with passing health checks only.
-func (h *Health) Service(service, tag string, passingOnly bool, q *QueryOptions) ([]*ServiceEntry, *QueryMeta, error) {
- r := h.c.newRequest("GET", "/v1/health/service/"+service)
- r.setQueryOptions(q)
- if tag != "" {
- r.params.Set("tag", tag)
- }
- if passingOnly {
- r.params.Set("passing", "1")
- }
- rtt, resp, err := requireOK(h.c.doRequest(r))
- if err != nil {
- return nil, nil, err
- }
- defer resp.Body.Close()
-
- qm := &QueryMeta{}
- parseQueryMeta(resp, qm)
- qm.RequestTime = rtt
-
- var out []*ServiceEntry
- if err := decodeBody(resp, &out); err != nil {
- return nil, nil, err
- }
- return out, qm, nil
-}
-
-// State is used to retreive all the checks in a given state.
-// The wildcard "any" state can also be used for all checks.
-func (h *Health) State(state string, q *QueryOptions) ([]*HealthCheck, *QueryMeta, error) {
- switch state {
- case "any":
- case "warning":
- case "critical":
- case "passing":
- case "unknown":
- default:
- return nil, nil, fmt.Errorf("Unsupported state: %v", state)
- }
- r := h.c.newRequest("GET", "/v1/health/state/"+state)
- r.setQueryOptions(q)
- rtt, resp, err := requireOK(h.c.doRequest(r))
- if err != nil {
- return nil, nil, err
- }
- defer resp.Body.Close()
-
- qm := &QueryMeta{}
- parseQueryMeta(resp, qm)
- qm.RequestTime = rtt
-
- var out []*HealthCheck
- if err := decodeBody(resp, &out); err != nil {
- return nil, nil, err
- }
- return out, qm, nil
-}
diff --git a/Godeps/_workspace/src/github.com/hashicorp/consul/api/health_test.go b/Godeps/_workspace/src/github.com/hashicorp/consul/api/health_test.go
deleted file mode 100644
index d80a4693ae..0000000000
--- a/Godeps/_workspace/src/github.com/hashicorp/consul/api/health_test.go
+++ /dev/null
@@ -1,125 +0,0 @@
-package api
-
-import (
- "fmt"
- "testing"
-
- "github.com/hashicorp/consul/testutil"
-)
-
-func TestHealth_Node(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- agent := c.Agent()
- health := c.Health()
-
- info, err := agent.Self()
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- name := info["Config"]["NodeName"].(string)
-
- testutil.WaitForResult(func() (bool, error) {
- checks, meta, err := health.Node(name, nil)
- if err != nil {
- return false, err
- }
- if meta.LastIndex == 0 {
- return false, fmt.Errorf("bad: %v", meta)
- }
- if len(checks) == 0 {
- return false, fmt.Errorf("bad: %v", checks)
- }
- return true, nil
- }, func(err error) {
- t.Fatalf("err: %s", err)
- })
-}
-
-func TestHealth_Checks(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- agent := c.Agent()
- health := c.Health()
-
- // Make a service with a check
- reg := &AgentServiceRegistration{
- Name: "foo",
- Check: &AgentServiceCheck{
- TTL: "15s",
- },
- }
- if err := agent.ServiceRegister(reg); err != nil {
- t.Fatalf("err: %v", err)
- }
- defer agent.ServiceDeregister("foo")
-
- testutil.WaitForResult(func() (bool, error) {
- checks, meta, err := health.Checks("foo", nil)
- if err != nil {
- return false, err
- }
- if meta.LastIndex == 0 {
- return false, fmt.Errorf("bad: %v", meta)
- }
- if len(checks) == 0 {
- return false, fmt.Errorf("Bad: %v", checks)
- }
- return true, nil
- }, func(err error) {
- t.Fatalf("err: %s", err)
- })
-}
-
-func TestHealth_Service(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- health := c.Health()
-
- testutil.WaitForResult(func() (bool, error) {
- // consul service should always exist...
- checks, meta, err := health.Service("consul", "", true, nil)
- if err != nil {
- return false, err
- }
- if meta.LastIndex == 0 {
- return false, fmt.Errorf("bad: %v", meta)
- }
- if len(checks) == 0 {
- return false, fmt.Errorf("Bad: %v", checks)
- }
- return true, nil
- }, func(err error) {
- t.Fatalf("err: %s", err)
- })
-}
-
-func TestHealth_State(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- health := c.Health()
-
- testutil.WaitForResult(func() (bool, error) {
- checks, meta, err := health.State("any", nil)
- if err != nil {
- return false, err
- }
- if meta.LastIndex == 0 {
- return false, fmt.Errorf("bad: %v", meta)
- }
- if len(checks) == 0 {
- return false, fmt.Errorf("Bad: %v", checks)
- }
- return true, nil
- }, func(err error) {
- t.Fatalf("err: %s", err)
- })
-}
diff --git a/Godeps/_workspace/src/github.com/hashicorp/consul/api/kv.go b/Godeps/_workspace/src/github.com/hashicorp/consul/api/kv.go
deleted file mode 100644
index c1a8923bef..0000000000
--- a/Godeps/_workspace/src/github.com/hashicorp/consul/api/kv.go
+++ /dev/null
@@ -1,240 +0,0 @@
-package api
-
-import (
- "bytes"
- "fmt"
- "io"
- "net/http"
- "strconv"
- "strings"
-)
-
-// KVPair is used to represent a single K/V entry
-type KVPair struct {
- Key string
- CreateIndex uint64
- ModifyIndex uint64
- LockIndex uint64
- Flags uint64
- Value []byte
- Session string
-}
-
-// KVPairs is a list of KVPair objects
-type KVPairs []*KVPair
-
-// KV is used to manipulate the K/V API
-type KV struct {
- c *Client
-}
-
-// KV is used to return a handle to the K/V apis
-func (c *Client) KV() *KV {
- return &KV{c}
-}
-
-// Get is used to lookup a single key
-func (k *KV) Get(key string, q *QueryOptions) (*KVPair, *QueryMeta, error) {
- resp, qm, err := k.getInternal(key, nil, q)
- if err != nil {
- return nil, nil, err
- }
- if resp == nil {
- return nil, qm, nil
- }
- defer resp.Body.Close()
-
- var entries []*KVPair
- if err := decodeBody(resp, &entries); err != nil {
- return nil, nil, err
- }
- if len(entries) > 0 {
- return entries[0], qm, nil
- }
- return nil, qm, nil
-}
-
-// List is used to lookup all keys under a prefix
-func (k *KV) List(prefix string, q *QueryOptions) (KVPairs, *QueryMeta, error) {
- resp, qm, err := k.getInternal(prefix, map[string]string{"recurse": ""}, q)
- if err != nil {
- return nil, nil, err
- }
- if resp == nil {
- return nil, qm, nil
- }
- defer resp.Body.Close()
-
- var entries []*KVPair
- if err := decodeBody(resp, &entries); err != nil {
- return nil, nil, err
- }
- return entries, qm, nil
-}
-
-// Keys is used to list all the keys under a prefix. Optionally,
-// a separator can be used to limit the responses.
-func (k *KV) Keys(prefix, separator string, q *QueryOptions) ([]string, *QueryMeta, error) {
- params := map[string]string{"keys": ""}
- if separator != "" {
- params["separator"] = separator
- }
- resp, qm, err := k.getInternal(prefix, params, q)
- if err != nil {
- return nil, nil, err
- }
- if resp == nil {
- return nil, qm, nil
- }
- defer resp.Body.Close()
-
- var entries []string
- if err := decodeBody(resp, &entries); err != nil {
- return nil, nil, err
- }
- return entries, qm, nil
-}
-
-func (k *KV) getInternal(key string, params map[string]string, q *QueryOptions) (*http.Response, *QueryMeta, error) {
- r := k.c.newRequest("GET", "/v1/kv/"+key)
- r.setQueryOptions(q)
- for param, val := range params {
- r.params.Set(param, val)
- }
- rtt, resp, err := k.c.doRequest(r)
- if err != nil {
- return nil, nil, err
- }
-
- qm := &QueryMeta{}
- parseQueryMeta(resp, qm)
- qm.RequestTime = rtt
-
- if resp.StatusCode == 404 {
- resp.Body.Close()
- return nil, qm, nil
- } else if resp.StatusCode != 200 {
- resp.Body.Close()
- return nil, nil, fmt.Errorf("Unexpected response code: %d", resp.StatusCode)
- }
- return resp, qm, nil
-}
-
-// Put is used to write a new value. Only the
-// Key, Flags and Value is respected.
-func (k *KV) Put(p *KVPair, q *WriteOptions) (*WriteMeta, error) {
- params := make(map[string]string, 1)
- if p.Flags != 0 {
- params["flags"] = strconv.FormatUint(p.Flags, 10)
- }
- _, wm, err := k.put(p.Key, params, p.Value, q)
- return wm, err
-}
-
-// CAS is used for a Check-And-Set operation. The Key,
-// ModifyIndex, Flags and Value are respected. Returns true
-// on success or false on failures.
-func (k *KV) CAS(p *KVPair, q *WriteOptions) (bool, *WriteMeta, error) {
- params := make(map[string]string, 2)
- if p.Flags != 0 {
- params["flags"] = strconv.FormatUint(p.Flags, 10)
- }
- params["cas"] = strconv.FormatUint(p.ModifyIndex, 10)
- return k.put(p.Key, params, p.Value, q)
-}
-
-// Acquire is used for a lock acquisiiton operation. The Key,
-// Flags, Value and Session are respected. Returns true
-// on success or false on failures.
-func (k *KV) Acquire(p *KVPair, q *WriteOptions) (bool, *WriteMeta, error) {
- params := make(map[string]string, 2)
- if p.Flags != 0 {
- params["flags"] = strconv.FormatUint(p.Flags, 10)
- }
- params["acquire"] = p.Session
- return k.put(p.Key, params, p.Value, q)
-}
-
-// Release is used for a lock release operation. The Key,
-// Flags, Value and Session are respected. Returns true
-// on success or false on failures.
-func (k *KV) Release(p *KVPair, q *WriteOptions) (bool, *WriteMeta, error) {
- params := make(map[string]string, 2)
- if p.Flags != 0 {
- params["flags"] = strconv.FormatUint(p.Flags, 10)
- }
- params["release"] = p.Session
- return k.put(p.Key, params, p.Value, q)
-}
-
-func (k *KV) put(key string, params map[string]string, body []byte, q *WriteOptions) (bool, *WriteMeta, error) {
- if len(key) > 0 && key[0] == '/' {
- return false, nil, fmt.Errorf("Invalid key. Key must not begin with a '/': %s", key)
- }
-
- r := k.c.newRequest("PUT", "/v1/kv/"+key)
- r.setWriteOptions(q)
- for param, val := range params {
- r.params.Set(param, val)
- }
- r.body = bytes.NewReader(body)
- rtt, resp, err := requireOK(k.c.doRequest(r))
- if err != nil {
- return false, nil, err
- }
- defer resp.Body.Close()
-
- qm := &WriteMeta{}
- qm.RequestTime = rtt
-
- var buf bytes.Buffer
- if _, err := io.Copy(&buf, resp.Body); err != nil {
- return false, nil, fmt.Errorf("Failed to read response: %v", err)
- }
- res := strings.Contains(string(buf.Bytes()), "true")
- return res, qm, nil
-}
-
-// Delete is used to delete a single key
-func (k *KV) Delete(key string, w *WriteOptions) (*WriteMeta, error) {
- _, qm, err := k.deleteInternal(key, nil, w)
- return qm, err
-}
-
-// DeleteCAS is used for a Delete Check-And-Set operation. The Key
-// and ModifyIndex are respected. Returns true on success or false on failures.
-func (k *KV) DeleteCAS(p *KVPair, q *WriteOptions) (bool, *WriteMeta, error) {
- params := map[string]string{
- "cas": strconv.FormatUint(p.ModifyIndex, 10),
- }
- return k.deleteInternal(p.Key, params, q)
-}
-
-// DeleteTree is used to delete all keys under a prefix
-func (k *KV) DeleteTree(prefix string, w *WriteOptions) (*WriteMeta, error) {
- _, qm, err := k.deleteInternal(prefix, map[string]string{"recurse": ""}, w)
- return qm, err
-}
-
-func (k *KV) deleteInternal(key string, params map[string]string, q *WriteOptions) (bool, *WriteMeta, error) {
- r := k.c.newRequest("DELETE", "/v1/kv/"+key)
- r.setWriteOptions(q)
- for param, val := range params {
- r.params.Set(param, val)
- }
- rtt, resp, err := requireOK(k.c.doRequest(r))
- if err != nil {
- return false, nil, err
- }
- defer resp.Body.Close()
-
- qm := &WriteMeta{}
- qm.RequestTime = rtt
-
- var buf bytes.Buffer
- if _, err := io.Copy(&buf, resp.Body); err != nil {
- return false, nil, fmt.Errorf("Failed to read response: %v", err)
- }
- res := strings.Contains(string(buf.Bytes()), "true")
- return res, qm, nil
-}
diff --git a/Godeps/_workspace/src/github.com/hashicorp/consul/api/kv_test.go b/Godeps/_workspace/src/github.com/hashicorp/consul/api/kv_test.go
deleted file mode 100644
index 758595d895..0000000000
--- a/Godeps/_workspace/src/github.com/hashicorp/consul/api/kv_test.go
+++ /dev/null
@@ -1,447 +0,0 @@
-package api
-
-import (
- "bytes"
- "path"
- "testing"
- "time"
-)
-
-func TestClientPutGetDelete(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- kv := c.KV()
-
- // Get a get without a key
- key := testKey()
- pair, _, err := kv.Get(key, nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- if pair != nil {
- t.Fatalf("unexpected value: %#v", pair)
- }
-
- value := []byte("test")
-
- // Put a key that begins with a '/', this should fail
- invalidKey := "/test"
- p := &KVPair{Key: invalidKey, Flags: 42, Value: value}
- if _, err := kv.Put(p, nil); err == nil {
- t.Fatalf("Invalid key not detected: %s", invalidKey)
- }
-
- // Put the key
- p = &KVPair{Key: key, Flags: 42, Value: value}
- if _, err := kv.Put(p, nil); err != nil {
- t.Fatalf("err: %v", err)
- }
-
- // Get should work
- pair, meta, err := kv.Get(key, nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- if pair == nil {
- t.Fatalf("expected value: %#v", pair)
- }
- if !bytes.Equal(pair.Value, value) {
- t.Fatalf("unexpected value: %#v", pair)
- }
- if pair.Flags != 42 {
- t.Fatalf("unexpected value: %#v", pair)
- }
- if meta.LastIndex == 0 {
- t.Fatalf("unexpected value: %#v", meta)
- }
-
- // Delete
- if _, err := kv.Delete(key, nil); err != nil {
- t.Fatalf("err: %v", err)
- }
-
- // Get should fail
- pair, _, err = kv.Get(key, nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- if pair != nil {
- t.Fatalf("unexpected value: %#v", pair)
- }
-}
-
-func TestClient_List_DeleteRecurse(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- kv := c.KV()
-
- // Generate some test keys
- prefix := testKey()
- var keys []string
- for i := 0; i < 100; i++ {
- keys = append(keys, path.Join(prefix, testKey()))
- }
-
- // Set values
- value := []byte("test")
- for _, key := range keys {
- p := &KVPair{Key: key, Value: value}
- if _, err := kv.Put(p, nil); err != nil {
- t.Fatalf("err: %v", err)
- }
- }
-
- // List the values
- pairs, meta, err := kv.List(prefix, nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- if len(pairs) != len(keys) {
- t.Fatalf("got %d keys", len(pairs))
- }
- for _, pair := range pairs {
- if !bytes.Equal(pair.Value, value) {
- t.Fatalf("unexpected value: %#v", pair)
- }
- }
- if meta.LastIndex == 0 {
- t.Fatalf("unexpected value: %#v", meta)
- }
-
- // Delete all
- if _, err := kv.DeleteTree(prefix, nil); err != nil {
- t.Fatalf("err: %v", err)
- }
-
- // List the values
- pairs, _, err = kv.List(prefix, nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- if len(pairs) != 0 {
- t.Fatalf("got %d keys", len(pairs))
- }
-}
-
-func TestClient_DeleteCAS(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- kv := c.KV()
-
- // Put the key
- key := testKey()
- value := []byte("test")
- p := &KVPair{Key: key, Value: value}
- if work, _, err := kv.CAS(p, nil); err != nil {
- t.Fatalf("err: %v", err)
- } else if !work {
- t.Fatalf("CAS failure")
- }
-
- // Get should work
- pair, meta, err := kv.Get(key, nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- if pair == nil {
- t.Fatalf("expected value: %#v", pair)
- }
- if meta.LastIndex == 0 {
- t.Fatalf("unexpected value: %#v", meta)
- }
-
- // CAS update with bad index
- p.ModifyIndex = 1
- if work, _, err := kv.DeleteCAS(p, nil); err != nil {
- t.Fatalf("err: %v", err)
- } else if work {
- t.Fatalf("unexpected CAS")
- }
-
- // CAS update with valid index
- p.ModifyIndex = meta.LastIndex
- if work, _, err := kv.DeleteCAS(p, nil); err != nil {
- t.Fatalf("err: %v", err)
- } else if !work {
- t.Fatalf("unexpected CAS failure")
- }
-}
-
-func TestClient_CAS(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- kv := c.KV()
-
- // Put the key
- key := testKey()
- value := []byte("test")
- p := &KVPair{Key: key, Value: value}
- if work, _, err := kv.CAS(p, nil); err != nil {
- t.Fatalf("err: %v", err)
- } else if !work {
- t.Fatalf("CAS failure")
- }
-
- // Get should work
- pair, meta, err := kv.Get(key, nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- if pair == nil {
- t.Fatalf("expected value: %#v", pair)
- }
- if meta.LastIndex == 0 {
- t.Fatalf("unexpected value: %#v", meta)
- }
-
- // CAS update with bad index
- newVal := []byte("foo")
- p.Value = newVal
- p.ModifyIndex = 1
- if work, _, err := kv.CAS(p, nil); err != nil {
- t.Fatalf("err: %v", err)
- } else if work {
- t.Fatalf("unexpected CAS")
- }
-
- // CAS update with valid index
- p.ModifyIndex = meta.LastIndex
- if work, _, err := kv.CAS(p, nil); err != nil {
- t.Fatalf("err: %v", err)
- } else if !work {
- t.Fatalf("unexpected CAS failure")
- }
-}
-
-func TestClient_WatchGet(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- kv := c.KV()
-
- // Get a get without a key
- key := testKey()
- pair, meta, err := kv.Get(key, nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- if pair != nil {
- t.Fatalf("unexpected value: %#v", pair)
- }
- if meta.LastIndex == 0 {
- t.Fatalf("unexpected value: %#v", meta)
- }
-
- // Put the key
- value := []byte("test")
- go func() {
- kv := c.KV()
-
- time.Sleep(100 * time.Millisecond)
- p := &KVPair{Key: key, Flags: 42, Value: value}
- if _, err := kv.Put(p, nil); err != nil {
- t.Fatalf("err: %v", err)
- }
- }()
-
- // Get should work
- options := &QueryOptions{WaitIndex: meta.LastIndex}
- pair, meta2, err := kv.Get(key, options)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- if pair == nil {
- t.Fatalf("expected value: %#v", pair)
- }
- if !bytes.Equal(pair.Value, value) {
- t.Fatalf("unexpected value: %#v", pair)
- }
- if pair.Flags != 42 {
- t.Fatalf("unexpected value: %#v", pair)
- }
- if meta2.LastIndex <= meta.LastIndex {
- t.Fatalf("unexpected value: %#v", meta2)
- }
-}
-
-func TestClient_WatchList(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- kv := c.KV()
-
- // Get a get without a key
- prefix := testKey()
- key := path.Join(prefix, testKey())
- pairs, meta, err := kv.List(prefix, nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- if len(pairs) != 0 {
- t.Fatalf("unexpected value: %#v", pairs)
- }
- if meta.LastIndex == 0 {
- t.Fatalf("unexpected value: %#v", meta)
- }
-
- // Put the key
- value := []byte("test")
- go func() {
- kv := c.KV()
-
- time.Sleep(100 * time.Millisecond)
- p := &KVPair{Key: key, Flags: 42, Value: value}
- if _, err := kv.Put(p, nil); err != nil {
- t.Fatalf("err: %v", err)
- }
- }()
-
- // Get should work
- options := &QueryOptions{WaitIndex: meta.LastIndex}
- pairs, meta2, err := kv.List(prefix, options)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- if len(pairs) != 1 {
- t.Fatalf("expected value: %#v", pairs)
- }
- if !bytes.Equal(pairs[0].Value, value) {
- t.Fatalf("unexpected value: %#v", pairs)
- }
- if pairs[0].Flags != 42 {
- t.Fatalf("unexpected value: %#v", pairs)
- }
- if meta2.LastIndex <= meta.LastIndex {
- t.Fatalf("unexpected value: %#v", meta2)
- }
-
-}
-
-func TestClient_Keys_DeleteRecurse(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- kv := c.KV()
-
- // Generate some test keys
- prefix := testKey()
- var keys []string
- for i := 0; i < 100; i++ {
- keys = append(keys, path.Join(prefix, testKey()))
- }
-
- // Set values
- value := []byte("test")
- for _, key := range keys {
- p := &KVPair{Key: key, Value: value}
- if _, err := kv.Put(p, nil); err != nil {
- t.Fatalf("err: %v", err)
- }
- }
-
- // List the values
- out, meta, err := kv.Keys(prefix, "", nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- if len(out) != len(keys) {
- t.Fatalf("got %d keys", len(out))
- }
- if meta.LastIndex == 0 {
- t.Fatalf("unexpected value: %#v", meta)
- }
-
- // Delete all
- if _, err := kv.DeleteTree(prefix, nil); err != nil {
- t.Fatalf("err: %v", err)
- }
-
- // List the values
- out, _, err = kv.Keys(prefix, "", nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- if len(out) != 0 {
- t.Fatalf("got %d keys", len(out))
- }
-}
-
-func TestClient_AcquireRelease(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- session := c.Session()
- kv := c.KV()
-
- // Make a session
- id, _, err := session.CreateNoChecks(nil, nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- defer session.Destroy(id, nil)
-
- // Acquire the key
- key := testKey()
- value := []byte("test")
- p := &KVPair{Key: key, Value: value, Session: id}
- if work, _, err := kv.Acquire(p, nil); err != nil {
- t.Fatalf("err: %v", err)
- } else if !work {
- t.Fatalf("Lock failure")
- }
-
- // Get should work
- pair, meta, err := kv.Get(key, nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- if pair == nil {
- t.Fatalf("expected value: %#v", pair)
- }
- if pair.LockIndex != 1 {
- t.Fatalf("Expected lock: %v", pair)
- }
- if pair.Session != id {
- t.Fatalf("Expected lock: %v", pair)
- }
- if meta.LastIndex == 0 {
- t.Fatalf("unexpected value: %#v", meta)
- }
-
- // Release
- if work, _, err := kv.Release(p, nil); err != nil {
- t.Fatalf("err: %v", err)
- } else if !work {
- t.Fatalf("Release fail")
- }
-
- // Get should work
- pair, meta, err = kv.Get(key, nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- if pair == nil {
- t.Fatalf("expected value: %#v", pair)
- }
- if pair.LockIndex != 1 {
- t.Fatalf("Expected lock: %v", pair)
- }
- if pair.Session != "" {
- t.Fatalf("Expected unlock: %v", pair)
- }
- if meta.LastIndex == 0 {
- t.Fatalf("unexpected value: %#v", meta)
- }
-}
diff --git a/Godeps/_workspace/src/github.com/hashicorp/consul/api/lock.go b/Godeps/_workspace/src/github.com/hashicorp/consul/api/lock.go
deleted file mode 100644
index a76685f04c..0000000000
--- a/Godeps/_workspace/src/github.com/hashicorp/consul/api/lock.go
+++ /dev/null
@@ -1,338 +0,0 @@
-package api
-
-import (
- "fmt"
- "sync"
- "time"
-)
-
-const (
- // DefaultLockSessionName is the Session Name we assign if none is provided
- DefaultLockSessionName = "Consul API Lock"
-
- // DefaultLockSessionTTL is the default session TTL if no Session is provided
- // when creating a new Lock. This is used because we do not have another
- // other check to depend upon.
- DefaultLockSessionTTL = "15s"
-
- // DefaultLockWaitTime is how long we block for at a time to check if lock
- // acquisition is possible. This affects the minimum time it takes to cancel
- // a Lock acquisition.
- DefaultLockWaitTime = 15 * time.Second
-
- // DefaultLockRetryTime is how long we wait after a failed lock acquisition
- // before attempting to do the lock again. This is so that once a lock-delay
- // is in affect, we do not hot loop retrying the acquisition.
- DefaultLockRetryTime = 5 * time.Second
-
- // LockFlagValue is a magic flag we set to indicate a key
- // is being used for a lock. It is used to detect a potential
- // conflict with a semaphore.
- LockFlagValue = 0x2ddccbc058a50c18
-)
-
-var (
- // ErrLockHeld is returned if we attempt to double lock
- ErrLockHeld = fmt.Errorf("Lock already held")
-
- // ErrLockNotHeld is returned if we attempt to unlock a lock
- // that we do not hold.
- ErrLockNotHeld = fmt.Errorf("Lock not held")
-
- // ErrLockInUse is returned if we attempt to destroy a lock
- // that is in use.
- ErrLockInUse = fmt.Errorf("Lock in use")
-
- // ErrLockConflict is returned if the flags on a key
- // used for a lock do not match expectation
- ErrLockConflict = fmt.Errorf("Existing key does not match lock use")
-)
-
-// Lock is used to implement client-side leader election. It is follows the
-// algorithm as described here: https://consul.io/docs/guides/leader-election.html.
-type Lock struct {
- c *Client
- opts *LockOptions
-
- isHeld bool
- sessionRenew chan struct{}
- lockSession string
- l sync.Mutex
-}
-
-// LockOptions is used to parameterize the Lock behavior.
-type LockOptions struct {
- Key string // Must be set and have write permissions
- Value []byte // Optional, value to associate with the lock
- Session string // Optional, created if not specified
- SessionName string // Optional, defaults to DefaultLockSessionName
- SessionTTL string // Optional, defaults to DefaultLockSessionTTL
-}
-
-// LockKey returns a handle to a lock struct which can be used
-// to acquire and release the mutex. The key used must have
-// write permissions.
-func (c *Client) LockKey(key string) (*Lock, error) {
- opts := &LockOptions{
- Key: key,
- }
- return c.LockOpts(opts)
-}
-
-// LockOpts returns a handle to a lock struct which can be used
-// to acquire and release the mutex. The key used must have
-// write permissions.
-func (c *Client) LockOpts(opts *LockOptions) (*Lock, error) {
- if opts.Key == "" {
- return nil, fmt.Errorf("missing key")
- }
- if opts.SessionName == "" {
- opts.SessionName = DefaultLockSessionName
- }
- if opts.SessionTTL == "" {
- opts.SessionTTL = DefaultLockSessionTTL
- } else {
- if _, err := time.ParseDuration(opts.SessionTTL); err != nil {
- return nil, fmt.Errorf("invalid SessionTTL: %v", err)
- }
- }
- l := &Lock{
- c: c,
- opts: opts,
- }
- return l, nil
-}
-
-// Lock attempts to acquire the lock and blocks while doing so.
-// Providing a non-nil stopCh can be used to abort the lock attempt.
-// Returns a channel that is closed if our lock is lost or an error.
-// This channel could be closed at any time due to session invalidation,
-// communication errors, operator intervention, etc. It is NOT safe to
-// assume that the lock is held until Unlock() unless the Session is specifically
-// created without any associated health checks. By default Consul sessions
-// prefer liveness over safety and an application must be able to handle
-// the lock being lost.
-func (l *Lock) Lock(stopCh <-chan struct{}) (<-chan struct{}, error) {
- // Hold the lock as we try to acquire
- l.l.Lock()
- defer l.l.Unlock()
-
- // Check if we already hold the lock
- if l.isHeld {
- return nil, ErrLockHeld
- }
-
- // Check if we need to create a session first
- l.lockSession = l.opts.Session
- if l.lockSession == "" {
- if s, err := l.createSession(); err != nil {
- return nil, fmt.Errorf("failed to create session: %v", err)
- } else {
- l.sessionRenew = make(chan struct{})
- l.lockSession = s
- session := l.c.Session()
- go session.RenewPeriodic(l.opts.SessionTTL, s, nil, l.sessionRenew)
-
- // If we fail to acquire the lock, cleanup the session
- defer func() {
- if !l.isHeld {
- close(l.sessionRenew)
- l.sessionRenew = nil
- }
- }()
- }
- }
-
- // Setup the query options
- kv := l.c.KV()
- qOpts := &QueryOptions{
- WaitTime: DefaultLockWaitTime,
- }
-
-WAIT:
- // Check if we should quit
- select {
- case <-stopCh:
- return nil, nil
- default:
- }
-
- // Look for an existing lock, blocking until not taken
- pair, meta, err := kv.Get(l.opts.Key, qOpts)
- if err != nil {
- return nil, fmt.Errorf("failed to read lock: %v", err)
- }
- if pair != nil && pair.Flags != LockFlagValue {
- return nil, ErrLockConflict
- }
- locked := false
- if pair != nil && pair.Session == l.lockSession {
- goto HELD
- }
- if pair != nil && pair.Session != "" {
- qOpts.WaitIndex = meta.LastIndex
- goto WAIT
- }
-
- // Try to acquire the lock
- pair = l.lockEntry(l.lockSession)
- locked, _, err = kv.Acquire(pair, nil)
- if err != nil {
- return nil, fmt.Errorf("failed to acquire lock: %v", err)
- }
-
- // Handle the case of not getting the lock
- if !locked {
- // Determine why the lock failed
- qOpts.WaitIndex = 0
- pair, meta, err = kv.Get(l.opts.Key, qOpts)
- if pair != nil && pair.Session != "" {
- //If the session is not null, this means that a wait can safely happen
- //using a long poll
- qOpts.WaitIndex = meta.LastIndex
- goto WAIT
- } else {
- // If the session is empty and the lock failed to acquire, then it means
- // a lock-delay is in effect and a timed wait must be used
- select {
- case <-time.After(DefaultLockRetryTime):
- goto WAIT
- case <-stopCh:
- return nil, nil
- }
- }
- }
-
-HELD:
- // Watch to ensure we maintain leadership
- leaderCh := make(chan struct{})
- go l.monitorLock(l.lockSession, leaderCh)
-
- // Set that we own the lock
- l.isHeld = true
-
- // Locked! All done
- return leaderCh, nil
-}
-
-// Unlock released the lock. It is an error to call this
-// if the lock is not currently held.
-func (l *Lock) Unlock() error {
- // Hold the lock as we try to release
- l.l.Lock()
- defer l.l.Unlock()
-
- // Ensure the lock is actually held
- if !l.isHeld {
- return ErrLockNotHeld
- }
-
- // Set that we no longer own the lock
- l.isHeld = false
-
- // Stop the session renew
- if l.sessionRenew != nil {
- defer func() {
- close(l.sessionRenew)
- l.sessionRenew = nil
- }()
- }
-
- // Get the lock entry, and clear the lock session
- lockEnt := l.lockEntry(l.lockSession)
- l.lockSession = ""
-
- // Release the lock explicitly
- kv := l.c.KV()
- _, _, err := kv.Release(lockEnt, nil)
- if err != nil {
- return fmt.Errorf("failed to release lock: %v", err)
- }
- return nil
-}
-
-// Destroy is used to cleanup the lock entry. It is not necessary
-// to invoke. It will fail if the lock is in use.
-func (l *Lock) Destroy() error {
- // Hold the lock as we try to release
- l.l.Lock()
- defer l.l.Unlock()
-
- // Check if we already hold the lock
- if l.isHeld {
- return ErrLockHeld
- }
-
- // Look for an existing lock
- kv := l.c.KV()
- pair, _, err := kv.Get(l.opts.Key, nil)
- if err != nil {
- return fmt.Errorf("failed to read lock: %v", err)
- }
-
- // Nothing to do if the lock does not exist
- if pair == nil {
- return nil
- }
-
- // Check for possible flag conflict
- if pair.Flags != LockFlagValue {
- return ErrLockConflict
- }
-
- // Check if it is in use
- if pair.Session != "" {
- return ErrLockInUse
- }
-
- // Attempt the delete
- didRemove, _, err := kv.DeleteCAS(pair, nil)
- if err != nil {
- return fmt.Errorf("failed to remove lock: %v", err)
- }
- if !didRemove {
- return ErrLockInUse
- }
- return nil
-}
-
-// createSession is used to create a new managed session
-func (l *Lock) createSession() (string, error) {
- session := l.c.Session()
- se := &SessionEntry{
- Name: l.opts.SessionName,
- TTL: l.opts.SessionTTL,
- }
- id, _, err := session.Create(se, nil)
- if err != nil {
- return "", err
- }
- return id, nil
-}
-
-// lockEntry returns a formatted KVPair for the lock
-func (l *Lock) lockEntry(session string) *KVPair {
- return &KVPair{
- Key: l.opts.Key,
- Value: l.opts.Value,
- Session: session,
- Flags: LockFlagValue,
- }
-}
-
-// monitorLock is a long running routine to monitor a lock ownership
-// It closes the stopCh if we lose our leadership.
-func (l *Lock) monitorLock(session string, stopCh chan struct{}) {
- defer close(stopCh)
- kv := l.c.KV()
- opts := &QueryOptions{RequireConsistent: true}
-WAIT:
- pair, meta, err := kv.Get(l.opts.Key, opts)
- if err != nil {
- return
- }
- if pair != nil && pair.Session == session {
- opts.WaitIndex = meta.LastIndex
- goto WAIT
- }
-}
diff --git a/Godeps/_workspace/src/github.com/hashicorp/consul/api/lock_test.go b/Godeps/_workspace/src/github.com/hashicorp/consul/api/lock_test.go
deleted file mode 100644
index 0a8fa5172a..0000000000
--- a/Godeps/_workspace/src/github.com/hashicorp/consul/api/lock_test.go
+++ /dev/null
@@ -1,363 +0,0 @@
-package api
-
-import (
- "log"
- "sync"
- "testing"
- "time"
-)
-
-func TestLock_LockUnlock(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- lock, err := c.LockKey("test/lock")
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- // Initial unlock should fail
- err = lock.Unlock()
- if err != ErrLockNotHeld {
- t.Fatalf("err: %v", err)
- }
-
- // Should work
- leaderCh, err := lock.Lock(nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- if leaderCh == nil {
- t.Fatalf("not leader")
- }
-
- // Double lock should fail
- _, err = lock.Lock(nil)
- if err != ErrLockHeld {
- t.Fatalf("err: %v", err)
- }
-
- // Should be leader
- select {
- case <-leaderCh:
- t.Fatalf("should be leader")
- default:
- }
-
- // Initial unlock should work
- err = lock.Unlock()
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- // Double unlock should fail
- err = lock.Unlock()
- if err != ErrLockNotHeld {
- t.Fatalf("err: %v", err)
- }
-
- // Should loose leadership
- select {
- case <-leaderCh:
- case <-time.After(time.Second):
- t.Fatalf("should not be leader")
- }
-}
-
-func TestLock_ForceInvalidate(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- lock, err := c.LockKey("test/lock")
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- // Should work
- leaderCh, err := lock.Lock(nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- if leaderCh == nil {
- t.Fatalf("not leader")
- }
- defer lock.Unlock()
-
- go func() {
- // Nuke the session, simulator an operator invalidation
- // or a health check failure
- session := c.Session()
- session.Destroy(lock.lockSession, nil)
- }()
-
- // Should loose leadership
- select {
- case <-leaderCh:
- case <-time.After(time.Second):
- t.Fatalf("should not be leader")
- }
-}
-
-func TestLock_DeleteKey(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- lock, err := c.LockKey("test/lock")
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- // Should work
- leaderCh, err := lock.Lock(nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- if leaderCh == nil {
- t.Fatalf("not leader")
- }
- defer lock.Unlock()
-
- go func() {
- // Nuke the key, simulate an operator intervention
- kv := c.KV()
- kv.Delete("test/lock", nil)
- }()
-
- // Should loose leadership
- select {
- case <-leaderCh:
- case <-time.After(time.Second):
- t.Fatalf("should not be leader")
- }
-}
-
-func TestLock_Contend(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- wg := &sync.WaitGroup{}
- acquired := make([]bool, 3)
- for idx := range acquired {
- wg.Add(1)
- go func(idx int) {
- defer wg.Done()
- lock, err := c.LockKey("test/lock")
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- // Should work eventually, will contend
- leaderCh, err := lock.Lock(nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- if leaderCh == nil {
- t.Fatalf("not leader")
- }
- defer lock.Unlock()
- log.Printf("Contender %d acquired", idx)
-
- // Set acquired and then leave
- acquired[idx] = true
- }(idx)
- }
-
- // Wait for termination
- doneCh := make(chan struct{})
- go func() {
- wg.Wait()
- close(doneCh)
- }()
-
- // Wait for everybody to get a turn
- select {
- case <-doneCh:
- case <-time.After(3 * DefaultLockRetryTime):
- t.Fatalf("timeout")
- }
-
- for idx, did := range acquired {
- if !did {
- t.Fatalf("contender %d never acquired", idx)
- }
- }
-}
-
-func TestLock_Destroy(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- lock, err := c.LockKey("test/lock")
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- // Should work
- leaderCh, err := lock.Lock(nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- if leaderCh == nil {
- t.Fatalf("not leader")
- }
-
- // Destroy should fail
- if err := lock.Destroy(); err != ErrLockHeld {
- t.Fatalf("err: %v", err)
- }
-
- // Should be able to release
- err = lock.Unlock()
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- // Acquire with a different lock
- l2, err := c.LockKey("test/lock")
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- // Should work
- leaderCh, err = l2.Lock(nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- if leaderCh == nil {
- t.Fatalf("not leader")
- }
-
- // Destroy should still fail
- if err := lock.Destroy(); err != ErrLockInUse {
- t.Fatalf("err: %v", err)
- }
-
- // Should relese
- err = l2.Unlock()
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- // Destroy should work
- err = lock.Destroy()
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- // Double destroy should work
- err = l2.Destroy()
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-}
-
-func TestLock_Conflict(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- sema, err := c.SemaphorePrefix("test/lock/", 2)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- // Should work
- lockCh, err := sema.Acquire(nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- if lockCh == nil {
- t.Fatalf("not hold")
- }
- defer sema.Release()
-
- lock, err := c.LockKey("test/lock/.lock")
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- // Should conflict with semaphore
- _, err = lock.Lock(nil)
- if err != ErrLockConflict {
- t.Fatalf("err: %v", err)
- }
-
- // Should conflict with semaphore
- err = lock.Destroy()
- if err != ErrLockConflict {
- t.Fatalf("err: %v", err)
- }
-}
-
-func TestLock_ReclaimLock(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- session, _, err := c.Session().Create(&SessionEntry{}, nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- lock, err := c.LockOpts(&LockOptions{Key: "test/lock", Session: session})
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- // Should work
- leaderCh, err := lock.Lock(nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- if leaderCh == nil {
- t.Fatalf("not leader")
- }
- defer lock.Unlock()
-
- l2, err := c.LockOpts(&LockOptions{Key: "test/lock", Session: session})
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- reclaimed := make(chan (<-chan struct{}), 1)
- go func() {
- l2Ch, err := l2.Lock(nil)
- if err != nil {
- t.Fatalf("not locked: %v", err)
- }
- reclaimed <- l2Ch
- }()
-
- // Should reclaim the lock
- var leader2Ch <-chan struct{}
-
- select {
- case leader2Ch = <-reclaimed:
- case <-time.After(time.Second):
- t.Fatalf("should have locked")
- }
-
- // unlock should work
- err = l2.Unlock()
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- //Both locks should see the unlock
- select {
- case <-leader2Ch:
- case <-time.After(time.Second):
- t.Fatalf("should not be leader")
- }
-
- select {
- case <-leaderCh:
- case <-time.After(time.Second):
- t.Fatalf("should not be leader")
- }
-}
diff --git a/Godeps/_workspace/src/github.com/hashicorp/consul/api/raw.go b/Godeps/_workspace/src/github.com/hashicorp/consul/api/raw.go
deleted file mode 100644
index 745a208c99..0000000000
--- a/Godeps/_workspace/src/github.com/hashicorp/consul/api/raw.go
+++ /dev/null
@@ -1,24 +0,0 @@
-package api
-
-// Raw can be used to do raw queries against custom endpoints
-type Raw struct {
- c *Client
-}
-
-// Raw returns a handle to query endpoints
-func (c *Client) Raw() *Raw {
- return &Raw{c}
-}
-
-// Query is used to do a GET request against an endpoint
-// and deserialize the response into an interface using
-// standard Consul conventions.
-func (raw *Raw) Query(endpoint string, out interface{}, q *QueryOptions) (*QueryMeta, error) {
- return raw.c.query(endpoint, out, q)
-}
-
-// Write is used to do a PUT request against an endpoint
-// and serialize/deserialized using the standard Consul conventions.
-func (raw *Raw) Write(endpoint string, in, out interface{}, q *WriteOptions) (*WriteMeta, error) {
- return raw.c.write(endpoint, in, out, q)
-}
diff --git a/Godeps/_workspace/src/github.com/hashicorp/consul/api/semaphore.go b/Godeps/_workspace/src/github.com/hashicorp/consul/api/semaphore.go
deleted file mode 100644
index ff4c2058ce..0000000000
--- a/Godeps/_workspace/src/github.com/hashicorp/consul/api/semaphore.go
+++ /dev/null
@@ -1,477 +0,0 @@
-package api
-
-import (
- "encoding/json"
- "fmt"
- "path"
- "sync"
- "time"
-)
-
-const (
- // DefaultSemaphoreSessionName is the Session Name we assign if none is provided
- DefaultSemaphoreSessionName = "Consul API Semaphore"
-
- // DefaultSemaphoreSessionTTL is the default session TTL if no Session is provided
- // when creating a new Semaphore. This is used because we do not have another
- // other check to depend upon.
- DefaultSemaphoreSessionTTL = "15s"
-
- // DefaultSemaphoreWaitTime is how long we block for at a time to check if semaphore
- // acquisition is possible. This affects the minimum time it takes to cancel
- // a Semaphore acquisition.
- DefaultSemaphoreWaitTime = 15 * time.Second
-
- // DefaultSemaphoreKey is the key used within the prefix to
- // use for coordination between all the contenders.
- DefaultSemaphoreKey = ".lock"
-
- // SemaphoreFlagValue is a magic flag we set to indicate a key
- // is being used for a semaphore. It is used to detect a potential
- // conflict with a lock.
- SemaphoreFlagValue = 0xe0f69a2baa414de0
-)
-
-var (
- // ErrSemaphoreHeld is returned if we attempt to double lock
- ErrSemaphoreHeld = fmt.Errorf("Semaphore already held")
-
- // ErrSemaphoreNotHeld is returned if we attempt to unlock a semaphore
- // that we do not hold.
- ErrSemaphoreNotHeld = fmt.Errorf("Semaphore not held")
-
- // ErrSemaphoreInUse is returned if we attempt to destroy a semaphore
- // that is in use.
- ErrSemaphoreInUse = fmt.Errorf("Semaphore in use")
-
- // ErrSemaphoreConflict is returned if the flags on a key
- // used for a semaphore do not match expectation
- ErrSemaphoreConflict = fmt.Errorf("Existing key does not match semaphore use")
-)
-
-// Semaphore is used to implement a distributed semaphore
-// using the Consul KV primitives.
-type Semaphore struct {
- c *Client
- opts *SemaphoreOptions
-
- isHeld bool
- sessionRenew chan struct{}
- lockSession string
- l sync.Mutex
-}
-
-// SemaphoreOptions is used to parameterize the Semaphore
-type SemaphoreOptions struct {
- Prefix string // Must be set and have write permissions
- Limit int // Must be set, and be positive
- Value []byte // Optional, value to associate with the contender entry
- Session string // OPtional, created if not specified
- SessionName string // Optional, defaults to DefaultLockSessionName
- SessionTTL string // Optional, defaults to DefaultLockSessionTTL
-}
-
-// semaphoreLock is written under the DefaultSemaphoreKey and
-// is used to coordinate between all the contenders.
-type semaphoreLock struct {
- // Limit is the integer limit of holders. This is used to
- // verify that all the holders agree on the value.
- Limit int
-
- // Holders is a list of all the semaphore holders.
- // It maps the session ID to true. It is used as a set effectively.
- Holders map[string]bool
-}
-
-// SemaphorePrefix is used to created a Semaphore which will operate
-// at the given KV prefix and uses the given limit for the semaphore.
-// The prefix must have write privileges, and the limit must be agreed
-// upon by all contenders.
-func (c *Client) SemaphorePrefix(prefix string, limit int) (*Semaphore, error) {
- opts := &SemaphoreOptions{
- Prefix: prefix,
- Limit: limit,
- }
- return c.SemaphoreOpts(opts)
-}
-
-// SemaphoreOpts is used to create a Semaphore with the given options.
-// The prefix must have write privileges, and the limit must be agreed
-// upon by all contenders. If a Session is not provided, one will be created.
-func (c *Client) SemaphoreOpts(opts *SemaphoreOptions) (*Semaphore, error) {
- if opts.Prefix == "" {
- return nil, fmt.Errorf("missing prefix")
- }
- if opts.Limit <= 0 {
- return nil, fmt.Errorf("semaphore limit must be positive")
- }
- if opts.SessionName == "" {
- opts.SessionName = DefaultSemaphoreSessionName
- }
- if opts.SessionTTL == "" {
- opts.SessionTTL = DefaultSemaphoreSessionTTL
- } else {
- if _, err := time.ParseDuration(opts.SessionTTL); err != nil {
- return nil, fmt.Errorf("invalid SessionTTL: %v", err)
- }
- }
- s := &Semaphore{
- c: c,
- opts: opts,
- }
- return s, nil
-}
-
-// Acquire attempts to reserve a slot in the semaphore, blocking until
-// success, interrupted via the stopCh or an error is encounted.
-// Providing a non-nil stopCh can be used to abort the attempt.
-// On success, a channel is returned that represents our slot.
-// This channel could be closed at any time due to session invalidation,
-// communication errors, operator intervention, etc. It is NOT safe to
-// assume that the slot is held until Release() unless the Session is specifically
-// created without any associated health checks. By default Consul sessions
-// prefer liveness over safety and an application must be able to handle
-// the session being lost.
-func (s *Semaphore) Acquire(stopCh <-chan struct{}) (<-chan struct{}, error) {
- // Hold the lock as we try to acquire
- s.l.Lock()
- defer s.l.Unlock()
-
- // Check if we already hold the semaphore
- if s.isHeld {
- return nil, ErrSemaphoreHeld
- }
-
- // Check if we need to create a session first
- s.lockSession = s.opts.Session
- if s.lockSession == "" {
- if sess, err := s.createSession(); err != nil {
- return nil, fmt.Errorf("failed to create session: %v", err)
- } else {
- s.sessionRenew = make(chan struct{})
- s.lockSession = sess
- session := s.c.Session()
- go session.RenewPeriodic(s.opts.SessionTTL, sess, nil, s.sessionRenew)
-
- // If we fail to acquire the lock, cleanup the session
- defer func() {
- if !s.isHeld {
- close(s.sessionRenew)
- s.sessionRenew = nil
- }
- }()
- }
- }
-
- // Create the contender entry
- kv := s.c.KV()
- made, _, err := kv.Acquire(s.contenderEntry(s.lockSession), nil)
- if err != nil || !made {
- return nil, fmt.Errorf("failed to make contender entry: %v", err)
- }
-
- // Setup the query options
- qOpts := &QueryOptions{
- WaitTime: DefaultSemaphoreWaitTime,
- }
-
-WAIT:
- // Check if we should quit
- select {
- case <-stopCh:
- return nil, nil
- default:
- }
-
- // Read the prefix
- pairs, meta, err := kv.List(s.opts.Prefix, qOpts)
- if err != nil {
- return nil, fmt.Errorf("failed to read prefix: %v", err)
- }
-
- // Decode the lock
- lockPair := s.findLock(pairs)
- if lockPair.Flags != SemaphoreFlagValue {
- return nil, ErrSemaphoreConflict
- }
- lock, err := s.decodeLock(lockPair)
- if err != nil {
- return nil, err
- }
-
- // Verify we agree with the limit
- if lock.Limit != s.opts.Limit {
- return nil, fmt.Errorf("semaphore limit conflict (lock: %d, local: %d)",
- lock.Limit, s.opts.Limit)
- }
-
- // Prune the dead holders
- s.pruneDeadHolders(lock, pairs)
-
- // Check if the lock is held
- if len(lock.Holders) >= lock.Limit {
- qOpts.WaitIndex = meta.LastIndex
- goto WAIT
- }
-
- // Create a new lock with us as a holder
- lock.Holders[s.lockSession] = true
- newLock, err := s.encodeLock(lock, lockPair.ModifyIndex)
- if err != nil {
- return nil, err
- }
-
- // Attempt the acquisition
- didSet, _, err := kv.CAS(newLock, nil)
- if err != nil {
- return nil, fmt.Errorf("failed to update lock: %v", err)
- }
- if !didSet {
- // Update failed, could have been a race with another contender,
- // retry the operation
- goto WAIT
- }
-
- // Watch to ensure we maintain ownership of the slot
- lockCh := make(chan struct{})
- go s.monitorLock(s.lockSession, lockCh)
-
- // Set that we own the lock
- s.isHeld = true
-
- // Acquired! All done
- return lockCh, nil
-}
-
-// Release is used to voluntarily give up our semaphore slot. It is
-// an error to call this if the semaphore has not been acquired.
-func (s *Semaphore) Release() error {
- // Hold the lock as we try to release
- s.l.Lock()
- defer s.l.Unlock()
-
- // Ensure the lock is actually held
- if !s.isHeld {
- return ErrSemaphoreNotHeld
- }
-
- // Set that we no longer own the lock
- s.isHeld = false
-
- // Stop the session renew
- if s.sessionRenew != nil {
- defer func() {
- close(s.sessionRenew)
- s.sessionRenew = nil
- }()
- }
-
- // Get and clear the lock session
- lockSession := s.lockSession
- s.lockSession = ""
-
- // Remove ourselves as a lock holder
- kv := s.c.KV()
- key := path.Join(s.opts.Prefix, DefaultSemaphoreKey)
-READ:
- pair, _, err := kv.Get(key, nil)
- if err != nil {
- return err
- }
- if pair == nil {
- pair = &KVPair{}
- }
- lock, err := s.decodeLock(pair)
- if err != nil {
- return err
- }
-
- // Create a new lock without us as a holder
- if _, ok := lock.Holders[lockSession]; ok {
- delete(lock.Holders, lockSession)
- newLock, err := s.encodeLock(lock, pair.ModifyIndex)
- if err != nil {
- return err
- }
-
- // Swap the locks
- didSet, _, err := kv.CAS(newLock, nil)
- if err != nil {
- return fmt.Errorf("failed to update lock: %v", err)
- }
- if !didSet {
- goto READ
- }
- }
-
- // Destroy the contender entry
- contenderKey := path.Join(s.opts.Prefix, lockSession)
- if _, err := kv.Delete(contenderKey, nil); err != nil {
- return err
- }
- return nil
-}
-
-// Destroy is used to cleanup the semaphore entry. It is not necessary
-// to invoke. It will fail if the semaphore is in use.
-func (s *Semaphore) Destroy() error {
- // Hold the lock as we try to acquire
- s.l.Lock()
- defer s.l.Unlock()
-
- // Check if we already hold the semaphore
- if s.isHeld {
- return ErrSemaphoreHeld
- }
-
- // List for the semaphore
- kv := s.c.KV()
- pairs, _, err := kv.List(s.opts.Prefix, nil)
- if err != nil {
- return fmt.Errorf("failed to read prefix: %v", err)
- }
-
- // Find the lock pair, bail if it doesn't exist
- lockPair := s.findLock(pairs)
- if lockPair.ModifyIndex == 0 {
- return nil
- }
- if lockPair.Flags != SemaphoreFlagValue {
- return ErrSemaphoreConflict
- }
-
- // Decode the lock
- lock, err := s.decodeLock(lockPair)
- if err != nil {
- return err
- }
-
- // Prune the dead holders
- s.pruneDeadHolders(lock, pairs)
-
- // Check if there are any holders
- if len(lock.Holders) > 0 {
- return ErrSemaphoreInUse
- }
-
- // Attempt the delete
- didRemove, _, err := kv.DeleteCAS(lockPair, nil)
- if err != nil {
- return fmt.Errorf("failed to remove semaphore: %v", err)
- }
- if !didRemove {
- return ErrSemaphoreInUse
- }
- return nil
-}
-
-// createSession is used to create a new managed session
-func (s *Semaphore) createSession() (string, error) {
- session := s.c.Session()
- se := &SessionEntry{
- Name: s.opts.SessionName,
- TTL: s.opts.SessionTTL,
- Behavior: SessionBehaviorDelete,
- }
- id, _, err := session.Create(se, nil)
- if err != nil {
- return "", err
- }
- return id, nil
-}
-
-// contenderEntry returns a formatted KVPair for the contender
-func (s *Semaphore) contenderEntry(session string) *KVPair {
- return &KVPair{
- Key: path.Join(s.opts.Prefix, session),
- Value: s.opts.Value,
- Session: session,
- Flags: SemaphoreFlagValue,
- }
-}
-
-// findLock is used to find the KV Pair which is used for coordination
-func (s *Semaphore) findLock(pairs KVPairs) *KVPair {
- key := path.Join(s.opts.Prefix, DefaultSemaphoreKey)
- for _, pair := range pairs {
- if pair.Key == key {
- return pair
- }
- }
- return &KVPair{Flags: SemaphoreFlagValue}
-}
-
-// decodeLock is used to decode a semaphoreLock from an
-// entry in Consul
-func (s *Semaphore) decodeLock(pair *KVPair) (*semaphoreLock, error) {
- // Handle if there is no lock
- if pair == nil || pair.Value == nil {
- return &semaphoreLock{
- Limit: s.opts.Limit,
- Holders: make(map[string]bool),
- }, nil
- }
-
- l := &semaphoreLock{}
- if err := json.Unmarshal(pair.Value, l); err != nil {
- return nil, fmt.Errorf("lock decoding failed: %v", err)
- }
- return l, nil
-}
-
-// encodeLock is used to encode a semaphoreLock into a KVPair
-// that can be PUT
-func (s *Semaphore) encodeLock(l *semaphoreLock, oldIndex uint64) (*KVPair, error) {
- enc, err := json.Marshal(l)
- if err != nil {
- return nil, fmt.Errorf("lock encoding failed: %v", err)
- }
- pair := &KVPair{
- Key: path.Join(s.opts.Prefix, DefaultSemaphoreKey),
- Value: enc,
- Flags: SemaphoreFlagValue,
- ModifyIndex: oldIndex,
- }
- return pair, nil
-}
-
-// pruneDeadHolders is used to remove all the dead lock holders
-func (s *Semaphore) pruneDeadHolders(lock *semaphoreLock, pairs KVPairs) {
- // Gather all the live holders
- alive := make(map[string]struct{}, len(pairs))
- for _, pair := range pairs {
- if pair.Session != "" {
- alive[pair.Session] = struct{}{}
- }
- }
-
- // Remove any holders that are dead
- for holder := range lock.Holders {
- if _, ok := alive[holder]; !ok {
- delete(lock.Holders, holder)
- }
- }
-}
-
-// monitorLock is a long running routine to monitor a semaphore ownership
-// It closes the stopCh if we lose our slot.
-func (s *Semaphore) monitorLock(session string, stopCh chan struct{}) {
- defer close(stopCh)
- kv := s.c.KV()
- opts := &QueryOptions{RequireConsistent: true}
-WAIT:
- pairs, meta, err := kv.List(s.opts.Prefix, opts)
- if err != nil {
- return
- }
- lockPair := s.findLock(pairs)
- lock, err := s.decodeLock(lockPair)
- if err != nil {
- return
- }
- s.pruneDeadHolders(lock, pairs)
- if _, ok := lock.Holders[session]; ok {
- opts.WaitIndex = meta.LastIndex
- goto WAIT
- }
-}
diff --git a/Godeps/_workspace/src/github.com/hashicorp/consul/api/semaphore_test.go b/Godeps/_workspace/src/github.com/hashicorp/consul/api/semaphore_test.go
deleted file mode 100644
index 5e5e53588c..0000000000
--- a/Godeps/_workspace/src/github.com/hashicorp/consul/api/semaphore_test.go
+++ /dev/null
@@ -1,313 +0,0 @@
-package api
-
-import (
- "log"
- "sync"
- "testing"
- "time"
-)
-
-func TestSemaphore_AcquireRelease(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- sema, err := c.SemaphorePrefix("test/semaphore", 2)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- // Initial release should fail
- err = sema.Release()
- if err != ErrSemaphoreNotHeld {
- t.Fatalf("err: %v", err)
- }
-
- // Should work
- lockCh, err := sema.Acquire(nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- if lockCh == nil {
- t.Fatalf("not hold")
- }
-
- // Double lock should fail
- _, err = sema.Acquire(nil)
- if err != ErrSemaphoreHeld {
- t.Fatalf("err: %v", err)
- }
-
- // Should be held
- select {
- case <-lockCh:
- t.Fatalf("should be held")
- default:
- }
-
- // Initial release should work
- err = sema.Release()
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- // Double unlock should fail
- err = sema.Release()
- if err != ErrSemaphoreNotHeld {
- t.Fatalf("err: %v", err)
- }
-
- // Should lose resource
- select {
- case <-lockCh:
- case <-time.After(time.Second):
- t.Fatalf("should not be held")
- }
-}
-
-func TestSemaphore_ForceInvalidate(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- sema, err := c.SemaphorePrefix("test/semaphore", 2)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- // Should work
- lockCh, err := sema.Acquire(nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- if lockCh == nil {
- t.Fatalf("not acquired")
- }
- defer sema.Release()
-
- go func() {
- // Nuke the session, simulator an operator invalidation
- // or a health check failure
- session := c.Session()
- session.Destroy(sema.lockSession, nil)
- }()
-
- // Should loose slot
- select {
- case <-lockCh:
- case <-time.After(time.Second):
- t.Fatalf("should not be locked")
- }
-}
-
-func TestSemaphore_DeleteKey(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- sema, err := c.SemaphorePrefix("test/semaphore", 2)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- // Should work
- lockCh, err := sema.Acquire(nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- if lockCh == nil {
- t.Fatalf("not locked")
- }
- defer sema.Release()
-
- go func() {
- // Nuke the key, simulate an operator intervention
- kv := c.KV()
- kv.DeleteTree("test/semaphore", nil)
- }()
-
- // Should loose leadership
- select {
- case <-lockCh:
- case <-time.After(time.Second):
- t.Fatalf("should not be locked")
- }
-}
-
-func TestSemaphore_Contend(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- wg := &sync.WaitGroup{}
- acquired := make([]bool, 4)
- for idx := range acquired {
- wg.Add(1)
- go func(idx int) {
- defer wg.Done()
- sema, err := c.SemaphorePrefix("test/semaphore", 2)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- // Should work eventually, will contend
- lockCh, err := sema.Acquire(nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- if lockCh == nil {
- t.Fatalf("not locked")
- }
- defer sema.Release()
- log.Printf("Contender %d acquired", idx)
-
- // Set acquired and then leave
- acquired[idx] = true
- }(idx)
- }
-
- // Wait for termination
- doneCh := make(chan struct{})
- go func() {
- wg.Wait()
- close(doneCh)
- }()
-
- // Wait for everybody to get a turn
- select {
- case <-doneCh:
- case <-time.After(3 * DefaultLockRetryTime):
- t.Fatalf("timeout")
- }
-
- for idx, did := range acquired {
- if !did {
- t.Fatalf("contender %d never acquired", idx)
- }
- }
-}
-
-func TestSemaphore_BadLimit(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- sema, err := c.SemaphorePrefix("test/semaphore", 0)
- if err == nil {
- t.Fatalf("should error")
- }
-
- sema, err = c.SemaphorePrefix("test/semaphore", 1)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- _, err = sema.Acquire(nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- sema2, err := c.SemaphorePrefix("test/semaphore", 2)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- _, err = sema2.Acquire(nil)
- if err.Error() != "semaphore limit conflict (lock: 1, local: 2)" {
- t.Fatalf("err: %v", err)
- }
-}
-
-func TestSemaphore_Destroy(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- sema, err := c.SemaphorePrefix("test/semaphore", 2)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- sema2, err := c.SemaphorePrefix("test/semaphore", 2)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- _, err = sema.Acquire(nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- _, err = sema2.Acquire(nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- // Destroy should fail, still held
- if err := sema.Destroy(); err != ErrSemaphoreHeld {
- t.Fatalf("err: %v", err)
- }
-
- err = sema.Release()
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- // Destroy should fail, still in use
- if err := sema.Destroy(); err != ErrSemaphoreInUse {
- t.Fatalf("err: %v", err)
- }
-
- err = sema2.Release()
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- // Destroy should work
- if err := sema.Destroy(); err != nil {
- t.Fatalf("err: %v", err)
- }
-
- // Destroy should work
- if err := sema2.Destroy(); err != nil {
- t.Fatalf("err: %v", err)
- }
-}
-
-func TestSemaphore_Conflict(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- lock, err := c.LockKey("test/sema/.lock")
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- // Should work
- leaderCh, err := lock.Lock(nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- if leaderCh == nil {
- t.Fatalf("not leader")
- }
- defer lock.Unlock()
-
- sema, err := c.SemaphorePrefix("test/sema/", 2)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- // Should conflict with lock
- _, err = sema.Acquire(nil)
- if err != ErrSemaphoreConflict {
- t.Fatalf("err: %v", err)
- }
-
- // Should conflict with lock
- err = sema.Destroy()
- if err != ErrSemaphoreConflict {
- t.Fatalf("err: %v", err)
- }
-}
diff --git a/Godeps/_workspace/src/github.com/hashicorp/consul/api/session.go b/Godeps/_workspace/src/github.com/hashicorp/consul/api/session.go
deleted file mode 100644
index a99da511d6..0000000000
--- a/Godeps/_workspace/src/github.com/hashicorp/consul/api/session.go
+++ /dev/null
@@ -1,201 +0,0 @@
-package api
-
-import (
- "fmt"
- "time"
-)
-
-const (
- // SessionBehaviorRelease is the default behavior and causes
- // all associated locks to be released on session invalidation.
- SessionBehaviorRelease = "release"
-
- // SessionBehaviorDelete is new in Consul 0.5 and changes the
- // behavior to delete all associated locks on session invalidation.
- // It can be used in a way similar to Ephemeral Nodes in ZooKeeper.
- SessionBehaviorDelete = "delete"
-)
-
-// SessionEntry represents a session in consul
-type SessionEntry struct {
- CreateIndex uint64
- ID string
- Name string
- Node string
- Checks []string
- LockDelay time.Duration
- Behavior string
- TTL string
-}
-
-// Session can be used to query the Session endpoints
-type Session struct {
- c *Client
-}
-
-// Session returns a handle to the session endpoints
-func (c *Client) Session() *Session {
- return &Session{c}
-}
-
-// CreateNoChecks is like Create but is used specifically to create
-// a session with no associated health checks.
-func (s *Session) CreateNoChecks(se *SessionEntry, q *WriteOptions) (string, *WriteMeta, error) {
- body := make(map[string]interface{})
- body["Checks"] = []string{}
- if se != nil {
- if se.Name != "" {
- body["Name"] = se.Name
- }
- if se.Node != "" {
- body["Node"] = se.Node
- }
- if se.LockDelay != 0 {
- body["LockDelay"] = durToMsec(se.LockDelay)
- }
- if se.Behavior != "" {
- body["Behavior"] = se.Behavior
- }
- if se.TTL != "" {
- body["TTL"] = se.TTL
- }
- }
- return s.create(body, q)
-
-}
-
-// Create makes a new session. Providing a session entry can
-// customize the session. It can also be nil to use defaults.
-func (s *Session) Create(se *SessionEntry, q *WriteOptions) (string, *WriteMeta, error) {
- var obj interface{}
- if se != nil {
- body := make(map[string]interface{})
- obj = body
- if se.Name != "" {
- body["Name"] = se.Name
- }
- if se.Node != "" {
- body["Node"] = se.Node
- }
- if se.LockDelay != 0 {
- body["LockDelay"] = durToMsec(se.LockDelay)
- }
- if len(se.Checks) > 0 {
- body["Checks"] = se.Checks
- }
- if se.Behavior != "" {
- body["Behavior"] = se.Behavior
- }
- if se.TTL != "" {
- body["TTL"] = se.TTL
- }
- }
- return s.create(obj, q)
-}
-
-func (s *Session) create(obj interface{}, q *WriteOptions) (string, *WriteMeta, error) {
- var out struct{ ID string }
- wm, err := s.c.write("/v1/session/create", obj, &out, q)
- if err != nil {
- return "", nil, err
- }
- return out.ID, wm, nil
-}
-
-// Destroy invalides a given session
-func (s *Session) Destroy(id string, q *WriteOptions) (*WriteMeta, error) {
- wm, err := s.c.write("/v1/session/destroy/"+id, nil, nil, q)
- if err != nil {
- return nil, err
- }
- return wm, nil
-}
-
-// Renew renews the TTL on a given session
-func (s *Session) Renew(id string, q *WriteOptions) (*SessionEntry, *WriteMeta, error) {
- var entries []*SessionEntry
- wm, err := s.c.write("/v1/session/renew/"+id, nil, &entries, q)
- if err != nil {
- return nil, nil, err
- }
- if len(entries) > 0 {
- return entries[0], wm, nil
- }
- return nil, wm, nil
-}
-
-// RenewPeriodic is used to periodically invoke Session.Renew on a
-// session until a doneCh is closed. This is meant to be used in a long running
-// goroutine to ensure a session stays valid.
-func (s *Session) RenewPeriodic(initialTTL string, id string, q *WriteOptions, doneCh chan struct{}) error {
- ttl, err := time.ParseDuration(initialTTL)
- if err != nil {
- return err
- }
-
- waitDur := ttl / 2
- lastRenewTime := time.Now()
- var lastErr error
- for {
- if time.Since(lastRenewTime) > ttl {
- return lastErr
- }
- select {
- case <-time.After(waitDur):
- entry, _, err := s.Renew(id, q)
- if err != nil {
- waitDur = time.Second
- lastErr = err
- continue
- }
- if entry == nil {
- waitDur = time.Second
- lastErr = fmt.Errorf("No SessionEntry returned")
- continue
- }
-
- // Handle the server updating the TTL
- ttl, _ = time.ParseDuration(entry.TTL)
- waitDur = ttl / 2
- lastRenewTime = time.Now()
-
- case <-doneCh:
- // Attempt a session destroy
- s.Destroy(id, q)
- return nil
- }
- }
-}
-
-// Info looks up a single session
-func (s *Session) Info(id string, q *QueryOptions) (*SessionEntry, *QueryMeta, error) {
- var entries []*SessionEntry
- qm, err := s.c.query("/v1/session/info/"+id, &entries, q)
- if err != nil {
- return nil, nil, err
- }
- if len(entries) > 0 {
- return entries[0], qm, nil
- }
- return nil, qm, nil
-}
-
-// List gets sessions for a node
-func (s *Session) Node(node string, q *QueryOptions) ([]*SessionEntry, *QueryMeta, error) {
- var entries []*SessionEntry
- qm, err := s.c.query("/v1/session/node/"+node, &entries, q)
- if err != nil {
- return nil, nil, err
- }
- return entries, qm, nil
-}
-
-// List gets all active sessions
-func (s *Session) List(q *QueryOptions) ([]*SessionEntry, *QueryMeta, error) {
- var entries []*SessionEntry
- qm, err := s.c.query("/v1/session/list", &entries, q)
- if err != nil {
- return nil, nil, err
- }
- return entries, qm, nil
-}
diff --git a/Godeps/_workspace/src/github.com/hashicorp/consul/api/session_test.go b/Godeps/_workspace/src/github.com/hashicorp/consul/api/session_test.go
deleted file mode 100644
index c503c21a07..0000000000
--- a/Godeps/_workspace/src/github.com/hashicorp/consul/api/session_test.go
+++ /dev/null
@@ -1,205 +0,0 @@
-package api
-
-import (
- "testing"
-)
-
-func TestSession_CreateDestroy(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- session := c.Session()
-
- id, meta, err := session.Create(nil, nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- if meta.RequestTime == 0 {
- t.Fatalf("bad: %v", meta)
- }
-
- if id == "" {
- t.Fatalf("invalid: %v", id)
- }
-
- meta, err = session.Destroy(id, nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- if meta.RequestTime == 0 {
- t.Fatalf("bad: %v", meta)
- }
-}
-
-func TestSession_CreateRenewDestroy(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- session := c.Session()
-
- se := &SessionEntry{
- TTL: "10s",
- }
-
- id, meta, err := session.Create(se, nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- defer session.Destroy(id, nil)
-
- if meta.RequestTime == 0 {
- t.Fatalf("bad: %v", meta)
- }
-
- if id == "" {
- t.Fatalf("invalid: %v", id)
- }
-
- if meta.RequestTime == 0 {
- t.Fatalf("bad: %v", meta)
- }
-
- renew, meta, err := session.Renew(id, nil)
-
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- if meta.RequestTime == 0 {
- t.Fatalf("bad: %v", meta)
- }
-
- if renew == nil {
- t.Fatalf("should get session")
- }
-
- if renew.ID != id {
- t.Fatalf("should have matching id")
- }
-
- if renew.TTL != "10s" {
- t.Fatalf("should get session with TTL")
- }
-}
-
-func TestSession_Info(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- session := c.Session()
-
- id, _, err := session.Create(nil, nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- defer session.Destroy(id, nil)
-
- info, qm, err := session.Info(id, nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- if qm.LastIndex == 0 {
- t.Fatalf("bad: %v", qm)
- }
- if !qm.KnownLeader {
- t.Fatalf("bad: %v", qm)
- }
-
- if info == nil {
- t.Fatalf("should get session")
- }
- if info.CreateIndex == 0 {
- t.Fatalf("bad: %v", info)
- }
- if info.ID != id {
- t.Fatalf("bad: %v", info)
- }
- if info.Name != "" {
- t.Fatalf("bad: %v", info)
- }
- if info.Node == "" {
- t.Fatalf("bad: %v", info)
- }
- if len(info.Checks) == 0 {
- t.Fatalf("bad: %v", info)
- }
- if info.LockDelay == 0 {
- t.Fatalf("bad: %v", info)
- }
- if info.Behavior != "release" {
- t.Fatalf("bad: %v", info)
- }
- if info.TTL != "" {
- t.Fatalf("bad: %v", info)
- }
-}
-
-func TestSession_Node(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- session := c.Session()
-
- id, _, err := session.Create(nil, nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- defer session.Destroy(id, nil)
-
- info, qm, err := session.Info(id, nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- sessions, qm, err := session.Node(info.Node, nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- if len(sessions) != 1 {
- t.Fatalf("bad: %v", sessions)
- }
-
- if qm.LastIndex == 0 {
- t.Fatalf("bad: %v", qm)
- }
- if !qm.KnownLeader {
- t.Fatalf("bad: %v", qm)
- }
-}
-
-func TestSession_List(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- session := c.Session()
-
- id, _, err := session.Create(nil, nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- defer session.Destroy(id, nil)
-
- sessions, qm, err := session.List(nil)
- if err != nil {
- t.Fatalf("err: %v", err)
- }
-
- if len(sessions) != 1 {
- t.Fatalf("bad: %v", sessions)
- }
-
- if qm.LastIndex == 0 {
- t.Fatalf("bad: %v", qm)
- }
- if !qm.KnownLeader {
- t.Fatalf("bad: %v", qm)
- }
-}
diff --git a/Godeps/_workspace/src/github.com/hashicorp/consul/api/status.go b/Godeps/_workspace/src/github.com/hashicorp/consul/api/status.go
deleted file mode 100644
index 74ef61a678..0000000000
--- a/Godeps/_workspace/src/github.com/hashicorp/consul/api/status.go
+++ /dev/null
@@ -1,43 +0,0 @@
-package api
-
-// Status can be used to query the Status endpoints
-type Status struct {
- c *Client
-}
-
-// Status returns a handle to the status endpoints
-func (c *Client) Status() *Status {
- return &Status{c}
-}
-
-// Leader is used to query for a known leader
-func (s *Status) Leader() (string, error) {
- r := s.c.newRequest("GET", "/v1/status/leader")
- _, resp, err := requireOK(s.c.doRequest(r))
- if err != nil {
- return "", err
- }
- defer resp.Body.Close()
-
- var leader string
- if err := decodeBody(resp, &leader); err != nil {
- return "", err
- }
- return leader, nil
-}
-
-// Peers is used to query for a known raft peers
-func (s *Status) Peers() ([]string, error) {
- r := s.c.newRequest("GET", "/v1/status/peers")
- _, resp, err := requireOK(s.c.doRequest(r))
- if err != nil {
- return nil, err
- }
- defer resp.Body.Close()
-
- var peers []string
- if err := decodeBody(resp, &peers); err != nil {
- return nil, err
- }
- return peers, nil
-}
diff --git a/Godeps/_workspace/src/github.com/hashicorp/consul/api/status_test.go b/Godeps/_workspace/src/github.com/hashicorp/consul/api/status_test.go
deleted file mode 100644
index 62dc1550ff..0000000000
--- a/Godeps/_workspace/src/github.com/hashicorp/consul/api/status_test.go
+++ /dev/null
@@ -1,37 +0,0 @@
-package api
-
-import (
- "testing"
-)
-
-func TestStatusLeader(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- status := c.Status()
-
- leader, err := status.Leader()
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- if leader == "" {
- t.Fatalf("Expected leader")
- }
-}
-
-func TestStatusPeers(t *testing.T) {
- t.Parallel()
- c, s := makeClient(t)
- defer s.Stop()
-
- status := c.Status()
-
- peers, err := status.Peers()
- if err != nil {
- t.Fatalf("err: %v", err)
- }
- if len(peers) == 0 {
- t.Fatalf("Expected peers ")
- }
-}
diff --git a/Godeps/_workspace/src/github.com/julienschmidt/httprouter/.travis.yml b/Godeps/_workspace/src/github.com/julienschmidt/httprouter/.travis.yml
deleted file mode 100644
index a4d6cc5326..0000000000
--- a/Godeps/_workspace/src/github.com/julienschmidt/httprouter/.travis.yml
+++ /dev/null
@@ -1,8 +0,0 @@
-sudo: false
-language: go
-go:
- - 1.1
- - 1.2
- - 1.3
- - 1.4
- - tip
diff --git a/Godeps/_workspace/src/github.com/julienschmidt/httprouter/LICENSE b/Godeps/_workspace/src/github.com/julienschmidt/httprouter/LICENSE
deleted file mode 100644
index b829abc8a1..0000000000
--- a/Godeps/_workspace/src/github.com/julienschmidt/httprouter/LICENSE
+++ /dev/null
@@ -1,24 +0,0 @@
-Copyright (c) 2013 Julien Schmidt. All rights reserved.
-
-
-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.
- * The names of the contributors may not 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 JULIEN SCHMIDT 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.
\ No newline at end of file
diff --git a/Godeps/_workspace/src/github.com/julienschmidt/httprouter/README.md b/Godeps/_workspace/src/github.com/julienschmidt/httprouter/README.md
deleted file mode 100644
index 785a108cae..0000000000
--- a/Godeps/_workspace/src/github.com/julienschmidt/httprouter/README.md
+++ /dev/null
@@ -1,323 +0,0 @@
-# HttpRouter [](https://travis-ci.org/julienschmidt/httprouter) [](http://gocover.io/github.com/julienschmidt/httprouter) [](http://godoc.org/github.com/julienschmidt/httprouter)
-
-HttpRouter is a lightweight high performance HTTP request router
-(also called *multiplexer* or just *mux* for short) for [Go](http://golang.org/).
-
-In contrast to the [default mux](http://golang.org/pkg/net/http/#ServeMux) of Go's net/http package, this router supports
-variables in the routing pattern and matches against the request method.
-It also scales better.
-
-The router is optimized for high performance and a small memory footprint.
-It scales well even with very long paths and a large number of routes.
-A compressing dynamic trie (radix tree) structure is used for efficient matching.
-
-## Features
-**Only explicit matches:** With other routers, like [http.ServeMux](http://golang.org/pkg/net/http/#ServeMux),
-a requested URL path could match multiple patterns. Therefore they have some
-awkward pattern priority rules, like *longest match* or *first registered,
-first matched*. By design of this router, a request can only match exactly one
-or no route. As a result, there are also no unintended matches, which makes it
-great for SEO and improves the user experience.
-
-**Stop caring about trailing slashes:** Choose the URL style you like, the
-router automatically redirects the client if a trailing slash is missing or if
-there is one extra. Of course it only does so, if the new path has a handler.
-If you don't like it, you can [turn off this behavior](http://godoc.org/github.com/julienschmidt/httprouter#Router.RedirectTrailingSlash).
-
-**Path auto-correction:** Besides detecting the missing or additional trailing
-slash at no extra cost, the router can also fix wrong cases and remove
-superfluous path elements (like `../` or `//`).
-Is [CAPTAIN CAPS LOCK](http://www.urbandictionary.com/define.php?term=Captain+Caps+Lock) one of your users?
-HttpRouter can help him by making a case-insensitive look-up and redirecting him
-to the correct URL.
-
-**Parameters in your routing pattern:** Stop parsing the requested URL path,
-just give the path segment a name and the router delivers the dynamic value to
-you. Because of the design of the router, path parameters are very cheap.
-
-**Zero Garbage:** The matching and dispatching process generates zero bytes of
-garbage. In fact, the only heap allocations that are made, is by building the
-slice of the key-value pairs for path parameters. If the request path contains
-no parameters, not a single heap allocation is necessary.
-
-**Best Performance:** [Benchmarks speak for themselves](https://github.com/julienschmidt/go-http-routing-benchmark).
-See below for technical details of the implementation.
-
-**No more server crashes:** You can set a [Panic handler](http://godoc.org/github.com/julienschmidt/httprouter#Router.PanicHandler) to deal with panics
-occurring during handling a HTTP request. The router then recovers and lets the
-PanicHandler log what happened and deliver a nice error page.
-
-Of course you can also set **custom [NotFound](http://godoc.org/github.com/julienschmidt/httprouter#Router.NotFound) and [MethodNotAllowed](http://godoc.org/github.com/julienschmidt/httprouter#Router.MethodNotAllowed) handlers** and [**serve static files**](http://godoc.org/github.com/julienschmidt/httprouter#Router.ServeFiles).
-
-## Usage
-This is just a quick introduction, view the [GoDoc](http://godoc.org/github.com/julienschmidt/httprouter) for details.
-
-Let's start with a trivial example:
-```go
-package main
-
-import (
- "fmt"
- "github.com/julienschmidt/httprouter"
- "net/http"
- "log"
-)
-
-func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
- fmt.Fprint(w, "Welcome!\n")
-}
-
-func Hello(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
- fmt.Fprintf(w, "hello, %s!\n", ps.ByName("name"))
-}
-
-func main() {
- router := httprouter.New()
- router.GET("/", Index)
- router.GET("/hello/:name", Hello)
-
- log.Fatal(http.ListenAndServe(":8080", router))
-}
-```
-
-### Named parameters
-As you can see, `:name` is a *named parameter*.
-The values are accessible via `httprouter.Params`, which is just a slice of `httprouter.Param`s.
-You can get the value of a parameter either by its index in the slice, or by using the `ByName(name)` method:
-`:name` can be retrived by `ByName("name")`.
-
-Named parameters only match a single path segment:
-```
-Pattern: /user/:user
-
- /user/gordon match
- /user/you match
- /user/gordon/profile no match
- /user/ no match
-```
-
-**Note:** Since this router has only explicit matches, you can not register static routes and parameters for the same path segment. For example you can not register the patterns `/user/new` and `/user/:user` for the same request method at the same time. The routing of different request methods is independent from each other.
-
-### Catch-All parameters
-The second type are *catch-all* parameters and have the form `*name`.
-Like the name suggests, they match everything.
-Therefore they must always be at the **end** of the pattern:
-```
-Pattern: /src/*filepath
-
- /src/ match
- /src/somefile.go match
- /src/subdir/somefile.go match
-```
-
-## How does it work?
-The router relies on a tree structure which makes heavy use of *common prefixes*,
-it is basically a *compact* [*prefix tree*](http://en.wikipedia.org/wiki/Trie)
-(or just [*Radix tree*](http://en.wikipedia.org/wiki/Radix_tree)).
-Nodes with a common prefix also share a common parent. Here is a short example
-what the routing tree for the `GET` request method could look like:
-
-```
-Priority Path Handle
-9 \ *<1>
-3 ├s nil
-2 |├earch\ *<2>
-1 |└upport\ *<3>
-2 ├blog\ *<4>
-1 | └:post nil
-1 | └\ *<5>
-2 ├about-us\ *<6>
-1 | └team\ *<7>
-1 └contact\ *<8>
-```
-Every `*` represents the memory address of a handler function (a pointer).
-If you follow a path trough the tree from the root to the leaf, you get the
-complete route path, e.g `\blog\:post\`, where `:post` is just a placeholder
-([*parameter*](#named-parameters)) for an actual post name. Unlike hash-maps, a
-tree structure also allows us to use dynamic parts like the `:post` parameter,
-since we actually match against the routing patterns instead of just comparing
-hashes. [As benchmarks show](https://github.com/julienschmidt/go-http-routing-benchmark),
-this works very well and efficient.
-
-Since URL paths have a hierarchical structure and make use only of a limited set
-of characters (byte values), it is very likely that there are a lot of common
-prefixes. This allows us to easily reduce the routing into ever smaller problems.
-Moreover the router manages a separate tree for every request method.
-For one thing it is more space efficient than holding a method->handle map in
-every single node, for another thing is also allows us to greatly reduce the
-routing problem before even starting the look-up in the prefix-tree.
-
-For even better scalability, the child nodes on each tree level are ordered by
-priority, where the priority is just the number of handles registered in sub
-nodes (children, grandchildren, and so on..).
-This helps in two ways:
-
-1. Nodes which are part of the most routing paths are evaluated first. This
-helps to make as much routes as possible to be reachable as fast as possible.
-2. It is some sort of cost compensation. The longest reachable path (highest
-cost) can always be evaluated first. The following scheme visualizes the tree
-structure. Nodes are evaluated from top to bottom and from left to right.
-
-```
-├------------
-├---------
-├-----
-├----
-├--
-├--
-└-
-```
-
-
-## Why doesn't this work with http.Handler?
-**It does!** The router itself implements the http.Handler interface.
-Moreover the router provides convenient [adapters for http.Handler](http://godoc.org/github.com/julienschmidt/httprouter#Router.Handler)s and [http.HandlerFunc](http://godoc.org/github.com/julienschmidt/httprouter#Router.HandlerFunc)s
-which allows them to be used as a [httprouter.Handle](http://godoc.org/github.com/julienschmidt/httprouter#Router.Handle) when registering a route.
-The only disadvantage is, that no parameter values can be retrieved when a
-http.Handler or http.HandlerFunc is used, since there is no efficient way to
-pass the values with the existing function parameters.
-Therefore [httprouter.Handle](http://godoc.org/github.com/julienschmidt/httprouter#Router.Handle) has a third function parameter.
-
-Just try it out for yourself, the usage of HttpRouter is very straightforward. The package is compact and minimalistic, but also probably one of the easiest routers to set up.
-
-
-## Where can I find Middleware *X*?
-This package just provides a very efficient request router with a few extra
-features. The router is just a [http.Handler](http://golang.org/pkg/net/http/#Handler),
-you can chain any http.Handler compatible middleware before the router,
-for example the [Gorilla handlers](http://www.gorillatoolkit.org/pkg/handlers).
-Or you could [just write your own](http://justinas.org/writing-http-middleware-in-go/),
-it's very easy!
-
-Alternatively, you could try [a web framework based on HttpRouter](#web-frameworks-based-on-httprouter).
-
-### Multi-domain / Sub-domains
-Here is a quick example: Does your server serve multiple domains / hosts?
-You want to use sub-domains?
-Define a router per host!
-```go
-// We need an object that implements the http.Handler interface.
-// Therefore we need a type for which we implement the ServeHTTP method.
-// We just use a map here, in which we map host names (with port) to http.Handlers
-type HostSwitch map[string]http.Handler
-
-// Implement the ServerHTTP method on our new type
-func (hs HostSwitch) ServeHTTP(w http.ResponseWriter, r *http.Request) {
- // Check if a http.Handler is registered for the given host.
- // If yes, use it to handle the request.
- if handler := hs[r.Host]; handler != nil {
- handler.ServeHTTP(w, r)
- } else {
- // Handle host names for wich no handler is registered
- http.Error(w, "Forbidden", 403) // Or Redirect?
- }
-}
-
-func main() {
- // Initialize a router as usual
- router := httprouter.New()
- router.GET("/", Index)
- router.GET("/hello/:name", Hello)
-
- // Make a new HostSwitch and insert the router (our http handler)
- // for example.com and port 12345
- hs := make(HostSwitch)
- hs["example.com:12345"] = router
-
- // Use the HostSwitch to listen and serve on port 12345
- log.Fatal(http.ListenAndServe(":12345", hs))
-}
-```
-
-### Basic Authentication
-Another quick example: Basic Authentification (RFC 2617) for handles:
-
-```go
-package main
-
-import (
- "bytes"
- "encoding/base64"
- "fmt"
- "github.com/julienschmidt/httprouter"
- "net/http"
- "log"
- "strings"
-)
-
-func BasicAuth(h httprouter.Handle, user, pass []byte) httprouter.Handle {
- return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
- const basicAuthPrefix string = "Basic "
-
- // Get the Basic Authentication credentials
- auth := r.Header.Get("Authorization")
- if strings.HasPrefix(auth, basicAuthPrefix) {
- // Check credentials
- payload, err := base64.StdEncoding.DecodeString(auth[len(basicAuthPrefix):])
- if err == nil {
- pair := bytes.SplitN(payload, []byte(":"), 2)
- if len(pair) == 2 &&
- bytes.Equal(pair[0], user) &&
- bytes.Equal(pair[1], pass) {
-
- // Delegate request to the given handle
- h(w, r, ps)
- return
- }
- }
- }
-
- // Request Basic Authentication otherwise
- w.Header().Set("WWW-Authenticate", "Basic realm=Restricted")
- http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
- }
-}
-
-func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
- fmt.Fprint(w, "Not protected!\n")
-}
-
-func Protected(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
- fmt.Fprint(w, "Protected!\n")
-}
-
-func main() {
- user := []byte("gordon")
- pass := []byte("secret!")
-
- router := httprouter.New()
- router.GET("/", Index)
- router.GET("/protected/", BasicAuth(Protected, user, pass))
-
- log.Fatal(http.ListenAndServe(":8080", router))
-}
-```
-
-## Chaining with the NotFound handler
-
-**NOTE: It might be required to set [Router.HandleMethodNotAllowed](http://godoc.org/github.com/julienschmidt/httprouter#Router.HandleMethodNotAllowed) to `false` to avoid problems.**
-
-You can use another [http.Handler](http://golang.org/pkg/net/http/#Handler), for example another router, to handle requests which could not be matched by this router by using the [Router.NotFound](http://godoc.org/github.com/julienschmidt/httprouter#Router.NotFound) handler. This allows chaining.
-
-### Static files
-The `NotFound` handler can for example be used to serve static files from the root path `/` (like an index.html file along with other assets):
-```go
-// Serve static files from the ./public directory
-router.NotFound = http.FileServer(http.Dir("public")).ServeHTTP
-```
-
-But this approach sidesteps the strict core rules of this router to avoid routing problems. A cleaner approach is to use a distinct sub-path for serving files, like `/static/*filepath` or `/files/*filepath`.
-
-## Web Frameworks based on HttpRouter
-If the HttpRouter is a bit too minimalistic for you, you might try one of the following more high-level 3rd-party web frameworks building upon the HttpRouter package:
-* [Ace](https://github.com/plimble/ace): Blazing fast Go Web Framework
-* [api2go](https://github.com/univedo/api2go): A JSON API Implementation for Go
-* [Gin](https://github.com/gin-gonic/gin): Features a martini-like API with much better performance
-* [Goat](https://github.com/bahlo/goat): A minimalistic REST API server in Go
-* [Hikaru](https://github.com/najeira/hikaru): Supports standalone and Google AppEngine
-* [Hitch](https://github.com/nbio/hitch): Hitch ties httprouter, [httpcontext](https://github.com/nbio/httpcontext), and middleware up in a bow
-* [kami](https://github.com/guregu/kami): A tiny web framework using x/net/context
-* [Medeina](https://github.com/imdario/medeina): Inspired by Ruby's Roda and Cuba
-* [Neko](https://github.com/rocwong/neko): A lightweight web application framework for Golang
-* [Roxanna](https://github.com/iamthemuffinman/Roxanna): An amalgamation of httprouter, better logging, and hot reload
-* [siesta](https://github.com/VividCortex/siesta): Composable HTTP handlers with contexts
diff --git a/Godeps/_workspace/src/github.com/julienschmidt/httprouter/path.go b/Godeps/_workspace/src/github.com/julienschmidt/httprouter/path.go
deleted file mode 100644
index 486134db37..0000000000
--- a/Godeps/_workspace/src/github.com/julienschmidt/httprouter/path.go
+++ /dev/null
@@ -1,123 +0,0 @@
-// Copyright 2013 Julien Schmidt. All rights reserved.
-// Based on the path package, Copyright 2009 The Go Authors.
-// Use of this source code is governed by a BSD-style license that can be found
-// in the LICENSE file.
-
-package httprouter
-
-// CleanPath is the URL version of path.Clean, it returns a canonical URL path
-// for p, eliminating . and .. elements.
-//
-// The following rules are applied iteratively until no further processing can
-// be done:
-// 1. Replace multiple slashes with a single slash.
-// 2. Eliminate each . path name element (the current directory).
-// 3. Eliminate each inner .. path name element (the parent directory)
-// along with the non-.. element that precedes it.
-// 4. Eliminate .. elements that begin a rooted path:
-// that is, replace "/.." by "/" at the beginning of a path.
-//
-// If the result of this process is an empty string, "/" is returned
-func CleanPath(p string) string {
- // Turn empty string into "/"
- if p == "" {
- return "/"
- }
-
- n := len(p)
- var buf []byte
-
- // Invariants:
- // reading from path; r is index of next byte to process.
- // writing to buf; w is index of next byte to write.
-
- // path must start with '/'
- r := 1
- w := 1
-
- if p[0] != '/' {
- r = 0
- buf = make([]byte, n+1)
- buf[0] = '/'
- }
-
- trailing := n > 2 && p[n-1] == '/'
-
- // A bit more clunky without a 'lazybuf' like the path package, but the loop
- // gets completely inlined (bufApp). So in contrast to the path package this
- // loop has no expensive function calls (except 1x make)
-
- for r < n {
- switch {
- case p[r] == '/':
- // empty path element, trailing slash is added after the end
- r++
-
- case p[r] == '.' && r+1 == n:
- trailing = true
- r++
-
- case p[r] == '.' && p[r+1] == '/':
- // . element
- r++
-
- case p[r] == '.' && p[r+1] == '.' && (r+2 == n || p[r+2] == '/'):
- // .. element: remove to last /
- r += 2
-
- if w > 1 {
- // can backtrack
- w--
-
- if buf == nil {
- for w > 1 && p[w] != '/' {
- w--
- }
- } else {
- for w > 1 && buf[w] != '/' {
- w--
- }
- }
- }
-
- default:
- // real path element.
- // add slash if needed
- if w > 1 {
- bufApp(&buf, p, w, '/')
- w++
- }
-
- // copy element
- for r < n && p[r] != '/' {
- bufApp(&buf, p, w, p[r])
- w++
- r++
- }
- }
- }
-
- // re-append trailing slash
- if trailing && w > 1 {
- bufApp(&buf, p, w, '/')
- w++
- }
-
- if buf == nil {
- return p[:w]
- }
- return string(buf[:w])
-}
-
-// internal helper to lazily create a buffer if necessary
-func bufApp(buf *[]byte, s string, w int, c byte) {
- if *buf == nil {
- if s[w] == c {
- return
- }
-
- *buf = make([]byte, len(s))
- copy(*buf, s[:w])
- }
- (*buf)[w] = c
-}
diff --git a/Godeps/_workspace/src/github.com/julienschmidt/httprouter/path_test.go b/Godeps/_workspace/src/github.com/julienschmidt/httprouter/path_test.go
deleted file mode 100644
index c4ceda5da2..0000000000
--- a/Godeps/_workspace/src/github.com/julienschmidt/httprouter/path_test.go
+++ /dev/null
@@ -1,92 +0,0 @@
-// Copyright 2013 Julien Schmidt. All rights reserved.
-// Based on the path package, Copyright 2009 The Go Authors.
-// Use of this source code is governed by a BSD-style license that can be found
-// in the LICENSE file.
-
-package httprouter
-
-import (
- "runtime"
- "testing"
-)
-
-var cleanTests = []struct {
- path, result string
-}{
- // Already clean
- {"/", "/"},
- {"/abc", "/abc"},
- {"/a/b/c", "/a/b/c"},
- {"/abc/", "/abc/"},
- {"/a/b/c/", "/a/b/c/"},
-
- // missing root
- {"", "/"},
- {"abc", "/abc"},
- {"abc/def", "/abc/def"},
- {"a/b/c", "/a/b/c"},
-
- // Remove doubled slash
- {"//", "/"},
- {"/abc//", "/abc/"},
- {"/abc/def//", "/abc/def/"},
- {"/a/b/c//", "/a/b/c/"},
- {"/abc//def//ghi", "/abc/def/ghi"},
- {"//abc", "/abc"},
- {"///abc", "/abc"},
- {"//abc//", "/abc/"},
-
- // Remove . elements
- {".", "/"},
- {"./", "/"},
- {"/abc/./def", "/abc/def"},
- {"/./abc/def", "/abc/def"},
- {"/abc/.", "/abc/"},
-
- // Remove .. elements
- {"..", "/"},
- {"../", "/"},
- {"../../", "/"},
- {"../..", "/"},
- {"../../abc", "/abc"},
- {"/abc/def/ghi/../jkl", "/abc/def/jkl"},
- {"/abc/def/../ghi/../jkl", "/abc/jkl"},
- {"/abc/def/..", "/abc"},
- {"/abc/def/../..", "/"},
- {"/abc/def/../../..", "/"},
- {"/abc/def/../../..", "/"},
- {"/abc/def/../../../ghi/jkl/../../../mno", "/mno"},
-
- // Combinations
- {"abc/./../def", "/def"},
- {"abc//./../def", "/def"},
- {"abc/../../././../def", "/def"},
-}
-
-func TestPathClean(t *testing.T) {
- for _, test := range cleanTests {
- if s := CleanPath(test.path); s != test.result {
- t.Errorf("CleanPath(%q) = %q, want %q", test.path, s, test.result)
- }
- if s := CleanPath(test.result); s != test.result {
- t.Errorf("CleanPath(%q) = %q, want %q", test.result, s, test.result)
- }
- }
-}
-
-func TestPathCleanMallocs(t *testing.T) {
- if testing.Short() {
- t.Skip("skipping malloc count in short mode")
- }
- if runtime.GOMAXPROCS(0) > 1 {
- t.Log("skipping AllocsPerRun checks; GOMAXPROCS>1")
- return
- }
-
- for _, test := range cleanTests {
- allocs := testing.AllocsPerRun(100, func() { CleanPath(test.result) })
- if allocs > 0 {
- t.Errorf("CleanPath(%q): %v allocs, want zero", test.result, allocs)
- }
- }
-}
diff --git a/Godeps/_workspace/src/github.com/julienschmidt/httprouter/router.go b/Godeps/_workspace/src/github.com/julienschmidt/httprouter/router.go
deleted file mode 100644
index 8b5ff34687..0000000000
--- a/Godeps/_workspace/src/github.com/julienschmidt/httprouter/router.go
+++ /dev/null
@@ -1,363 +0,0 @@
-// Copyright 2013 Julien Schmidt. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be found
-// in the LICENSE file.
-
-// Package httprouter is a trie based high performance HTTP request router.
-//
-// A trivial example is:
-//
-// package main
-//
-// import (
-// "fmt"
-// "github.com/julienschmidt/httprouter"
-// "net/http"
-// "log"
-// )
-//
-// func Index(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
-// fmt.Fprint(w, "Welcome!\n")
-// }
-//
-// func Hello(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
-// fmt.Fprintf(w, "hello, %s!\n", ps.ByName("name"))
-// }
-//
-// func main() {
-// router := httprouter.New()
-// router.GET("/", Index)
-// router.GET("/hello/:name", Hello)
-//
-// log.Fatal(http.ListenAndServe(":8080", router))
-// }
-//
-// The router matches incoming requests by the request method and the path.
-// If a handle is registered for this path and method, the router delegates the
-// request to that function.
-// For the methods GET, POST, PUT, PATCH and DELETE shortcut functions exist to
-// register handles, for all other methods router.Handle can be used.
-//
-// The registered path, against which the router matches incoming requests, can
-// contain two types of parameters:
-// Syntax Type
-// :name named parameter
-// *name catch-all parameter
-//
-// Named parameters are dynamic path segments. They match anything until the
-// next '/' or the path end:
-// Path: /blog/:category/:post
-//
-// Requests:
-// /blog/go/request-routers match: category="go", post="request-routers"
-// /blog/go/request-routers/ no match, but the router would redirect
-// /blog/go/ no match
-// /blog/go/request-routers/comments no match
-//
-// Catch-all parameters match anything until the path end, including the
-// directory index (the '/' before the catch-all). Since they match anything
-// until the end, catch-all parameters must always be the final path element.
-// Path: /files/*filepath
-//
-// Requests:
-// /files/ match: filepath="/"
-// /files/LICENSE match: filepath="/LICENSE"
-// /files/templates/article.html match: filepath="/templates/article.html"
-// /files no match, but the router would redirect
-//
-// The value of parameters is saved as a slice of the Param struct, consisting
-// each of a key and a value. The slice is passed to the Handle func as a third
-// parameter.
-// There are two ways to retrieve the value of a parameter:
-// // by the name of the parameter
-// user := ps.ByName("user") // defined by :user or *user
-//
-// // by the index of the parameter. This way you can also get the name (key)
-// thirdKey := ps[2].Key // the name of the 3rd parameter
-// thirdValue := ps[2].Value // the value of the 3rd parameter
-package httprouter
-
-import (
- "net/http"
-)
-
-// Handle is a function that can be registered to a route to handle HTTP
-// requests. Like http.HandlerFunc, but has a third parameter for the values of
-// wildcards (variables).
-type Handle func(http.ResponseWriter, *http.Request, Params)
-
-// Param is a single URL parameter, consisting of a key and a value.
-type Param struct {
- Key string
- Value string
-}
-
-// Params is a Param-slice, as returned by the router.
-// The slice is ordered, the first URL parameter is also the first slice value.
-// It is therefore safe to read values by the index.
-type Params []Param
-
-// ByName returns the value of the first Param which key matches the given name.
-// If no matching Param is found, an empty string is returned.
-func (ps Params) ByName(name string) string {
- for i := range ps {
- if ps[i].Key == name {
- return ps[i].Value
- }
- }
- return ""
-}
-
-// Router is a http.Handler which can be used to dispatch requests to different
-// handler functions via configurable routes
-type Router struct {
- trees map[string]*node
-
- // Enables automatic redirection if the current route can't be matched but a
- // handler for the path with (without) the trailing slash exists.
- // For example if /foo/ is requested but a route only exists for /foo, the
- // client is redirected to /foo with http status code 301 for GET requests
- // and 307 for all other request methods.
- RedirectTrailingSlash bool
-
- // If enabled, the router tries to fix the current request path, if no
- // handle is registered for it.
- // First superfluous path elements like ../ or // are removed.
- // Afterwards the router does a case-insensitive lookup of the cleaned path.
- // If a handle can be found for this route, the router makes a redirection
- // to the corrected path with status code 301 for GET requests and 307 for
- // all other request methods.
- // For example /FOO and /..//Foo could be redirected to /foo.
- // RedirectTrailingSlash is independent of this option.
- RedirectFixedPath bool
-
- // If enabled, the router checks if another method is allowed for the
- // current route, if the current request can not be routed.
- // If this is the case, the request is answered with 'Method Not Allowed'
- // and HTTP status code 405.
- // If no other Method is allowed, the request is delegated to the NotFound
- // handler.
- HandleMethodNotAllowed bool
-
- // Configurable http.Handler which is called when no matching route is
- // found. If it is not set, http.NotFound is used.
- NotFound http.Handler
-
- // Configurable http.Handler which is called when a request
- // cannot be routed and HandleMethodNotAllowed is true.
- // If it is not set, http.Error with http.StatusMethodNotAllowed is used.
- MethodNotAllowed http.Handler
-
- // Function to handle panics recovered from http handlers.
- // It should be used to generate a error page and return the http error code
- // 500 (Internal Server Error).
- // The handler can be used to keep your server from crashing because of
- // unrecovered panics.
- PanicHandler func(http.ResponseWriter, *http.Request, interface{})
-}
-
-// Make sure the Router conforms with the http.Handler interface
-var _ http.Handler = New()
-
-// New returns a new initialized Router.
-// Path auto-correction, including trailing slashes, is enabled by default.
-func New() *Router {
- return &Router{
- RedirectTrailingSlash: true,
- RedirectFixedPath: true,
- HandleMethodNotAllowed: true,
- }
-}
-
-// GET is a shortcut for router.Handle("GET", path, handle)
-func (r *Router) GET(path string, handle Handle) {
- r.Handle("GET", path, handle)
-}
-
-// HEAD is a shortcut for router.Handle("HEAD", path, handle)
-func (r *Router) HEAD(path string, handle Handle) {
- r.Handle("HEAD", path, handle)
-}
-
-// OPTIONS is a shortcut for router.Handle("OPTIONS", path, handle)
-func (r *Router) OPTIONS(path string, handle Handle) {
- r.Handle("OPTIONS", path, handle)
-}
-
-// POST is a shortcut for router.Handle("POST", path, handle)
-func (r *Router) POST(path string, handle Handle) {
- r.Handle("POST", path, handle)
-}
-
-// PUT is a shortcut for router.Handle("PUT", path, handle)
-func (r *Router) PUT(path string, handle Handle) {
- r.Handle("PUT", path, handle)
-}
-
-// PATCH is a shortcut for router.Handle("PATCH", path, handle)
-func (r *Router) PATCH(path string, handle Handle) {
- r.Handle("PATCH", path, handle)
-}
-
-// DELETE is a shortcut for router.Handle("DELETE", path, handle)
-func (r *Router) DELETE(path string, handle Handle) {
- r.Handle("DELETE", path, handle)
-}
-
-// Handle registers a new request handle with the given path and method.
-//
-// For GET, POST, PUT, PATCH and DELETE requests the respective shortcut
-// functions can be used.
-//
-// This function is intended for bulk loading and to allow the usage of less
-// frequently used, non-standardized or custom methods (e.g. for internal
-// communication with a proxy).
-func (r *Router) Handle(method, path string, handle Handle) {
- if path[0] != '/' {
- panic("path must begin with '/' in path '" + path + "'")
- }
-
- if r.trees == nil {
- r.trees = make(map[string]*node)
- }
-
- root := r.trees[method]
- if root == nil {
- root = new(node)
- r.trees[method] = root
- }
-
- root.addRoute(path, handle)
-}
-
-// Handler is an adapter which allows the usage of an http.Handler as a
-// request handle.
-func (r *Router) Handler(method, path string, handler http.Handler) {
- r.Handle(method, path,
- func(w http.ResponseWriter, req *http.Request, _ Params) {
- handler.ServeHTTP(w, req)
- },
- )
-}
-
-// HandlerFunc is an adapter which allows the usage of an http.HandlerFunc as a
-// request handle.
-func (r *Router) HandlerFunc(method, path string, handler http.HandlerFunc) {
- r.Handler(method, path, handler)
-}
-
-// ServeFiles serves files from the given file system root.
-// The path must end with "/*filepath", files are then served from the local
-// path /defined/root/dir/*filepath.
-// For example if root is "/etc" and *filepath is "passwd", the local file
-// "/etc/passwd" would be served.
-// Internally a http.FileServer is used, therefore http.NotFound is used instead
-// of the Router's NotFound handler.
-// To use the operating system's file system implementation,
-// use http.Dir:
-// router.ServeFiles("/src/*filepath", http.Dir("/var/www"))
-func (r *Router) ServeFiles(path string, root http.FileSystem) {
- if len(path) < 10 || path[len(path)-10:] != "/*filepath" {
- panic("path must end with /*filepath in path '" + path + "'")
- }
-
- fileServer := http.FileServer(root)
-
- r.GET(path, func(w http.ResponseWriter, req *http.Request, ps Params) {
- req.URL.Path = ps.ByName("filepath")
- fileServer.ServeHTTP(w, req)
- })
-}
-
-func (r *Router) recv(w http.ResponseWriter, req *http.Request) {
- if rcv := recover(); rcv != nil {
- r.PanicHandler(w, req, rcv)
- }
-}
-
-// Lookup allows the manual lookup of a method + path combo.
-// This is e.g. useful to build a framework around this router.
-// If the path was found, it returns the handle function and the path parameter
-// values. Otherwise the third return value indicates whether a redirection to
-// the same path with an extra / without the trailing slash should be performed.
-func (r *Router) Lookup(method, path string) (Handle, Params, bool) {
- if root := r.trees[method]; root != nil {
- return root.getValue(path)
- }
- return nil, nil, false
-}
-
-// ServeHTTP makes the router implement the http.Handler interface.
-func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
- if r.PanicHandler != nil {
- defer r.recv(w, req)
- }
-
- if root := r.trees[req.Method]; root != nil {
- path := req.URL.Path
-
- if handle, ps, tsr := root.getValue(path); handle != nil {
- handle(w, req, ps)
- return
- } else if req.Method != "CONNECT" && path != "/" {
- code := 301 // Permanent redirect, request with GET method
- if req.Method != "GET" {
- // Temporary redirect, request with same method
- // As of Go 1.3, Go does not support status code 308.
- code = 307
- }
-
- if tsr && r.RedirectTrailingSlash {
- if len(path) > 1 && path[len(path)-1] == '/' {
- req.URL.Path = path[:len(path)-1]
- } else {
- req.URL.Path = path + "/"
- }
- http.Redirect(w, req, req.URL.String(), code)
- return
- }
-
- // Try to fix the request path
- if r.RedirectFixedPath {
- fixedPath, found := root.findCaseInsensitivePath(
- CleanPath(path),
- r.RedirectTrailingSlash,
- )
- if found {
- req.URL.Path = string(fixedPath)
- http.Redirect(w, req, req.URL.String(), code)
- return
- }
- }
- }
- }
-
- // Handle 405
- if r.HandleMethodNotAllowed {
- for method := range r.trees {
- // Skip the requested method - we already tried this one
- if method == req.Method {
- continue
- }
-
- handle, _, _ := r.trees[method].getValue(req.URL.Path)
- if handle != nil {
- if r.MethodNotAllowed != nil {
- r.MethodNotAllowed.ServeHTTP(w, req)
- } else {
- http.Error(w,
- http.StatusText(http.StatusMethodNotAllowed),
- http.StatusMethodNotAllowed,
- )
- }
- return
- }
- }
- }
-
- // Handle 404
- if r.NotFound != nil {
- r.NotFound.ServeHTTP(w, req)
- } else {
- http.NotFound(w, req)
- }
-}
diff --git a/Godeps/_workspace/src/github.com/julienschmidt/httprouter/router_test.go b/Godeps/_workspace/src/github.com/julienschmidt/httprouter/router_test.go
deleted file mode 100644
index e3141bd281..0000000000
--- a/Godeps/_workspace/src/github.com/julienschmidt/httprouter/router_test.go
+++ /dev/null
@@ -1,420 +0,0 @@
-// Copyright 2013 Julien Schmidt. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be found
-// in the LICENSE file.
-
-package httprouter
-
-import (
- "errors"
- "fmt"
- "net/http"
- "net/http/httptest"
- "reflect"
- "testing"
-)
-
-type mockResponseWriter struct{}
-
-func (m *mockResponseWriter) Header() (h http.Header) {
- return http.Header{}
-}
-
-func (m *mockResponseWriter) Write(p []byte) (n int, err error) {
- return len(p), nil
-}
-
-func (m *mockResponseWriter) WriteString(s string) (n int, err error) {
- return len(s), nil
-}
-
-func (m *mockResponseWriter) WriteHeader(int) {}
-
-func TestParams(t *testing.T) {
- ps := Params{
- Param{"param1", "value1"},
- Param{"param2", "value2"},
- Param{"param3", "value3"},
- }
- for i := range ps {
- if val := ps.ByName(ps[i].Key); val != ps[i].Value {
- t.Errorf("Wrong value for %s: Got %s; Want %s", ps[i].Key, val, ps[i].Value)
- }
- }
- if val := ps.ByName("noKey"); val != "" {
- t.Errorf("Expected empty string for not found key; got: %s", val)
- }
-}
-
-func TestRouter(t *testing.T) {
- router := New()
-
- routed := false
- router.Handle("GET", "/user/:name", func(w http.ResponseWriter, r *http.Request, ps Params) {
- routed = true
- want := Params{Param{"name", "gopher"}}
- if !reflect.DeepEqual(ps, want) {
- t.Fatalf("wrong wildcard values: want %v, got %v", want, ps)
- }
- })
-
- w := new(mockResponseWriter)
-
- req, _ := http.NewRequest("GET", "/user/gopher", nil)
- router.ServeHTTP(w, req)
-
- if !routed {
- t.Fatal("routing failed")
- }
-}
-
-type handlerStruct struct {
- handeled *bool
-}
-
-func (h handlerStruct) ServeHTTP(w http.ResponseWriter, r *http.Request) {
- *h.handeled = true
-}
-
-func TestRouterAPI(t *testing.T) {
- var get, head, options, post, put, patch, delete, handler, handlerFunc bool
-
- httpHandler := handlerStruct{&handler}
-
- router := New()
- router.GET("/GET", func(w http.ResponseWriter, r *http.Request, _ Params) {
- get = true
- })
- router.HEAD("/GET", func(w http.ResponseWriter, r *http.Request, _ Params) {
- head = true
- })
- router.OPTIONS("/GET", func(w http.ResponseWriter, r *http.Request, _ Params) {
- options = true
- })
- router.POST("/POST", func(w http.ResponseWriter, r *http.Request, _ Params) {
- post = true
- })
- router.PUT("/PUT", func(w http.ResponseWriter, r *http.Request, _ Params) {
- put = true
- })
- router.PATCH("/PATCH", func(w http.ResponseWriter, r *http.Request, _ Params) {
- patch = true
- })
- router.DELETE("/DELETE", func(w http.ResponseWriter, r *http.Request, _ Params) {
- delete = true
- })
- router.Handler("GET", "/Handler", httpHandler)
- router.HandlerFunc("GET", "/HandlerFunc", func(w http.ResponseWriter, r *http.Request) {
- handlerFunc = true
- })
-
- w := new(mockResponseWriter)
-
- r, _ := http.NewRequest("GET", "/GET", nil)
- router.ServeHTTP(w, r)
- if !get {
- t.Error("routing GET failed")
- }
-
- r, _ = http.NewRequest("HEAD", "/GET", nil)
- router.ServeHTTP(w, r)
- if !head {
- t.Error("routing HEAD failed")
- }
-
- r, _ = http.NewRequest("OPTIONS", "/GET", nil)
- router.ServeHTTP(w, r)
- if !options {
- t.Error("routing OPTIONS failed")
- }
-
- r, _ = http.NewRequest("POST", "/POST", nil)
- router.ServeHTTP(w, r)
- if !post {
- t.Error("routing POST failed")
- }
-
- r, _ = http.NewRequest("PUT", "/PUT", nil)
- router.ServeHTTP(w, r)
- if !put {
- t.Error("routing PUT failed")
- }
-
- r, _ = http.NewRequest("PATCH", "/PATCH", nil)
- router.ServeHTTP(w, r)
- if !patch {
- t.Error("routing PATCH failed")
- }
-
- r, _ = http.NewRequest("DELETE", "/DELETE", nil)
- router.ServeHTTP(w, r)
- if !delete {
- t.Error("routing DELETE failed")
- }
-
- r, _ = http.NewRequest("GET", "/Handler", nil)
- router.ServeHTTP(w, r)
- if !handler {
- t.Error("routing Handler failed")
- }
-
- r, _ = http.NewRequest("GET", "/HandlerFunc", nil)
- router.ServeHTTP(w, r)
- if !handlerFunc {
- t.Error("routing HandlerFunc failed")
- }
-}
-
-func TestRouterRoot(t *testing.T) {
- router := New()
- recv := catchPanic(func() {
- router.GET("noSlashRoot", nil)
- })
- if recv == nil {
- t.Fatal("registering path not beginning with '/' did not panic")
- }
-}
-
-func TestRouterChaining(t *testing.T) {
- router1 := New()
- router2 := New()
- router1.NotFound = router2
-
- fooHit := false
- router1.POST("/foo", func(w http.ResponseWriter, req *http.Request, _ Params) {
- fooHit = true
- w.WriteHeader(http.StatusOK)
- })
-
- barHit := false
- router2.POST("/bar", func(w http.ResponseWriter, req *http.Request, _ Params) {
- barHit = true
- w.WriteHeader(http.StatusOK)
- })
-
- r, _ := http.NewRequest("POST", "/foo", nil)
- w := httptest.NewRecorder()
- router1.ServeHTTP(w, r)
- if !(w.Code == http.StatusOK && fooHit) {
- t.Errorf("Regular routing failed with router chaining.")
- t.FailNow()
- }
-
- r, _ = http.NewRequest("POST", "/bar", nil)
- w = httptest.NewRecorder()
- router1.ServeHTTP(w, r)
- if !(w.Code == http.StatusOK && barHit) {
- t.Errorf("Chained routing failed with router chaining.")
- t.FailNow()
- }
-
- r, _ = http.NewRequest("POST", "/qax", nil)
- w = httptest.NewRecorder()
- router1.ServeHTTP(w, r)
- if !(w.Code == http.StatusNotFound) {
- t.Errorf("NotFound behavior failed with router chaining.")
- t.FailNow()
- }
-}
-
-func TestRouterNotAllowed(t *testing.T) {
- handlerFunc := func(_ http.ResponseWriter, _ *http.Request, _ Params) {}
-
- router := New()
- router.POST("/path", handlerFunc)
-
- // Test not allowed
- r, _ := http.NewRequest("GET", "/path", nil)
- w := httptest.NewRecorder()
- router.ServeHTTP(w, r)
- if !(w.Code == http.StatusMethodNotAllowed) {
- t.Errorf("NotAllowed handling failed: Code=%d, Header=%v", w.Code, w.Header())
- }
-
- w = httptest.NewRecorder()
- responseText := "custom method"
- router.MethodNotAllowed = http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
- w.WriteHeader(http.StatusTeapot)
- w.Write([]byte(responseText))
- })
- router.ServeHTTP(w, r)
- if got := w.Body.String(); !(got == responseText) {
- t.Errorf("unexpected response got %q want %q", got, responseText)
- }
- if w.Code != http.StatusTeapot {
- t.Errorf("unexpected response code %d want %d", w.Code, http.StatusTeapot)
- }
-}
-
-func TestRouterNotFound(t *testing.T) {
- handlerFunc := func(_ http.ResponseWriter, _ *http.Request, _ Params) {}
-
- router := New()
- router.GET("/path", handlerFunc)
- router.GET("/dir/", handlerFunc)
- router.GET("/", handlerFunc)
-
- testRoutes := []struct {
- route string
- code int
- header string
- }{
- {"/path/", 301, "map[Location:[/path]]"}, // TSR -/
- {"/dir", 301, "map[Location:[/dir/]]"}, // TSR +/
- {"", 301, "map[Location:[/]]"}, // TSR +/
- {"/PATH", 301, "map[Location:[/path]]"}, // Fixed Case
- {"/DIR/", 301, "map[Location:[/dir/]]"}, // Fixed Case
- {"/PATH/", 301, "map[Location:[/path]]"}, // Fixed Case -/
- {"/DIR", 301, "map[Location:[/dir/]]"}, // Fixed Case +/
- {"/../path", 301, "map[Location:[/path]]"}, // CleanPath
- {"/nope", 404, ""}, // NotFound
- }
- for _, tr := range testRoutes {
- r, _ := http.NewRequest("GET", tr.route, nil)
- w := httptest.NewRecorder()
- router.ServeHTTP(w, r)
- if !(w.Code == tr.code && (w.Code == 404 || fmt.Sprint(w.Header()) == tr.header)) {
- t.Errorf("NotFound handling route %s failed: Code=%d, Header=%v", tr.route, w.Code, w.Header())
- }
- }
-
- // Test custom not found handler
- var notFound bool
- router.NotFound = http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
- rw.WriteHeader(404)
- notFound = true
- })
- r, _ := http.NewRequest("GET", "/nope", nil)
- w := httptest.NewRecorder()
- router.ServeHTTP(w, r)
- if !(w.Code == 404 && notFound == true) {
- t.Errorf("Custom NotFound handler failed: Code=%d, Header=%v", w.Code, w.Header())
- }
-
- // Test other method than GET (want 307 instead of 301)
- router.PATCH("/path", handlerFunc)
- r, _ = http.NewRequest("PATCH", "/path/", nil)
- w = httptest.NewRecorder()
- router.ServeHTTP(w, r)
- if !(w.Code == 307 && fmt.Sprint(w.Header()) == "map[Location:[/path]]") {
- t.Errorf("Custom NotFound handler failed: Code=%d, Header=%v", w.Code, w.Header())
- }
-
- // Test special case where no node for the prefix "/" exists
- router = New()
- router.GET("/a", handlerFunc)
- r, _ = http.NewRequest("GET", "/", nil)
- w = httptest.NewRecorder()
- router.ServeHTTP(w, r)
- if !(w.Code == 404) {
- t.Errorf("NotFound handling route / failed: Code=%d", w.Code)
- }
-}
-
-func TestRouterPanicHandler(t *testing.T) {
- router := New()
- panicHandled := false
-
- router.PanicHandler = func(rw http.ResponseWriter, r *http.Request, p interface{}) {
- panicHandled = true
- }
-
- router.Handle("PUT", "/user/:name", func(_ http.ResponseWriter, _ *http.Request, _ Params) {
- panic("oops!")
- })
-
- w := new(mockResponseWriter)
- req, _ := http.NewRequest("PUT", "/user/gopher", nil)
-
- defer func() {
- if rcv := recover(); rcv != nil {
- t.Fatal("handling panic failed")
- }
- }()
-
- router.ServeHTTP(w, req)
-
- if !panicHandled {
- t.Fatal("simulating failed")
- }
-}
-
-func TestRouterLookup(t *testing.T) {
- routed := false
- wantHandle := func(_ http.ResponseWriter, _ *http.Request, _ Params) {
- routed = true
- }
- wantParams := Params{Param{"name", "gopher"}}
-
- router := New()
-
- // try empty router first
- handle, _, tsr := router.Lookup("GET", "/nope")
- if handle != nil {
- t.Fatalf("Got handle for unregistered pattern: %v", handle)
- }
- if tsr {
- t.Error("Got wrong TSR recommendation!")
- }
-
- // insert route and try again
- router.GET("/user/:name", wantHandle)
-
- handle, params, tsr := router.Lookup("GET", "/user/gopher")
- if handle == nil {
- t.Fatal("Got no handle!")
- } else {
- handle(nil, nil, nil)
- if !routed {
- t.Fatal("Routing failed!")
- }
- }
-
- if !reflect.DeepEqual(params, wantParams) {
- t.Fatalf("Wrong parameter values: want %v, got %v", wantParams, params)
- }
-
- handle, _, tsr = router.Lookup("GET", "/user/gopher/")
- if handle != nil {
- t.Fatalf("Got handle for unregistered pattern: %v", handle)
- }
- if !tsr {
- t.Error("Got no TSR recommendation!")
- }
-
- handle, _, tsr = router.Lookup("GET", "/nope")
- if handle != nil {
- t.Fatalf("Got handle for unregistered pattern: %v", handle)
- }
- if tsr {
- t.Error("Got wrong TSR recommendation!")
- }
-}
-
-type mockFileSystem struct {
- opened bool
-}
-
-func (mfs *mockFileSystem) Open(name string) (http.File, error) {
- mfs.opened = true
- return nil, errors.New("this is just a mock")
-}
-
-func TestRouterServeFiles(t *testing.T) {
- router := New()
- mfs := &mockFileSystem{}
-
- recv := catchPanic(func() {
- router.ServeFiles("/noFilepath", mfs)
- })
- if recv == nil {
- t.Fatal("registering path not ending with '*filepath' did not panic")
- }
-
- router.ServeFiles("/*filepath", mfs)
- w := new(mockResponseWriter)
- r, _ := http.NewRequest("GET", "/favicon.ico", nil)
- router.ServeHTTP(w, r)
- if !mfs.opened {
- t.Error("serving file failed")
- }
-}
diff --git a/Godeps/_workspace/src/github.com/julienschmidt/httprouter/tree.go b/Godeps/_workspace/src/github.com/julienschmidt/httprouter/tree.go
deleted file mode 100644
index a15bc2cbc3..0000000000
--- a/Godeps/_workspace/src/github.com/julienschmidt/httprouter/tree.go
+++ /dev/null
@@ -1,555 +0,0 @@
-// Copyright 2013 Julien Schmidt. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be found
-// in the LICENSE file.
-
-package httprouter
-
-import (
- "strings"
- "unicode"
-)
-
-func min(a, b int) int {
- if a <= b {
- return a
- }
- return b
-}
-
-func countParams(path string) uint8 {
- var n uint
- for i := 0; i < len(path); i++ {
- if path[i] != ':' && path[i] != '*' {
- continue
- }
- n++
- }
- if n >= 255 {
- return 255
- }
- return uint8(n)
-}
-
-type nodeType uint8
-
-const (
- static nodeType = 0
- param nodeType = 1
- catchAll nodeType = 2
-)
-
-type node struct {
- path string
- wildChild bool
- nType nodeType
- maxParams uint8
- indices string
- children []*node
- handle Handle
- priority uint32
-}
-
-// increments priority of the given child and reorders if necessary
-func (n *node) incrementChildPrio(pos int) int {
- n.children[pos].priority++
- prio := n.children[pos].priority
-
- // adjust position (move to front)
- newPos := pos
- for newPos > 0 && n.children[newPos-1].priority < prio {
- // swap node positions
- tmpN := n.children[newPos-1]
- n.children[newPos-1] = n.children[newPos]
- n.children[newPos] = tmpN
-
- newPos--
- }
-
- // build new index char string
- if newPos != pos {
- n.indices = n.indices[:newPos] + // unchanged prefix, might be empty
- n.indices[pos:pos+1] + // the index char we move
- n.indices[newPos:pos] + n.indices[pos+1:] // rest without char at 'pos'
- }
-
- return newPos
-}
-
-// addRoute adds a node with the given handle to the path.
-// Not concurrency-safe!
-func (n *node) addRoute(path string, handle Handle) {
- fullPath := path
- n.priority++
- numParams := countParams(path)
-
- // non-empty tree
- if len(n.path) > 0 || len(n.children) > 0 {
- walk:
- for {
- // Update maxParams of the current node
- if numParams > n.maxParams {
- n.maxParams = numParams
- }
-
- // Find the longest common prefix.
- // This also implies that the common prefix contains no ':' or '*'
- // since the existing key can't contain those chars.
- i := 0
- max := min(len(path), len(n.path))
- for i < max && path[i] == n.path[i] {
- i++
- }
-
- // Split edge
- if i < len(n.path) {
- child := node{
- path: n.path[i:],
- wildChild: n.wildChild,
- indices: n.indices,
- children: n.children,
- handle: n.handle,
- priority: n.priority - 1,
- }
-
- // Update maxParams (max of all children)
- for i := range child.children {
- if child.children[i].maxParams > child.maxParams {
- child.maxParams = child.children[i].maxParams
- }
- }
-
- n.children = []*node{&child}
- // []byte for proper unicode char conversion, see #65
- n.indices = string([]byte{n.path[i]})
- n.path = path[:i]
- n.handle = nil
- n.wildChild = false
- }
-
- // Make new node a child of this node
- if i < len(path) {
- path = path[i:]
-
- if n.wildChild {
- n = n.children[0]
- n.priority++
-
- // Update maxParams of the child node
- if numParams > n.maxParams {
- n.maxParams = numParams
- }
- numParams--
-
- // Check if the wildcard matches
- if len(path) >= len(n.path) && n.path == path[:len(n.path)] {
- // check for longer wildcard, e.g. :name and :names
- if len(n.path) >= len(path) || path[len(n.path)] == '/' {
- continue walk
- }
- }
-
- panic("path segment '" + path +
- "' conflicts with existing wildcard '" + n.path +
- "' in path '" + fullPath + "'")
- }
-
- c := path[0]
-
- // slash after param
- if n.nType == param && c == '/' && len(n.children) == 1 {
- n = n.children[0]
- n.priority++
- continue walk
- }
-
- // Check if a child with the next path byte exists
- for i := 0; i < len(n.indices); i++ {
- if c == n.indices[i] {
- i = n.incrementChildPrio(i)
- n = n.children[i]
- continue walk
- }
- }
-
- // Otherwise insert it
- if c != ':' && c != '*' {
- // []byte for proper unicode char conversion, see #65
- n.indices += string([]byte{c})
- child := &node{
- maxParams: numParams,
- }
- n.children = append(n.children, child)
- n.incrementChildPrio(len(n.indices) - 1)
- n = child
- }
- n.insertChild(numParams, path, fullPath, handle)
- return
-
- } else if i == len(path) { // Make node a (in-path) leaf
- if n.handle != nil {
- panic("a handle is already registered for path ''" + fullPath + "'")
- }
- n.handle = handle
- }
- return
- }
- } else { // Empty tree
- n.insertChild(numParams, path, fullPath, handle)
- }
-}
-
-func (n *node) insertChild(numParams uint8, path, fullPath string, handle Handle) {
- var offset int // already handled bytes of the path
-
- // find prefix until first wildcard (beginning with ':'' or '*'')
- for i, max := 0, len(path); numParams > 0; i++ {
- c := path[i]
- if c != ':' && c != '*' {
- continue
- }
-
- // find wildcard end (either '/' or path end)
- end := i + 1
- for end < max && path[end] != '/' {
- switch path[end] {
- // the wildcard name must not contain ':' and '*'
- case ':', '*':
- panic("only one wildcard per path segment is allowed, has: '" +
- path[i:] + "' in path '" + fullPath + "'")
- default:
- end++
- }
- }
-
- // check if this Node existing children which would be
- // unreachable if we insert the wildcard here
- if len(n.children) > 0 {
- panic("wildcard route '" + path[i:end] +
- "' conflicts with existing children in path '" + fullPath + "'")
- }
-
- // check if the wildcard has a name
- if end-i < 2 {
- panic("wildcards must be named with a non-empty name in path '" + fullPath + "'")
- }
-
- if c == ':' { // param
- // split path at the beginning of the wildcard
- if i > 0 {
- n.path = path[offset:i]
- offset = i
- }
-
- child := &node{
- nType: param,
- maxParams: numParams,
- }
- n.children = []*node{child}
- n.wildChild = true
- n = child
- n.priority++
- numParams--
-
- // if the path doesn't end with the wildcard, then there
- // will be another non-wildcard subpath starting with '/'
- if end < max {
- n.path = path[offset:end]
- offset = end
-
- child := &node{
- maxParams: numParams,
- priority: 1,
- }
- n.children = []*node{child}
- n = child
- }
-
- } else { // catchAll
- if end != max || numParams > 1 {
- panic("catch-all routes are only allowed at the end of the path in path '" + fullPath + "'")
- }
-
- if len(n.path) > 0 && n.path[len(n.path)-1] == '/' {
- panic("catch-all conflicts with existing handle for the path segment root in path '" + fullPath + "'")
- }
-
- // currently fixed width 1 for '/'
- i--
- if path[i] != '/' {
- panic("no / before catch-all in path '" + fullPath + "'")
- }
-
- n.path = path[offset:i]
-
- // first node: catchAll node with empty path
- child := &node{
- wildChild: true,
- nType: catchAll,
- maxParams: 1,
- }
- n.children = []*node{child}
- n.indices = string(path[i])
- n = child
- n.priority++
-
- // second node: node holding the variable
- child = &node{
- path: path[i:],
- nType: catchAll,
- maxParams: 1,
- handle: handle,
- priority: 1,
- }
- n.children = []*node{child}
-
- return
- }
- }
-
- // insert remaining path part and handle to the leaf
- n.path = path[offset:]
- n.handle = handle
-}
-
-// Returns the handle registered with the given path (key). The values of
-// wildcards are saved to a map.
-// If no handle can be found, a TSR (trailing slash redirect) recommendation is
-// made if a handle exists with an extra (without the) trailing slash for the
-// given path.
-func (n *node) getValue(path string) (handle Handle, p Params, tsr bool) {
-walk: // Outer loop for walking the tree
- for {
- if len(path) > len(n.path) {
- if path[:len(n.path)] == n.path {
- path = path[len(n.path):]
- // If this node does not have a wildcard (param or catchAll)
- // child, we can just look up the next child node and continue
- // to walk down the tree
- if !n.wildChild {
- c := path[0]
- for i := 0; i < len(n.indices); i++ {
- if c == n.indices[i] {
- n = n.children[i]
- continue walk
- }
- }
-
- // Nothing found.
- // We can recommend to redirect to the same URL without a
- // trailing slash if a leaf exists for that path.
- tsr = (path == "/" && n.handle != nil)
- return
-
- }
-
- // handle wildcard child
- n = n.children[0]
- switch n.nType {
- case param:
- // find param end (either '/' or path end)
- end := 0
- for end < len(path) && path[end] != '/' {
- end++
- }
-
- // save param value
- if p == nil {
- // lazy allocation
- p = make(Params, 0, n.maxParams)
- }
- i := len(p)
- p = p[:i+1] // expand slice within preallocated capacity
- p[i].Key = n.path[1:]
- p[i].Value = path[:end]
-
- // we need to go deeper!
- if end < len(path) {
- if len(n.children) > 0 {
- path = path[end:]
- n = n.children[0]
- continue walk
- }
-
- // ... but we can't
- tsr = (len(path) == end+1)
- return
- }
-
- if handle = n.handle; handle != nil {
- return
- } else if len(n.children) == 1 {
- // No handle found. Check if a handle for this path + a
- // trailing slash exists for TSR recommendation
- n = n.children[0]
- tsr = (n.path == "/" && n.handle != nil)
- }
-
- return
-
- case catchAll:
- // save param value
- if p == nil {
- // lazy allocation
- p = make(Params, 0, n.maxParams)
- }
- i := len(p)
- p = p[:i+1] // expand slice within preallocated capacity
- p[i].Key = n.path[2:]
- p[i].Value = path
-
- handle = n.handle
- return
-
- default:
- panic("invalid node type")
- }
- }
- } else if path == n.path {
- // We should have reached the node containing the handle.
- // Check if this node has a handle registered.
- if handle = n.handle; handle != nil {
- return
- }
-
- // No handle found. Check if a handle for this path + a
- // trailing slash exists for trailing slash recommendation
- for i := 0; i < len(n.indices); i++ {
- if n.indices[i] == '/' {
- n = n.children[i]
- tsr = (len(n.path) == 1 && n.handle != nil) ||
- (n.nType == catchAll && n.children[0].handle != nil)
- return
- }
- }
-
- return
- }
-
- // Nothing found. We can recommend to redirect to the same URL with an
- // extra trailing slash if a leaf exists for that path
- tsr = (path == "/") ||
- (len(n.path) == len(path)+1 && n.path[len(path)] == '/' &&
- path == n.path[:len(n.path)-1] && n.handle != nil)
- return
- }
-}
-
-// Makes a case-insensitive lookup of the given path and tries to find a handler.
-// It can optionally also fix trailing slashes.
-// It returns the case-corrected path and a bool indicating whether the lookup
-// was successful.
-func (n *node) findCaseInsensitivePath(path string, fixTrailingSlash bool) (ciPath []byte, found bool) {
- ciPath = make([]byte, 0, len(path)+1) // preallocate enough memory
-
- // Outer loop for walking the tree
- for len(path) >= len(n.path) && strings.ToLower(path[:len(n.path)]) == strings.ToLower(n.path) {
- path = path[len(n.path):]
- ciPath = append(ciPath, n.path...)
-
- if len(path) > 0 {
- // If this node does not have a wildcard (param or catchAll) child,
- // we can just look up the next child node and continue to walk down
- // the tree
- if !n.wildChild {
- r := unicode.ToLower(rune(path[0]))
- for i, index := range n.indices {
- // must use recursive approach since both index and
- // ToLower(index) could exist. We must check both.
- if r == unicode.ToLower(index) {
- out, found := n.children[i].findCaseInsensitivePath(path, fixTrailingSlash)
- if found {
- return append(ciPath, out...), true
- }
- }
- }
-
- // Nothing found. We can recommend to redirect to the same URL
- // without a trailing slash if a leaf exists for that path
- found = (fixTrailingSlash && path == "/" && n.handle != nil)
- return
- }
-
- n = n.children[0]
- switch n.nType {
- case param:
- // find param end (either '/' or path end)
- k := 0
- for k < len(path) && path[k] != '/' {
- k++
- }
-
- // add param value to case insensitive path
- ciPath = append(ciPath, path[:k]...)
-
- // we need to go deeper!
- if k < len(path) {
- if len(n.children) > 0 {
- path = path[k:]
- n = n.children[0]
- continue
- }
-
- // ... but we can't
- if fixTrailingSlash && len(path) == k+1 {
- return ciPath, true
- }
- return
- }
-
- if n.handle != nil {
- return ciPath, true
- } else if fixTrailingSlash && len(n.children) == 1 {
- // No handle found. Check if a handle for this path + a
- // trailing slash exists
- n = n.children[0]
- if n.path == "/" && n.handle != nil {
- return append(ciPath, '/'), true
- }
- }
- return
-
- case catchAll:
- return append(ciPath, path...), true
-
- default:
- panic("invalid node type")
- }
- } else {
- // We should have reached the node containing the handle.
- // Check if this node has a handle registered.
- if n.handle != nil {
- return ciPath, true
- }
-
- // No handle found.
- // Try to fix the path by adding a trailing slash
- if fixTrailingSlash {
- for i := 0; i < len(n.indices); i++ {
- if n.indices[i] == '/' {
- n = n.children[i]
- if (len(n.path) == 1 && n.handle != nil) ||
- (n.nType == catchAll && n.children[0].handle != nil) {
- return append(ciPath, '/'), true
- }
- return
- }
- }
- }
- return
- }
- }
-
- // Nothing found.
- // Try to fix the path by adding / removing a trailing slash
- if fixTrailingSlash {
- if path == "/" {
- return ciPath, true
- }
- if len(path)+1 == len(n.path) && n.path[len(path)] == '/' &&
- strings.ToLower(path) == strings.ToLower(n.path[:len(path)]) &&
- n.handle != nil {
- return append(ciPath, n.path...), true
- }
- }
- return
-}
diff --git a/Godeps/_workspace/src/github.com/julienschmidt/httprouter/tree_test.go b/Godeps/_workspace/src/github.com/julienschmidt/httprouter/tree_test.go
deleted file mode 100644
index 64f26d1a38..0000000000
--- a/Godeps/_workspace/src/github.com/julienschmidt/httprouter/tree_test.go
+++ /dev/null
@@ -1,611 +0,0 @@
-// Copyright 2013 Julien Schmidt. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be found
-// in the LICENSE file.
-
-package httprouter
-
-import (
- "fmt"
- "net/http"
- "reflect"
- "strings"
- "testing"
-)
-
-func printChildren(n *node, prefix string) {
- fmt.Printf(" %02d:%02d %s%s[%d] %v %t %d \r\n", n.priority, n.maxParams, prefix, n.path, len(n.children), n.handle, n.wildChild, n.nType)
- for l := len(n.path); l > 0; l-- {
- prefix += " "
- }
- for _, child := range n.children {
- printChildren(child, prefix)
- }
-}
-
-// Used as a workaround since we can't compare functions or their adresses
-var fakeHandlerValue string
-
-func fakeHandler(val string) Handle {
- return func(http.ResponseWriter, *http.Request, Params) {
- fakeHandlerValue = val
- }
-}
-
-type testRequests []struct {
- path string
- nilHandler bool
- route string
- ps Params
-}
-
-func checkRequests(t *testing.T, tree *node, requests testRequests) {
- for _, request := range requests {
- handler, ps, _ := tree.getValue(request.path)
-
- if handler == nil {
- if !request.nilHandler {
- t.Errorf("handle mismatch for route '%s': Expected non-nil handle", request.path)
- }
- } else if request.nilHandler {
- t.Errorf("handle mismatch for route '%s': Expected nil handle", request.path)
- } else {
- handler(nil, nil, nil)
- if fakeHandlerValue != request.route {
- t.Errorf("handle mismatch for route '%s': Wrong handle (%s != %s)", request.path, fakeHandlerValue, request.route)
- }
- }
-
- if !reflect.DeepEqual(ps, request.ps) {
- t.Errorf("Params mismatch for route '%s'", request.path)
- }
- }
-}
-
-func checkPriorities(t *testing.T, n *node) uint32 {
- var prio uint32
- for i := range n.children {
- prio += checkPriorities(t, n.children[i])
- }
-
- if n.handle != nil {
- prio++
- }
-
- if n.priority != prio {
- t.Errorf(
- "priority mismatch for node '%s': is %d, should be %d",
- n.path, n.priority, prio,
- )
- }
-
- return prio
-}
-
-func checkMaxParams(t *testing.T, n *node) uint8 {
- var maxParams uint8
- for i := range n.children {
- params := checkMaxParams(t, n.children[i])
- if params > maxParams {
- maxParams = params
- }
- }
- if n.nType != static && !n.wildChild {
- maxParams++
- }
-
- if n.maxParams != maxParams {
- t.Errorf(
- "maxParams mismatch for node '%s': is %d, should be %d",
- n.path, n.maxParams, maxParams,
- )
- }
-
- return maxParams
-}
-
-func TestCountParams(t *testing.T) {
- if countParams("/path/:param1/static/*catch-all") != 2 {
- t.Fail()
- }
- if countParams(strings.Repeat("/:param", 256)) != 255 {
- t.Fail()
- }
-}
-
-func TestTreeAddAndGet(t *testing.T) {
- tree := &node{}
-
- routes := [...]string{
- "/hi",
- "/contact",
- "/co",
- "/c",
- "/a",
- "/ab",
- "/doc/",
- "/doc/go_faq.html",
- "/doc/go1.html",
- "/α",
- "/β",
- }
- for _, route := range routes {
- tree.addRoute(route, fakeHandler(route))
- }
-
- //printChildren(tree, "")
-
- checkRequests(t, tree, testRequests{
- {"/a", false, "/a", nil},
- {"/", true, "", nil},
- {"/hi", false, "/hi", nil},
- {"/contact", false, "/contact", nil},
- {"/co", false, "/co", nil},
- {"/con", true, "", nil}, // key mismatch
- {"/cona", true, "", nil}, // key mismatch
- {"/no", true, "", nil}, // no matching child
- {"/ab", false, "/ab", nil},
- {"/α", false, "/α", nil},
- {"/β", false, "/β", nil},
- })
-
- checkPriorities(t, tree)
- checkMaxParams(t, tree)
-}
-
-func TestTreeWildcard(t *testing.T) {
- tree := &node{}
-
- routes := [...]string{
- "/",
- "/cmd/:tool/:sub",
- "/cmd/:tool/",
- "/src/*filepath",
- "/search/",
- "/search/:query",
- "/user_:name",
- "/user_:name/about",
- "/files/:dir/*filepath",
- "/doc/",
- "/doc/go_faq.html",
- "/doc/go1.html",
- "/info/:user/public",
- "/info/:user/project/:project",
- }
- for _, route := range routes {
- tree.addRoute(route, fakeHandler(route))
- }
-
- //printChildren(tree, "")
-
- checkRequests(t, tree, testRequests{
- {"/", false, "/", nil},
- {"/cmd/test/", false, "/cmd/:tool/", Params{Param{"tool", "test"}}},
- {"/cmd/test", true, "", Params{Param{"tool", "test"}}},
- {"/cmd/test/3", false, "/cmd/:tool/:sub", Params{Param{"tool", "test"}, Param{"sub", "3"}}},
- {"/src/", false, "/src/*filepath", Params{Param{"filepath", "/"}}},
- {"/src/some/file.png", false, "/src/*filepath", Params{Param{"filepath", "/some/file.png"}}},
- {"/search/", false, "/search/", nil},
- {"/search/someth!ng+in+ünìcodé", false, "/search/:query", Params{Param{"query", "someth!ng+in+ünìcodé"}}},
- {"/search/someth!ng+in+ünìcodé/", true, "", Params{Param{"query", "someth!ng+in+ünìcodé"}}},
- {"/user_gopher", false, "/user_:name", Params{Param{"name", "gopher"}}},
- {"/user_gopher/about", false, "/user_:name/about", Params{Param{"name", "gopher"}}},
- {"/files/js/inc/framework.js", false, "/files/:dir/*filepath", Params{Param{"dir", "js"}, Param{"filepath", "/inc/framework.js"}}},
- {"/info/gordon/public", false, "/info/:user/public", Params{Param{"user", "gordon"}}},
- {"/info/gordon/project/go", false, "/info/:user/project/:project", Params{Param{"user", "gordon"}, Param{"project", "go"}}},
- })
-
- checkPriorities(t, tree)
- checkMaxParams(t, tree)
-}
-
-func catchPanic(testFunc func()) (recv interface{}) {
- defer func() {
- recv = recover()
- }()
-
- testFunc()
- return
-}
-
-type testRoute struct {
- path string
- conflict bool
-}
-
-func testRoutes(t *testing.T, routes []testRoute) {
- tree := &node{}
-
- for _, route := range routes {
- recv := catchPanic(func() {
- tree.addRoute(route.path, nil)
- })
-
- if route.conflict {
- if recv == nil {
- t.Errorf("no panic for conflicting route '%s'", route.path)
- }
- } else if recv != nil {
- t.Errorf("unexpected panic for route '%s': %v", route.path, recv)
- }
- }
-
- //printChildren(tree, "")
-}
-
-func TestTreeWildcardConflict(t *testing.T) {
- routes := []testRoute{
- {"/cmd/:tool/:sub", false},
- {"/cmd/vet", true},
- {"/src/*filepath", false},
- {"/src/*filepathx", true},
- {"/src/", true},
- {"/src1/", false},
- {"/src1/*filepath", true},
- {"/src2*filepath", true},
- {"/search/:query", false},
- {"/search/invalid", true},
- {"/user_:name", false},
- {"/user_x", true},
- {"/user_:name", false},
- {"/id:id", false},
- {"/id/:id", true},
- }
- testRoutes(t, routes)
-}
-
-func TestTreeChildConflict(t *testing.T) {
- routes := []testRoute{
- {"/cmd/vet", false},
- {"/cmd/:tool/:sub", true},
- {"/src/AUTHORS", false},
- {"/src/*filepath", true},
- {"/user_x", false},
- {"/user_:name", true},
- {"/id/:id", false},
- {"/id:id", true},
- {"/:id", true},
- {"/*filepath", true},
- }
- testRoutes(t, routes)
-}
-
-func TestTreeDupliatePath(t *testing.T) {
- tree := &node{}
-
- routes := [...]string{
- "/",
- "/doc/",
- "/src/*filepath",
- "/search/:query",
- "/user_:name",
- }
- for _, route := range routes {
- recv := catchPanic(func() {
- tree.addRoute(route, fakeHandler(route))
- })
- if recv != nil {
- t.Fatalf("panic inserting route '%s': %v", route, recv)
- }
-
- // Add again
- recv = catchPanic(func() {
- tree.addRoute(route, nil)
- })
- if recv == nil {
- t.Fatalf("no panic while inserting duplicate route '%s", route)
- }
- }
-
- //printChildren(tree, "")
-
- checkRequests(t, tree, testRequests{
- {"/", false, "/", nil},
- {"/doc/", false, "/doc/", nil},
- {"/src/some/file.png", false, "/src/*filepath", Params{Param{"filepath", "/some/file.png"}}},
- {"/search/someth!ng+in+ünìcodé", false, "/search/:query", Params{Param{"query", "someth!ng+in+ünìcodé"}}},
- {"/user_gopher", false, "/user_:name", Params{Param{"name", "gopher"}}},
- })
-}
-
-func TestEmptyWildcardName(t *testing.T) {
- tree := &node{}
-
- routes := [...]string{
- "/user:",
- "/user:/",
- "/cmd/:/",
- "/src/*",
- }
- for _, route := range routes {
- recv := catchPanic(func() {
- tree.addRoute(route, nil)
- })
- if recv == nil {
- t.Fatalf("no panic while inserting route with empty wildcard name '%s", route)
- }
- }
-}
-
-func TestTreeCatchAllConflict(t *testing.T) {
- routes := []testRoute{
- {"/src/*filepath/x", true},
- {"/src2/", false},
- {"/src2/*filepath/x", true},
- }
- testRoutes(t, routes)
-}
-
-func TestTreeCatchAllConflictRoot(t *testing.T) {
- routes := []testRoute{
- {"/", false},
- {"/*filepath", true},
- }
- testRoutes(t, routes)
-}
-
-func TestTreeDoubleWildcard(t *testing.T) {
- const panicMsg = "only one wildcard per path segment is allowed"
-
- routes := [...]string{
- "/:foo:bar",
- "/:foo:bar/",
- "/:foo*bar",
- }
-
- for _, route := range routes {
- tree := &node{}
- recv := catchPanic(func() {
- tree.addRoute(route, nil)
- })
-
- if rs, ok := recv.(string); !ok || !strings.HasPrefix(rs, panicMsg) {
- t.Fatalf(`"Expected panic "%s" for route '%s', got "%v"`, panicMsg, route, recv)
- }
- }
-}
-
-/*func TestTreeDuplicateWildcard(t *testing.T) {
- tree := &node{}
-
- routes := [...]string{
- "/:id/:name/:id",
- }
- for _, route := range routes {
- ...
- }
-}*/
-
-func TestTreeTrailingSlashRedirect(t *testing.T) {
- tree := &node{}
-
- routes := [...]string{
- "/hi",
- "/b/",
- "/search/:query",
- "/cmd/:tool/",
- "/src/*filepath",
- "/x",
- "/x/y",
- "/y/",
- "/y/z",
- "/0/:id",
- "/0/:id/1",
- "/1/:id/",
- "/1/:id/2",
- "/aa",
- "/a/",
- "/doc",
- "/doc/go_faq.html",
- "/doc/go1.html",
- "/no/a",
- "/no/b",
- "/api/hello/:name",
- }
- for _, route := range routes {
- recv := catchPanic(func() {
- tree.addRoute(route, fakeHandler(route))
- })
- if recv != nil {
- t.Fatalf("panic inserting route '%s': %v", route, recv)
- }
- }
-
- //printChildren(tree, "")
-
- tsrRoutes := [...]string{
- "/hi/",
- "/b",
- "/search/gopher/",
- "/cmd/vet",
- "/src",
- "/x/",
- "/y",
- "/0/go/",
- "/1/go",
- "/a",
- "/doc/",
- }
- for _, route := range tsrRoutes {
- handler, _, tsr := tree.getValue(route)
- if handler != nil {
- t.Fatalf("non-nil handler for TSR route '%s", route)
- } else if !tsr {
- t.Errorf("expected TSR recommendation for route '%s'", route)
- }
- }
-
- noTsrRoutes := [...]string{
- "/",
- "/no",
- "/no/",
- "/_",
- "/_/",
- "/api/world/abc",
- }
- for _, route := range noTsrRoutes {
- handler, _, tsr := tree.getValue(route)
- if handler != nil {
- t.Fatalf("non-nil handler for No-TSR route '%s", route)
- } else if tsr {
- t.Errorf("expected no TSR recommendation for route '%s'", route)
- }
- }
-}
-
-func TestTreeFindCaseInsensitivePath(t *testing.T) {
- tree := &node{}
-
- routes := [...]string{
- "/hi",
- "/b/",
- "/ABC/",
- "/search/:query",
- "/cmd/:tool/",
- "/src/*filepath",
- "/x",
- "/x/y",
- "/y/",
- "/y/z",
- "/0/:id",
- "/0/:id/1",
- "/1/:id/",
- "/1/:id/2",
- "/aa",
- "/a/",
- "/doc",
- "/doc/go_faq.html",
- "/doc/go1.html",
- "/doc/go/away",
- "/no/a",
- "/no/b",
- }
-
- for _, route := range routes {
- recv := catchPanic(func() {
- tree.addRoute(route, fakeHandler(route))
- })
- if recv != nil {
- t.Fatalf("panic inserting route '%s': %v", route, recv)
- }
- }
-
- // Check out == in for all registered routes
- // With fixTrailingSlash = true
- for _, route := range routes {
- out, found := tree.findCaseInsensitivePath(route, true)
- if !found {
- t.Errorf("Route '%s' not found!", route)
- } else if string(out) != route {
- t.Errorf("Wrong result for route '%s': %s", route, string(out))
- }
- }
- // With fixTrailingSlash = false
- for _, route := range routes {
- out, found := tree.findCaseInsensitivePath(route, false)
- if !found {
- t.Errorf("Route '%s' not found!", route)
- } else if string(out) != route {
- t.Errorf("Wrong result for route '%s': %s", route, string(out))
- }
- }
-
- tests := []struct {
- in string
- out string
- found bool
- slash bool
- }{
- {"/HI", "/hi", true, false},
- {"/HI/", "/hi", true, true},
- {"/B", "/b/", true, true},
- {"/B/", "/b/", true, false},
- {"/abc", "/ABC/", true, true},
- {"/abc/", "/ABC/", true, false},
- {"/aBc", "/ABC/", true, true},
- {"/aBc/", "/ABC/", true, false},
- {"/abC", "/ABC/", true, true},
- {"/abC/", "/ABC/", true, false},
- {"/SEARCH/QUERY", "/search/QUERY", true, false},
- {"/SEARCH/QUERY/", "/search/QUERY", true, true},
- {"/CMD/TOOL/", "/cmd/TOOL/", true, false},
- {"/CMD/TOOL", "/cmd/TOOL/", true, true},
- {"/SRC/FILE/PATH", "/src/FILE/PATH", true, false},
- {"/x/Y", "/x/y", true, false},
- {"/x/Y/", "/x/y", true, true},
- {"/X/y", "/x/y", true, false},
- {"/X/y/", "/x/y", true, true},
- {"/X/Y", "/x/y", true, false},
- {"/X/Y/", "/x/y", true, true},
- {"/Y/", "/y/", true, false},
- {"/Y", "/y/", true, true},
- {"/Y/z", "/y/z", true, false},
- {"/Y/z/", "/y/z", true, true},
- {"/Y/Z", "/y/z", true, false},
- {"/Y/Z/", "/y/z", true, true},
- {"/y/Z", "/y/z", true, false},
- {"/y/Z/", "/y/z", true, true},
- {"/Aa", "/aa", true, false},
- {"/Aa/", "/aa", true, true},
- {"/AA", "/aa", true, false},
- {"/AA/", "/aa", true, true},
- {"/aA", "/aa", true, false},
- {"/aA/", "/aa", true, true},
- {"/A/", "/a/", true, false},
- {"/A", "/a/", true, true},
- {"/DOC", "/doc", true, false},
- {"/DOC/", "/doc", true, true},
- {"/NO", "", false, true},
- {"/DOC/GO", "", false, true},
- }
- // With fixTrailingSlash = true
- for _, test := range tests {
- out, found := tree.findCaseInsensitivePath(test.in, true)
- if found != test.found || (found && (string(out) != test.out)) {
- t.Errorf("Wrong result for '%s': got %s, %t; want %s, %t",
- test.in, string(out), found, test.out, test.found)
- return
- }
- }
- // With fixTrailingSlash = false
- for _, test := range tests {
- out, found := tree.findCaseInsensitivePath(test.in, false)
- if test.slash {
- if found { // test needs a trailingSlash fix. It must not be found!
- t.Errorf("Found without fixTrailingSlash: %s; got %s", test.in, string(out))
- }
- } else {
- if found != test.found || (found && (string(out) != test.out)) {
- t.Errorf("Wrong result for '%s': got %s, %t; want %s, %t",
- test.in, string(out), found, test.out, test.found)
- return
- }
- }
- }
-}
-
-func TestTreeInvalidNodeType(t *testing.T) {
- const panicMsg = "invalid node type"
-
- tree := &node{}
- tree.addRoute("/", fakeHandler("/"))
- tree.addRoute("/:page", fakeHandler("/:page"))
-
- // set invalid node type
- tree.children[0].nType = 42
-
- // normal lookup
- recv := catchPanic(func() {
- tree.getValue("/test")
- })
- if rs, ok := recv.(string); !ok || rs != panicMsg {
- t.Fatalf("Expected panic '"+panicMsg+"', got '%v'", recv)
- }
-
- // case-insensitive lookup
- recv = catchPanic(func() {
- tree.findCaseInsensitivePath("/test", true)
- })
- if rs, ok := recv.(string); !ok || rs != panicMsg {
- t.Fatalf("Expected panic '"+panicMsg+"', got '%v'", recv)
- }
-}
diff --git a/Godeps/_workspace/src/github.com/matttproud/golang_protobuf_extensions/LICENSE b/Godeps/_workspace/src/github.com/matttproud/golang_protobuf_extensions/LICENSE
deleted file mode 100644
index 13f15dfce0..0000000000
--- a/Godeps/_workspace/src/github.com/matttproud/golang_protobuf_extensions/LICENSE
+++ /dev/null
@@ -1,201 +0,0 @@
- 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 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.
diff --git a/Godeps/_workspace/src/github.com/matttproud/golang_protobuf_extensions/pbutil/all_test.go b/Godeps/_workspace/src/github.com/matttproud/golang_protobuf_extensions/pbutil/all_test.go
deleted file mode 100644
index 094156e66c..0000000000
--- a/Godeps/_workspace/src/github.com/matttproud/golang_protobuf_extensions/pbutil/all_test.go
+++ /dev/null
@@ -1,320 +0,0 @@
-// 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 (
- "bytes"
- "math/rand"
- "reflect"
- "testing"
- "testing/quick"
-
- "github.com/matttproud/golang_protobuf_extensions/pbtest"
-
- . "github.com/golang/protobuf/proto"
- . "github.com/golang/protobuf/proto/testdata"
-)
-
-func TestWriteDelimited(t *testing.T) {
- for _, test := range []struct {
- msg Message
- buf []byte
- n int
- err error
- }{
- {
- msg: &Empty{},
- n: 1,
- buf: []byte{0},
- },
- {
- msg: &GoEnum{Foo: FOO_FOO1.Enum()},
- n: 3,
- buf: []byte{2, 8, 1},
- },
- {
- msg: &Strings{
- StringField: String(`This is my gigantic, unhappy string. It exceeds
-the encoding size of a single byte varint. We are using it to fuzz test the
-correctness of the header decoding mechanisms, which may prove problematic.
-I expect it may. Let's hope you enjoy testing as much as we do.`),
- },
- n: 271,
- buf: []byte{141, 2, 10, 138, 2, 84, 104, 105, 115, 32, 105, 115, 32, 109,
- 121, 32, 103, 105, 103, 97, 110, 116, 105, 99, 44, 32, 117, 110, 104,
- 97, 112, 112, 121, 32, 115, 116, 114, 105, 110, 103, 46, 32, 32, 73,
- 116, 32, 101, 120, 99, 101, 101, 100, 115, 10, 116, 104, 101, 32, 101,
- 110, 99, 111, 100, 105, 110, 103, 32, 115, 105, 122, 101, 32, 111, 102,
- 32, 97, 32, 115, 105, 110, 103, 108, 101, 32, 98, 121, 116, 101, 32,
- 118, 97, 114, 105, 110, 116, 46, 32, 32, 87, 101, 32, 97, 114, 101, 32,
- 117, 115, 105, 110, 103, 32, 105, 116, 32, 116, 111, 32, 102, 117, 122,
- 122, 32, 116, 101, 115, 116, 32, 116, 104, 101, 10, 99, 111, 114, 114,
- 101, 99, 116, 110, 101, 115, 115, 32, 111, 102, 32, 116, 104, 101, 32,
- 104, 101, 97, 100, 101, 114, 32, 100, 101, 99, 111, 100, 105, 110, 103,
- 32, 109, 101, 99, 104, 97, 110, 105, 115, 109, 115, 44, 32, 119, 104,
- 105, 99, 104, 32, 109, 97, 121, 32, 112, 114, 111, 118, 101, 32, 112,
- 114, 111, 98, 108, 101, 109, 97, 116, 105, 99, 46, 10, 73, 32, 101, 120,
- 112, 101, 99, 116, 32, 105, 116, 32, 109, 97, 121, 46, 32, 32, 76, 101,
- 116, 39, 115, 32, 104, 111, 112, 101, 32, 121, 111, 117, 32, 101, 110,
- 106, 111, 121, 32, 116, 101, 115, 116, 105, 110, 103, 32, 97, 115, 32,
- 109, 117, 99, 104, 32, 97, 115, 32, 119, 101, 32, 100, 111, 46},
- },
- } {
- var buf bytes.Buffer
- if n, err := WriteDelimited(&buf, test.msg); n != test.n || err != test.err {
- t.Fatalf("WriteDelimited(buf, %#v) = %v, %v; want %v, %v", test.msg, n, err, test.n, test.err)
- }
- if out := buf.Bytes(); !bytes.Equal(out, test.buf) {
- t.Fatalf("WriteDelimited(buf, %#v); buf = %v; want %v", test.msg, out, test.buf)
- }
- }
-}
-
-func TestReadDelimited(t *testing.T) {
- for _, test := range []struct {
- buf []byte
- msg Message
- n int
- err error
- }{
- {
- buf: []byte{0},
- msg: &Empty{},
- n: 1,
- },
- {
- n: 3,
- buf: []byte{2, 8, 1},
- msg: &GoEnum{Foo: FOO_FOO1.Enum()},
- },
- {
- buf: []byte{141, 2, 10, 138, 2, 84, 104, 105, 115, 32, 105, 115, 32, 109,
- 121, 32, 103, 105, 103, 97, 110, 116, 105, 99, 44, 32, 117, 110, 104,
- 97, 112, 112, 121, 32, 115, 116, 114, 105, 110, 103, 46, 32, 32, 73,
- 116, 32, 101, 120, 99, 101, 101, 100, 115, 10, 116, 104, 101, 32, 101,
- 110, 99, 111, 100, 105, 110, 103, 32, 115, 105, 122, 101, 32, 111, 102,
- 32, 97, 32, 115, 105, 110, 103, 108, 101, 32, 98, 121, 116, 101, 32,
- 118, 97, 114, 105, 110, 116, 46, 32, 32, 87, 101, 32, 97, 114, 101, 32,
- 117, 115, 105, 110, 103, 32, 105, 116, 32, 116, 111, 32, 102, 117, 122,
- 122, 32, 116, 101, 115, 116, 32, 116, 104, 101, 10, 99, 111, 114, 114,
- 101, 99, 116, 110, 101, 115, 115, 32, 111, 102, 32, 116, 104, 101, 32,
- 104, 101, 97, 100, 101, 114, 32, 100, 101, 99, 111, 100, 105, 110, 103,
- 32, 109, 101, 99, 104, 97, 110, 105, 115, 109, 115, 44, 32, 119, 104,
- 105, 99, 104, 32, 109, 97, 121, 32, 112, 114, 111, 118, 101, 32, 112,
- 114, 111, 98, 108, 101, 109, 97, 116, 105, 99, 46, 10, 73, 32, 101, 120,
- 112, 101, 99, 116, 32, 105, 116, 32, 109, 97, 121, 46, 32, 32, 76, 101,
- 116, 39, 115, 32, 104, 111, 112, 101, 32, 121, 111, 117, 32, 101, 110,
- 106, 111, 121, 32, 116, 101, 115, 116, 105, 110, 103, 32, 97, 115, 32,
- 109, 117, 99, 104, 32, 97, 115, 32, 119, 101, 32, 100, 111, 46},
- msg: &Strings{
- StringField: String(`This is my gigantic, unhappy string. It exceeds
-the encoding size of a single byte varint. We are using it to fuzz test the
-correctness of the header decoding mechanisms, which may prove problematic.
-I expect it may. Let's hope you enjoy testing as much as we do.`),
- },
- n: 271,
- },
- } {
- msg := Clone(test.msg)
- msg.Reset()
- if n, err := ReadDelimited(bytes.NewBuffer(test.buf), msg); n != test.n || err != test.err {
- t.Fatalf("ReadDelimited(%v, msg) = %v, %v; want %v, %v", test.buf, n, err, test.n, test.err)
- }
- if !Equal(msg, test.msg) {
- t.Fatalf("ReadDelimited(%v, msg); msg = %v; want %v", test.buf, msg, test.msg)
- }
- }
-}
-
-func TestEndToEndValid(t *testing.T) {
- for _, test := range [][]Message{
- {&Empty{}},
- {&GoEnum{Foo: FOO_FOO1.Enum()}, &Empty{}, &GoEnum{Foo: FOO_FOO1.Enum()}},
- {&GoEnum{Foo: FOO_FOO1.Enum()}},
- {&Strings{
- StringField: String(`This is my gigantic, unhappy string. It exceeds
-the encoding size of a single byte varint. We are using it to fuzz test the
-correctness of the header decoding mechanisms, which may prove problematic.
-I expect it may. Let's hope you enjoy testing as much as we do.`),
- }},
- } {
- var buf bytes.Buffer
- var written int
- for i, msg := range test {
- n, err := WriteDelimited(&buf, msg)
- if err != nil {
- // Assumption: TestReadDelimited and TestWriteDelimited are sufficient
- // and inputs for this test are explicitly exercised there.
- t.Fatalf("WriteDelimited(buf, %v[%d]) = ?, %v; wanted ?, nil", test, i, err)
- }
- written += n
- }
- var read int
- for i, msg := range test {
- out := Clone(msg)
- out.Reset()
- n, _ := ReadDelimited(&buf, out)
- // Decide to do EOF checking?
- read += n
- if !Equal(out, msg) {
- t.Fatalf("out = %v; want %v[%d] = %#v", out, test, i, msg)
- }
- }
- if read != written {
- t.Fatalf("%v read = %d; want %d", test, read, written)
- }
- }
-}
-
-// rndMessage generates a random valid Protocol Buffer message.
-func rndMessage(r *rand.Rand) Message {
- var t reflect.Type
- switch v := rand.Intn(23); v {
- // TODO(br): Uncomment the elements below once fix is incorporated, except
- // for the elements marked as patently incompatible.
- // case 0:
- // t = reflect.TypeOf(&GoEnum{})
- // break
- // case 1:
- // t = reflect.TypeOf(&GoTestField{})
- // break
- case 2:
- t = reflect.TypeOf(&GoTest{})
- break
- // case 3:
- // t = reflect.TypeOf(&GoSkipTest{})
- // break
- // case 4:
- // t = reflect.TypeOf(&NonPackedTest{})
- // break
- // case 5:
- // t = reflect.TypeOf(&PackedTest{})
- // break
- case 6:
- t = reflect.TypeOf(&MaxTag{})
- break
- case 7:
- t = reflect.TypeOf(&OldMessage{})
- break
- case 8:
- t = reflect.TypeOf(&NewMessage{})
- break
- case 9:
- t = reflect.TypeOf(&InnerMessage{})
- break
- case 10:
- t = reflect.TypeOf(&OtherMessage{})
- break
- case 11:
- // PATENTLY INVALID FOR FUZZ GENERATION
- // t = reflect.TypeOf(&MyMessage{})
- break
- // case 12:
- // t = reflect.TypeOf(&Ext{})
- // break
- case 13:
- // PATENTLY INVALID FOR FUZZ GENERATION
- // t = reflect.TypeOf(&MyMessageSet{})
- break
- // case 14:
- // t = reflect.TypeOf(&Empty{})
- // break
- // case 15:
- // t = reflect.TypeOf(&MessageList{})
- // break
- // case 16:
- // t = reflect.TypeOf(&Strings{})
- // break
- // case 17:
- // t = reflect.TypeOf(&Defaults{})
- // break
- // case 17:
- // t = reflect.TypeOf(&SubDefaults{})
- // break
- // case 18:
- // t = reflect.TypeOf(&RepeatedEnum{})
- // break
- case 19:
- t = reflect.TypeOf(&MoreRepeated{})
- break
- // case 20:
- // t = reflect.TypeOf(&GroupOld{})
- // break
- // case 21:
- // t = reflect.TypeOf(&GroupNew{})
- // break
- case 22:
- t = reflect.TypeOf(&FloatingPoint{})
- break
- default:
- // TODO(br): Replace with an unreachable once fixed.
- t = reflect.TypeOf(&GoTest{})
- break
- }
- if t == nil {
- t = reflect.TypeOf(&GoTest{})
- }
- v, ok := quick.Value(t, r)
- if !ok {
- panic("attempt to generate illegal item; consult item 11")
- }
- if err := pbtest.SanitizeGenerated(v.Interface().(Message)); err != nil {
- panic(err)
- }
- return v.Interface().(Message)
-}
-
-// rndMessages generates several random Protocol Buffer messages.
-func rndMessages(r *rand.Rand) []Message {
- n := r.Intn(128)
- out := make([]Message, 0, n)
- for i := 0; i < n; i++ {
- out = append(out, rndMessage(r))
- }
- return out
-}
-
-func TestFuzz(t *testing.T) {
- rnd := rand.New(rand.NewSource(42))
- check := func() bool {
- messages := rndMessages(rnd)
- var buf bytes.Buffer
- var written int
- for i, msg := range messages {
- n, err := WriteDelimited(&buf, msg)
- if err != nil {
- t.Fatalf("WriteDelimited(buf, %v[%d]) = ?, %v; wanted ?, nil", messages, i, err)
- }
- written += n
- }
- var read int
- for i, msg := range messages {
- out := Clone(msg)
- out.Reset()
- n, _ := ReadDelimited(&buf, out)
- read += n
- if !Equal(out, msg) {
- t.Fatalf("out = %v; want %v[%d] = %#v", out, messages, i, msg)
- }
- }
- if read != written {
- t.Fatalf("%v read = %d; want %d", messages, read, written)
- }
- return true
- }
- if err := quick.Check(check, nil); err != nil {
- t.Fatal(err)
- }
-}
diff --git a/Godeps/_workspace/src/github.com/matttproud/golang_protobuf_extensions/pbutil/decode.go b/Godeps/_workspace/src/github.com/matttproud/golang_protobuf_extensions/pbutil/decode.go
deleted file mode 100644
index 66d9b5458f..0000000000
--- a/Godeps/_workspace/src/github.com/matttproud/golang_protobuf_extensions/pbutil/decode.go
+++ /dev/null
@@ -1,75 +0,0 @@
-// 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.
- headerBuf := make([]byte, binary.MaxVarintLen32)
- 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)
-}
diff --git a/Godeps/_workspace/src/github.com/matttproud/golang_protobuf_extensions/pbutil/doc.go b/Godeps/_workspace/src/github.com/matttproud/golang_protobuf_extensions/pbutil/doc.go
deleted file mode 100644
index c318385cbe..0000000000
--- a/Godeps/_workspace/src/github.com/matttproud/golang_protobuf_extensions/pbutil/doc.go
+++ /dev/null
@@ -1,16 +0,0 @@
-// 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
diff --git a/Godeps/_workspace/src/github.com/matttproud/golang_protobuf_extensions/pbutil/encode.go b/Godeps/_workspace/src/github.com/matttproud/golang_protobuf_extensions/pbutil/encode.go
deleted file mode 100644
index 4b76ea9a1d..0000000000
--- a/Godeps/_workspace/src/github.com/matttproud/golang_protobuf_extensions/pbutil/encode.go
+++ /dev/null
@@ -1,46 +0,0 @@
-// 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
- }
-
- buf := make([]byte, binary.MaxVarintLen32)
- 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
-}
diff --git a/Godeps/_workspace/src/github.com/matttproud/golang_protobuf_extensions/pbutil/fixtures_test.go b/Godeps/_workspace/src/github.com/matttproud/golang_protobuf_extensions/pbutil/fixtures_test.go
deleted file mode 100644
index d6d9b25594..0000000000
--- a/Godeps/_workspace/src/github.com/matttproud/golang_protobuf_extensions/pbutil/fixtures_test.go
+++ /dev/null
@@ -1,103 +0,0 @@
-// Copyright 2010 The Go Authors. All rights reserved.
-// http://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 pbutil
-
-import (
- . "github.com/golang/protobuf/proto"
- . "github.com/golang/protobuf/proto/testdata"
-)
-
-// FROM https://github.com/golang/protobuf/blob/master/proto/all_test.go.
-
-func initGoTestField() *GoTestField {
- f := new(GoTestField)
- f.Label = String("label")
- f.Type = String("type")
- return f
-}
-
-// These are all structurally equivalent but the tag numbers differ.
-// (It's remarkable that required, optional, and repeated all have
-// 8 letters.)
-func initGoTest_RequiredGroup() *GoTest_RequiredGroup {
- return &GoTest_RequiredGroup{
- RequiredField: String("required"),
- }
-}
-
-func initGoTest_OptionalGroup() *GoTest_OptionalGroup {
- return &GoTest_OptionalGroup{
- RequiredField: String("optional"),
- }
-}
-
-func initGoTest_RepeatedGroup() *GoTest_RepeatedGroup {
- return &GoTest_RepeatedGroup{
- RequiredField: String("repeated"),
- }
-}
-
-func initGoTest(setdefaults bool) *GoTest {
- pb := new(GoTest)
- if setdefaults {
- pb.F_BoolDefaulted = Bool(Default_GoTest_F_BoolDefaulted)
- pb.F_Int32Defaulted = Int32(Default_GoTest_F_Int32Defaulted)
- pb.F_Int64Defaulted = Int64(Default_GoTest_F_Int64Defaulted)
- pb.F_Fixed32Defaulted = Uint32(Default_GoTest_F_Fixed32Defaulted)
- pb.F_Fixed64Defaulted = Uint64(Default_GoTest_F_Fixed64Defaulted)
- pb.F_Uint32Defaulted = Uint32(Default_GoTest_F_Uint32Defaulted)
- pb.F_Uint64Defaulted = Uint64(Default_GoTest_F_Uint64Defaulted)
- pb.F_FloatDefaulted = Float32(Default_GoTest_F_FloatDefaulted)
- pb.F_DoubleDefaulted = Float64(Default_GoTest_F_DoubleDefaulted)
- pb.F_StringDefaulted = String(Default_GoTest_F_StringDefaulted)
- pb.F_BytesDefaulted = Default_GoTest_F_BytesDefaulted
- pb.F_Sint32Defaulted = Int32(Default_GoTest_F_Sint32Defaulted)
- pb.F_Sint64Defaulted = Int64(Default_GoTest_F_Sint64Defaulted)
- }
-
- pb.Kind = GoTest_TIME.Enum()
- pb.RequiredField = initGoTestField()
- pb.F_BoolRequired = Bool(true)
- pb.F_Int32Required = Int32(3)
- pb.F_Int64Required = Int64(6)
- pb.F_Fixed32Required = Uint32(32)
- pb.F_Fixed64Required = Uint64(64)
- pb.F_Uint32Required = Uint32(3232)
- pb.F_Uint64Required = Uint64(6464)
- pb.F_FloatRequired = Float32(3232)
- pb.F_DoubleRequired = Float64(6464)
- pb.F_StringRequired = String("string")
- pb.F_BytesRequired = []byte("bytes")
- pb.F_Sint32Required = Int32(-32)
- pb.F_Sint64Required = Int64(-64)
- pb.Requiredgroup = initGoTest_RequiredGroup()
-
- return pb
-}
diff --git a/Godeps/_workspace/src/github.com/miekg/dns/.gitignore b/Godeps/_workspace/src/github.com/miekg/dns/.gitignore
deleted file mode 100644
index 776cd950c2..0000000000
--- a/Godeps/_workspace/src/github.com/miekg/dns/.gitignore
+++ /dev/null
@@ -1,4 +0,0 @@
-*.6
-tags
-test.out
-a.out
diff --git a/Godeps/_workspace/src/github.com/miekg/dns/.travis.yml b/Godeps/_workspace/src/github.com/miekg/dns/.travis.yml
deleted file mode 100644
index f0a9d223c3..0000000000
--- a/Godeps/_workspace/src/github.com/miekg/dns/.travis.yml
+++ /dev/null
@@ -1,6 +0,0 @@
-language: go
-go:
- - 1.3
- - 1.4
-script:
- - go test -short -bench=.
diff --git a/Godeps/_workspace/src/github.com/miekg/dns/AUTHORS b/Godeps/_workspace/src/github.com/miekg/dns/AUTHORS
deleted file mode 100644
index 1965683525..0000000000
--- a/Godeps/_workspace/src/github.com/miekg/dns/AUTHORS
+++ /dev/null
@@ -1 +0,0 @@
-Miek Gieben
diff --git a/Godeps/_workspace/src/github.com/miekg/dns/CONTRIBUTORS b/Godeps/_workspace/src/github.com/miekg/dns/CONTRIBUTORS
deleted file mode 100644
index f77e8a895f..0000000000
--- a/Godeps/_workspace/src/github.com/miekg/dns/CONTRIBUTORS
+++ /dev/null
@@ -1,9 +0,0 @@
-Alex A. Skinner
-Andrew Tunnell-Jones
-Ask Bjørn Hansen
-Dave Cheney
-Dusty Wilson
-Marek Majkowski
-Peter van Dijk
-Omri Bahumi
-Alex Sergeyev
diff --git a/Godeps/_workspace/src/github.com/miekg/dns/COPYRIGHT b/Godeps/_workspace/src/github.com/miekg/dns/COPYRIGHT
deleted file mode 100644
index 35702b10e8..0000000000
--- a/Godeps/_workspace/src/github.com/miekg/dns/COPYRIGHT
+++ /dev/null
@@ -1,9 +0,0 @@
-Copyright 2009 The Go Authors. All rights reserved. Use of this source code
-is governed by a BSD-style license that can be found in the LICENSE file.
-Extensions of the original work are copyright (c) 2011 Miek Gieben
-
-Copyright 2011 Miek Gieben. All rights reserved. Use of this source code is
-governed by a BSD-style license that can be found in the LICENSE file.
-
-Copyright 2014 CloudFlare. All rights reserved. Use of this source code is
-governed by a BSD-style license that can be found in the LICENSE file.
diff --git a/Godeps/_workspace/src/github.com/miekg/dns/LICENSE b/Godeps/_workspace/src/github.com/miekg/dns/LICENSE
deleted file mode 100644
index 5763fa7fe5..0000000000
--- a/Godeps/_workspace/src/github.com/miekg/dns/LICENSE
+++ /dev/null
@@ -1,32 +0,0 @@
-Extensions of the original work are copyright (c) 2011 Miek Gieben
-
-As this is fork of the official Go code the same license applies:
-
-Copyright (c) 2009 The Go Authors. All rights reserved.
-
-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.
-
diff --git a/Godeps/_workspace/src/github.com/miekg/dns/README.md b/Godeps/_workspace/src/github.com/miekg/dns/README.md
deleted file mode 100644
index 73d6270985..0000000000
--- a/Godeps/_workspace/src/github.com/miekg/dns/README.md
+++ /dev/null
@@ -1,144 +0,0 @@
-[](https://travis-ci.org/miekg/dns)
-
-# Alternative (more granular) approach to a DNS library
-
-> Less is more.
-
-Complete and usable DNS library. All widely used Resource Records are
-supported, including the DNSSEC types. It follows a lean and mean philosophy.
-If there is stuff you should know as a DNS programmer there isn't a convenience
-function for it. Server side and client side programming is supported, i.e. you
-can build servers and resolvers with it.
-
-If you like this, you may also be interested in:
-
-* https://github.com/miekg/unbound -- Go wrapper for the Unbound resolver.
-
-# Goals
-
-* KISS;
-* Fast;
-* Small API, if its easy to code in Go, don't make a function for it.
-
-# Users
-
-A not-so-up-to-date-list-that-may-be-actually-current:
-
-* https://github.com/abh/geodns
-* http://www.statdns.com/
-* http://www.dnsinspect.com/
-* https://github.com/chuangbo/jianbing-dictionary-dns
-* http://www.dns-lg.com/
-* https://github.com/fcambus/rrda
-* https://github.com/kenshinx/godns
-* https://github.com/skynetservices/skydns
-* https://github.com/DevelopersPL/godnsagent
-* https://github.com/duedil-ltd/discodns
-* https://github.com/StalkR/dns-reverse-proxy
-* https://github.com/tianon/rawdns
-* https://mesosphere.github.io/mesos-dns/
-* https://pulse.turbobytes.com/
-
-Send pull request if you want to be listed here.
-
-# Features
-
-* UDP/TCP queries, IPv4 and IPv6;
-* RFC 1035 zone file parsing ($INCLUDE, $ORIGIN, $TTL and $GENERATE (for all record types) are supported;
-* Fast:
- * Reply speed around ~ 80K qps (faster hardware results in more qps);
- * Parsing RRs ~ 100K RR/s, that's 5M records in about 50 seconds;
-* Server side programming (mimicking the net/http package);
-* Client side programming;
-* DNSSEC: signing, validating and key generation for DSA, RSA and ECDSA;
-* EDNS0, NSID;
-* AXFR/IXFR;
-* TSIG, SIG(0);
-* DNS name compression;
-* Depends only on the standard library.
-
-Have fun!
-
-Miek Gieben - 2010-2012 -
-
-# Building
-
-Building is done with the `go` tool. If you have setup your GOPATH
-correctly, the following should work:
-
- go get github.com/miekg/dns
- go build github.com/miekg/dns
-
-## Examples
-
-A short "how to use the API" is at the beginning of doc.go (this also will show
-when you call `godoc github.com/miekg/dns`).
-
-Example programs can be found in the `github.com/miekg/exdns` repository.
-
-## Supported RFCs
-
-*all of them*
-
-* 103{4,5} - DNS standard
-* 1348 - NSAP record
-* 1982 - Serial Arithmetic
-* 1876 - LOC record
-* 1995 - IXFR
-* 1996 - DNS notify
-* 2136 - DNS Update (dynamic updates)
-* 2181 - RRset definition - there is no RRset type though, just []RR
-* 2537 - RSAMD5 DNS keys
-* 2065 - DNSSEC (updated in later RFCs)
-* 2671 - EDNS record
-* 2782 - SRV record
-* 2845 - TSIG record
-* 2915 - NAPTR record
-* 2929 - DNS IANA Considerations
-* 3110 - RSASHA1 DNS keys
-* 3225 - DO bit (DNSSEC OK)
-* 340{1,2,3} - NAPTR record
-* 3445 - Limiting the scope of (DNS)KEY
-* 3597 - Unknown RRs
-* 4025 - IPSECKEY
-* 403{3,4,5} - DNSSEC + validation functions
-* 4255 - SSHFP record
-* 4343 - Case insensitivity
-* 4408 - SPF record
-* 4509 - SHA256 Hash in DS
-* 4592 - Wildcards in the DNS
-* 4635 - HMAC SHA TSIG
-* 4701 - DHCID
-* 4892 - id.server
-* 5001 - NSID
-* 5155 - NSEC3 record
-* 5205 - HIP record
-* 5702 - SHA2 in the DNS
-* 5936 - AXFR
-* 5966 - TCP implementation recommendations
-* 6605 - ECDSA
-* 6725 - IANA Registry Update
-* 6742 - ILNP DNS
-* 6844 - CAA record
-* 6891 - EDNS0 update
-* 6895 - DNS IANA considerations
-* 6975 - Algorithm Understanding in DNSSEC
-* 7043 - EUI48/EUI64 records
-* 7314 - DNS (EDNS) EXPIRE Option
-* xxxx - URI record (draft)
-* xxxx - EDNS0 DNS Update Lease (draft)
-
-## Loosely based upon
-
-* `ldns`
-* `NSD`
-* `Net::DNS`
-* `GRONG`
-
-## TODO
-
-* privatekey.Precompute() when signing?
-* Last remaining RRs: APL, ATMA, A6 and NXT and IPSECKEY;
-* Missing in parsing: ISDN, UNSPEC, ATMA;
-* NSEC(3) cover/match/closest enclose;
-* Replies with TC bit are not parsed to the end;
diff --git a/Godeps/_workspace/src/github.com/miekg/dns/client.go b/Godeps/_workspace/src/github.com/miekg/dns/client.go
deleted file mode 100644
index 140a7add7b..0000000000
--- a/Godeps/_workspace/src/github.com/miekg/dns/client.go
+++ /dev/null
@@ -1,378 +0,0 @@
-package dns
-
-// A client implementation.
-
-import (
- "bytes"
- "io"
- "net"
- "time"
-)
-
-const dnsTimeout time.Duration = 2 * time.Second
-const tcpIdleTimeout time.Duration = 8 * time.Second
-
-// A Conn represents a connection to a DNS server.
-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 must be fully qualified
- rtt time.Duration
- t time.Time
- tsigRequestMAC string
-}
-
-// A Client defines parameters for a DNS client.
-type Client struct {
- Net string // if "tcp" a TCP query will be initiated, otherwise an UDP one (default is "" for UDP)
- UDPSize uint16 // minimum receive buffer for UDP messages
- DialTimeout time.Duration // net.DialTimeout, defaults to 2 seconds
- ReadTimeout time.Duration // net.Conn.SetReadTimeout value for connections, defaults to 2 seconds
- WriteTimeout time.Duration // net.Conn.SetWriteTimeout value for connections, defaults to 2 seconds
- TsigSecret map[string]string // secret(s) for Tsig map[], zonename must be fully qualified
- SingleInflight bool // if true suppress multiple outstanding queries for the same Qname, Qtype and Qclass
- group singleflight
-}
-
-// Exchange performs a synchronous UDP query. It sends the message m to the address
-// contained in a and waits for an reply. Exchange does not retry a failed query, nor
-// will it fall back to TCP in case of truncation.
-// If you need to send a DNS message on an already existing connection, you can use the
-// following:
-//
-// co := &dns.Conn{Conn: c} // c is your net.Conn
-// co.WriteMsg(m)
-// in, err := co.ReadMsg()
-// co.Close()
-//
-func Exchange(m *Msg, a string) (r *Msg, err error) {
- var co *Conn
- co, err = DialTimeout("udp", a, dnsTimeout)
- if err != nil {
- return nil, err
- }
-
- defer co.Close()
- co.SetReadDeadline(time.Now().Add(dnsTimeout))
- co.SetWriteDeadline(time.Now().Add(dnsTimeout))
-
- opt := m.IsEdns0()
- // If EDNS0 is used use that for size.
- if opt != nil && opt.UDPSize() >= MinMsgSize {
- co.UDPSize = opt.UDPSize()
- }
-
- if err = co.WriteMsg(m); err != nil {
- return nil, err
- }
- r, err = co.ReadMsg()
- if err == nil && r.Id != m.Id {
- err = ErrId
- }
- return r, err
-}
-
-// ExchangeConn performs a synchronous query. It sends the message m via the connection
-// c and waits for a reply. The connection c is not closed by ExchangeConn.
-// This function is going away, but can easily be mimicked:
-//
-// co := &dns.Conn{Conn: c} // c is your net.Conn
-// co.WriteMsg(m)
-// in, _ := co.ReadMsg()
-// co.Close()
-//
-func ExchangeConn(c net.Conn, m *Msg) (r *Msg, err error) {
- println("dns: this function is deprecated")
- co := new(Conn)
- co.Conn = c
- if err = co.WriteMsg(m); err != nil {
- return nil, err
- }
- r, err = co.ReadMsg()
- if err == nil && r.Id != m.Id {
- err = ErrId
- }
- return r, err
-}
-
-// Exchange performs an synchronous query. It sends the message m to the address
-// contained in a and waits for an reply. Basic use pattern with a *dns.Client:
-//
-// c := new(dns.Client)
-// in, rtt, err := c.Exchange(message, "127.0.0.1:53")
-//
-// Exchange does not retry a failed query, nor will it fall back to TCP in
-// case of truncation.
-func (c *Client) Exchange(m *Msg, a string) (r *Msg, rtt time.Duration, err error) {
- if !c.SingleInflight {
- return c.exchange(m, a)
- }
- // This adds a bunch of garbage, TODO(miek).
- t := "nop"
- if t1, ok := TypeToString[m.Question[0].Qtype]; ok {
- t = t1
- }
- cl := "nop"
- if cl1, ok := ClassToString[m.Question[0].Qclass]; ok {
- cl = cl1
- }
- r, rtt, err, shared := c.group.Do(m.Question[0].Name+t+cl, func() (*Msg, time.Duration, error) {
- return c.exchange(m, a)
- })
- if err != nil {
- return r, rtt, err
- }
- if shared {
- return r.Copy(), rtt, nil
- }
- return r, rtt, nil
-}
-
-func (c *Client) dialTimeout() time.Duration {
- if c.DialTimeout != 0 {
- return c.DialTimeout
- }
- return dnsTimeout
-}
-
-func (c *Client) readTimeout() time.Duration {
- if c.ReadTimeout != 0 {
- return c.ReadTimeout
- }
- return dnsTimeout
-}
-
-func (c *Client) writeTimeout() time.Duration {
- if c.WriteTimeout != 0 {
- return c.WriteTimeout
- }
- return dnsTimeout
-}
-
-func (c *Client) exchange(m *Msg, a string) (r *Msg, rtt time.Duration, err error) {
- var co *Conn
- if c.Net == "" {
- co, err = DialTimeout("udp", a, c.dialTimeout())
- } else {
- co, err = DialTimeout(c.Net, a, c.dialTimeout())
- }
- if err != nil {
- return nil, 0, err
- }
- defer co.Close()
-
- opt := m.IsEdns0()
- // If EDNS0 is used use that for size.
- if opt != nil && opt.UDPSize() >= MinMsgSize {
- co.UDPSize = opt.UDPSize()
- }
- // Otherwise use the client's configured UDP size.
- if opt == nil && c.UDPSize >= MinMsgSize {
- co.UDPSize = c.UDPSize
- }
-
- co.SetReadDeadline(time.Now().Add(c.readTimeout()))
- co.SetWriteDeadline(time.Now().Add(c.writeTimeout()))
-
- co.TsigSecret = c.TsigSecret
- if err = co.WriteMsg(m); err != nil {
- return nil, 0, err
- }
- r, err = co.ReadMsg()
- if err == nil && r.Id != m.Id {
- err = ErrId
- }
- return r, co.rtt, err
-}
-
-// ReadMsg reads a message from the connection co.
-// If the received message contains a TSIG record the transaction
-// signature is verified.
-func (co *Conn) ReadMsg() (*Msg, error) {
- p, err := co.ReadMsgHeader(nil)
- if err != nil {
- return nil, err
- }
-
- m := new(Msg)
- if err := m.Unpack(p); err != nil {
- return nil, err
- }
- if t := m.IsTsig(); t != nil {
- if _, ok := co.TsigSecret[t.Hdr.Name]; !ok {
- return m, ErrSecret
- }
- // Need to work on the original message p, as that was used to calculate the tsig.
- err = TsigVerify(p, co.TsigSecret[t.Hdr.Name], co.tsigRequestMAC, false)
- }
- return m, err
-}
-
-// ReadMsgHeader reads a DNS message, parses and populates hdr (when hdr is not nil).
-// Returns message as a byte slice to be parsed with Msg.Unpack later on.
-// Note that error handling on the message body is not possible as only the header is parsed.
-func (co *Conn) ReadMsgHeader(hdr *Header) ([]byte, error) {
- var (
- p []byte
- n int
- err error
- )
-
- if t, ok := co.Conn.(*net.TCPConn); ok {
- // First two bytes specify the length of the entire message.
- l, err := tcpMsgLen(t)
- if err != nil {
- return nil, err
- }
- p = make([]byte, l)
- n, err = tcpRead(t, p)
- } else {
- if co.UDPSize > MinMsgSize {
- p = make([]byte, co.UDPSize)
- } else {
- p = make([]byte, MinMsgSize)
- }
- n, err = co.Read(p)
- }
-
- if err != nil {
- return nil, err
- } else if n < headerSize {
- return nil, ErrShortRead
- }
-
- p = p[:n]
- if hdr != nil {
- if _, err = UnpackStruct(hdr, p, 0); err != nil {
- return nil, err
- }
- }
- return p, err
-}
-
-// tcpMsgLen is a helper func to read first two bytes of stream as uint16 packet length.
-func tcpMsgLen(t *net.TCPConn) (int, error) {
- p := []byte{0, 0}
- n, err := t.Read(p)
- if err != nil {
- return 0, err
- }
- if n != 2 {
- return 0, ErrShortRead
- }
- l, _ := unpackUint16(p, 0)
- if l == 0 {
- return 0, ErrShortRead
- }
- return int(l), nil
-}
-
-// tcpRead calls TCPConn.Read enough times to fill allocated buffer.
-func tcpRead(t *net.TCPConn, p []byte) (int, error) {
- n, err := t.Read(p)
- if err != nil {
- return n, err
- }
- for n < len(p) {
- j, err := t.Read(p[n:])
- if err != nil {
- return n, err
- }
- n += j
- }
- return n, err
-}
-
-// Read implements the net.Conn read method.
-func (co *Conn) Read(p []byte) (n int, err error) {
- if co.Conn == nil {
- return 0, ErrConnEmpty
- }
- if len(p) < 2 {
- return 0, io.ErrShortBuffer
- }
- if t, ok := co.Conn.(*net.TCPConn); ok {
- l, err := tcpMsgLen(t)
- if err != nil {
- return 0, err
- }
- if l > len(p) {
- return int(l), io.ErrShortBuffer
- }
- return tcpRead(t, p[:l])
- }
- // UDP connection
- n, err = co.Conn.Read(p)
- if err != nil {
- return n, err
- }
-
- co.rtt = time.Since(co.t)
- return n, err
-}
-
-// WriteMsg sends a message throught the connection co.
-// If the message m contains a TSIG record the transaction
-// signature is calculated.
-func (co *Conn) WriteMsg(m *Msg) (err error) {
- var out []byte
- if t := m.IsTsig(); t != nil {
- mac := ""
- if _, ok := co.TsigSecret[t.Hdr.Name]; !ok {
- return ErrSecret
- }
- out, mac, err = TsigGenerate(m, co.TsigSecret[t.Hdr.Name], co.tsigRequestMAC, false)
- // Set for the next read, allthough only used in zone transfers
- co.tsigRequestMAC = mac
- } else {
- out, err = m.Pack()
- }
- if err != nil {
- return err
- }
- co.t = time.Now()
- if _, err = co.Write(out); err != nil {
- return err
- }
- return nil
-}
-
-// Write implements the net.Conn Write method.
-func (co *Conn) Write(p []byte) (n int, err error) {
- if t, ok := co.Conn.(*net.TCPConn); ok {
- lp := len(p)
- if lp < 2 {
- return 0, io.ErrShortBuffer
- }
- if lp > MaxMsgSize {
- return 0, &Error{err: "message too large"}
- }
- l := make([]byte, 2, lp+2)
- l[0], l[1] = packUint16(uint16(lp))
- p = append(l, p...)
- n, err := io.Copy(t, bytes.NewReader(p))
- return int(n), err
- }
- n, err = co.Conn.(*net.UDPConn).Write(p)
- return n, err
-}
-
-// Dial connects to the address on the named network.
-func Dial(network, address string) (conn *Conn, err error) {
- conn = new(Conn)
- conn.Conn, err = net.Dial(network, address)
- if err != nil {
- return nil, err
- }
- return conn, nil
-}
-
-// DialTimeout acts like Dial but takes a timeout.
-func DialTimeout(network, address string, timeout time.Duration) (conn *Conn, err error) {
- conn = new(Conn)
- conn.Conn, err = net.DialTimeout(network, address, timeout)
- if err != nil {
- return nil, err
- }
- return conn, nil
-}
diff --git a/Godeps/_workspace/src/github.com/miekg/dns/client_test.go b/Godeps/_workspace/src/github.com/miekg/dns/client_test.go
deleted file mode 100644
index f2ade1485a..0000000000
--- a/Godeps/_workspace/src/github.com/miekg/dns/client_test.go
+++ /dev/null
@@ -1,286 +0,0 @@
-package dns
-
-import (
- "strconv"
- "testing"
- "time"
-)
-
-func TestClientSync(t *testing.T) {
- HandleFunc("miek.nl.", HelloServer)
- defer HandleRemove("miek.nl.")
-
- s, addrstr, err := RunLocalUDPServer("127.0.0.1:0")
- if err != nil {
- t.Fatalf("Unable to run test server: %v", err)
- }
- defer s.Shutdown()
-
- m := new(Msg)
- m.SetQuestion("miek.nl.", TypeSOA)
-
- c := new(Client)
- r, _, err := c.Exchange(m, addrstr)
- if err != nil {
- t.Errorf("failed to exchange: %v", err)
- }
- if r != nil && r.Rcode != RcodeSuccess {
- t.Errorf("failed to get an valid answer\n%v", r)
- }
- // And now with plain Exchange().
- r, err = Exchange(m, addrstr)
- if err != nil {
- t.Errorf("failed to exchange: %v", err)
- }
- if r == nil || r.Rcode != RcodeSuccess {
- t.Errorf("failed to get an valid answer\n%v", r)
- }
-}
-
-func TestClientSyncBadId(t *testing.T) {
- HandleFunc("miek.nl.", HelloServerBadId)
- defer HandleRemove("miek.nl.")
-
- s, addrstr, err := RunLocalUDPServer("127.0.0.1:0")
- if err != nil {
- t.Fatalf("Unable to run test server: %v", err)
- }
- defer s.Shutdown()
-
- m := new(Msg)
- m.SetQuestion("miek.nl.", TypeSOA)
-
- c := new(Client)
- if _, _, err := c.Exchange(m, addrstr); err != ErrId {
- t.Errorf("did not find a bad Id")
- }
- // And now with plain Exchange().
- if _, err := Exchange(m, addrstr); err != ErrId {
- t.Errorf("did not find a bad Id")
- }
-}
-
-func TestClientEDNS0(t *testing.T) {
- HandleFunc("miek.nl.", HelloServer)
- defer HandleRemove("miek.nl.")
-
- s, addrstr, err := RunLocalUDPServer("127.0.0.1:0")
- if err != nil {
- t.Fatalf("Unable to run test server: %v", err)
- }
- defer s.Shutdown()
-
- m := new(Msg)
- m.SetQuestion("miek.nl.", TypeDNSKEY)
-
- m.SetEdns0(2048, true)
-
- c := new(Client)
- r, _, err := c.Exchange(m, addrstr)
- if err != nil {
- t.Errorf("failed to exchange: %v", err)
- }
-
- if r != nil && r.Rcode != RcodeSuccess {
- t.Errorf("failed to get an valid answer\n%v", r)
- }
-}
-
-// Validates the transmission and parsing of local EDNS0 options.
-func TestClientEDNS0Local(t *testing.T) {
-
- optStr1 := "1979:0x0707"
- optStr2 := strconv.Itoa(EDNS0LOCALSTART) + ":0x0601"
-
- handler := func(w ResponseWriter, req *Msg) {
- m := new(Msg)
- m.SetReply(req)
-
- m.Extra = make([]RR, 1, 2)
- m.Extra[0] = &TXT{Hdr: RR_Header{Name: m.Question[0].Name, Rrtype: TypeTXT, Class: ClassINET, Ttl: 0}, Txt: []string{"Hello local edns"}}
-
- // If the local options are what we expect, then reflect them back.
- ec1 := req.Extra[0].(*OPT).Option[0].(*EDNS0_LOCAL).String()
- ec2 := req.Extra[0].(*OPT).Option[1].(*EDNS0_LOCAL).String()
- if ec1 == optStr1 && ec2 == optStr2 {
- m.Extra = append(m.Extra, req.Extra[0])
- }
-
- w.WriteMsg(m)
- }
-
- HandleFunc("miek.nl.", handler)
- defer HandleRemove("miek.nl.")
-
- s, addrstr, err := RunLocalUDPServer("127.0.0.1:0")
- if err != nil {
- t.Fatalf("Unable to run test server: %s", err)
- }
- defer s.Shutdown()
-
- m := new(Msg)
- m.SetQuestion("miek.nl.", TypeTXT)
-
- // Add two local edns options to the query.
- ec1 := &EDNS0_LOCAL{Code: 1979, Data: []byte{7, 7}}
- ec2 := &EDNS0_LOCAL{Code: EDNS0LOCALSTART, Data: []byte{6, 1}}
- o := &OPT{Hdr: RR_Header{Name: ".", Rrtype: TypeOPT}, Option: []EDNS0{ec1, ec2}}
- m.Extra = append(m.Extra, o)
-
- c := new(Client)
- r, _, e := c.Exchange(m, addrstr)
- if e != nil {
- t.Logf("failed to exchange: %s", e.Error())
- t.Fail()
- }
-
- if r != nil && r.Rcode != RcodeSuccess {
- t.Log("failed to get a valid answer")
- t.Fail()
- t.Logf("%v\n", r)
- }
-
- txt := r.Extra[0].(*TXT).Txt[0]
- if txt != "Hello local edns" {
- t.Log("Unexpected result for miek.nl", txt, "!= Hello local edns")
- t.Fail()
- }
-
- // Validate the local options in the reply.
- got := r.Extra[1].(*OPT).Option[0].(*EDNS0_LOCAL).String()
- if got != optStr1 {
- t.Log("failed to get local edns0 answer; got %s, expected %s", got, optStr1)
- t.Fail()
- t.Logf("%v\n", r)
- }
-
- got = r.Extra[1].(*OPT).Option[1].(*EDNS0_LOCAL).String()
- if got != optStr2 {
- t.Log("failed to get local edns0 answer; got %s, expected %s", got, optStr2)
- t.Fail()
- t.Logf("%v\n", r)
- }
-}
-
-func TestSingleSingleInflight(t *testing.T) {
- HandleFunc("miek.nl.", HelloServer)
- defer HandleRemove("miek.nl.")
-
- s, addrstr, err := RunLocalUDPServer("127.0.0.1:0")
- if err != nil {
- t.Fatalf("Unable to run test server: %v", err)
- }
- defer s.Shutdown()
-
- m := new(Msg)
- m.SetQuestion("miek.nl.", TypeDNSKEY)
-
- c := new(Client)
- c.SingleInflight = true
- nr := 10
- ch := make(chan time.Duration)
- for i := 0; i < nr; i++ {
- go func() {
- _, rtt, _ := c.Exchange(m, addrstr)
- ch <- rtt
- }()
- }
- i := 0
- var first time.Duration
- // With inflight *all* rtt are identical, and by doing actual lookups
- // the changes that this is a coincidence is small.
-Loop:
- for {
- select {
- case rtt := <-ch:
- if i == 0 {
- first = rtt
- } else {
- if first != rtt {
- t.Errorf("all rtts should be equal. got %d want %d", rtt, first)
- }
- }
- i++
- if i == 10 {
- break Loop
- }
- }
- }
-}
-
-// ExampleUpdateLeaseTSIG shows how to update a lease signed with TSIG.
-func ExampleUpdateLeaseTSIG(t *testing.T) {
- m := new(Msg)
- m.SetUpdate("t.local.ip6.io.")
- rr, _ := NewRR("t.local.ip6.io. 30 A 127.0.0.1")
- rrs := make([]RR, 1)
- rrs[0] = rr
- m.Insert(rrs)
-
- leaseRr := new(OPT)
- leaseRr.Hdr.Name = "."
- leaseRr.Hdr.Rrtype = TypeOPT
- e := new(EDNS0_UL)
- e.Code = EDNS0UL
- e.Lease = 120
- leaseRr.Option = append(leaseRr.Option, e)
- m.Extra = append(m.Extra, leaseRr)
-
- c := new(Client)
- m.SetTsig("polvi.", HmacMD5, 300, time.Now().Unix())
- c.TsigSecret = map[string]string{"polvi.": "pRZgBrBvI4NAHZYhxmhs/Q=="}
-
- _, _, err := c.Exchange(m, "127.0.0.1:53")
- if err != nil {
- t.Error(err)
- }
-}
-
-func TestClientConn(t *testing.T) {
- HandleFunc("miek.nl.", HelloServer)
- defer HandleRemove("miek.nl.")
-
- // This uses TCP just to make it slightly different than TestClientSync
- s, addrstr, err := RunLocalTCPServer("127.0.0.1:0")
- if err != nil {
- t.Fatalf("Unable to run test server: %v", err)
- }
- defer s.Shutdown()
-
- m := new(Msg)
- m.SetQuestion("miek.nl.", TypeSOA)
-
- cn, err := Dial("tcp", addrstr)
- if err != nil {
- t.Errorf("failed to dial %s: %v", addrstr, err)
- }
-
- err = cn.WriteMsg(m)
- if err != nil {
- t.Errorf("failed to exchange: %v", err)
- }
- r, err := cn.ReadMsg()
- if r == nil || r.Rcode != RcodeSuccess {
- t.Errorf("failed to get an valid answer\n%v", r)
- }
-
- err = cn.WriteMsg(m)
- if err != nil {
- t.Errorf("failed to exchange: %v", err)
- }
- h := new(Header)
- buf, err := cn.ReadMsgHeader(h)
- if buf == nil {
- t.Errorf("failed to get an valid answer\n%v", r)
- }
- if int(h.Bits&0xF) != RcodeSuccess {
- t.Errorf("failed to get an valid answer in ReadMsgHeader\n%v", r)
- }
- if h.Ancount != 0 || h.Qdcount != 1 || h.Nscount != 0 || h.Arcount != 1 {
- t.Errorf("expected to have question and additional in response; got something else: %+v", h)
- }
- if err = r.Unpack(buf); err != nil {
- t.Errorf("unable to unpack message fully: %v", err)
- }
-
-}
diff --git a/Godeps/_workspace/src/github.com/miekg/dns/clientconfig.go b/Godeps/_workspace/src/github.com/miekg/dns/clientconfig.go
deleted file mode 100644
index cfa9ad0b22..0000000000
--- a/Godeps/_workspace/src/github.com/miekg/dns/clientconfig.go
+++ /dev/null
@@ -1,99 +0,0 @@
-package dns
-
-import (
- "bufio"
- "os"
- "strconv"
- "strings"
-)
-
-// ClientConfig wraps the contents of the /etc/resolv.conf file.
-type ClientConfig struct {
- Servers []string // servers to use
- Search []string // suffixes to append to local name
- Port string // what port to use
- Ndots int // number of dots in name to trigger absolute lookup
- Timeout int // seconds before giving up on packet
- Attempts int // lost packets before giving up on server, not used in the package dns
-}
-
-// ClientConfigFromFile parses a resolv.conf(5) like file and returns
-// a *ClientConfig.
-func ClientConfigFromFile(resolvconf string) (*ClientConfig, error) {
- file, err := os.Open(resolvconf)
- if err != nil {
- return nil, err
- }
- defer file.Close()
- c := new(ClientConfig)
- scanner := bufio.NewScanner(file)
- c.Servers = make([]string, 0)
- c.Search = make([]string, 0)
- c.Port = "53"
- c.Ndots = 1
- c.Timeout = 5
- c.Attempts = 2
-
- for scanner.Scan() {
- if err := scanner.Err(); err != nil {
- return nil, err
- }
- line := scanner.Text()
- f := strings.Fields(line)
- if len(f) < 1 {
- continue
- }
- switch f[0] {
- case "nameserver": // add one name server
- if len(f) > 1 {
- // One more check: make sure server name is
- // just an IP address. Otherwise we need DNS
- // to look it up.
- name := f[1]
- c.Servers = append(c.Servers, name)
- }
-
- case "domain": // set search path to just this domain
- if len(f) > 1 {
- c.Search = make([]string, 1)
- c.Search[0] = f[1]
- } else {
- c.Search = make([]string, 0)
- }
-
- case "search": // set search path to given servers
- c.Search = make([]string, len(f)-1)
- for i := 0; i < len(c.Search); i++ {
- c.Search[i] = f[i+1]
- }
-
- case "options": // magic options
- for i := 1; i < len(f); i++ {
- s := f[i]
- switch {
- case len(s) >= 6 && s[:6] == "ndots:":
- n, _ := strconv.Atoi(s[6:])
- if n < 1 {
- n = 1
- }
- c.Ndots = n
- case len(s) >= 8 && s[:8] == "timeout:":
- n, _ := strconv.Atoi(s[8:])
- if n < 1 {
- n = 1
- }
- c.Timeout = n
- case len(s) >= 8 && s[:9] == "attempts:":
- n, _ := strconv.Atoi(s[9:])
- if n < 1 {
- n = 1
- }
- c.Attempts = n
- case s == "rotate":
- /* not imp */
- }
- }
- }
- }
- return c, nil
-}
diff --git a/Godeps/_workspace/src/github.com/miekg/dns/clientconfig_test.go b/Godeps/_workspace/src/github.com/miekg/dns/clientconfig_test.go
deleted file mode 100644
index f01a59be6a..0000000000
--- a/Godeps/_workspace/src/github.com/miekg/dns/clientconfig_test.go
+++ /dev/null
@@ -1,55 +0,0 @@
-package dns
-
-import (
- "io/ioutil"
- "os"
- "path/filepath"
- "testing"
-)
-
-const normal string = `
-# Comment
-domain somedomain.com
-nameserver 10.28.10.2
-nameserver 11.28.10.1
-`
-
-const missingNewline string = `
-domain somedomain.com
-nameserver 10.28.10.2
-nameserver 11.28.10.1` // <- NOTE: NO newline.
-
-func testConfig(t *testing.T, data string) {
- tempDir, err := ioutil.TempDir("", "")
- if err != nil {
- t.Fatalf("TempDir: %v", err)
- }
- defer os.RemoveAll(tempDir)
-
- path := filepath.Join(tempDir, "resolv.conf")
- if err := ioutil.WriteFile(path, []byte(data), 0644); err != nil {
- t.Fatalf("WriteFile: %v", err)
- }
- cc, err := ClientConfigFromFile(path)
- if err != nil {
- t.Errorf("error parsing resolv.conf: %v", err)
- }
- if l := len(cc.Servers); l != 2 {
- t.Errorf("incorrect number of nameservers detected: %d", l)
- }
- if l := len(cc.Search); l != 1 {
- t.Errorf("domain directive not parsed correctly: %v", cc.Search)
- } else {
- if cc.Search[0] != "somedomain.com" {
- t.Errorf("domain is unexpected: %v", cc.Search[0])
- }
- }
-}
-
-func TestNameserver(t *testing.T) {
- testConfig(t, normal)
-}
-
-func TestMissingFinalNewLine(t *testing.T) {
- testConfig(t, missingNewline)
-}
diff --git a/Godeps/_workspace/src/github.com/miekg/dns/defaults.go b/Godeps/_workspace/src/github.com/miekg/dns/defaults.go
deleted file mode 100644
index 09331c9f60..0000000000
--- a/Godeps/_workspace/src/github.com/miekg/dns/defaults.go
+++ /dev/null
@@ -1,248 +0,0 @@
-package dns
-
-import (
- "errors"
- "net"
- "strconv"
-)
-
-const hexDigit = "0123456789abcdef"
-
-// Everything is assumed in ClassINET.
-
-// SetReply creates a reply message from a request message.
-func (dns *Msg) SetReply(request *Msg) *Msg {
- dns.Id = request.Id
- dns.RecursionDesired = request.RecursionDesired // Copy rd bit
- dns.Response = true
- dns.Opcode = OpcodeQuery
- dns.Rcode = RcodeSuccess
- if len(request.Question) > 0 {
- dns.Question = make([]Question, 1)
- dns.Question[0] = request.Question[0]
- }
- return dns
-}
-
-// SetQuestion creates a question message, it sets the Question
-// section, generates an Id and sets the RecursionDesired (RD)
-// bit to true.
-func (dns *Msg) SetQuestion(z string, t uint16) *Msg {
- dns.Id = Id()
- dns.RecursionDesired = true
- dns.Question = make([]Question, 1)
- dns.Question[0] = Question{z, t, ClassINET}
- return dns
-}
-
-// SetNotify creates a notify message, it sets the Question
-// section, generates an Id and sets the Authoritative (AA)
-// bit to true.
-func (dns *Msg) SetNotify(z string) *Msg {
- dns.Opcode = OpcodeNotify
- dns.Authoritative = true
- dns.Id = Id()
- dns.Question = make([]Question, 1)
- dns.Question[0] = Question{z, TypeSOA, ClassINET}
- return dns
-}
-
-// SetRcode creates an error message suitable for the request.
-func (dns *Msg) SetRcode(request *Msg, rcode int) *Msg {
- dns.SetReply(request)
- dns.Rcode = rcode
- return dns
-}
-
-// SetRcodeFormatError creates a message with FormError set.
-func (dns *Msg) SetRcodeFormatError(request *Msg) *Msg {
- dns.Rcode = RcodeFormatError
- dns.Opcode = OpcodeQuery
- dns.Response = true
- dns.Authoritative = false
- dns.Id = request.Id
- return dns
-}
-
-// SetUpdate makes the message a dynamic update message. It
-// sets the ZONE section to: z, TypeSOA, ClassINET.
-func (dns *Msg) SetUpdate(z string) *Msg {
- dns.Id = Id()
- dns.Response = false
- dns.Opcode = OpcodeUpdate
- dns.Compress = false // BIND9 cannot handle compression
- dns.Question = make([]Question, 1)
- dns.Question[0] = Question{z, TypeSOA, ClassINET}
- return dns
-}
-
-// SetIxfr creates message for requesting an IXFR.
-func (dns *Msg) SetIxfr(z string, serial uint32, ns, mbox string) *Msg {
- dns.Id = Id()
- dns.Question = make([]Question, 1)
- dns.Ns = make([]RR, 1)
- s := new(SOA)
- s.Hdr = RR_Header{z, TypeSOA, ClassINET, defaultTtl, 0}
- s.Serial = serial
- s.Ns = ns
- s.Mbox = mbox
- dns.Question[0] = Question{z, TypeIXFR, ClassINET}
- dns.Ns[0] = s
- return dns
-}
-
-// SetAxfr creates message for requesting an AXFR.
-func (dns *Msg) SetAxfr(z string) *Msg {
- dns.Id = Id()
- dns.Question = make([]Question, 1)
- dns.Question[0] = Question{z, TypeAXFR, ClassINET}
- return dns
-}
-
-// SetTsig appends a TSIG RR to the message.
-// This is only a skeleton TSIG RR that is added as the last RR in the
-// additional section. The Tsig is calculated when the message is being send.
-func (dns *Msg) SetTsig(z, algo string, fudge, timesigned int64) *Msg {
- t := new(TSIG)
- t.Hdr = RR_Header{z, TypeTSIG, ClassANY, 0, 0}
- t.Algorithm = algo
- t.Fudge = 300
- t.TimeSigned = uint64(timesigned)
- t.OrigId = dns.Id
- dns.Extra = append(dns.Extra, t)
- return dns
-}
-
-// SetEdns0 appends a EDNS0 OPT RR to the message.
-// TSIG should always the last RR in a message.
-func (dns *Msg) SetEdns0(udpsize uint16, do bool) *Msg {
- e := new(OPT)
- e.Hdr.Name = "."
- e.Hdr.Rrtype = TypeOPT
- e.SetUDPSize(udpsize)
- if do {
- e.SetDo()
- }
- dns.Extra = append(dns.Extra, e)
- return dns
-}
-
-// IsTsig checks if the message has a TSIG record as the last record
-// in the additional section. It returns the TSIG record found or nil.
-func (dns *Msg) IsTsig() *TSIG {
- if len(dns.Extra) > 0 {
- if dns.Extra[len(dns.Extra)-1].Header().Rrtype == TypeTSIG {
- return dns.Extra[len(dns.Extra)-1].(*TSIG)
- }
- }
- return nil
-}
-
-// IsEdns0 checks if the message has a EDNS0 (OPT) record, any EDNS0
-// record in the additional section will do. It returns the OPT record
-// found or nil.
-func (dns *Msg) IsEdns0() *OPT {
- for _, r := range dns.Extra {
- if r.Header().Rrtype == TypeOPT {
- return r.(*OPT)
- }
- }
- return nil
-}
-
-// IsDomainName checks if s is a valid domainname, it returns
-// the number of labels and true, when a domain name is valid.
-// Note that non fully qualified domain name is considered valid, in this case the
-// last label is counted in the number of labels.
-// When false is returned the number of labels is not defined.
-func IsDomainName(s string) (labels int, ok bool) {
- _, labels, err := packDomainName(s, nil, 0, nil, false)
- return labels, err == nil
-}
-
-// IsSubDomain checks if child is indeed a child of the parent. Both child and
-// parent are *not* downcased before doing the comparison.
-func IsSubDomain(parent, child string) bool {
- // Entire child is contained in parent
- return CompareDomainName(parent, child) == CountLabel(parent)
-}
-
-// IsMsg sanity checks buf and returns an error if it isn't a valid DNS packet.
-// The checking is performed on the binary payload.
-func IsMsg(buf []byte) error {
- // Header
- if len(buf) < 12 {
- return errors.New("dns: bad message header")
- }
- // Header: Opcode
- // TODO(miek): more checks here, e.g. check all header bits.
- return nil
-}
-
-// IsFqdn checks if a domain name is fully qualified.
-func IsFqdn(s string) bool {
- l := len(s)
- if l == 0 {
- return false
- }
- return s[l-1] == '.'
-}
-
-// Fqdn return the fully qualified domain name from s.
-// If s is already fully qualified, it behaves as the identity function.
-func Fqdn(s string) string {
- if IsFqdn(s) {
- return s
- }
- return s + "."
-}
-
-// Copied from the official Go code.
-
-// ReverseAddr returns the in-addr.arpa. or ip6.arpa. hostname of the IP
-// address suitable for reverse DNS (PTR) record lookups or an error if it fails
-// to parse the IP address.
-func ReverseAddr(addr string) (arpa string, err error) {
- ip := net.ParseIP(addr)
- if ip == nil {
- return "", &Error{err: "unrecognized address: " + addr}
- }
- if ip.To4() != nil {
- return strconv.Itoa(int(ip[15])) + "." + strconv.Itoa(int(ip[14])) + "." + strconv.Itoa(int(ip[13])) + "." +
- strconv.Itoa(int(ip[12])) + ".in-addr.arpa.", nil
- }
- // Must be IPv6
- buf := make([]byte, 0, len(ip)*4+len("ip6.arpa."))
- // Add it, in reverse, to the buffer
- for i := len(ip) - 1; i >= 0; i-- {
- v := ip[i]
- buf = append(buf, hexDigit[v&0xF])
- buf = append(buf, '.')
- buf = append(buf, hexDigit[v>>4])
- buf = append(buf, '.')
- }
- // Append "ip6.arpa." and return (buf already has the final .)
- buf = append(buf, "ip6.arpa."...)
- return string(buf), nil
-}
-
-// String returns the string representation for the type t.
-func (t Type) String() string {
- if t1, ok := TypeToString[uint16(t)]; ok {
- return t1
- }
- return "TYPE" + strconv.Itoa(int(t))
-}
-
-// String returns the string representation for the class c.
-func (c Class) String() string {
- if c1, ok := ClassToString[uint16(c)]; ok {
- return c1
- }
- return "CLASS" + strconv.Itoa(int(c))
-}
-
-// String returns the string representation for the name n.
-func (n Name) String() string {
- return sprintName(string(n))
-}
diff --git a/Godeps/_workspace/src/github.com/miekg/dns/dns.go b/Godeps/_workspace/src/github.com/miekg/dns/dns.go
deleted file mode 100644
index 1c37a09dd2..0000000000
--- a/Godeps/_workspace/src/github.com/miekg/dns/dns.go
+++ /dev/null
@@ -1,102 +0,0 @@
-package dns
-
-import "strconv"
-
-const (
- year68 = 1 << 31 // For RFC1982 (Serial Arithmetic) calculations in 32 bits.
- // DefaultMsgSize is the standard default for messages larger than 512 bytes.
- DefaultMsgSize = 4096
- // MinMsgSize is the minimal size of a DNS packet.
- MinMsgSize = 512
- // MaxMsgSize is the largest possible DNS packet.
- MaxMsgSize = 65535
- defaultTtl = 3600 // Default internal TTL.
-)
-
-// Error represents a DNS error
-type Error struct{ err string }
-
-func (e *Error) Error() string {
- if e == nil {
- return "dns: "
- }
- return "dns: " + e.err
-}
-
-// An RR represents a resource record.
-type RR interface {
- // Header returns the header of an resource record. The header contains
- // everything up to the rdata.
- Header() *RR_Header
- // String returns the text representation of the resource record.
- String() string
- // copy returns a copy of the RR
- copy() RR
- // len returns the length (in octets) of the uncompressed RR in wire format.
- len() int
-}
-
-// DNS resource records.
-// There are many types of RRs,
-// but they all share the same header.
-type RR_Header struct {
- Name string `dns:"cdomain-name"`
- Rrtype uint16
- Class uint16
- Ttl uint32
- Rdlength uint16 // length of data after header
-}
-
-// Header returns itself. This is here to make RR_Header implement the RR interface.
-func (h *RR_Header) Header() *RR_Header { return h }
-
-// Just to imlement the RR interface.
-func (h *RR_Header) copy() RR { return nil }
-
-func (h *RR_Header) copyHeader() *RR_Header {
- r := new(RR_Header)
- r.Name = h.Name
- r.Rrtype = h.Rrtype
- r.Class = h.Class
- r.Ttl = h.Ttl
- r.Rdlength = h.Rdlength
- return r
-}
-
-func (h *RR_Header) String() string {
- var s string
-
- if h.Rrtype == TypeOPT {
- s = ";"
- // and maybe other things
- }
-
- s += sprintName(h.Name) + "\t"
- s += strconv.FormatInt(int64(h.Ttl), 10) + "\t"
- s += Class(h.Class).String() + "\t"
- s += Type(h.Rrtype).String() + "\t"
- return s
-}
-
-func (h *RR_Header) len() int {
- l := len(h.Name) + 1
- l += 10 // rrtype(2) + class(2) + ttl(4) + rdlength(2)
- return l
-}
-
-// ToRFC3597 converts a known RR to the unknown RR representation
-// from RFC 3597.
-func (rr *RFC3597) ToRFC3597(r RR) error {
- buf := make([]byte, r.len()*2)
- off, err := PackStruct(r, buf, 0)
- if err != nil {
- return err
- }
- buf = buf[:off]
- rawSetRdlength(buf, 0, off)
- _, err = UnpackStruct(rr, buf, 0)
- if err != nil {
- return err
- }
- return nil
-}
diff --git a/Godeps/_workspace/src/github.com/miekg/dns/dns_test.go b/Godeps/_workspace/src/github.com/miekg/dns/dns_test.go
deleted file mode 100644
index 7cf810eac7..0000000000
--- a/Godeps/_workspace/src/github.com/miekg/dns/dns_test.go
+++ /dev/null
@@ -1,578 +0,0 @@
-package dns
-
-import (
- "encoding/hex"
- "net"
- "testing"
-)
-
-func TestPackUnpack(t *testing.T) {
- out := new(Msg)
- out.Answer = make([]RR, 1)
- key := new(DNSKEY)
- key = &DNSKEY{Flags: 257, Protocol: 3, Algorithm: RSASHA1}
- key.Hdr = RR_Header{Name: "miek.nl.", Rrtype: TypeDNSKEY, Class: ClassINET, Ttl: 3600}
- key.PublicKey = "AwEAAaHIwpx3w4VHKi6i1LHnTaWeHCL154Jug0Rtc9ji5qwPXpBo6A5sRv7cSsPQKPIwxLpyCrbJ4mr2L0EPOdvP6z6YfljK2ZmTbogU9aSU2fiq/4wjxbdkLyoDVgtO+JsxNN4bjr4WcWhsmk1Hg93FV9ZpkWb0Tbad8DFqNDzr//kZ"
-
- out.Answer[0] = key
- msg, err := out.Pack()
- if err != nil {
- t.Error("failed to pack msg with DNSKEY")
- }
- in := new(Msg)
- if in.Unpack(msg) != nil {
- t.Error("failed to unpack msg with DNSKEY")
- }
-
- sig := new(RRSIG)
- sig = &RRSIG{TypeCovered: TypeDNSKEY, Algorithm: RSASHA1, Labels: 2,
- OrigTtl: 3600, Expiration: 4000, Inception: 4000, KeyTag: 34641, SignerName: "miek.nl.",
- Signature: "AwEAAaHIwpx3w4VHKi6i1LHnTaWeHCL154Jug0Rtc9ji5qwPXpBo6A5sRv7cSsPQKPIwxLpyCrbJ4mr2L0EPOdvP6z6YfljK2ZmTbogU9aSU2fiq/4wjxbdkLyoDVgtO+JsxNN4bjr4WcWhsmk1Hg93FV9ZpkWb0Tbad8DFqNDzr//kZ"}
- sig.Hdr = RR_Header{Name: "miek.nl.", Rrtype: TypeRRSIG, Class: ClassINET, Ttl: 3600}
-
- out.Answer[0] = sig
- msg, err = out.Pack()
- if err != nil {
- t.Error("failed to pack msg with RRSIG")
- }
-
- if in.Unpack(msg) != nil {
- t.Error("failed to unpack msg with RRSIG")
- }
-}
-
-func TestPackUnpack2(t *testing.T) {
- m := new(Msg)
- m.Extra = make([]RR, 1)
- m.Answer = make([]RR, 1)
- dom := "miek.nl."
- rr := new(A)
- rr.Hdr = RR_Header{Name: dom, Rrtype: TypeA, Class: ClassINET, Ttl: 0}
- rr.A = net.IPv4(127, 0, 0, 1)
-
- x := new(TXT)
- x.Hdr = RR_Header{Name: dom, Rrtype: TypeTXT, Class: ClassINET, Ttl: 0}
- x.Txt = []string{"heelalaollo"}
-
- m.Extra[0] = x
- m.Answer[0] = rr
- _, err := m.Pack()
- if err != nil {
- t.Error("Packing failed: ", err)
- return
- }
-}
-
-func TestPackUnpack3(t *testing.T) {
- m := new(Msg)
- m.Extra = make([]RR, 2)
- m.Answer = make([]RR, 1)
- dom := "miek.nl."
- rr := new(A)
- rr.Hdr = RR_Header{Name: dom, Rrtype: TypeA, Class: ClassINET, Ttl: 0}
- rr.A = net.IPv4(127, 0, 0, 1)
-
- x1 := new(TXT)
- x1.Hdr = RR_Header{Name: dom, Rrtype: TypeTXT, Class: ClassINET, Ttl: 0}
- x1.Txt = []string{}
-
- x2 := new(TXT)
- x2.Hdr = RR_Header{Name: dom, Rrtype: TypeTXT, Class: ClassINET, Ttl: 0}
- x2.Txt = []string{"heelalaollo"}
-
- m.Extra[0] = x1
- m.Extra[1] = x2
- m.Answer[0] = rr
- b, err := m.Pack()
- if err != nil {
- t.Error("packing failed: ", err)
- return
- }
-
- var unpackMsg Msg
- err = unpackMsg.Unpack(b)
- if err != nil {
- t.Error("unpacking failed")
- return
- }
-}
-
-func TestBailiwick(t *testing.T) {
- yes := map[string]string{
- "miek.nl": "ns.miek.nl",
- ".": "miek.nl",
- }
- for parent, child := range yes {
- if !IsSubDomain(parent, child) {
- t.Errorf("%s should be child of %s", child, parent)
- t.Errorf("comparelabels %d", CompareDomainName(parent, child))
- t.Errorf("lenlabels %d %d", CountLabel(parent), CountLabel(child))
- }
- }
- no := map[string]string{
- "www.miek.nl": "ns.miek.nl",
- "m\\.iek.nl": "ns.miek.nl",
- "w\\.iek.nl": "w.iek.nl",
- "p\\\\.iek.nl": "ns.p.iek.nl", // p\\.iek.nl , literal \ in domain name
- "miek.nl": ".",
- }
- for parent, child := range no {
- if IsSubDomain(parent, child) {
- t.Errorf("%s should not be child of %s", child, parent)
- t.Errorf("comparelabels %d", CompareDomainName(parent, child))
- t.Errorf("lenlabels %d %d", CountLabel(parent), CountLabel(child))
- }
- }
-}
-
-func TestPack(t *testing.T) {
- rr := []string{"US. 86400 IN NSEC 0-.us. NS SOA RRSIG NSEC DNSKEY TYPE65534"}
- m := new(Msg)
- var err error
- m.Answer = make([]RR, 1)
- for _, r := range rr {
- m.Answer[0], err = NewRR(r)
- if err != nil {
- t.Errorf("failed to create RR: %v", err)
- continue
- }
- if _, err := m.Pack(); err != nil {
- t.Errorf("packing failed: %v", err)
- }
- }
- x := new(Msg)
- ns, _ := NewRR("pool.ntp.org. 390 IN NS a.ntpns.org")
- ns.(*NS).Ns = "a.ntpns.org"
- x.Ns = append(m.Ns, ns)
- x.Ns = append(m.Ns, ns)
- x.Ns = append(m.Ns, ns)
- // This crashes due to the fact the a.ntpns.org isn't a FQDN
- // How to recover() from a remove panic()?
- if _, err := x.Pack(); err == nil {
- t.Error("packing should fail")
- }
- x.Answer = make([]RR, 1)
- x.Answer[0], err = NewRR(rr[0])
- if _, err := x.Pack(); err == nil {
- t.Error("packing should fail")
- }
- x.Question = make([]Question, 1)
- x.Question[0] = Question{";sd#eddddséâèµââ
â¥âxzztsestxssweewwsssstx@s@Zåµe@cn.pool.ntp.org.", TypeA, ClassINET}
- if _, err := x.Pack(); err == nil {
- t.Error("packing should fail")
- }
-}
-
-func TestPackNAPTR(t *testing.T) {
- for _, n := range []string{
- `apple.com. IN NAPTR 100 50 "se" "SIP+D2U" "" _sip._udp.apple.com.`,
- `apple.com. IN NAPTR 90 50 "se" "SIP+D2T" "" _sip._tcp.apple.com.`,
- `apple.com. IN NAPTR 50 50 "se" "SIPS+D2T" "" _sips._tcp.apple.com.`,
- } {
- rr, _ := NewRR(n)
- msg := make([]byte, rr.len())
- if off, err := PackRR(rr, msg, 0, nil, false); err != nil {
- t.Errorf("packing failed: %v", err)
- t.Errorf("length %d, need more than %d", rr.len(), off)
- } else {
- t.Logf("buf size needed: %d", off)
- }
- }
-}
-
-func TestCompressLength(t *testing.T) {
- m := new(Msg)
- m.SetQuestion("miek.nl", TypeMX)
- ul := m.Len()
- m.Compress = true
- if ul != m.Len() {
- t.Fatalf("should be equal")
- }
-}
-
-// Does the predicted length match final packed length?
-func TestMsgCompressLength(t *testing.T) {
- makeMsg := func(question string, ans, ns, e []RR) *Msg {
- msg := new(Msg)
- msg.SetQuestion(Fqdn(question), TypeANY)
- msg.Answer = append(msg.Answer, ans...)
- msg.Ns = append(msg.Ns, ns...)
- msg.Extra = append(msg.Extra, e...)
- msg.Compress = true
- return msg
- }
-
- name1 := "12345678901234567890123456789012345.12345678.123."
- rrA, _ := NewRR(name1 + " 3600 IN A 192.0.2.1")
- rrMx, _ := NewRR(name1 + " 3600 IN MX 10 " + name1)
- tests := []*Msg{
- makeMsg(name1, []RR{rrA}, nil, nil),
- makeMsg(name1, []RR{rrMx, rrMx}, nil, nil)}
-
- for _, msg := range tests {
- predicted := msg.Len()
- buf, err := msg.Pack()
- if err != nil {
- t.Error(err)
- }
- if predicted < len(buf) {
- t.Errorf("predicted compressed length is wrong: predicted %s (len=%d) %d, actual %d",
- msg.Question[0].Name, len(msg.Answer), predicted, len(buf))
- }
- }
-}
-
-func TestMsgLength(t *testing.T) {
- makeMsg := func(question string, ans, ns, e []RR) *Msg {
- msg := new(Msg)
- msg.SetQuestion(Fqdn(question), TypeANY)
- msg.Answer = append(msg.Answer, ans...)
- msg.Ns = append(msg.Ns, ns...)
- msg.Extra = append(msg.Extra, e...)
- return msg
- }
-
- name1 := "12345678901234567890123456789012345.12345678.123."
- rrA, _ := NewRR(name1 + " 3600 IN A 192.0.2.1")
- rrMx, _ := NewRR(name1 + " 3600 IN MX 10 " + name1)
- tests := []*Msg{
- makeMsg(name1, []RR{rrA}, nil, nil),
- makeMsg(name1, []RR{rrMx, rrMx}, nil, nil)}
-
- for _, msg := range tests {
- predicted := msg.Len()
- buf, err := msg.Pack()
- if err != nil {
- t.Error(err)
- }
- if predicted < len(buf) {
- t.Errorf("predicted length is wrong: predicted %s (len=%d), actual %d",
- msg.Question[0].Name, predicted, len(buf))
- }
- }
-}
-
-func TestMsgLength2(t *testing.T) {
- // Serialized replies
- var testMessages = []string{
- // google.com. IN A?
- "064e81800001000b0004000506676f6f676c6503636f6d0000010001c00c00010001000000050004adc22986c00c00010001000000050004adc22987c00c00010001000000050004adc22988c00c00010001000000050004adc22989c00c00010001000000050004adc2298ec00c00010001000000050004adc22980c00c00010001000000050004adc22981c00c00010001000000050004adc22982c00c00010001000000050004adc22983c00c00010001000000050004adc22984c00c00010001000000050004adc22985c00c00020001000000050006036e7331c00cc00c00020001000000050006036e7332c00cc00c00020001000000050006036e7333c00cc00c00020001000000050006036e7334c00cc0d800010001000000050004d8ef200ac0ea00010001000000050004d8ef220ac0fc00010001000000050004d8ef240ac10e00010001000000050004d8ef260a0000290500000000050000",
- // amazon.com. IN A? (reply has no EDNS0 record)
- // TODO(miek): this one is off-by-one, need to find out why
- //"6de1818000010004000a000806616d617a6f6e03636f6d0000010001c00c000100010000000500044815c2d4c00c000100010000000500044815d7e8c00c00010001000000050004b02062a6c00c00010001000000050004cdfbf236c00c000200010000000500140570646e733408756c747261646e73036f726700c00c000200010000000500150570646e733508756c747261646e7304696e666f00c00c000200010000000500160570646e733608756c747261646e7302636f02756b00c00c00020001000000050014036e7331037033310664796e656374036e657400c00c00020001000000050006036e7332c0cfc00c00020001000000050006036e7333c0cfc00c00020001000000050006036e7334c0cfc00c000200010000000500110570646e733108756c747261646e73c0dac00c000200010000000500080570646e7332c127c00c000200010000000500080570646e7333c06ec0cb00010001000000050004d04e461fc0eb00010001000000050004cc0dfa1fc0fd00010001000000050004d04e471fc10f00010001000000050004cc0dfb1fc12100010001000000050004cc4a6c01c121001c000100000005001020010502f3ff00000000000000000001c13e00010001000000050004cc4a6d01c13e001c0001000000050010261000a1101400000000000000000001",
- // yahoo.com. IN A?
- "fc2d81800001000300070008057961686f6f03636f6d0000010001c00c00010001000000050004628afd6dc00c00010001000000050004628bb718c00c00010001000000050004cebe242dc00c00020001000000050006036e7336c00cc00c00020001000000050006036e7338c00cc00c00020001000000050006036e7331c00cc00c00020001000000050006036e7332c00cc00c00020001000000050006036e7333c00cc00c00020001000000050006036e7334c00cc00c00020001000000050006036e7335c00cc07b0001000100000005000444b48310c08d00010001000000050004448eff10c09f00010001000000050004cb54dd35c0b100010001000000050004628a0b9dc0c30001000100000005000477a0f77cc05700010001000000050004ca2bdfaac06900010001000000050004caa568160000290500000000050000",
- // microsoft.com. IN A?
- "f4368180000100020005000b096d6963726f736f667403636f6d0000010001c00c0001000100000005000440040b25c00c0001000100000005000441373ac9c00c0002000100000005000e036e7331046d736674036e657400c00c00020001000000050006036e7332c04fc00c00020001000000050006036e7333c04fc00c00020001000000050006036e7334c04fc00c00020001000000050006036e7335c04fc04b000100010000000500044137253ec04b001c00010000000500102a010111200500000000000000010001c0650001000100000005000440043badc065001c00010000000500102a010111200600060000000000010001c07700010001000000050004d5c7b435c077001c00010000000500102a010111202000000000000000010001c08900010001000000050004cf2e4bfec089001c00010000000500102404f800200300000000000000010001c09b000100010000000500044137e28cc09b001c00010000000500102a010111200f000100000000000100010000290500000000050000",
- // google.com. IN MX?
- "724b8180000100050004000b06676f6f676c6503636f6d00000f0001c00c000f000100000005000c000a056173706d78016cc00cc00c000f0001000000050009001404616c7431c02ac00c000f0001000000050009001e04616c7432c02ac00c000f0001000000050009002804616c7433c02ac00c000f0001000000050009003204616c7434c02ac00c00020001000000050006036e7332c00cc00c00020001000000050006036e7333c00cc00c00020001000000050006036e7334c00cc00c00020001000000050006036e7331c00cc02a00010001000000050004adc2421bc02a001c00010000000500102a00145040080c01000000000000001bc04200010001000000050004adc2461bc05700010001000000050004adc2451bc06c000100010000000500044a7d8f1bc081000100010000000500044a7d191bc0ca00010001000000050004d8ef200ac09400010001000000050004d8ef220ac0a600010001000000050004d8ef240ac0b800010001000000050004d8ef260a0000290500000000050000",
- // reddit.com. IN A?
- "12b98180000100080000000c0672656464697403636f6d0000020001c00c0002000100000005000f046175733204616b616d036e657400c00c000200010000000500070475736534c02dc00c000200010000000500070475737733c02dc00c000200010000000500070475737735c02dc00c00020001000000050008056173696131c02dc00c00020001000000050008056173696139c02dc00c00020001000000050008056e73312d31c02dc00c0002000100000005000a076e73312d313935c02dc02800010001000000050004c30a242ec04300010001000000050004451f1d39c05600010001000000050004451f3bc7c0690001000100000005000460073240c07c000100010000000500046007fb81c090000100010000000500047c283484c090001c00010000000500102a0226f0006700000000000000000064c0a400010001000000050004c16c5b01c0a4001c000100000005001026001401000200000000000000000001c0b800010001000000050004c16c5bc3c0b8001c0001000000050010260014010002000000000000000000c30000290500000000050000",
- }
-
- for i, hexData := range testMessages {
- // we won't fail the decoding of the hex
- input, _ := hex.DecodeString(hexData)
- m := new(Msg)
- m.Unpack(input)
- //println(m.String())
- m.Compress = true
- lenComp := m.Len()
- b, _ := m.Pack()
- pacComp := len(b)
- m.Compress = false
- lenUnComp := m.Len()
- b, _ = m.Pack()
- pacUnComp := len(b)
- if pacComp+1 != lenComp {
- t.Errorf("msg.Len(compressed)=%d actual=%d for test %d", lenComp, pacComp, i)
- }
- if pacUnComp+1 != lenUnComp {
- t.Errorf("msg.Len(uncompressed)=%d actual=%d for test %d", lenUnComp, pacUnComp, i)
- }
- }
-}
-
-func TestMsgLengthCompressionMalformed(t *testing.T) {
- // SOA with empty hostmaster, which is illegal
- soa := &SOA{Hdr: RR_Header{Name: ".", Rrtype: TypeSOA, Class: ClassINET, Ttl: 12345},
- Ns: ".",
- Mbox: "",
- Serial: 0,
- Refresh: 28800,
- Retry: 7200,
- Expire: 604800,
- Minttl: 60}
- m := new(Msg)
- m.Compress = true
- m.Ns = []RR{soa}
- m.Len() // Should not crash.
-}
-
-func BenchmarkMsgLength(b *testing.B) {
- b.StopTimer()
- makeMsg := func(question string, ans, ns, e []RR) *Msg {
- msg := new(Msg)
- msg.SetQuestion(Fqdn(question), TypeANY)
- msg.Answer = append(msg.Answer, ans...)
- msg.Ns = append(msg.Ns, ns...)
- msg.Extra = append(msg.Extra, e...)
- msg.Compress = true
- return msg
- }
- name1 := "12345678901234567890123456789012345.12345678.123."
- rrMx, _ := NewRR(name1 + " 3600 IN MX 10 " + name1)
- msg := makeMsg(name1, []RR{rrMx, rrMx}, nil, nil)
- b.StartTimer()
- for i := 0; i < b.N; i++ {
- msg.Len()
- }
-}
-
-func BenchmarkMsgLengthPack(b *testing.B) {
- makeMsg := func(question string, ans, ns, e []RR) *Msg {
- msg := new(Msg)
- msg.SetQuestion(Fqdn(question), TypeANY)
- msg.Answer = append(msg.Answer, ans...)
- msg.Ns = append(msg.Ns, ns...)
- msg.Extra = append(msg.Extra, e...)
- msg.Compress = true
- return msg
- }
- name1 := "12345678901234567890123456789012345.12345678.123."
- rrMx, _ := NewRR(name1 + " 3600 IN MX 10 " + name1)
- msg := makeMsg(name1, []RR{rrMx, rrMx}, nil, nil)
- b.ResetTimer()
- for i := 0; i < b.N; i++ {
- _, _ = msg.Pack()
- }
-}
-
-func BenchmarkMsgPackBuffer(b *testing.B) {
- makeMsg := func(question string, ans, ns, e []RR) *Msg {
- msg := new(Msg)
- msg.SetQuestion(Fqdn(question), TypeANY)
- msg.Answer = append(msg.Answer, ans...)
- msg.Ns = append(msg.Ns, ns...)
- msg.Extra = append(msg.Extra, e...)
- msg.Compress = true
- return msg
- }
- name1 := "12345678901234567890123456789012345.12345678.123."
- rrMx, _ := NewRR(name1 + " 3600 IN MX 10 " + name1)
- msg := makeMsg(name1, []RR{rrMx, rrMx}, nil, nil)
- buf := make([]byte, 512)
- b.ResetTimer()
- for i := 0; i < b.N; i++ {
- _, _ = msg.PackBuffer(buf)
- }
-}
-
-func BenchmarkMsgUnpack(b *testing.B) {
- makeMsg := func(question string, ans, ns, e []RR) *Msg {
- msg := new(Msg)
- msg.SetQuestion(Fqdn(question), TypeANY)
- msg.Answer = append(msg.Answer, ans...)
- msg.Ns = append(msg.Ns, ns...)
- msg.Extra = append(msg.Extra, e...)
- msg.Compress = true
- return msg
- }
- name1 := "12345678901234567890123456789012345.12345678.123."
- rrMx, _ := NewRR(name1 + " 3600 IN MX 10 " + name1)
- msg := makeMsg(name1, []RR{rrMx, rrMx}, nil, nil)
- msgBuf, _ := msg.Pack()
- b.ResetTimer()
- for i := 0; i < b.N; i++ {
- _ = msg.Unpack(msgBuf)
- }
-}
-
-func BenchmarkPackDomainName(b *testing.B) {
- name1 := "12345678901234567890123456789012345.12345678.123."
- buf := make([]byte, len(name1)+1)
- b.ResetTimer()
- for i := 0; i < b.N; i++ {
- _, _ = PackDomainName(name1, buf, 0, nil, false)
- }
-}
-
-func BenchmarkUnpackDomainName(b *testing.B) {
- name1 := "12345678901234567890123456789012345.12345678.123."
- buf := make([]byte, len(name1)+1)
- _, _ = PackDomainName(name1, buf, 0, nil, false)
- b.ResetTimer()
- for i := 0; i < b.N; i++ {
- _, _, _ = UnpackDomainName(buf, 0)
- }
-}
-
-func BenchmarkUnpackDomainNameUnprintable(b *testing.B) {
- name1 := "\x02\x02\x02\x025\x02\x02\x02\x02.12345678.123."
- buf := make([]byte, len(name1)+1)
- _, _ = PackDomainName(name1, buf, 0, nil, false)
- b.ResetTimer()
- for i := 0; i < b.N; i++ {
- _, _, _ = UnpackDomainName(buf, 0)
- }
-}
-
-func TestToRFC3597(t *testing.T) {
- a, _ := NewRR("miek.nl. IN A 10.0.1.1")
- x := new(RFC3597)
- x.ToRFC3597(a)
- if x.String() != `miek.nl. 3600 CLASS1 TYPE1 \# 4 0a000101` {
- t.Error("string mismatch")
- }
-}
-
-func TestNoRdataPack(t *testing.T) {
- data := make([]byte, 1024)
- for typ, fn := range typeToRR {
- r := fn()
- *r.Header() = RR_Header{Name: "miek.nl.", Rrtype: typ, Class: ClassINET, Ttl: 3600}
- _, err := PackRR(r, data, 0, nil, false)
- if err != nil {
- t.Errorf("failed to pack RR with zero rdata: %s: %v", TypeToString[typ], err)
- }
- }
-}
-
-// TODO(miek): fix dns buffer too small errors this throws
-func TestNoRdataUnpack(t *testing.T) {
- data := make([]byte, 1024)
- for typ, fn := range typeToRR {
- if typ == TypeSOA || typ == TypeTSIG || typ == TypeWKS {
- // SOA, TSIG will not be seen (like this) in dyn. updates?
- // WKS is an bug, but...deprecated record.
- continue
- }
- r := fn()
- *r.Header() = RR_Header{Name: "miek.nl.", Rrtype: typ, Class: ClassINET, Ttl: 3600}
- off, err := PackRR(r, data, 0, nil, false)
- if err != nil {
- // Should always works, TestNoDataPack should have caught this
- t.Errorf("failed to pack RR: %v", err)
- continue
- }
- rr, _, err := UnpackRR(data[:off], 0)
- if err != nil {
- t.Errorf("failed to unpack RR with zero rdata: %s: %v", TypeToString[typ], err)
- }
- t.Log(rr)
- }
-}
-
-func TestRdataOverflow(t *testing.T) {
- rr := new(RFC3597)
- rr.Hdr.Name = "."
- rr.Hdr.Class = ClassINET
- rr.Hdr.Rrtype = 65280
- rr.Rdata = hex.EncodeToString(make([]byte, 0xFFFF))
- buf := make([]byte, 0xFFFF*2)
- if _, err := PackRR(rr, buf, 0, nil, false); err != nil {
- t.Fatalf("maximum size rrdata pack failed: %v", err)
- }
- rr.Rdata += "00"
- if _, err := PackRR(rr, buf, 0, nil, false); err != ErrRdata {
- t.Fatalf("oversize rrdata pack didn't return ErrRdata - instead: %v", err)
- }
-}
-
-func TestCopy(t *testing.T) {
- rr, _ := NewRR("miek.nl. 2311 IN A 127.0.0.1") // Weird TTL to avoid catching TTL
- rr1 := Copy(rr)
- if rr.String() != rr1.String() {
- t.Fatalf("Copy() failed %s != %s", rr.String(), rr1.String())
- }
-}
-
-func TestMsgCopy(t *testing.T) {
- m := new(Msg)
- m.SetQuestion("miek.nl.", TypeA)
- rr, _ := NewRR("miek.nl. 2311 IN A 127.0.0.1")
- m.Answer = []RR{rr}
- rr, _ = NewRR("miek.nl. 2311 IN NS 127.0.0.1")
- m.Ns = []RR{rr}
-
- m1 := m.Copy()
- if m.String() != m1.String() {
- t.Fatalf("Msg.Copy() failed %s != %s", m.String(), m1.String())
- }
-
- m1.Answer[0], _ = NewRR("somethingelse.nl. 2311 IN A 127.0.0.1")
- if m.String() == m1.String() {
- t.Fatalf("Msg.Copy() failed; change to copy changed template %s", m.String())
- }
-
- rr, _ = NewRR("miek.nl. 2311 IN A 127.0.0.2")
- m1.Answer = append(m1.Answer, rr)
- if m1.Ns[0].String() == m1.Answer[1].String() {
- t.Fatalf("Msg.Copy() failed; append changed underlying array %s", m1.Ns[0].String())
- }
-}
-
-func BenchmarkCopy(b *testing.B) {
- b.ReportAllocs()
- m := new(Msg)
- m.SetQuestion("miek.nl.", TypeA)
- rr, _ := NewRR("miek.nl. 2311 IN A 127.0.0.1")
- m.Answer = []RR{rr}
- rr, _ = NewRR("miek.nl. 2311 IN NS 127.0.0.1")
- m.Ns = []RR{rr}
- rr, _ = NewRR("miek.nl. 2311 IN A 127.0.0.1")
- m.Extra = []RR{rr}
-
- b.ResetTimer()
- for i := 0; i < b.N; i++ {
- m.Copy()
- }
-}
-
-func TestPackIPSECKEY(t *testing.T) {
- tests := []string{
- "38.2.0.192.in-addr.arpa. 7200 IN IPSECKEY ( 10 1 2 192.0.2.38 AQNRU3mG7TVTO2BkR47usntb102uFJtugbo6BSGvgqt4AQ== )",
- "38.2.0.192.in-addr.arpa. 7200 IN IPSECKEY ( 10 0 2 . AQNRU3mG7TVTO2BkR47usntb102uFJtugbo6BSGvgqt4AQ== )",
- "38.2.0.192.in-addr.arpa. 7200 IN IPSECKEY ( 10 1 2 192.0.2.3 AQNRU3mG7TVTO2BkR47usntb102uFJtugbo6BSGvgqt4AQ== )",
- "38.1.0.192.in-addr.arpa. 7200 IN IPSECKEY ( 10 3 2 mygateway.example.com. AQNRU3mG7TVTO2BkR47usntb102uFJtugbo6BSGvgqt4AQ== )",
- "0.d.4.0.3.0.e.f.f.f.3.f.0.1.2.0 7200 IN IPSECKEY ( 10 2 2 2001:0DB8:0:8002::2000:1 AQNRU3mG7TVTO2BkR47usntb102uFJtugbo6BSGvgqt4AQ== )",
- }
- buf := make([]byte, 1024)
- for _, t1 := range tests {
- rr, _ := NewRR(t1)
- off, err := PackRR(rr, buf, 0, nil, false)
- if err != nil {
- t.Errorf("failed to pack IPSECKEY %v: %s", err, t1)
- continue
- }
-
- rr, _, err = UnpackRR(buf[:off], 0)
- if err != nil {
- t.Errorf("failed to unpack IPSECKEY %v: %s", err, t1)
- }
- t.Log(rr)
- }
-}
-
-func TestMsgPackBuffer(t *testing.T) {
- var testMessages = []string{
- // news.ycombinator.com.in.escapemg.com. IN A, response
- "586285830001000000010000046e6577730b79636f6d62696e61746f7203636f6d02696e086573636170656d6703636f6d0000010001c0210006000100000e10002c036e7332c02103646e730b67726f6f7665736861726bc02d77ed50e600002a3000000e1000093a8000000e10",
-
- // news.ycombinator.com.in.escapemg.com. IN A, question
- "586201000001000000000000046e6577730b79636f6d62696e61746f7203636f6d02696e086573636170656d6703636f6d0000010001",
-
- "398781020001000000000000046e6577730b79636f6d62696e61746f7203636f6d0000010001",
- }
-
- for i, hexData := range testMessages {
- // we won't fail the decoding of the hex
- input, _ := hex.DecodeString(hexData)
- m := new(Msg)
- if err := m.Unpack(input); err != nil {
- t.Errorf("packet %d failed to unpack", i)
- continue
- }
- t.Logf("packet %d %s", i, m.String())
- }
-}
diff --git a/Godeps/_workspace/src/github.com/miekg/dns/dnssec.go b/Godeps/_workspace/src/github.com/miekg/dns/dnssec.go
deleted file mode 100644
index 21ef3775a3..0000000000
--- a/Godeps/_workspace/src/github.com/miekg/dns/dnssec.go
+++ /dev/null
@@ -1,634 +0,0 @@
-package dns
-
-import (
- "bytes"
- "crypto"
- "crypto/dsa"
- "crypto/ecdsa"
- "crypto/elliptic"
- "crypto/md5"
- "crypto/rsa"
- "crypto/sha1"
- "crypto/sha256"
- "crypto/sha512"
- "encoding/hex"
- "hash"
- "io"
- "math/big"
- "sort"
- "strings"
- "time"
-)
-
-// DNSSEC encryption algorithm codes.
-const (
- _ uint8 = iota
- RSAMD5
- DH
- DSA
- _ // Skip 4, RFC 6725, section 2.1
- RSASHA1
- DSANSEC3SHA1
- RSASHA1NSEC3SHA1
- RSASHA256
- _ // Skip 9, RFC 6725, section 2.1
- RSASHA512
- _ // Skip 11, RFC 6725, section 2.1
- ECCGOST
- ECDSAP256SHA256
- ECDSAP384SHA384
- INDIRECT uint8 = 252
- PRIVATEDNS uint8 = 253 // Private (experimental keys)
- PRIVATEOID uint8 = 254
-)
-
-// DNSSEC hashing algorithm codes.
-const (
- _ uint8 = iota
- SHA1 // RFC 4034
- SHA256 // RFC 4509
- GOST94 // RFC 5933
- SHA384 // Experimental
- SHA512 // Experimental
-)
-
-// DNSKEY flag values.
-const (
- SEP = 1
- REVOKE = 1 << 7
- ZONE = 1 << 8
-)
-
-// The RRSIG needs to be converted to wireformat with some of
-// the rdata (the signature) missing. Use this struct to easy
-// the conversion (and re-use the pack/unpack functions).
-type rrsigWireFmt struct {
- TypeCovered uint16
- Algorithm uint8
- Labels uint8
- OrigTtl uint32
- Expiration uint32
- Inception uint32
- KeyTag uint16
- SignerName string `dns:"domain-name"`
- /* No Signature */
-}
-
-// Used for converting DNSKEY's rdata to wirefmt.
-type dnskeyWireFmt struct {
- Flags uint16
- Protocol uint8
- Algorithm uint8
- PublicKey string `dns:"base64"`
- /* Nothing is left out */
-}
-
-func divRoundUp(a, b int) int {
- return (a + b - 1) / b
-}
-
-// KeyTag calculates the keytag (or key-id) of the DNSKEY.
-func (k *DNSKEY) KeyTag() uint16 {
- if k == nil {
- return 0
- }
- var keytag int
- switch k.Algorithm {
- case RSAMD5:
- // Look at the bottom two bytes of the modules, which the last
- // item in the pubkey. We could do this faster by looking directly
- // at the base64 values. But I'm lazy.
- modulus, _ := fromBase64([]byte(k.PublicKey))
- if len(modulus) > 1 {
- x, _ := unpackUint16(modulus, len(modulus)-2)
- keytag = int(x)
- }
- default:
- keywire := new(dnskeyWireFmt)
- keywire.Flags = k.Flags
- keywire.Protocol = k.Protocol
- keywire.Algorithm = k.Algorithm
- keywire.PublicKey = k.PublicKey
- wire := make([]byte, DefaultMsgSize)
- n, err := PackStruct(keywire, wire, 0)
- if err != nil {
- return 0
- }
- wire = wire[:n]
- for i, v := range wire {
- if i&1 != 0 {
- keytag += int(v) // must be larger than uint32
- } else {
- keytag += int(v) << 8
- }
- }
- keytag += (keytag >> 16) & 0xFFFF
- keytag &= 0xFFFF
- }
- return uint16(keytag)
-}
-
-// ToDS converts a DNSKEY record to a DS record.
-func (k *DNSKEY) ToDS(h uint8) *DS {
- if k == nil {
- return nil
- }
- ds := new(DS)
- ds.Hdr.Name = k.Hdr.Name
- ds.Hdr.Class = k.Hdr.Class
- ds.Hdr.Rrtype = TypeDS
- ds.Hdr.Ttl = k.Hdr.Ttl
- ds.Algorithm = k.Algorithm
- ds.DigestType = h
- ds.KeyTag = k.KeyTag()
-
- keywire := new(dnskeyWireFmt)
- keywire.Flags = k.Flags
- keywire.Protocol = k.Protocol
- keywire.Algorithm = k.Algorithm
- keywire.PublicKey = k.PublicKey
- wire := make([]byte, DefaultMsgSize)
- n, err := PackStruct(keywire, wire, 0)
- if err != nil {
- return nil
- }
- wire = wire[:n]
-
- owner := make([]byte, 255)
- off, err1 := PackDomainName(strings.ToLower(k.Hdr.Name), owner, 0, nil, false)
- if err1 != nil {
- return nil
- }
- owner = owner[:off]
- // RFC4034:
- // digest = digest_algorithm( DNSKEY owner name | DNSKEY RDATA);
- // "|" denotes concatenation
- // DNSKEY RDATA = Flags | Protocol | Algorithm | Public Key.
-
- // digest buffer
- digest := append(owner, wire...) // another copy
-
- switch h {
- case SHA1:
- s := sha1.New()
- io.WriteString(s, string(digest))
- ds.Digest = hex.EncodeToString(s.Sum(nil))
- case SHA256:
- s := sha256.New()
- io.WriteString(s, string(digest))
- ds.Digest = hex.EncodeToString(s.Sum(nil))
- case SHA384:
- s := sha512.New384()
- io.WriteString(s, string(digest))
- ds.Digest = hex.EncodeToString(s.Sum(nil))
- case GOST94:
- /* I have no clue */
- default:
- return nil
- }
- return ds
-}
-
-// ToCDNSKEY converts a DNSKEY record to a CDNSKEY record.
-func (k *DNSKEY) ToCDNSKEY() *CDNSKEY {
- c := &CDNSKEY{DNSKEY: *k}
- c.Hdr = *k.Hdr.copyHeader()
- c.Hdr.Rrtype = TypeCDNSKEY
- return c
-}
-
-// ToCDS converts a DS record to a CDS record.
-func (d *DS) ToCDS() *CDS {
- c := &CDS{DS: *d}
- c.Hdr = *d.Hdr.copyHeader()
- c.Hdr.Rrtype = TypeCDS
- return c
-}
-
-// Sign signs an RRSet. The signature needs to be filled in with
-// the values: Inception, Expiration, KeyTag, SignerName and Algorithm.
-// The rest is copied from the RRset. Sign returns true when the signing went OK,
-// otherwise false.
-// There is no check if RRSet is a proper (RFC 2181) RRSet.
-// If OrigTTL is non zero, it is used as-is, otherwise the TTL of the RRset
-// is used as the OrigTTL.
-func (rr *RRSIG) Sign(k PrivateKey, rrset []RR) error {
- if k == nil {
- return ErrPrivKey
- }
- // s.Inception and s.Expiration may be 0 (rollover etc.), the rest must be set
- if rr.KeyTag == 0 || len(rr.SignerName) == 0 || rr.Algorithm == 0 {
- return ErrKey
- }
-
- rr.Hdr.Rrtype = TypeRRSIG
- rr.Hdr.Name = rrset[0].Header().Name
- rr.Hdr.Class = rrset[0].Header().Class
- if rr.OrigTtl == 0 { // If set don't override
- rr.OrigTtl = rrset[0].Header().Ttl
- }
- rr.TypeCovered = rrset[0].Header().Rrtype
- rr.Labels = uint8(CountLabel(rrset[0].Header().Name))
-
- if strings.HasPrefix(rrset[0].Header().Name, "*") {
- rr.Labels-- // wildcard, remove from label count
- }
-
- sigwire := new(rrsigWireFmt)
- sigwire.TypeCovered = rr.TypeCovered
- sigwire.Algorithm = rr.Algorithm
- sigwire.Labels = rr.Labels
- sigwire.OrigTtl = rr.OrigTtl
- sigwire.Expiration = rr.Expiration
- sigwire.Inception = rr.Inception
- sigwire.KeyTag = rr.KeyTag
- // For signing, lowercase this name
- sigwire.SignerName = strings.ToLower(rr.SignerName)
-
- // Create the desired binary blob
- signdata := make([]byte, DefaultMsgSize)
- n, err := PackStruct(sigwire, signdata, 0)
- if err != nil {
- return err
- }
- signdata = signdata[:n]
- wire, err := rawSignatureData(rrset, rr)
- if err != nil {
- return err
- }
- signdata = append(signdata, wire...)
-
- var h hash.Hash
- switch rr.Algorithm {
- case DSA, DSANSEC3SHA1:
- // TODO: this seems bugged, will panic
- case RSASHA1, RSASHA1NSEC3SHA1:
- h = sha1.New()
- case RSASHA256, ECDSAP256SHA256:
- h = sha256.New()
- case ECDSAP384SHA384:
- h = sha512.New384()
- case RSASHA512:
- h = sha512.New()
- case RSAMD5:
- fallthrough // Deprecated in RFC 6725
- default:
- return ErrAlg
- }
-
- _, err = h.Write(signdata)
- if err != nil {
- return err
- }
- sighash := h.Sum(nil)
-
- signature, err := k.Sign(sighash, rr.Algorithm)
- if err != nil {
- return err
- }
- rr.Signature = toBase64(signature)
-
- return nil
-}
-
-// Verify validates an RRSet with the signature and key. This is only the
-// cryptographic test, the signature validity period must be checked separately.
-// This function copies the rdata of some RRs (to lowercase domain names) for the validation to work.
-func (rr *RRSIG) Verify(k *DNSKEY, rrset []RR) error {
- // First the easy checks
- if len(rrset) == 0 {
- return ErrRRset
- }
- if rr.KeyTag != k.KeyTag() {
- return ErrKey
- }
- if rr.Hdr.Class != k.Hdr.Class {
- return ErrKey
- }
- if rr.Algorithm != k.Algorithm {
- return ErrKey
- }
- if strings.ToLower(rr.SignerName) != strings.ToLower(k.Hdr.Name) {
- return ErrKey
- }
- if k.Protocol != 3 {
- return ErrKey
- }
- for _, r := range rrset {
- if r.Header().Class != rr.Hdr.Class {
- return ErrRRset
- }
- if r.Header().Rrtype != rr.TypeCovered {
- return ErrRRset
- }
- }
- // RFC 4035 5.3.2. Reconstructing the Signed Data
- // Copy the sig, except the rrsig data
- sigwire := new(rrsigWireFmt)
- sigwire.TypeCovered = rr.TypeCovered
- sigwire.Algorithm = rr.Algorithm
- sigwire.Labels = rr.Labels
- sigwire.OrigTtl = rr.OrigTtl
- sigwire.Expiration = rr.Expiration
- sigwire.Inception = rr.Inception
- sigwire.KeyTag = rr.KeyTag
- sigwire.SignerName = strings.ToLower(rr.SignerName)
- // Create the desired binary blob
- signeddata := make([]byte, DefaultMsgSize)
- n, err := PackStruct(sigwire, signeddata, 0)
- if err != nil {
- return err
- }
- signeddata = signeddata[:n]
- wire, err := rawSignatureData(rrset, rr)
- if err != nil {
- return err
- }
- signeddata = append(signeddata, wire...)
-
- sigbuf := rr.sigBuf() // Get the binary signature data
- if rr.Algorithm == PRIVATEDNS { // PRIVATEOID
- // TODO(mg)
- // remove the domain name and assume its our
- }
-
- switch rr.Algorithm {
- case RSASHA1, RSASHA1NSEC3SHA1, RSASHA256, RSASHA512, RSAMD5:
- // TODO(mg): this can be done quicker, ie. cache the pubkey data somewhere??
- pubkey := k.publicKeyRSA() // Get the key
- if pubkey == nil {
- return ErrKey
- }
- // Setup the hash as defined for this alg.
- var h hash.Hash
- var ch crypto.Hash
- switch rr.Algorithm {
- case RSAMD5:
- h = md5.New()
- ch = crypto.MD5
- case RSASHA1, RSASHA1NSEC3SHA1:
- h = sha1.New()
- ch = crypto.SHA1
- case RSASHA256:
- h = sha256.New()
- ch = crypto.SHA256
- case RSASHA512:
- h = sha512.New()
- ch = crypto.SHA512
- }
- io.WriteString(h, string(signeddata))
- sighash := h.Sum(nil)
- return rsa.VerifyPKCS1v15(pubkey, ch, sighash, sigbuf)
- case ECDSAP256SHA256, ECDSAP384SHA384:
- pubkey := k.publicKeyECDSA()
- if pubkey == nil {
- return ErrKey
- }
- var h hash.Hash
- switch rr.Algorithm {
- case ECDSAP256SHA256:
- h = sha256.New()
- case ECDSAP384SHA384:
- h = sha512.New384()
- }
- io.WriteString(h, string(signeddata))
- sighash := h.Sum(nil)
- // Split sigbuf into the r and s coordinates
- r := big.NewInt(0)
- r.SetBytes(sigbuf[:len(sigbuf)/2])
- s := big.NewInt(0)
- s.SetBytes(sigbuf[len(sigbuf)/2:])
- if ecdsa.Verify(pubkey, sighash, r, s) {
- return nil
- }
- return ErrSig
- }
- // Unknown alg
- return ErrAlg
-}
-
-// ValidityPeriod uses RFC1982 serial arithmetic to calculate
-// if a signature period is valid. If t is the zero time, the
-// current time is taken other t is.
-func (rr *RRSIG) ValidityPeriod(t time.Time) bool {
- var utc int64
- if t.IsZero() {
- utc = time.Now().UTC().Unix()
- } else {
- utc = t.UTC().Unix()
- }
- modi := (int64(rr.Inception) - utc) / year68
- mode := (int64(rr.Expiration) - utc) / year68
- ti := int64(rr.Inception) + (modi * year68)
- te := int64(rr.Expiration) + (mode * year68)
- return ti <= utc && utc <= te
-}
-
-// Return the signatures base64 encodedig sigdata as a byte slice.
-func (rr *RRSIG) sigBuf() []byte {
- sigbuf, err := fromBase64([]byte(rr.Signature))
- if err != nil {
- return nil
- }
- return sigbuf
-}
-
-// publicKeyRSA returns the RSA public key from a DNSKEY record.
-func (k *DNSKEY) publicKeyRSA() *rsa.PublicKey {
- keybuf, err := fromBase64([]byte(k.PublicKey))
- if err != nil {
- return nil
- }
-
- // RFC 2537/3110, section 2. RSA Public KEY Resource Records
- // Length is in the 0th byte, unless its zero, then it
- // it in bytes 1 and 2 and its a 16 bit number
- explen := uint16(keybuf[0])
- keyoff := 1
- if explen == 0 {
- explen = uint16(keybuf[1])<<8 | uint16(keybuf[2])
- keyoff = 3
- }
- pubkey := new(rsa.PublicKey)
-
- pubkey.N = big.NewInt(0)
- shift := uint64((explen - 1) * 8)
- expo := uint64(0)
- for i := int(explen - 1); i > 0; i-- {
- expo += uint64(keybuf[keyoff+i]) << shift
- shift -= 8
- }
- // Remainder
- expo += uint64(keybuf[keyoff])
- if expo > 2<<31 {
- // Larger expo than supported.
- // println("dns: F5 primes (or larger) are not supported")
- return nil
- }
- pubkey.E = int(expo)
-
- pubkey.N.SetBytes(keybuf[keyoff+int(explen):])
- return pubkey
-}
-
-// publicKeyECDSA returns the Curve public key from the DNSKEY record.
-func (k *DNSKEY) publicKeyECDSA() *ecdsa.PublicKey {
- keybuf, err := fromBase64([]byte(k.PublicKey))
- if err != nil {
- return nil
- }
- pubkey := new(ecdsa.PublicKey)
- switch k.Algorithm {
- case ECDSAP256SHA256:
- pubkey.Curve = elliptic.P256()
- if len(keybuf) != 64 {
- // wrongly encoded key
- return nil
- }
- case ECDSAP384SHA384:
- pubkey.Curve = elliptic.P384()
- if len(keybuf) != 96 {
- // Wrongly encoded key
- return nil
- }
- }
- pubkey.X = big.NewInt(0)
- pubkey.X.SetBytes(keybuf[:len(keybuf)/2])
- pubkey.Y = big.NewInt(0)
- pubkey.Y.SetBytes(keybuf[len(keybuf)/2:])
- return pubkey
-}
-
-func (k *DNSKEY) publicKeyDSA() *dsa.PublicKey {
- keybuf, err := fromBase64([]byte(k.PublicKey))
- if err != nil {
- return nil
- }
- if len(keybuf) < 22 {
- return nil
- }
- t, keybuf := int(keybuf[0]), keybuf[1:]
- size := 64 + t*8
- q, keybuf := keybuf[:20], keybuf[20:]
- if len(keybuf) != 3*size {
- return nil
- }
- p, keybuf := keybuf[:size], keybuf[size:]
- g, y := keybuf[:size], keybuf[size:]
- pubkey := new(dsa.PublicKey)
- pubkey.Parameters.Q = big.NewInt(0).SetBytes(q)
- pubkey.Parameters.P = big.NewInt(0).SetBytes(p)
- pubkey.Parameters.G = big.NewInt(0).SetBytes(g)
- pubkey.Y = big.NewInt(0).SetBytes(y)
- return pubkey
-}
-
-type wireSlice [][]byte
-
-func (p wireSlice) Len() int { return len(p) }
-func (p wireSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
-func (p wireSlice) Less(i, j int) bool {
- _, ioff, _ := UnpackDomainName(p[i], 0)
- _, joff, _ := UnpackDomainName(p[j], 0)
- return bytes.Compare(p[i][ioff+10:], p[j][joff+10:]) < 0
-}
-
-// Return the raw signature data.
-func rawSignatureData(rrset []RR, s *RRSIG) (buf []byte, err error) {
- wires := make(wireSlice, len(rrset))
- for i, r := range rrset {
- r1 := r.copy()
- r1.Header().Ttl = s.OrigTtl
- labels := SplitDomainName(r1.Header().Name)
- // 6.2. Canonical RR Form. (4) - wildcards
- if len(labels) > int(s.Labels) {
- // Wildcard
- r1.Header().Name = "*." + strings.Join(labels[len(labels)-int(s.Labels):], ".") + "."
- }
- // RFC 4034: 6.2. Canonical RR Form. (2) - domain name to lowercase
- r1.Header().Name = strings.ToLower(r1.Header().Name)
- // 6.2. Canonical RR Form. (3) - domain rdata to lowercase.
- // NS, MD, MF, CNAME, SOA, MB, MG, MR, PTR,
- // HINFO, MINFO, MX, RP, AFSDB, RT, SIG, PX, NXT, NAPTR, KX,
- // SRV, DNAME, A6
- switch x := r1.(type) {
- case *NS:
- x.Ns = strings.ToLower(x.Ns)
- case *CNAME:
- x.Target = strings.ToLower(x.Target)
- case *SOA:
- x.Ns = strings.ToLower(x.Ns)
- x.Mbox = strings.ToLower(x.Mbox)
- case *MB:
- x.Mb = strings.ToLower(x.Mb)
- case *MG:
- x.Mg = strings.ToLower(x.Mg)
- case *MR:
- x.Mr = strings.ToLower(x.Mr)
- case *PTR:
- x.Ptr = strings.ToLower(x.Ptr)
- case *MINFO:
- x.Rmail = strings.ToLower(x.Rmail)
- x.Email = strings.ToLower(x.Email)
- case *MX:
- x.Mx = strings.ToLower(x.Mx)
- case *NAPTR:
- x.Replacement = strings.ToLower(x.Replacement)
- case *KX:
- x.Exchanger = strings.ToLower(x.Exchanger)
- case *SRV:
- x.Target = strings.ToLower(x.Target)
- case *DNAME:
- x.Target = strings.ToLower(x.Target)
- }
- // 6.2. Canonical RR Form. (5) - origTTL
- wire := make([]byte, r1.len()+1) // +1 to be safe(r)
- off, err1 := PackRR(r1, wire, 0, nil, false)
- if err1 != nil {
- return nil, err1
- }
- wire = wire[:off]
- wires[i] = wire
- }
- sort.Sort(wires)
- for i, wire := range wires {
- if i > 0 && bytes.Equal(wire, wires[i-1]) {
- continue
- }
- buf = append(buf, wire...)
- }
- return buf, nil
-}
-
-// Map for algorithm names.
-var AlgorithmToString = map[uint8]string{
- RSAMD5: "RSAMD5",
- DH: "DH",
- DSA: "DSA",
- RSASHA1: "RSASHA1",
- DSANSEC3SHA1: "DSA-NSEC3-SHA1",
- RSASHA1NSEC3SHA1: "RSASHA1-NSEC3-SHA1",
- RSASHA256: "RSASHA256",
- RSASHA512: "RSASHA512",
- ECCGOST: "ECC-GOST",
- ECDSAP256SHA256: "ECDSAP256SHA256",
- ECDSAP384SHA384: "ECDSAP384SHA384",
- INDIRECT: "INDIRECT",
- PRIVATEDNS: "PRIVATEDNS",
- PRIVATEOID: "PRIVATEOID",
-}
-
-// Map of algorithm strings.
-var StringToAlgorithm = reverseInt8(AlgorithmToString)
-
-// Map for hash names.
-var HashToString = map[uint8]string{
- SHA1: "SHA1",
- SHA256: "SHA256",
- GOST94: "GOST94",
- SHA384: "SHA384",
- SHA512: "SHA512",
-}
-
-// Map of hash strings.
-var StringToHash = reverseInt8(HashToString)
diff --git a/Godeps/_workspace/src/github.com/miekg/dns/dnssec_keygen.go b/Godeps/_workspace/src/github.com/miekg/dns/dnssec_keygen.go
deleted file mode 100644
index 739beebe06..0000000000
--- a/Godeps/_workspace/src/github.com/miekg/dns/dnssec_keygen.go
+++ /dev/null
@@ -1,155 +0,0 @@
-package dns
-
-import (
- "crypto/dsa"
- "crypto/ecdsa"
- "crypto/elliptic"
- "crypto/rand"
- "crypto/rsa"
- "math/big"
-)
-
-// Generate generates a DNSKEY of the given bit size.
-// The public part is put inside the DNSKEY record.
-// The Algorithm in the key must be set as this will define
-// what kind of DNSKEY will be generated.
-// The ECDSA algorithms imply a fixed keysize, in that case
-// bits should be set to the size of the algorithm.
-func (k *DNSKEY) Generate(bits int) (PrivateKey, error) {
- switch k.Algorithm {
- case DSA, DSANSEC3SHA1:
- if bits != 1024 {
- return nil, ErrKeySize
- }
- case RSAMD5, RSASHA1, RSASHA256, RSASHA1NSEC3SHA1:
- if bits < 512 || bits > 4096 {
- return nil, ErrKeySize
- }
- case RSASHA512:
- if bits < 1024 || bits > 4096 {
- return nil, ErrKeySize
- }
- case ECDSAP256SHA256:
- if bits != 256 {
- return nil, ErrKeySize
- }
- case ECDSAP384SHA384:
- if bits != 384 {
- return nil, ErrKeySize
- }
- }
-
- switch k.Algorithm {
- case DSA, DSANSEC3SHA1:
- params := new(dsa.Parameters)
- if err := dsa.GenerateParameters(params, rand.Reader, dsa.L1024N160); err != nil {
- return nil, err
- }
- priv := new(dsa.PrivateKey)
- priv.PublicKey.Parameters = *params
- err := dsa.GenerateKey(priv, rand.Reader)
- if err != nil {
- return nil, err
- }
- k.setPublicKeyDSA(params.Q, params.P, params.G, priv.PublicKey.Y)
- return (*DSAPrivateKey)(priv), nil
- case RSAMD5, RSASHA1, RSASHA256, RSASHA512, RSASHA1NSEC3SHA1:
- priv, err := rsa.GenerateKey(rand.Reader, bits)
- if err != nil {
- return nil, err
- }
- k.setPublicKeyRSA(priv.PublicKey.E, priv.PublicKey.N)
- return (*RSAPrivateKey)(priv), nil
- case ECDSAP256SHA256, ECDSAP384SHA384:
- var c elliptic.Curve
- switch k.Algorithm {
- case ECDSAP256SHA256:
- c = elliptic.P256()
- case ECDSAP384SHA384:
- c = elliptic.P384()
- }
- priv, err := ecdsa.GenerateKey(c, rand.Reader)
- if err != nil {
- return nil, err
- }
- k.setPublicKeyECDSA(priv.PublicKey.X, priv.PublicKey.Y)
- return (*ECDSAPrivateKey)(priv), nil
- default:
- return nil, ErrAlg
- }
-}
-
-// Set the public key (the value E and N)
-func (k *DNSKEY) setPublicKeyRSA(_E int, _N *big.Int) bool {
- if _E == 0 || _N == nil {
- return false
- }
- buf := exponentToBuf(_E)
- buf = append(buf, _N.Bytes()...)
- k.PublicKey = toBase64(buf)
- return true
-}
-
-// Set the public key for Elliptic Curves
-func (k *DNSKEY) setPublicKeyECDSA(_X, _Y *big.Int) bool {
- if _X == nil || _Y == nil {
- return false
- }
- var intlen int
- switch k.Algorithm {
- case ECDSAP256SHA256:
- intlen = 32
- case ECDSAP384SHA384:
- intlen = 48
- }
- k.PublicKey = toBase64(curveToBuf(_X, _Y, intlen))
- return true
-}
-
-// Set the public key for DSA
-func (k *DNSKEY) setPublicKeyDSA(_Q, _P, _G, _Y *big.Int) bool {
- if _Q == nil || _P == nil || _G == nil || _Y == nil {
- return false
- }
- buf := dsaToBuf(_Q, _P, _G, _Y)
- k.PublicKey = toBase64(buf)
- return true
-}
-
-// Set the public key (the values E and N) for RSA
-// RFC 3110: Section 2. RSA Public KEY Resource Records
-func exponentToBuf(_E int) []byte {
- var buf []byte
- i := big.NewInt(int64(_E))
- if len(i.Bytes()) < 256 {
- buf = make([]byte, 1)
- buf[0] = uint8(len(i.Bytes()))
- } else {
- buf = make([]byte, 3)
- buf[0] = 0
- buf[1] = uint8(len(i.Bytes()) >> 8)
- buf[2] = uint8(len(i.Bytes()))
- }
- buf = append(buf, i.Bytes()...)
- return buf
-}
-
-// Set the public key for X and Y for Curve. The two
-// values are just concatenated.
-func curveToBuf(_X, _Y *big.Int, intlen int) []byte {
- buf := intToBytes(_X, intlen)
- buf = append(buf, intToBytes(_Y, intlen)...)
- return buf
-}
-
-// Set the public key for X and Y for Curve. The two
-// values are just concatenated.
-func dsaToBuf(_Q, _P, _G, _Y *big.Int) []byte {
- t := divRoundUp(divRoundUp(_G.BitLen(), 8)-64, 8)
- buf := []byte{byte(t)}
- buf = append(buf, intToBytes(_Q, 20)...)
- buf = append(buf, intToBytes(_P, 64+t*8)...)
- buf = append(buf, intToBytes(_G, 64+t*8)...)
- buf = append(buf, intToBytes(_Y, 64+t*8)...)
- return buf
-}
diff --git a/Godeps/_workspace/src/github.com/miekg/dns/dnssec_keyscan.go b/Godeps/_workspace/src/github.com/miekg/dns/dnssec_keyscan.go
deleted file mode 100644
index ac84fbcb4f..0000000000
--- a/Godeps/_workspace/src/github.com/miekg/dns/dnssec_keyscan.go
+++ /dev/null
@@ -1,248 +0,0 @@
-package dns
-
-import (
- "crypto/dsa"
- "crypto/ecdsa"
- "crypto/rsa"
- "io"
- "math/big"
- "strconv"
- "strings"
-)
-
-// NewPrivateKey returns a PrivateKey by parsing the string s.
-// s should be in the same form of the BIND private key files.
-func (k *DNSKEY) NewPrivateKey(s string) (PrivateKey, error) {
- if s[len(s)-1] != '\n' { // We need a closing newline
- return k.ReadPrivateKey(strings.NewReader(s+"\n"), "")
- }
- return k.ReadPrivateKey(strings.NewReader(s), "")
-}
-
-// ReadPrivateKey reads a private key from the io.Reader q. The string file is
-// only used in error reporting.
-// The public key must be known, because some cryptographic algorithms embed
-// the public inside the privatekey.
-func (k *DNSKEY) ReadPrivateKey(q io.Reader, file string) (PrivateKey, error) {
- m, e := parseKey(q, file)
- if m == nil {
- return nil, e
- }
- if _, ok := m["private-key-format"]; !ok {
- return nil, ErrPrivKey
- }
- if m["private-key-format"] != "v1.2" && m["private-key-format"] != "v1.3" {
- return nil, ErrPrivKey
- }
- // TODO(mg): check if the pubkey matches the private key
- algo, err := strconv.Atoi(strings.SplitN(m["algorithm"], " ", 2)[0])
- if err != nil {
- return nil, ErrPrivKey
- }
- switch uint8(algo) {
- case DSA:
- priv, e := readPrivateKeyDSA(m)
- if e != nil {
- return nil, e
- }
- pub := k.publicKeyDSA()
- if pub == nil {
- return nil, ErrKey
- }
- priv.PublicKey = *pub
- return (*DSAPrivateKey)(priv), e
- case RSAMD5:
- fallthrough
- case RSASHA1:
- fallthrough
- case RSASHA1NSEC3SHA1:
- fallthrough
- case RSASHA256:
- fallthrough
- case RSASHA512:
- priv, e := readPrivateKeyRSA(m)
- if e != nil {
- return nil, e
- }
- pub := k.publicKeyRSA()
- if pub == nil {
- return nil, ErrKey
- }
- priv.PublicKey = *pub
- return (*RSAPrivateKey)(priv), e
- case ECCGOST:
- return nil, ErrPrivKey
- case ECDSAP256SHA256:
- fallthrough
- case ECDSAP384SHA384:
- priv, e := readPrivateKeyECDSA(m)
- if e != nil {
- return nil, e
- }
- pub := k.publicKeyECDSA()
- if pub == nil {
- return nil, ErrKey
- }
- priv.PublicKey = *pub
- return (*ECDSAPrivateKey)(priv), e
- default:
- return nil, ErrPrivKey
- }
-}
-
-// Read a private key (file) string and create a public key. Return the private key.
-func readPrivateKeyRSA(m map[string]string) (*rsa.PrivateKey, error) {
- p := new(rsa.PrivateKey)
- p.Primes = []*big.Int{nil, nil}
- for k, v := range m {
- switch k {
- case "modulus", "publicexponent", "privateexponent", "prime1", "prime2":
- v1, err := fromBase64([]byte(v))
- if err != nil {
- return nil, err
- }
- switch k {
- case "modulus":
- p.PublicKey.N = big.NewInt(0)
- p.PublicKey.N.SetBytes(v1)
- case "publicexponent":
- i := big.NewInt(0)
- i.SetBytes(v1)
- p.PublicKey.E = int(i.Int64()) // int64 should be large enough
- case "privateexponent":
- p.D = big.NewInt(0)
- p.D.SetBytes(v1)
- case "prime1":
- p.Primes[0] = big.NewInt(0)
- p.Primes[0].SetBytes(v1)
- case "prime2":
- p.Primes[1] = big.NewInt(0)
- p.Primes[1].SetBytes(v1)
- }
- case "exponent1", "exponent2", "coefficient":
- // not used in Go (yet)
- case "created", "publish", "activate":
- // not used in Go (yet)
- }
- }
- return p, nil
-}
-
-func readPrivateKeyDSA(m map[string]string) (*dsa.PrivateKey, error) {
- p := new(dsa.PrivateKey)
- p.X = big.NewInt(0)
- for k, v := range m {
- switch k {
- case "private_value(x)":
- v1, err := fromBase64([]byte(v))
- if err != nil {
- return nil, err
- }
- p.X.SetBytes(v1)
- case "created", "publish", "activate":
- /* not used in Go (yet) */
- }
- }
- return p, nil
-}
-
-func readPrivateKeyECDSA(m map[string]string) (*ecdsa.PrivateKey, error) {
- p := new(ecdsa.PrivateKey)
- p.D = big.NewInt(0)
- // TODO: validate that the required flags are present
- for k, v := range m {
- switch k {
- case "privatekey":
- v1, err := fromBase64([]byte(v))
- if err != nil {
- return nil, err
- }
- p.D.SetBytes(v1)
- case "created", "publish", "activate":
- /* not used in Go (yet) */
- }
- }
- return p, nil
-}
-
-// parseKey reads a private key from r. It returns a map[string]string,
-// with the key-value pairs, or an error when the file is not correct.
-func parseKey(r io.Reader, file string) (map[string]string, error) {
- s := scanInit(r)
- m := make(map[string]string)
- c := make(chan lex)
- k := ""
- // Start the lexer
- go klexer(s, c)
- for l := range c {
- // It should alternate
- switch l.value {
- case zKey:
- k = l.token
- case zValue:
- if k == "" {
- return nil, &ParseError{file, "no private key seen", l}
- }
- //println("Setting", strings.ToLower(k), "to", l.token, "b")
- m[strings.ToLower(k)] = l.token
- k = ""
- }
- }
- return m, nil
-}
-
-// klexer scans the sourcefile and returns tokens on the channel c.
-func klexer(s *scan, c chan lex) {
- var l lex
- str := "" // Hold the current read text
- commt := false
- key := true
- x, err := s.tokenText()
- defer close(c)
- for err == nil {
- l.column = s.position.Column
- l.line = s.position.Line
- switch x {
- case ':':
- if commt {
- break
- }
- l.token = str
- if key {
- l.value = zKey
- c <- l
- // Next token is a space, eat it
- s.tokenText()
- key = false
- str = ""
- } else {
- l.value = zValue
- }
- case ';':
- commt = true
- case '\n':
- if commt {
- // Reset a comment
- commt = false
- }
- l.value = zValue
- l.token = str
- c <- l
- str = ""
- commt = false
- key = true
- default:
- if commt {
- break
- }
- str += string(x)
- }
- x, err = s.tokenText()
- }
- if len(str) > 0 {
- // Send remainder
- l.token = str
- l.value = zValue
- c <- l
- }
-}
diff --git a/Godeps/_workspace/src/github.com/miekg/dns/dnssec_privkey.go b/Godeps/_workspace/src/github.com/miekg/dns/dnssec_privkey.go
deleted file mode 100644
index 0b8f282b63..0000000000
--- a/Godeps/_workspace/src/github.com/miekg/dns/dnssec_privkey.go
+++ /dev/null
@@ -1,144 +0,0 @@
-package dns
-
-import (
- "crypto"
- "crypto/dsa"
- "crypto/ecdsa"
- "crypto/rand"
- "crypto/rsa"
- "math/big"
- "strconv"
-)
-
-const format = "Private-key-format: v1.3\n"
-
-// PrivateKey ... TODO(miek)
-type PrivateKey interface {
- Sign([]byte, uint8) ([]byte, error)
- String(uint8) string
-}
-
-// PrivateKeyString converts a PrivateKey to a string. This string has the same
-// format as the private-key-file of BIND9 (Private-key-format: v1.3).
-// It needs some info from the key (the algorithm), so its a method of the
-// DNSKEY and calls PrivateKey.String(alg).
-func (r *DNSKEY) PrivateKeyString(p PrivateKey) string {
- return p.String(r.Algorithm)
-}
-
-type RSAPrivateKey rsa.PrivateKey
-
-func (p *RSAPrivateKey) Sign(hashed []byte, alg uint8) ([]byte, error) {
- var hash crypto.Hash
- switch alg {
- case RSASHA1, RSASHA1NSEC3SHA1:
- hash = crypto.SHA1
- case RSASHA256:
- hash = crypto.SHA256
- case RSASHA512:
- hash = crypto.SHA512
- default:
- return nil, ErrAlg
- }
- return rsa.SignPKCS1v15(nil, (*rsa.PrivateKey)(p), hash, hashed)
-}
-
-func (p *RSAPrivateKey) String(alg uint8) string {
- algorithm := strconv.Itoa(int(alg)) + " (" + AlgorithmToString[alg] + ")"
- modulus := toBase64(p.PublicKey.N.Bytes())
- e := big.NewInt(int64(p.PublicKey.E))
- publicExponent := toBase64(e.Bytes())
- privateExponent := toBase64(p.D.Bytes())
- prime1 := toBase64(p.Primes[0].Bytes())
- prime2 := toBase64(p.Primes[1].Bytes())
- // Calculate Exponent1/2 and Coefficient as per: http://en.wikipedia.org/wiki/RSA#Using_the_Chinese_remainder_algorithm
- // and from: http://code.google.com/p/go/issues/detail?id=987
- one := big.NewInt(1)
- p1 := big.NewInt(0).Sub(p.Primes[0], one)
- q1 := big.NewInt(0).Sub(p.Primes[1], one)
- exp1 := big.NewInt(0).Mod(p.D, p1)
- exp2 := big.NewInt(0).Mod(p.D, q1)
- coeff := big.NewInt(0).ModInverse(p.Primes[1], p.Primes[0])
-
- exponent1 := toBase64(exp1.Bytes())
- exponent2 := toBase64(exp2.Bytes())
- coefficient := toBase64(coeff.Bytes())
-
- return format +
- "Algorithm: " + algorithm + "\n" +
- "Modulus: " + modulus + "\n" +
- "PublicExponent: " + publicExponent + "\n" +
- "PrivateExponent: " + privateExponent + "\n" +
- "Prime1: " + prime1 + "\n" +
- "Prime2: " + prime2 + "\n" +
- "Exponent1: " + exponent1 + "\n" +
- "Exponent2: " + exponent2 + "\n" +
- "Coefficient: " + coefficient + "\n"
-}
-
-type ECDSAPrivateKey ecdsa.PrivateKey
-
-func (p *ECDSAPrivateKey) Sign(hashed []byte, alg uint8) ([]byte, error) {
- var intlen int
- switch alg {
- case ECDSAP256SHA256:
- intlen = 32
- case ECDSAP384SHA384:
- intlen = 48
- default:
- return nil, ErrAlg
- }
- r1, s1, err := ecdsa.Sign(rand.Reader, (*ecdsa.PrivateKey)(p), hashed)
- if err != nil {
- return nil, err
- }
- signature := intToBytes(r1, intlen)
- signature = append(signature, intToBytes(s1, intlen)...)
- return signature, nil
-}
-
-func (p *ECDSAPrivateKey) String(alg uint8) string {
- algorithm := strconv.Itoa(int(alg)) + " (" + AlgorithmToString[alg] + ")"
- var intlen int
- switch alg {
- case ECDSAP256SHA256:
- intlen = 32
- case ECDSAP384SHA384:
- intlen = 48
- }
- private := toBase64(intToBytes(p.D, intlen))
- return format +
- "Algorithm: " + algorithm + "\n" +
- "PrivateKey: " + private + "\n"
-}
-
-type DSAPrivateKey dsa.PrivateKey
-
-func (p *DSAPrivateKey) Sign(hashed []byte, alg uint8) ([]byte, error) {
- r1, s1, err := dsa.Sign(rand.Reader, (*dsa.PrivateKey)(p), hashed)
- if err != nil {
- return nil, err
- }
- t := divRoundUp(divRoundUp(p.PublicKey.Y.BitLen(), 8)-64, 8)
- signature := []byte{byte(t)}
- signature = append(signature, intToBytes(r1, 20)...)
- signature = append(signature, intToBytes(s1, 20)...)
- return signature, nil
-}
-
-func (p *DSAPrivateKey) String(alg uint8) string {
- algorithm := strconv.Itoa(int(alg)) + " (" + AlgorithmToString[alg] + ")"
- T := divRoundUp(divRoundUp(p.PublicKey.Parameters.G.BitLen(), 8)-64, 8)
- prime := toBase64(intToBytes(p.PublicKey.Parameters.P, 64+T*8))
- subprime := toBase64(intToBytes(p.PublicKey.Parameters.Q, 20))
- base := toBase64(intToBytes(p.PublicKey.Parameters.G, 64+T*8))
- priv := toBase64(intToBytes(p.X, 20))
- pub := toBase64(intToBytes(p.PublicKey.Y, 64+T*8))
- return format +
- "Algorithm: " + algorithm + "\n" +
- "Prime(p): " + prime + "\n" +
- "Subprime(q): " + subprime + "\n" +
- "Base(g): " + base + "\n" +
- "Private_value(x): " + priv + "\n" +
- "Public_value(y): " + pub + "\n"
-}
diff --git a/Godeps/_workspace/src/github.com/miekg/dns/dnssec_test.go b/Godeps/_workspace/src/github.com/miekg/dns/dnssec_test.go
deleted file mode 100644
index 48c22362c5..0000000000
--- a/Godeps/_workspace/src/github.com/miekg/dns/dnssec_test.go
+++ /dev/null
@@ -1,658 +0,0 @@
-package dns
-
-import (
- "reflect"
- "strings"
- "testing"
- "time"
-)
-
-func getKey() *DNSKEY {
- key := new(DNSKEY)
- key.Hdr.Name = "miek.nl."
- key.Hdr.Class = ClassINET
- key.Hdr.Ttl = 14400
- key.Flags = 256
- key.Protocol = 3
- key.Algorithm = RSASHA256
- key.PublicKey = "AwEAAcNEU67LJI5GEgF9QLNqLO1SMq1EdoQ6E9f85ha0k0ewQGCblyW2836GiVsm6k8Kr5ECIoMJ6fZWf3CQSQ9ycWfTyOHfmI3eQ/1Covhb2y4bAmL/07PhrL7ozWBW3wBfM335Ft9xjtXHPy7ztCbV9qZ4TVDTW/Iyg0PiwgoXVesz"
- return key
-}
-
-func getSoa() *SOA {
- soa := new(SOA)
- soa.Hdr = RR_Header{"miek.nl.", TypeSOA, ClassINET, 14400, 0}
- soa.Ns = "open.nlnetlabs.nl."
- soa.Mbox = "miekg.atoom.net."
- soa.Serial = 1293945905
- soa.Refresh = 14400
- soa.Retry = 3600
- soa.Expire = 604800
- soa.Minttl = 86400
- return soa
-}
-
-func TestGenerateEC(t *testing.T) {
- if testing.Short() {
- t.Skip("skipping test in short mode.")
- }
- key := new(DNSKEY)
- key.Hdr.Rrtype = TypeDNSKEY
- key.Hdr.Name = "miek.nl."
- key.Hdr.Class = ClassINET
- key.Hdr.Ttl = 14400
- key.Flags = 256
- key.Protocol = 3
- key.Algorithm = ECDSAP256SHA256
- privkey, _ := key.Generate(256)
- t.Log(key.String())
- t.Log(key.PrivateKeyString(privkey))
-}
-
-func TestGenerateDSA(t *testing.T) {
- if testing.Short() {
- t.Skip("skipping test in short mode.")
- }
- key := new(DNSKEY)
- key.Hdr.Rrtype = TypeDNSKEY
- key.Hdr.Name = "miek.nl."
- key.Hdr.Class = ClassINET
- key.Hdr.Ttl = 14400
- key.Flags = 256
- key.Protocol = 3
- key.Algorithm = DSA
- privkey, _ := key.Generate(1024)
- t.Log(key.String())
- t.Log(key.PrivateKeyString(privkey))
-}
-
-func TestGenerateRSA(t *testing.T) {
- if testing.Short() {
- t.Skip("skipping test in short mode.")
- }
- key := new(DNSKEY)
- key.Hdr.Rrtype = TypeDNSKEY
- key.Hdr.Name = "miek.nl."
- key.Hdr.Class = ClassINET
- key.Hdr.Ttl = 14400
- key.Flags = 256
- key.Protocol = 3
- key.Algorithm = RSASHA256
- privkey, _ := key.Generate(1024)
- t.Log(key.String())
- t.Log(key.PrivateKeyString(privkey))
-}
-
-func TestSecure(t *testing.T) {
- soa := getSoa()
-
- sig := new(RRSIG)
- sig.Hdr = RR_Header{"miek.nl.", TypeRRSIG, ClassINET, 14400, 0}
- sig.TypeCovered = TypeSOA
- sig.Algorithm = RSASHA256
- sig.Labels = 2
- sig.Expiration = 1296534305 // date -u '+%s' -d"2011-02-01 04:25:05"
- sig.Inception = 1293942305 // date -u '+%s' -d"2011-01-02 04:25:05"
- sig.OrigTtl = 14400
- sig.KeyTag = 12051
- sig.SignerName = "miek.nl."
- sig.Signature = "oMCbslaAVIp/8kVtLSms3tDABpcPRUgHLrOR48OOplkYo+8TeEGWwkSwaz/MRo2fB4FxW0qj/hTlIjUGuACSd+b1wKdH5GvzRJc2pFmxtCbm55ygAh4EUL0F6U5cKtGJGSXxxg6UFCQ0doJCmiGFa78LolaUOXImJrk6AFrGa0M="
-
- key := new(DNSKEY)
- key.Hdr.Name = "miek.nl."
- key.Hdr.Class = ClassINET
- key.Hdr.Ttl = 14400
- key.Flags = 256
- key.Protocol = 3
- key.Algorithm = RSASHA256
- key.PublicKey = "AwEAAcNEU67LJI5GEgF9QLNqLO1SMq1EdoQ6E9f85ha0k0ewQGCblyW2836GiVsm6k8Kr5ECIoMJ6fZWf3CQSQ9ycWfTyOHfmI3eQ/1Covhb2y4bAmL/07PhrL7ozWBW3wBfM335Ft9xjtXHPy7ztCbV9qZ4TVDTW/Iyg0PiwgoXVesz"
-
- // It should validate. Period is checked separately, so this will keep on working
- if sig.Verify(key, []RR{soa}) != nil {
- t.Error("failure to validate")
- }
-}
-
-func TestSignature(t *testing.T) {
- sig := new(RRSIG)
- sig.Hdr.Name = "miek.nl."
- sig.Hdr.Class = ClassINET
- sig.Hdr.Ttl = 3600
- sig.TypeCovered = TypeDNSKEY
- sig.Algorithm = RSASHA1
- sig.Labels = 2
- sig.OrigTtl = 4000
- sig.Expiration = 1000 //Thu Jan 1 02:06:40 CET 1970
- sig.Inception = 800 //Thu Jan 1 01:13:20 CET 1970
- sig.KeyTag = 34641
- sig.SignerName = "miek.nl."
- sig.Signature = "AwEAAaHIwpx3w4VHKi6i1LHnTaWeHCL154Jug0Rtc9ji5qwPXpBo6A5sRv7cSsPQKPIwxLpyCrbJ4mr2L0EPOdvP6z6YfljK2ZmTbogU9aSU2fiq/4wjxbdkLyoDVgtO+JsxNN4bjr4WcWhsmk1Hg93FV9ZpkWb0Tbad8DFqNDzr//kZ"
-
- // Should not be valid
- if sig.ValidityPeriod(time.Now()) {
- t.Error("should not be valid")
- }
-
- sig.Inception = 315565800 //Tue Jan 1 10:10:00 CET 1980
- sig.Expiration = 4102477800 //Fri Jan 1 10:10:00 CET 2100
- if !sig.ValidityPeriod(time.Now()) {
- t.Error("should be valid")
- }
-}
-
-func TestSignVerify(t *testing.T) {
- // The record we want to sign
- soa := new(SOA)
- soa.Hdr = RR_Header{"miek.nl.", TypeSOA, ClassINET, 14400, 0}
- soa.Ns = "open.nlnetlabs.nl."
- soa.Mbox = "miekg.atoom.net."
- soa.Serial = 1293945905
- soa.Refresh = 14400
- soa.Retry = 3600
- soa.Expire = 604800
- soa.Minttl = 86400
-
- soa1 := new(SOA)
- soa1.Hdr = RR_Header{"*.miek.nl.", TypeSOA, ClassINET, 14400, 0}
- soa1.Ns = "open.nlnetlabs.nl."
- soa1.Mbox = "miekg.atoom.net."
- soa1.Serial = 1293945905
- soa1.Refresh = 14400
- soa1.Retry = 3600
- soa1.Expire = 604800
- soa1.Minttl = 86400
-
- srv := new(SRV)
- srv.Hdr = RR_Header{"srv.miek.nl.", TypeSRV, ClassINET, 14400, 0}
- srv.Port = 1000
- srv.Weight = 800
- srv.Target = "web1.miek.nl."
-
- // With this key
- key := new(DNSKEY)
- key.Hdr.Rrtype = TypeDNSKEY
- key.Hdr.Name = "miek.nl."
- key.Hdr.Class = ClassINET
- key.Hdr.Ttl = 14400
- key.Flags = 256
- key.Protocol = 3
- key.Algorithm = RSASHA256
- privkey, _ := key.Generate(512)
-
- // Fill in the values of the Sig, before signing
- sig := new(RRSIG)
- sig.Hdr = RR_Header{"miek.nl.", TypeRRSIG, ClassINET, 14400, 0}
- sig.TypeCovered = soa.Hdr.Rrtype
- sig.Labels = uint8(CountLabel(soa.Hdr.Name)) // works for all 3
- sig.OrigTtl = soa.Hdr.Ttl
- sig.Expiration = 1296534305 // date -u '+%s' -d"2011-02-01 04:25:05"
- sig.Inception = 1293942305 // date -u '+%s' -d"2011-01-02 04:25:05"
- sig.KeyTag = key.KeyTag() // Get the keyfrom the Key
- sig.SignerName = key.Hdr.Name
- sig.Algorithm = RSASHA256
-
- for _, r := range []RR{soa, soa1, srv} {
- if sig.Sign(privkey, []RR{r}) != nil {
- t.Error("failure to sign the record")
- continue
- }
- if sig.Verify(key, []RR{r}) != nil {
- t.Error("failure to validate")
- continue
- }
- t.Logf("validated: %s", r.Header().Name)
- }
-}
-
-func Test65534(t *testing.T) {
- t6 := new(RFC3597)
- t6.Hdr = RR_Header{"miek.nl.", 65534, ClassINET, 14400, 0}
- t6.Rdata = "505D870001"
- key := new(DNSKEY)
- key.Hdr.Name = "miek.nl."
- key.Hdr.Rrtype = TypeDNSKEY
- key.Hdr.Class = ClassINET
- key.Hdr.Ttl = 14400
- key.Flags = 256
- key.Protocol = 3
- key.Algorithm = RSASHA256
- privkey, _ := key.Generate(1024)
-
- sig := new(RRSIG)
- sig.Hdr = RR_Header{"miek.nl.", TypeRRSIG, ClassINET, 14400, 0}
- sig.TypeCovered = t6.Hdr.Rrtype
- sig.Labels = uint8(CountLabel(t6.Hdr.Name))
- sig.OrigTtl = t6.Hdr.Ttl
- sig.Expiration = 1296534305 // date -u '+%s' -d"2011-02-01 04:25:05"
- sig.Inception = 1293942305 // date -u '+%s' -d"2011-01-02 04:25:05"
- sig.KeyTag = key.KeyTag()
- sig.SignerName = key.Hdr.Name
- sig.Algorithm = RSASHA256
- if err := sig.Sign(privkey, []RR{t6}); err != nil {
- t.Error(err)
- t.Error("failure to sign the TYPE65534 record")
- }
- if err := sig.Verify(key, []RR{t6}); err != nil {
- t.Error(err)
- t.Error("failure to validate")
- } else {
- t.Logf("validated: %s", t6.Header().Name)
- }
-}
-
-func TestDnskey(t *testing.T) {
- pubkey, err := ReadRR(strings.NewReader(`
-miek.nl. IN DNSKEY 256 3 10 AwEAAZuMCu2FdugHkTrXYgl5qixvcDw1aDDlvL46/xJKbHBAHY16fNUb2b65cwko2Js/aJxUYJbZk5dwCDZxYfrfbZVtDPQuc3o8QaChVxC7/JYz2AHc9qHvqQ1j4VrH71RWINlQo6VYjzN/BGpMhOZoZOEwzp1HfsOE3lNYcoWU1smL ;{id = 5240 (zsk), size = 1024b}
-`), "Kmiek.nl.+010+05240.key")
- if err != nil {
- t.Fatal(err)
- }
- privStr := `Private-key-format: v1.3
-Algorithm: 10 (RSASHA512)
-Modulus: m4wK7YV26AeROtdiCXmqLG9wPDVoMOW8vjr/EkpscEAdjXp81RvZvrlzCSjYmz9onFRgltmTl3AINnFh+t9tlW0M9C5zejxBoKFXELv8ljPYAdz2oe+pDWPhWsfvVFYg2VCjpViPM38EakyE5mhk4TDOnUd+w4TeU1hyhZTWyYs=
-PublicExponent: AQAB
-PrivateExponent: UfCoIQ/Z38l8vB6SSqOI/feGjHEl/fxIPX4euKf0D/32k30fHbSaNFrFOuIFmWMB3LimWVEs6u3dpbB9CQeCVg7hwU5puG7OtuiZJgDAhNeOnxvo5btp4XzPZrJSxR4WNQnwIiYWbl0aFlL1VGgHC/3By89ENZyWaZcMLW4KGWE=
-Prime1: yxwC6ogAu8aVcDx2wg1V0b5M5P6jP8qkRFVMxWNTw60Vkn+ECvw6YAZZBHZPaMyRYZLzPgUlyYRd0cjupy4+fQ==
-Prime2: xA1bF8M0RTIQ6+A11AoVG6GIR/aPGg5sogRkIZ7ID/sF6g9HMVU/CM2TqVEBJLRPp73cv6ZeC3bcqOCqZhz+pw==
-Exponent1: xzkblyZ96bGYxTVZm2/vHMOXswod4KWIyMoOepK6B/ZPcZoIT6omLCgtypWtwHLfqyCz3MK51Nc0G2EGzg8rFQ==
-Exponent2: Pu5+mCEb7T5F+kFNZhQadHUklt0JUHbi3hsEvVoHpEGSw3BGDQrtIflDde0/rbWHgDPM4WQY+hscd8UuTXrvLw==
-Coefficient: UuRoNqe7YHnKmQzE6iDWKTMIWTuoqqrFAmXPmKQnC+Y+BQzOVEHUo9bXdDnoI9hzXP1gf8zENMYwYLeWpuYlFQ==
-`
- privkey, err := pubkey.(*DNSKEY).ReadPrivateKey(strings.NewReader(privStr),
- "Kmiek.nl.+010+05240.private")
- if err != nil {
- t.Fatal(err)
- }
- if pubkey.(*DNSKEY).PublicKey != "AwEAAZuMCu2FdugHkTrXYgl5qixvcDw1aDDlvL46/xJKbHBAHY16fNUb2b65cwko2Js/aJxUYJbZk5dwCDZxYfrfbZVtDPQuc3o8QaChVxC7/JYz2AHc9qHvqQ1j4VrH71RWINlQo6VYjzN/BGpMhOZoZOEwzp1HfsOE3lNYcoWU1smL" {
- t.Error("pubkey is not what we've read")
- }
- if pubkey.(*DNSKEY).PrivateKeyString(privkey) != privStr {
- t.Error("privkey is not what we've read")
- t.Errorf("%v", pubkey.(*DNSKEY).PrivateKeyString(privkey))
- }
-}
-
-func TestTag(t *testing.T) {
- key := new(DNSKEY)
- key.Hdr.Name = "miek.nl."
- key.Hdr.Rrtype = TypeDNSKEY
- key.Hdr.Class = ClassINET
- key.Hdr.Ttl = 3600
- key.Flags = 256
- key.Protocol = 3
- key.Algorithm = RSASHA256
- key.PublicKey = "AwEAAcNEU67LJI5GEgF9QLNqLO1SMq1EdoQ6E9f85ha0k0ewQGCblyW2836GiVsm6k8Kr5ECIoMJ6fZWf3CQSQ9ycWfTyOHfmI3eQ/1Covhb2y4bAmL/07PhrL7ozWBW3wBfM335Ft9xjtXHPy7ztCbV9qZ4TVDTW/Iyg0PiwgoXVesz"
-
- tag := key.KeyTag()
- if tag != 12051 {
- t.Errorf("wrong key tag: %d for key %v", tag, key)
- }
-}
-
-func TestKeyRSA(t *testing.T) {
- if testing.Short() {
- t.Skip("skipping test in short mode.")
- }
- key := new(DNSKEY)
- key.Hdr.Name = "miek.nl."
- key.Hdr.Rrtype = TypeDNSKEY
- key.Hdr.Class = ClassINET
- key.Hdr.Ttl = 3600
- key.Flags = 256
- key.Protocol = 3
- key.Algorithm = RSASHA256
- priv, _ := key.Generate(2048)
-
- soa := new(SOA)
- soa.Hdr = RR_Header{"miek.nl.", TypeSOA, ClassINET, 14400, 0}
- soa.Ns = "open.nlnetlabs.nl."
- soa.Mbox = "miekg.atoom.net."
- soa.Serial = 1293945905
- soa.Refresh = 14400
- soa.Retry = 3600
- soa.Expire = 604800
- soa.Minttl = 86400
-
- sig := new(RRSIG)
- sig.Hdr = RR_Header{"miek.nl.", TypeRRSIG, ClassINET, 14400, 0}
- sig.TypeCovered = TypeSOA
- sig.Algorithm = RSASHA256
- sig.Labels = 2
- sig.Expiration = 1296534305 // date -u '+%s' -d"2011-02-01 04:25:05"
- sig.Inception = 1293942305 // date -u '+%s' -d"2011-01-02 04:25:05"
- sig.OrigTtl = soa.Hdr.Ttl
- sig.KeyTag = key.KeyTag()
- sig.SignerName = key.Hdr.Name
-
- if err := sig.Sign(priv, []RR{soa}); err != nil {
- t.Error("failed to sign")
- return
- }
- if err := sig.Verify(key, []RR{soa}); err != nil {
- t.Error("failed to verify")
- }
-}
-
-func TestKeyToDS(t *testing.T) {
- key := new(DNSKEY)
- key.Hdr.Name = "miek.nl."
- key.Hdr.Rrtype = TypeDNSKEY
- key.Hdr.Class = ClassINET
- key.Hdr.Ttl = 3600
- key.Flags = 256
- key.Protocol = 3
- key.Algorithm = RSASHA256
- key.PublicKey = "AwEAAcNEU67LJI5GEgF9QLNqLO1SMq1EdoQ6E9f85ha0k0ewQGCblyW2836GiVsm6k8Kr5ECIoMJ6fZWf3CQSQ9ycWfTyOHfmI3eQ/1Covhb2y4bAmL/07PhrL7ozWBW3wBfM335Ft9xjtXHPy7ztCbV9qZ4TVDTW/Iyg0PiwgoXVesz"
-
- ds := key.ToDS(SHA1)
- if strings.ToUpper(ds.Digest) != "B5121BDB5B8D86D0CC5FFAFBAAABE26C3E20BAC1" {
- t.Errorf("wrong DS digest for SHA1\n%v", ds)
- }
-}
-
-func TestSignRSA(t *testing.T) {
- pub := "miek.nl. IN DNSKEY 256 3 5 AwEAAb+8lGNCxJgLS8rYVer6EnHVuIkQDghdjdtewDzU3G5R7PbMbKVRvH2Ma7pQyYceoaqWZQirSj72euPWfPxQnMy9ucCylA+FuH9cSjIcPf4PqJfdupHk9X6EBYjxrCLY4p1/yBwgyBIRJtZtAqM3ceAH2WovEJD6rTtOuHo5AluJ"
-
- priv := `Private-key-format: v1.3
-Algorithm: 5 (RSASHA1)
-Modulus: v7yUY0LEmAtLythV6voScdW4iRAOCF2N217APNTcblHs9sxspVG8fYxrulDJhx6hqpZlCKtKPvZ649Z8/FCczL25wLKUD4W4f1xKMhw9/g+ol926keT1foQFiPGsItjinX/IHCDIEhEm1m0Cozdx4AfZai8QkPqtO064ejkCW4k=
-PublicExponent: AQAB
-PrivateExponent: YPwEmwjk5HuiROKU4xzHQ6l1hG8Iiha4cKRG3P5W2b66/EN/GUh07ZSf0UiYB67o257jUDVEgwCuPJz776zfApcCB4oGV+YDyEu7Hp/rL8KcSN0la0k2r9scKwxTp4BTJT23zyBFXsV/1wRDK1A5NxsHPDMYi2SoK63Enm/1ptk=
-Prime1: /wjOG+fD0ybNoSRn7nQ79udGeR1b0YhUA5mNjDx/x2fxtIXzygYk0Rhx9QFfDy6LOBvz92gbNQlzCLz3DJt5hw==
-Prime2: wHZsJ8OGhkp5p3mrJFZXMDc2mbYusDVTA+t+iRPdS797Tj0pjvU2HN4vTnTj8KBQp6hmnY7dLp9Y1qserySGbw==
-Exponent1: N0A7FsSRIg+IAN8YPQqlawoTtG1t1OkJ+nWrurPootScApX6iMvn8fyvw3p2k51rv84efnzpWAYiC8SUaQDNxQ==
-Exponent2: SvuYRaGyvo0zemE3oS+WRm2scxR8eiA8WJGeOc+obwOKCcBgeZblXzfdHGcEC1KaOcetOwNW/vwMA46lpLzJNw==
-Coefficient: 8+7ZN/JgByqv0NfULiFKTjtyegUcijRuyij7yNxYbCBneDvZGxJwKNi4YYXWx743pcAj4Oi4Oh86gcmxLs+hGw==
-Created: 20110302104537
-Publish: 20110302104537
-Activate: 20110302104537`
-
- xk, _ := NewRR(pub)
- k := xk.(*DNSKEY)
- p, err := k.NewPrivateKey(priv)
- if err != nil {
- t.Error(err)
- }
- switch priv := p.(type) {
- case *RSAPrivateKey:
- if 65537 != priv.PublicKey.E {
- t.Error("exponenent should be 65537")
- }
- default:
- t.Errorf("we should have read an RSA key: %v", priv)
- }
- if k.KeyTag() != 37350 {
- t.Errorf("keytag should be 37350, got %d %v", k.KeyTag(), k)
- }
-
- soa := new(SOA)
- soa.Hdr = RR_Header{"miek.nl.", TypeSOA, ClassINET, 14400, 0}
- soa.Ns = "open.nlnetlabs.nl."
- soa.Mbox = "miekg.atoom.net."
- soa.Serial = 1293945905
- soa.Refresh = 14400
- soa.Retry = 3600
- soa.Expire = 604800
- soa.Minttl = 86400
-
- sig := new(RRSIG)
- sig.Hdr = RR_Header{"miek.nl.", TypeRRSIG, ClassINET, 14400, 0}
- sig.Expiration = 1296534305 // date -u '+%s' -d"2011-02-01 04:25:05"
- sig.Inception = 1293942305 // date -u '+%s' -d"2011-01-02 04:25:05"
- sig.KeyTag = k.KeyTag()
- sig.SignerName = k.Hdr.Name
- sig.Algorithm = k.Algorithm
-
- sig.Sign(p, []RR{soa})
- if sig.Signature != "D5zsobpQcmMmYsUMLxCVEtgAdCvTu8V/IEeP4EyLBjqPJmjt96bwM9kqihsccofA5LIJ7DN91qkCORjWSTwNhzCv7bMyr2o5vBZElrlpnRzlvsFIoAZCD9xg6ZY7ZyzUJmU6IcTwG4v3xEYajcpbJJiyaw/RqR90MuRdKPiBzSo=" {
- t.Errorf("signature is not correct: %v", sig)
- }
-}
-
-func TestSignVerifyECDSA(t *testing.T) {
- pub := `example.net. 3600 IN DNSKEY 257 3 14 (
- xKYaNhWdGOfJ+nPrL8/arkwf2EY3MDJ+SErKivBVSum1
- w/egsXvSADtNJhyem5RCOpgQ6K8X1DRSEkrbYQ+OB+v8
- /uX45NBwY8rp65F6Glur8I/mlVNgF6W/qTI37m40 )`
- priv := `Private-key-format: v1.2
-Algorithm: 14 (ECDSAP384SHA384)
-PrivateKey: WURgWHCcYIYUPWgeLmiPY2DJJk02vgrmTfitxgqcL4vwW7BOrbawVmVe0d9V94SR`
-
- eckey, err := NewRR(pub)
- if err != nil {
- t.Fatal(err)
- }
- privkey, err := eckey.(*DNSKEY).NewPrivateKey(priv)
- if err != nil {
- t.Fatal(err)
- }
- // TODO: Create separate test for this
- ds := eckey.(*DNSKEY).ToDS(SHA384)
- if ds.KeyTag != 10771 {
- t.Fatal("wrong keytag on DS")
- }
- if ds.Digest != "72d7b62976ce06438e9c0bf319013cf801f09ecc84b8d7e9495f27e305c6a9b0563a9b5f4d288405c3008a946df983d6" {
- t.Fatal("wrong DS Digest")
- }
- a, _ := NewRR("www.example.net. 3600 IN A 192.0.2.1")
- sig := new(RRSIG)
- sig.Hdr = RR_Header{"example.net.", TypeRRSIG, ClassINET, 14400, 0}
- sig.Expiration, _ = StringToTime("20100909102025")
- sig.Inception, _ = StringToTime("20100812102025")
- sig.KeyTag = eckey.(*DNSKEY).KeyTag()
- sig.SignerName = eckey.(*DNSKEY).Hdr.Name
- sig.Algorithm = eckey.(*DNSKEY).Algorithm
-
- if sig.Sign(privkey, []RR{a}) != nil {
- t.Fatal("failure to sign the record")
- }
-
- if err := sig.Verify(eckey.(*DNSKEY), []RR{a}); err != nil {
- t.Fatalf("Failure to validate:\n%s\n%s\n%s\n\n%s\n\n%v",
- eckey.(*DNSKEY).String(),
- a.String(),
- sig.String(),
- eckey.(*DNSKEY).PrivateKeyString(privkey),
- err,
- )
- }
-}
-
-func TestSignVerifyECDSA2(t *testing.T) {
- srv1, err := NewRR("srv.miek.nl. IN SRV 1000 800 0 web1.miek.nl.")
- if err != nil {
- t.Fatal(err)
- }
- srv := srv1.(*SRV)
-
- // With this key
- key := new(DNSKEY)
- key.Hdr.Rrtype = TypeDNSKEY
- key.Hdr.Name = "miek.nl."
- key.Hdr.Class = ClassINET
- key.Hdr.Ttl = 14400
- key.Flags = 256
- key.Protocol = 3
- key.Algorithm = ECDSAP256SHA256
- privkey, err := key.Generate(256)
- if err != nil {
- t.Fatal("failure to generate key")
- }
-
- // Fill in the values of the Sig, before signing
- sig := new(RRSIG)
- sig.Hdr = RR_Header{"miek.nl.", TypeRRSIG, ClassINET, 14400, 0}
- sig.TypeCovered = srv.Hdr.Rrtype
- sig.Labels = uint8(CountLabel(srv.Hdr.Name)) // works for all 3
- sig.OrigTtl = srv.Hdr.Ttl
- sig.Expiration = 1296534305 // date -u '+%s' -d"2011-02-01 04:25:05"
- sig.Inception = 1293942305 // date -u '+%s' -d"2011-01-02 04:25:05"
- sig.KeyTag = key.KeyTag() // Get the keyfrom the Key
- sig.SignerName = key.Hdr.Name
- sig.Algorithm = ECDSAP256SHA256
-
- if sig.Sign(privkey, []RR{srv}) != nil {
- t.Fatal("failure to sign the record")
- }
-
- err = sig.Verify(key, []RR{srv})
- if err != nil {
- t.Logf("Failure to validate:\n%s\n%s\n%s\n\n%s\n\n%v",
- key.String(),
- srv.String(),
- sig.String(),
- key.PrivateKeyString(privkey),
- err,
- )
- }
-}
-
-// Here the test vectors from the relevant RFCs are checked.
-// rfc6605 6.1
-func TestRFC6605P256(t *testing.T) {
- exDNSKEY := `example.net. 3600 IN DNSKEY 257 3 13 (
- GojIhhXUN/u4v54ZQqGSnyhWJwaubCvTmeexv7bR6edb
- krSqQpF64cYbcB7wNcP+e+MAnLr+Wi9xMWyQLc8NAA== )`
- exPriv := `Private-key-format: v1.2
-Algorithm: 13 (ECDSAP256SHA256)
-PrivateKey: GU6SnQ/Ou+xC5RumuIUIuJZteXT2z0O/ok1s38Et6mQ=`
- rrDNSKEY, err := NewRR(exDNSKEY)
- if err != nil {
- t.Fatal(err)
- }
- priv, err := rrDNSKEY.(*DNSKEY).NewPrivateKey(exPriv)
- if err != nil {
- t.Fatal(err)
- }
-
- exDS := `example.net. 3600 IN DS 55648 13 2 (
- b4c8c1fe2e7477127b27115656ad6256f424625bf5c1
- e2770ce6d6e37df61d17 )`
- rrDS, err := NewRR(exDS)
- if err != nil {
- t.Fatal(err)
- }
- ourDS := rrDNSKEY.(*DNSKEY).ToDS(SHA256)
- if !reflect.DeepEqual(ourDS, rrDS.(*DS)) {
- t.Errorf("DS record differs:\n%v\n%v", ourDS, rrDS.(*DS))
- }
-
- exA := `www.example.net. 3600 IN A 192.0.2.1`
- exRRSIG := `www.example.net. 3600 IN RRSIG A 13 3 3600 (
- 20100909100439 20100812100439 55648 example.net.
- qx6wLYqmh+l9oCKTN6qIc+bw6ya+KJ8oMz0YP107epXA
- yGmt+3SNruPFKG7tZoLBLlUzGGus7ZwmwWep666VCw== )`
- rrA, err := NewRR(exA)
- if err != nil {
- t.Fatal(err)
- }
- rrRRSIG, err := NewRR(exRRSIG)
- if err != nil {
- t.Fatal(err)
- }
- if err = rrRRSIG.(*RRSIG).Verify(rrDNSKEY.(*DNSKEY), []RR{rrA}); err != nil {
- t.Errorf("Failure to validate the spec RRSIG: %v", err)
- }
-
- ourRRSIG := &RRSIG{
- Hdr: RR_Header{
- Ttl: rrA.Header().Ttl,
- },
- KeyTag: rrDNSKEY.(*DNSKEY).KeyTag(),
- SignerName: rrDNSKEY.(*DNSKEY).Hdr.Name,
- Algorithm: rrDNSKEY.(*DNSKEY).Algorithm,
- }
- ourRRSIG.Expiration, _ = StringToTime("20100909100439")
- ourRRSIG.Inception, _ = StringToTime("20100812100439")
- err = ourRRSIG.Sign(priv, []RR{rrA})
- if err != nil {
- t.Fatal(err)
- }
-
- if err = ourRRSIG.Verify(rrDNSKEY.(*DNSKEY), []RR{rrA}); err != nil {
- t.Errorf("Failure to validate our RRSIG: %v", err)
- }
-
- // Signatures are randomized
- rrRRSIG.(*RRSIG).Signature = ""
- ourRRSIG.Signature = ""
- if !reflect.DeepEqual(ourRRSIG, rrRRSIG.(*RRSIG)) {
- t.Fatalf("RRSIG record differs:\n%v\n%v", ourRRSIG, rrRRSIG.(*RRSIG))
- }
-}
-
-// rfc6605 6.2
-func TestRFC6605P384(t *testing.T) {
- exDNSKEY := `example.net. 3600 IN DNSKEY 257 3 14 (
- xKYaNhWdGOfJ+nPrL8/arkwf2EY3MDJ+SErKivBVSum1
- w/egsXvSADtNJhyem5RCOpgQ6K8X1DRSEkrbYQ+OB+v8
- /uX45NBwY8rp65F6Glur8I/mlVNgF6W/qTI37m40 )`
- exPriv := `Private-key-format: v1.2
-Algorithm: 14 (ECDSAP384SHA384)
-PrivateKey: WURgWHCcYIYUPWgeLmiPY2DJJk02vgrmTfitxgqcL4vwW7BOrbawVmVe0d9V94SR`
- rrDNSKEY, err := NewRR(exDNSKEY)
- if err != nil {
- t.Fatal(err)
- }
- priv, err := rrDNSKEY.(*DNSKEY).NewPrivateKey(exPriv)
- if err != nil {
- t.Fatal(err)
- }
-
- exDS := `example.net. 3600 IN DS 10771 14 4 (
- 72d7b62976ce06438e9c0bf319013cf801f09ecc84b8
- d7e9495f27e305c6a9b0563a9b5f4d288405c3008a94
- 6df983d6 )`
- rrDS, err := NewRR(exDS)
- if err != nil {
- t.Fatal(err)
- }
- ourDS := rrDNSKEY.(*DNSKEY).ToDS(SHA384)
- if !reflect.DeepEqual(ourDS, rrDS.(*DS)) {
- t.Fatalf("DS record differs:\n%v\n%v", ourDS, rrDS.(*DS))
- }
-
- exA := `www.example.net. 3600 IN A 192.0.2.1`
- exRRSIG := `www.example.net. 3600 IN RRSIG A 14 3 3600 (
- 20100909102025 20100812102025 10771 example.net.
- /L5hDKIvGDyI1fcARX3z65qrmPsVz73QD1Mr5CEqOiLP
- 95hxQouuroGCeZOvzFaxsT8Glr74hbavRKayJNuydCuz
- WTSSPdz7wnqXL5bdcJzusdnI0RSMROxxwGipWcJm )`
- rrA, err := NewRR(exA)
- if err != nil {
- t.Fatal(err)
- }
- rrRRSIG, err := NewRR(exRRSIG)
- if err != nil {
- t.Fatal(err)
- }
- if err = rrRRSIG.(*RRSIG).Verify(rrDNSKEY.(*DNSKEY), []RR{rrA}); err != nil {
- t.Errorf("Failure to validate the spec RRSIG: %v", err)
- }
-
- ourRRSIG := &RRSIG{
- Hdr: RR_Header{
- Ttl: rrA.Header().Ttl,
- },
- KeyTag: rrDNSKEY.(*DNSKEY).KeyTag(),
- SignerName: rrDNSKEY.(*DNSKEY).Hdr.Name,
- Algorithm: rrDNSKEY.(*DNSKEY).Algorithm,
- }
- ourRRSIG.Expiration, _ = StringToTime("20100909102025")
- ourRRSIG.Inception, _ = StringToTime("20100812102025")
- err = ourRRSIG.Sign(priv, []RR{rrA})
- if err != nil {
- t.Fatal(err)
- }
-
- if err = ourRRSIG.Verify(rrDNSKEY.(*DNSKEY), []RR{rrA}); err != nil {
- t.Errorf("Failure to validate our RRSIG: %v", err)
- }
-
- // Signatures are randomized
- rrRRSIG.(*RRSIG).Signature = ""
- ourRRSIG.Signature = ""
- if !reflect.DeepEqual(ourRRSIG, rrRRSIG.(*RRSIG)) {
- t.Fatalf("RRSIG record differs:\n%v\n%v", ourRRSIG, rrRRSIG.(*RRSIG))
- }
-}
diff --git a/Godeps/_workspace/src/github.com/miekg/dns/doc.go b/Godeps/_workspace/src/github.com/miekg/dns/doc.go
deleted file mode 100644
index 34d59ab144..0000000000
--- a/Godeps/_workspace/src/github.com/miekg/dns/doc.go
+++ /dev/null
@@ -1,250 +0,0 @@
-/*
-Package dns implements a full featured interface to the Domain Name System.
-Server- and client-side programming is supported.
-The package allows complete control over what is send out to the DNS. The package
-API follows the less-is-more principle, by presenting a small, clean interface.
-
-The package dns supports (asynchronous) querying/replying, incoming/outgoing zone transfers,
-TSIG, EDNS0, dynamic updates, notifies and DNSSEC validation/signing.
-Note that domain names MUST be fully qualified, before sending them, unqualified
-names in a message will result in a packing failure.
-
-Resource records are native types. They are not stored in wire format.
-Basic usage pattern for creating a new resource record:
-
- r := new(dns.MX)
- r.Hdr = dns.RR_Header{Name: "miek.nl.", Rrtype: dns.TypeMX, Class: dns.ClassINET, Ttl: 3600}
- r.Preference = 10
- r.Mx = "mx.miek.nl."
-
-Or directly from a string:
-
- mx, err := dns.NewRR("miek.nl. 3600 IN MX 10 mx.miek.nl.")
-
-Or when the default TTL (3600) and class (IN) suit you:
-
- mx, err := dns.NewRR("miek.nl. MX 10 mx.miek.nl.")
-
-Or even:
-
- mx, err := dns.NewRR("$ORIGIN nl.\nmiek 1H IN MX 10 mx.miek")
-
-In the DNS messages are exchanged, these messages contain resource
-records (sets). Use pattern for creating a message:
-
- m := new(dns.Msg)
- m.SetQuestion("miek.nl.", dns.TypeMX)
-
-Or when not certain if the domain name is fully qualified:
-
- m.SetQuestion(dns.Fqdn("miek.nl"), dns.TypeMX)
-
-The message m is now a message with the question section set to ask
-the MX records for the miek.nl. zone.
-
-The following is slightly more verbose, but more flexible:
-
- m1 := new(dns.Msg)
- m1.Id = dns.Id()
- m1.RecursionDesired = true
- m1.Question = make([]dns.Question, 1)
- m1.Question[0] = dns.Question{"miek.nl.", dns.TypeMX, dns.ClassINET}
-
-After creating a message it can be send.
-Basic use pattern for synchronous querying the DNS at a
-server configured on 127.0.0.1 and port 53:
-
- c := new(dns.Client)
- in, rtt, err := c.Exchange(m1, "127.0.0.1:53")
-
-Suppressing
-multiple outstanding queries (with the same question, type and class) is as easy as setting:
-
- c.SingleInflight = true
-
-If these "advanced" features are not needed, a simple UDP query can be send,
-with:
-
- in, err := dns.Exchange(m1, "127.0.0.1:53")
-
-When this functions returns you will get dns message. A dns message consists
-out of four sections.
-The question section: in.Question, the answer section: in.Answer,
-the authority section: in.Ns and the additional section: in.Extra.
-
-Each of these sections (except the Question section) contain a []RR. Basic
-use pattern for accessing the rdata of a TXT RR as the first RR in
-the Answer section:
-
- if t, ok := in.Answer[0].(*dns.TXT); ok {
- // do something with t.Txt
- }
-
-Domain Name and TXT Character String Representations
-
-Both domain names and TXT character strings are converted to presentation
-form both when unpacked and when converted to strings.
-
-For TXT character strings, tabs, carriage returns and line feeds will be
-converted to \t, \r and \n respectively. Back slashes and quotations marks
-will be escaped. Bytes below 32 and above 127 will be converted to \DDD
-form.
-
-For domain names, in addition to the above rules brackets, periods,
-spaces, semicolons and the at symbol are escaped.
-
-DNSSEC
-
-DNSSEC (DNS Security Extension) adds a layer of security to the DNS. It
-uses public key cryptography to sign resource records. The
-public keys are stored in DNSKEY records and the signatures in RRSIG records.
-
-Requesting DNSSEC information for a zone is done by adding the DO (DNSSEC OK) bit
-to an request.
-
- m := new(dns.Msg)
- m.SetEdns0(4096, true)
-
-Signature generation, signature verification and key generation are all supported.
-
-DYNAMIC UPDATES
-
-Dynamic updates reuses the DNS message format, but renames three of
-the sections. Question is Zone, Answer is Prerequisite, Authority is
-Update, only the Additional is not renamed. See RFC 2136 for the gory details.
-
-You can set a rather complex set of rules for the existence of absence of
-certain resource records or names in a zone to specify if resource records
-should be added or removed. The table from RFC 2136 supplemented with the Go
-DNS function shows which functions exist to specify the prerequisites.
-
-3.2.4 - Table Of Metavalues Used In Prerequisite Section
-
- CLASS TYPE RDATA Meaning Function
- --------------------------------------------------------------
- ANY ANY empty Name is in use dns.NameUsed
- ANY rrset empty RRset exists (value indep) dns.RRsetUsed
- NONE ANY empty Name is not in use dns.NameNotUsed
- NONE rrset empty RRset does not exist dns.RRsetNotUsed
- zone rrset rr RRset exists (value dep) dns.Used
-
-The prerequisite section can also be left empty.
-If you have decided on the prerequisites you can tell what RRs should
-be added or deleted. The next table shows the options you have and
-what functions to call.
-
-3.4.2.6 - Table Of Metavalues Used In Update Section
-
- CLASS TYPE RDATA Meaning Function
- ---------------------------------------------------------------
- ANY ANY empty Delete all RRsets from name dns.RemoveName
- ANY rrset empty Delete an RRset dns.RemoveRRset
- NONE rrset rr Delete an RR from RRset dns.Remove
- zone rrset rr Add to an RRset dns.Insert
-
-TRANSACTION SIGNATURE
-
-An TSIG or transaction signature adds a HMAC TSIG record to each message sent.
-The supported algorithms include: HmacMD5, HmacSHA1, HmacSHA256 and HmacSHA512.
-
-Basic use pattern when querying with a TSIG name "axfr." (note that these key names
-must be fully qualified - as they are domain names) and the base64 secret
-"so6ZGir4GPAqINNh9U5c3A==":
-
- c := new(dns.Client)
- c.TsigSecret = map[string]string{"axfr.": "so6ZGir4GPAqINNh9U5c3A=="}
- m := new(dns.Msg)
- m.SetQuestion("miek.nl.", dns.TypeMX)
- m.SetTsig("axfr.", dns.HmacMD5, 300, time.Now().Unix())
- ...
- // When sending the TSIG RR is calculated and filled in before sending
-
-When requesting an zone transfer (almost all TSIG usage is when requesting zone transfers), with
-TSIG, this is the basic use pattern. In this example we request an AXFR for
-miek.nl. with TSIG key named "axfr." and secret "so6ZGir4GPAqINNh9U5c3A=="
-and using the server 176.58.119.54:
-
- t := new(dns.Transfer)
- m := new(dns.Msg)
- t.TsigSecret = map[string]string{"axfr.": "so6ZGir4GPAqINNh9U5c3A=="}
- m.SetAxfr("miek.nl.")
- m.SetTsig("axfr.", dns.HmacMD5, 300, time.Now().Unix())
- c, err := t.In(m, "176.58.119.54:53")
- for r := range c { ... }
-
-You can now read the records from the transfer as they come in. Each envelope is checked with TSIG.
-If something is not correct an error is returned.
-
-Basic use pattern validating and replying to a message that has TSIG set.
-
- server := &dns.Server{Addr: ":53", Net: "udp"}
- server.TsigSecret = map[string]string{"axfr.": "so6ZGir4GPAqINNh9U5c3A=="}
- go server.ListenAndServe()
- dns.HandleFunc(".", handleRequest)
-
- func handleRequest(w dns.ResponseWriter, r *dns.Msg) {
- m := new(Msg)
- m.SetReply(r)
- if r.IsTsig() {
- if w.TsigStatus() == nil {
- // *Msg r has an TSIG record and it was validated
- m.SetTsig("axfr.", dns.HmacMD5, 300, time.Now().Unix())
- } else {
- // *Msg r has an TSIG records and it was not valided
- }
- }
- w.WriteMsg(m)
- }
-
-PRIVATE RRS
-
-RFC 6895 sets aside a range of type codes for private use. This range
-is 65,280 - 65,534 (0xFF00 - 0xFFFE). When experimenting with new Resource Records these
-can be used, before requesting an official type code from IANA.
-
-see http://miek.nl/posts/2014/Sep/21/Private%20RRs%20and%20IDN%20in%20Go%20DNS/ for more
-information.
-
-EDNS0
-
-EDNS0 is an extension mechanism for the DNS defined in RFC 2671 and updated
-by RFC 6891. It defines an new RR type, the OPT RR, which is then completely
-abused.
-Basic use pattern for creating an (empty) OPT RR:
-
- o := new(dns.OPT)
- o.Hdr.Name = "." // MUST be the root zone, per definition.
- o.Hdr.Rrtype = dns.TypeOPT
-
-The rdata of an OPT RR consists out of a slice of EDNS0 (RFC 6891)
-interfaces. Currently only a few have been standardized: EDNS0_NSID
-(RFC 5001) and EDNS0_SUBNET (draft-vandergaast-edns-client-subnet-02). Note
-that these options may be combined in an OPT RR.
-Basic use pattern for a server to check if (and which) options are set:
-
- // o is a dns.OPT
- for _, s := range o.Option {
- switch e := s.(type) {
- case *dns.EDNS0_NSID:
- // do stuff with e.Nsid
- case *dns.EDNS0_SUBNET:
- // access e.Family, e.Address, etc.
- }
- }
-
-SIG(0)
-
-From RFC 2931:
-
- SIG(0) provides protection for DNS transactions and requests ....
- ... protection for glue records, DNS requests, protection for message headers
- on requests and responses, and protection of the overall integrity of a response.
-
-It works like TSIG, except that SIG(0) uses public key cryptography, instead of the shared
-secret approach in TSIG.
-Supported algorithms: DSA, ECDSAP256SHA256, ECDSAP384SHA384, RSASHA1, RSASHA256 and
-RSASHA512.
-
-Signing subsequent messages in multi-message sessions is not implemented.
-*/
-package dns
diff --git a/Godeps/_workspace/src/github.com/miekg/dns/dyn_test.go b/Godeps/_workspace/src/github.com/miekg/dns/dyn_test.go
deleted file mode 100644
index 09986a5e4e..0000000000
--- a/Godeps/_workspace/src/github.com/miekg/dns/dyn_test.go
+++ /dev/null
@@ -1,3 +0,0 @@
-package dns
-
-// Find better solution
diff --git a/Godeps/_workspace/src/github.com/miekg/dns/edns.go b/Godeps/_workspace/src/github.com/miekg/dns/edns.go
deleted file mode 100644
index d2bfecbb2f..0000000000
--- a/Godeps/_workspace/src/github.com/miekg/dns/edns.go
+++ /dev/null
@@ -1,523 +0,0 @@
-package dns
-
-import (
- "encoding/hex"
- "errors"
- "net"
- "strconv"
-)
-
-// EDNS0 Option codes.
-const (
- EDNS0LLQ = 0x1 // long lived queries: http://tools.ietf.org/html/draft-sekar-dns-llq-01
- EDNS0UL = 0x2 // update lease draft: http://files.dns-sd.org/draft-sekar-dns-ul.txt
- EDNS0NSID = 0x3 // nsid (RFC5001)
- EDNS0DAU = 0x5 // DNSSEC Algorithm Understood
- EDNS0DHU = 0x6 // DS Hash Understood
- EDNS0N3U = 0x7 // NSEC3 Hash Understood
- EDNS0SUBNET = 0x8 // client-subnet (RFC6891)
- EDNS0EXPIRE = 0x9 // EDNS0 expire
- EDNS0SUBNETDRAFT = 0x50fa // Don't use! Use EDNS0SUBNET
- EDNS0LOCALSTART = 0xFDE9 // Beginning of range reserved for local/experimental use (RFC6891)
- EDNS0LOCALEND = 0xFFFE // End of range reserved for local/experimental use (RFC6891)
- _DO = 1 << 15 // dnssec ok
-)
-
-// OPT is the EDNS0 RR appended to messages to convey extra (meta) information.
-// See RFC 6891.
-type OPT struct {
- Hdr RR_Header
- Option []EDNS0 `dns:"opt"`
-}
-
-func (rr *OPT) Header() *RR_Header {
- return &rr.Hdr
-}
-
-func (rr *OPT) String() string {
- s := "\n;; OPT PSEUDOSECTION:\n; EDNS: version " + strconv.Itoa(int(rr.Version())) + "; "
- if rr.Do() {
- s += "flags: do; "
- } else {
- s += "flags: ; "
- }
- s += "udp: " + strconv.Itoa(int(rr.UDPSize()))
-
- for _, o := range rr.Option {
- switch o.(type) {
- case *EDNS0_NSID:
- s += "\n; NSID: " + o.String()
- h, e := o.pack()
- var r string
- if e == nil {
- for _, c := range h {
- r += "(" + string(c) + ")"
- }
- s += " " + r
- }
- case *EDNS0_SUBNET:
- s += "\n; SUBNET: " + o.String()
- if o.(*EDNS0_SUBNET).DraftOption {
- s += " (draft)"
- }
- case *EDNS0_UL:
- s += "\n; UPDATE LEASE: " + o.String()
- case *EDNS0_LLQ:
- s += "\n; LONG LIVED QUERIES: " + o.String()
- case *EDNS0_DAU:
- s += "\n; DNSSEC ALGORITHM UNDERSTOOD: " + o.String()
- case *EDNS0_DHU:
- s += "\n; DS HASH UNDERSTOOD: " + o.String()
- case *EDNS0_N3U:
- s += "\n; NSEC3 HASH UNDERSTOOD: " + o.String()
- case *EDNS0_LOCAL:
- s += "\n; LOCAL OPT: " + o.String()
- }
- }
- return s
-}
-
-func (rr *OPT) len() int {
- l := rr.Hdr.len()
- for i := 0; i < len(rr.Option); i++ {
- l += 4 // Account for 2-byte option code and 2-byte option length.
- lo, _ := rr.Option[i].pack()
- l += len(lo)
- }
- return l
-}
-
-func (rr *OPT) copy() RR {
- return &OPT{*rr.Hdr.copyHeader(), rr.Option}
-}
-
-// return the old value -> delete SetVersion?
-
-// Version returns the EDNS version used. Only zero is defined.
-func (rr *OPT) Version() uint8 {
- return uint8((rr.Hdr.Ttl & 0x00FF0000) >> 16)
-}
-
-// SetVersion sets the version of EDNS. This is usually zero.
-func (rr *OPT) SetVersion(v uint8) {
- rr.Hdr.Ttl = rr.Hdr.Ttl&0xFF00FFFF | (uint32(v) << 16)
-}
-
-// ExtendedRcode returns the EDNS extended RCODE field (the upper 8 bits of the TTL).
-func (rr *OPT) ExtendedRcode() uint8 {
- return uint8((rr.Hdr.Ttl & 0xFF000000) >> 24)
-}
-
-// SetExtendedRcode sets the EDNS extended RCODE field.
-func (rr *OPT) SetExtendedRcode(v uint8) {
- rr.Hdr.Ttl = rr.Hdr.Ttl&0x00FFFFFF | (uint32(v) << 24)
-}
-
-// UDPSize returns the UDP buffer size.
-func (rr *OPT) UDPSize() uint16 {
- return rr.Hdr.Class
-}
-
-// SetUDPSize sets the UDP buffer size.
-func (rr *OPT) SetUDPSize(size uint16) {
- rr.Hdr.Class = size
-}
-
-// Do returns the value of the DO (DNSSEC OK) bit.
-func (rr *OPT) Do() bool {
- return rr.Hdr.Ttl&_DO == _DO
-}
-
-// SetDo sets the DO (DNSSEC OK) bit.
-func (rr *OPT) SetDo() {
- rr.Hdr.Ttl |= _DO
-}
-
-// EDNS0 defines an EDNS0 Option. An OPT RR can have multiple options appended to
-// it.
-type EDNS0 interface {
- // Option returns the option code for the option.
- Option() uint16
- // pack returns the bytes of the option data.
- pack() ([]byte, error)
- // unpack sets the data as found in the buffer. Is also sets
- // the length of the slice as the length of the option data.
- unpack([]byte) error
- // String returns the string representation of the option.
- String() string
-}
-
-// The nsid EDNS0 option is used to retrieve a nameserver
-// identifier. When sending a request Nsid must be set to the empty string
-// The identifier is an opaque string encoded as hex.
-// Basic use pattern for creating an nsid option:
-//
-// o := new(dns.OPT)
-// o.Hdr.Name = "."
-// o.Hdr.Rrtype = dns.TypeOPT
-// e := new(dns.EDNS0_NSID)
-// e.Code = dns.EDNS0NSID
-// e.Nsid = "AA"
-// o.Option = append(o.Option, e)
-type EDNS0_NSID struct {
- Code uint16 // Always EDNS0NSID
- Nsid string // This string needs to be hex encoded
-}
-
-func (e *EDNS0_NSID) pack() ([]byte, error) {
- h, err := hex.DecodeString(e.Nsid)
- if err != nil {
- return nil, err
- }
- return h, nil
-}
-
-func (e *EDNS0_NSID) Option() uint16 { return EDNS0NSID }
-func (e *EDNS0_NSID) unpack(b []byte) error { e.Nsid = hex.EncodeToString(b); return nil }
-func (e *EDNS0_NSID) String() string { return string(e.Nsid) }
-
-// The subnet EDNS0 option is used to give the remote nameserver
-// an idea of where the client lives. It can then give back a different
-// answer depending on the location or network topology.
-// Basic use pattern for creating an subnet option:
-//
-// o := new(dns.OPT)
-// o.Hdr.Name = "."
-// o.Hdr.Rrtype = dns.TypeOPT
-// e := new(dns.EDNS0_SUBNET)
-// e.Code = dns.EDNS0SUBNET
-// e.Family = 1 // 1 for IPv4 source address, 2 for IPv6
-// e.NetMask = 32 // 32 for IPV4, 128 for IPv6
-// e.SourceScope = 0
-// e.Address = net.ParseIP("127.0.0.1").To4() // for IPv4
-// // e.Address = net.ParseIP("2001:7b8:32a::2") // for IPV6
-// o.Option = append(o.Option, e)
-type EDNS0_SUBNET struct {
- Code uint16 // Always EDNS0SUBNET
- Family uint16 // 1 for IP, 2 for IP6
- SourceNetmask uint8
- SourceScope uint8
- Address net.IP
- DraftOption bool // Set to true if using the old (0x50fa) option code
-}
-
-func (e *EDNS0_SUBNET) Option() uint16 {
- if e.DraftOption {
- return EDNS0SUBNETDRAFT
- }
- return EDNS0SUBNET
-}
-
-func (e *EDNS0_SUBNET) pack() ([]byte, error) {
- b := make([]byte, 4)
- b[0], b[1] = packUint16(e.Family)
- b[2] = e.SourceNetmask
- b[3] = e.SourceScope
- switch e.Family {
- case 1:
- if e.SourceNetmask > net.IPv4len*8 {
- return nil, errors.New("dns: bad netmask")
- }
- ip := make([]byte, net.IPv4len)
- a := e.Address.To4().Mask(net.CIDRMask(int(e.SourceNetmask), net.IPv4len*8))
- for i := 0; i < net.IPv4len; i++ {
- if i+1 > len(e.Address) {
- break
- }
- ip[i] = a[i]
- }
- needLength := e.SourceNetmask / 8
- if e.SourceNetmask%8 > 0 {
- needLength++
- }
- ip = ip[:needLength]
- b = append(b, ip...)
- case 2:
- if e.SourceNetmask > net.IPv6len*8 {
- return nil, errors.New("dns: bad netmask")
- }
- ip := make([]byte, net.IPv6len)
- a := e.Address.Mask(net.CIDRMask(int(e.SourceNetmask), net.IPv6len*8))
- for i := 0; i < net.IPv6len; i++ {
- if i+1 > len(e.Address) {
- break
- }
- ip[i] = a[i]
- }
- needLength := e.SourceNetmask / 8
- if e.SourceNetmask%8 > 0 {
- needLength++
- }
- ip = ip[:needLength]
- b = append(b, ip...)
- default:
- return nil, errors.New("dns: bad address family")
- }
- return b, nil
-}
-
-func (e *EDNS0_SUBNET) unpack(b []byte) error {
- lb := len(b)
- if lb < 4 {
- return ErrBuf
- }
- e.Family, _ = unpackUint16(b, 0)
- e.SourceNetmask = b[2]
- e.SourceScope = b[3]
- switch e.Family {
- case 1:
- addr := make([]byte, 4)
- for i := 0; i < int(e.SourceNetmask/8); i++ {
- if i >= len(addr) || 4+i >= len(b) {
- return ErrBuf
- }
- addr[i] = b[4+i]
- }
- e.Address = net.IPv4(addr[0], addr[1], addr[2], addr[3])
- case 2:
- addr := make([]byte, 16)
- for i := 0; i < int(e.SourceNetmask/8); i++ {
- if i >= len(addr) || 4+i >= len(b) {
- return ErrBuf
- }
- addr[i] = b[4+i]
- }
- e.Address = net.IP{addr[0], addr[1], addr[2], addr[3], addr[4],
- addr[5], addr[6], addr[7], addr[8], addr[9], addr[10],
- addr[11], addr[12], addr[13], addr[14], addr[15]}
- }
- return nil
-}
-
-func (e *EDNS0_SUBNET) String() (s string) {
- if e.Address == nil {
- s = ""
- } else if e.Address.To4() != nil {
- s = e.Address.String()
- } else {
- s = "[" + e.Address.String() + "]"
- }
- s += "/" + strconv.Itoa(int(e.SourceNetmask)) + "/" + strconv.Itoa(int(e.SourceScope))
- return
-}
-
-// The UL (Update Lease) EDNS0 (draft RFC) option is used to tell the server to set
-// an expiration on an update RR. This is helpful for clients that cannot clean
-// up after themselves. This is a draft RFC and more information can be found at
-// http://files.dns-sd.org/draft-sekar-dns-ul.txt
-//
-// o := new(dns.OPT)
-// o.Hdr.Name = "."
-// o.Hdr.Rrtype = dns.TypeOPT
-// e := new(dns.EDNS0_UL)
-// e.Code = dns.EDNS0UL
-// e.Lease = 120 // in seconds
-// o.Option = append(o.Option, e)
-type EDNS0_UL struct {
- Code uint16 // Always EDNS0UL
- Lease uint32
-}
-
-func (e *EDNS0_UL) Option() uint16 { return EDNS0UL }
-func (e *EDNS0_UL) String() string { return strconv.FormatUint(uint64(e.Lease), 10) }
-
-// Copied: http://golang.org/src/pkg/net/dnsmsg.go
-func (e *EDNS0_UL) pack() ([]byte, error) {
- b := make([]byte, 4)
- b[0] = byte(e.Lease >> 24)
- b[1] = byte(e.Lease >> 16)
- b[2] = byte(e.Lease >> 8)
- b[3] = byte(e.Lease)
- return b, nil
-}
-
-func (e *EDNS0_UL) unpack(b []byte) error {
- if len(b) < 4 {
- return ErrBuf
- }
- e.Lease = uint32(b[0])<<24 | uint32(b[1])<<16 | uint32(b[2])<<8 | uint32(b[3])
- return nil
-}
-
-// Long Lived Queries: http://tools.ietf.org/html/draft-sekar-dns-llq-01
-// Implemented for completeness, as the EDNS0 type code is assigned.
-type EDNS0_LLQ struct {
- Code uint16 // Always EDNS0LLQ
- Version uint16
- Opcode uint16
- Error uint16
- Id uint64
- LeaseLife uint32
-}
-
-func (e *EDNS0_LLQ) Option() uint16 { return EDNS0LLQ }
-
-func (e *EDNS0_LLQ) pack() ([]byte, error) {
- b := make([]byte, 18)
- b[0], b[1] = packUint16(e.Version)
- b[2], b[3] = packUint16(e.Opcode)
- b[4], b[5] = packUint16(e.Error)
- b[6] = byte(e.Id >> 56)
- b[7] = byte(e.Id >> 48)
- b[8] = byte(e.Id >> 40)
- b[9] = byte(e.Id >> 32)
- b[10] = byte(e.Id >> 24)
- b[11] = byte(e.Id >> 16)
- b[12] = byte(e.Id >> 8)
- b[13] = byte(e.Id)
- b[14] = byte(e.LeaseLife >> 24)
- b[15] = byte(e.LeaseLife >> 16)
- b[16] = byte(e.LeaseLife >> 8)
- b[17] = byte(e.LeaseLife)
- return b, nil
-}
-
-func (e *EDNS0_LLQ) unpack(b []byte) error {
- if len(b) < 18 {
- return ErrBuf
- }
- e.Version, _ = unpackUint16(b, 0)
- e.Opcode, _ = unpackUint16(b, 2)
- e.Error, _ = unpackUint16(b, 4)
- e.Id = uint64(b[6])<<56 | uint64(b[6+1])<<48 | uint64(b[6+2])<<40 |
- uint64(b[6+3])<<32 | uint64(b[6+4])<<24 | uint64(b[6+5])<<16 | uint64(b[6+6])<<8 | uint64(b[6+7])
- e.LeaseLife = uint32(b[14])<<24 | uint32(b[14+1])<<16 | uint32(b[14+2])<<8 | uint32(b[14+3])
- return nil
-}
-
-func (e *EDNS0_LLQ) String() string {
- s := strconv.FormatUint(uint64(e.Version), 10) + " " + strconv.FormatUint(uint64(e.Opcode), 10) +
- " " + strconv.FormatUint(uint64(e.Error), 10) + " " + strconv.FormatUint(uint64(e.Id), 10) +
- " " + strconv.FormatUint(uint64(e.LeaseLife), 10)
- return s
-}
-
-type EDNS0_DAU struct {
- Code uint16 // Always EDNS0DAU
- AlgCode []uint8
-}
-
-func (e *EDNS0_DAU) Option() uint16 { return EDNS0DAU }
-func (e *EDNS0_DAU) pack() ([]byte, error) { return e.AlgCode, nil }
-func (e *EDNS0_DAU) unpack(b []byte) error { e.AlgCode = b; return nil }
-
-func (e *EDNS0_DAU) String() string {
- s := ""
- for i := 0; i < len(e.AlgCode); i++ {
- if a, ok := AlgorithmToString[e.AlgCode[i]]; ok {
- s += " " + a
- } else {
- s += " " + strconv.Itoa(int(e.AlgCode[i]))
- }
- }
- return s
-}
-
-type EDNS0_DHU struct {
- Code uint16 // Always EDNS0DHU
- AlgCode []uint8
-}
-
-func (e *EDNS0_DHU) Option() uint16 { return EDNS0DHU }
-func (e *EDNS0_DHU) pack() ([]byte, error) { return e.AlgCode, nil }
-func (e *EDNS0_DHU) unpack(b []byte) error { e.AlgCode = b; return nil }
-
-func (e *EDNS0_DHU) String() string {
- s := ""
- for i := 0; i < len(e.AlgCode); i++ {
- if a, ok := HashToString[e.AlgCode[i]]; ok {
- s += " " + a
- } else {
- s += " " + strconv.Itoa(int(e.AlgCode[i]))
- }
- }
- return s
-}
-
-type EDNS0_N3U struct {
- Code uint16 // Always EDNS0N3U
- AlgCode []uint8
-}
-
-func (e *EDNS0_N3U) Option() uint16 { return EDNS0N3U }
-func (e *EDNS0_N3U) pack() ([]byte, error) { return e.AlgCode, nil }
-func (e *EDNS0_N3U) unpack(b []byte) error { e.AlgCode = b; return nil }
-
-func (e *EDNS0_N3U) String() string {
- // Re-use the hash map
- s := ""
- for i := 0; i < len(e.AlgCode); i++ {
- if a, ok := HashToString[e.AlgCode[i]]; ok {
- s += " " + a
- } else {
- s += " " + strconv.Itoa(int(e.AlgCode[i]))
- }
- }
- return s
-}
-
-type EDNS0_EXPIRE struct {
- Code uint16 // Always EDNS0EXPIRE
- Expire uint32
-}
-
-func (e *EDNS0_EXPIRE) Option() uint16 { return EDNS0EXPIRE }
-func (e *EDNS0_EXPIRE) String() string { return strconv.FormatUint(uint64(e.Expire), 10) }
-
-func (e *EDNS0_EXPIRE) pack() ([]byte, error) {
- b := make([]byte, 4)
- b[0] = byte(e.Expire >> 24)
- b[1] = byte(e.Expire >> 16)
- b[2] = byte(e.Expire >> 8)
- b[3] = byte(e.Expire)
- return b, nil
-}
-
-func (e *EDNS0_EXPIRE) unpack(b []byte) error {
- if len(b) < 4 {
- return ErrBuf
- }
- e.Expire = uint32(b[0])<<24 | uint32(b[1])<<16 | uint32(b[2])<<8 | uint32(b[3])
- return nil
-}
-
-// The local EDNS0 option is used for local/experimental purposes. The option
-// code is recommended to be within the range [EDNS0LOCALSTART, EDNS0LOCALEND]
-// (RFC6891), although any unassigned code can actually be used. The content of
-// the option is made available in Data, unaltered.
-// Basic use pattern for creating a local option:
-//
-// o := new(dns.OPT)
-// o.Hdr.Name = "."
-// o.Hdr.Rrtype = dns.TypeOPT
-// e := new(dns.EDNS0_LOCAL)
-// e.Code = dns.EDNS0LOCALSTART
-// e.Data = []byte{72, 82, 74}
-// o.Option = append(o.Option, e)
-type EDNS0_LOCAL struct {
- Code uint16
- Data []byte
-}
-
-func (e *EDNS0_LOCAL) Option() uint16 { return e.Code }
-func (e *EDNS0_LOCAL) String() string {
- return strconv.FormatInt(int64(e.Code), 10) + ":0x" + hex.EncodeToString(e.Data)
-}
-
-func (e *EDNS0_LOCAL) pack() ([]byte, error) {
- b := make([]byte, len(e.Data))
- copied := copy(b, e.Data)
- if copied != len(e.Data) {
- return nil, ErrBuf
- }
- return b, nil
-}
-
-func (e *EDNS0_LOCAL) unpack(b []byte) error {
- e.Data = make([]byte, len(b))
- copied := copy(e.Data, b)
- if copied != len(b) {
- return ErrBuf
- }
- return nil
-}
diff --git a/Godeps/_workspace/src/github.com/miekg/dns/edns_test.go b/Godeps/_workspace/src/github.com/miekg/dns/edns_test.go
deleted file mode 100644
index 8ee82ab426..0000000000
--- a/Godeps/_workspace/src/github.com/miekg/dns/edns_test.go
+++ /dev/null
@@ -1,48 +0,0 @@
-package dns
-
-import "testing"
-
-func TestOPTTtl(t *testing.T) {
- e := &OPT{}
- e.Hdr.Name = "."
- e.Hdr.Rrtype = TypeOPT
-
- if e.Do() {
- t.Fail()
- }
-
- e.SetDo()
- if !e.Do() {
- t.Fail()
- }
-
- oldTtl := e.Hdr.Ttl
-
- if e.Version() != 0 {
- t.Fail()
- }
-
- e.SetVersion(42)
- if e.Version() != 42 {
- t.Fail()
- }
-
- e.SetVersion(0)
- if e.Hdr.Ttl != oldTtl {
- t.Fail()
- }
-
- if e.ExtendedRcode() != 0 {
- t.Fail()
- }
-
- e.SetExtendedRcode(42)
- if e.ExtendedRcode() != 42 {
- t.Fail()
- }
-
- e.SetExtendedRcode(0)
- if e.Hdr.Ttl != oldTtl {
- t.Fail()
- }
-}
diff --git a/Godeps/_workspace/src/github.com/miekg/dns/example_test.go b/Godeps/_workspace/src/github.com/miekg/dns/example_test.go
deleted file mode 100644
index 1578a4d053..0000000000
--- a/Godeps/_workspace/src/github.com/miekg/dns/example_test.go
+++ /dev/null
@@ -1,147 +0,0 @@
-package dns_test
-
-import (
- "errors"
- "fmt"
- "github.com/miekg/dns"
- "log"
- "net"
-)
-
-// Retrieve the MX records for miek.nl.
-func ExampleMX() {
- config, _ := dns.ClientConfigFromFile("/etc/resolv.conf")
- c := new(dns.Client)
- m := new(dns.Msg)
- m.SetQuestion("miek.nl.", dns.TypeMX)
- m.RecursionDesired = true
- r, _, err := c.Exchange(m, config.Servers[0]+":"+config.Port)
- if err != nil {
- return
- }
- if r.Rcode != dns.RcodeSuccess {
- return
- }
- for _, a := range r.Answer {
- if mx, ok := a.(*dns.MX); ok {
- fmt.Printf("%s\n", mx.String())
- }
- }
-}
-
-// Retrieve the DNSKEY records of a zone and convert them
-// to DS records for SHA1, SHA256 and SHA384.
-func ExampleDS(zone string) {
- config, _ := dns.ClientConfigFromFile("/etc/resolv.conf")
- c := new(dns.Client)
- m := new(dns.Msg)
- if zone == "" {
- zone = "miek.nl"
- }
- m.SetQuestion(dns.Fqdn(zone), dns.TypeDNSKEY)
- m.SetEdns0(4096, true)
- r, _, err := c.Exchange(m, config.Servers[0]+":"+config.Port)
- if err != nil {
- return
- }
- if r.Rcode != dns.RcodeSuccess {
- return
- }
- for _, k := range r.Answer {
- if key, ok := k.(*dns.DNSKEY); ok {
- for _, alg := range []uint8{dns.SHA1, dns.SHA256, dns.SHA384} {
- fmt.Printf("%s; %d\n", key.ToDS(alg).String(), key.Flags)
- }
- }
- }
-}
-
-const TypeAPAIR = 0x0F99
-
-type APAIR struct {
- addr [2]net.IP
-}
-
-func NewAPAIR() dns.PrivateRdata { return new(APAIR) }
-
-func (rd *APAIR) String() string { return rd.addr[0].String() + " " + rd.addr[1].String() }
-func (rd *APAIR) Parse(txt []string) error {
- if len(txt) != 2 {
- return errors.New("two addresses required for APAIR")
- }
- for i, s := range txt {
- ip := net.ParseIP(s)
- if ip == nil {
- return errors.New("invalid IP in APAIR text representation")
- }
- rd.addr[i] = ip
- }
- return nil
-}
-
-func (rd *APAIR) Pack(buf []byte) (int, error) {
- b := append([]byte(rd.addr[0]), []byte(rd.addr[1])...)
- n := copy(buf, b)
- if n != len(b) {
- return n, dns.ErrBuf
- }
- return n, nil
-}
-
-func (rd *APAIR) Unpack(buf []byte) (int, error) {
- ln := net.IPv4len * 2
- if len(buf) != ln {
- return 0, errors.New("invalid length of APAIR rdata")
- }
- cp := make([]byte, ln)
- copy(cp, buf) // clone bytes to use them in IPs
-
- rd.addr[0] = net.IP(cp[:3])
- rd.addr[1] = net.IP(cp[4:])
-
- return len(buf), nil
-}
-
-func (rd *APAIR) Copy(dest dns.PrivateRdata) error {
- cp := make([]byte, rd.Len())
- _, err := rd.Pack(cp)
- if err != nil {
- return err
- }
-
- d := dest.(*APAIR)
- d.addr[0] = net.IP(cp[:3])
- d.addr[1] = net.IP(cp[4:])
- return nil
-}
-
-func (rd *APAIR) Len() int {
- return net.IPv4len * 2
-}
-
-func ExamplePrivateHandle() {
- dns.PrivateHandle("APAIR", TypeAPAIR, NewAPAIR)
- defer dns.PrivateHandleRemove(TypeAPAIR)
-
- rr, err := dns.NewRR("miek.nl. APAIR (1.2.3.4 1.2.3.5)")
- if err != nil {
- log.Fatal("could not parse APAIR record: ", err)
- }
- fmt.Println(rr)
- // Output: miek.nl. 3600 IN APAIR 1.2.3.4 1.2.3.5
-
- m := new(dns.Msg)
- m.Id = 12345
- m.SetQuestion("miek.nl.", TypeAPAIR)
- m.Answer = append(m.Answer, rr)
-
- fmt.Println(m)
- // ;; opcode: QUERY, status: NOERROR, id: 12345
- // ;; flags: rd; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 0
- //
- // ;; QUESTION SECTION:
- // ;miek.nl. IN APAIR
- //
- // ;; ANSWER SECTION:
- // miek.nl. 3600 IN APAIR 1.2.3.4 1.2.3.5
-}
diff --git a/Godeps/_workspace/src/github.com/miekg/dns/format.go b/Godeps/_workspace/src/github.com/miekg/dns/format.go
deleted file mode 100644
index 1ac1664fe2..0000000000
--- a/Godeps/_workspace/src/github.com/miekg/dns/format.go
+++ /dev/null
@@ -1,96 +0,0 @@
-package dns
-
-import (
- "net"
- "reflect"
- "strconv"
-)
-
-// NumField returns the number of rdata fields r has.
-func NumField(r RR) int {
- return reflect.ValueOf(r).Elem().NumField() - 1 // Remove RR_Header
-}
-
-// Field returns the rdata field i as a string. Fields are indexed starting from 1.
-// RR types that holds slice data, for instance the NSEC type bitmap will return a single
-// string where the types are concatenated using a space.
-// Accessing non existing fields will cause a panic.
-func Field(r RR, i int) string {
- if i == 0 {
- return ""
- }
- d := reflect.ValueOf(r).Elem().Field(i)
- switch k := d.Kind(); k {
- case reflect.String:
- return d.String()
- case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
- return strconv.FormatInt(d.Int(), 10)
- case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
- return strconv.FormatUint(d.Uint(), 10)
- case reflect.Slice:
- switch reflect.ValueOf(r).Elem().Type().Field(i).Tag {
- case `dns:"a"`:
- // TODO(miek): Hmm store this as 16 bytes
- if d.Len() < net.IPv6len {
- return net.IPv4(byte(d.Index(0).Uint()),
- byte(d.Index(1).Uint()),
- byte(d.Index(2).Uint()),
- byte(d.Index(3).Uint())).String()
- }
- return net.IPv4(byte(d.Index(12).Uint()),
- byte(d.Index(13).Uint()),
- byte(d.Index(14).Uint()),
- byte(d.Index(15).Uint())).String()
- case `dns:"aaaa"`:
- return net.IP{
- byte(d.Index(0).Uint()),
- byte(d.Index(1).Uint()),
- byte(d.Index(2).Uint()),
- byte(d.Index(3).Uint()),
- byte(d.Index(4).Uint()),
- byte(d.Index(5).Uint()),
- byte(d.Index(6).Uint()),
- byte(d.Index(7).Uint()),
- byte(d.Index(8).Uint()),
- byte(d.Index(9).Uint()),
- byte(d.Index(10).Uint()),
- byte(d.Index(11).Uint()),
- byte(d.Index(12).Uint()),
- byte(d.Index(13).Uint()),
- byte(d.Index(14).Uint()),
- byte(d.Index(15).Uint()),
- }.String()
- case `dns:"nsec"`:
- if d.Len() == 0 {
- return ""
- }
- s := Type(d.Index(0).Uint()).String()
- for i := 1; i < d.Len(); i++ {
- s += " " + Type(d.Index(i).Uint()).String()
- }
- return s
- case `dns:"wks"`:
- if d.Len() == 0 {
- return ""
- }
- s := strconv.Itoa(int(d.Index(0).Uint()))
- for i := 0; i < d.Len(); i++ {
- s += " " + strconv.Itoa(int(d.Index(i).Uint()))
- }
- return s
- default:
- // if it does not have a tag its a string slice
- fallthrough
- case `dns:"txt"`:
- if d.Len() == 0 {
- return ""
- }
- s := d.Index(0).String()
- for i := 1; i < d.Len(); i++ {
- s += " " + d.Index(i).String()
- }
- return s
- }
- }
- return ""
-}
diff --git a/Godeps/_workspace/src/github.com/miekg/dns/idn/code_points.go b/Godeps/_workspace/src/github.com/miekg/dns/idn/code_points.go
deleted file mode 100644
index 129c3742f5..0000000000
--- a/Godeps/_workspace/src/github.com/miekg/dns/idn/code_points.go
+++ /dev/null
@@ -1,2346 +0,0 @@
-package idn
-
-const (
- propertyUnknown property = iota // unknown character property
- propertyPVALID // allowed to be used in IDNs
- propertyCONTEXTJ // invisible or problematic characters (join controls)
- propertyCONTEXTO // invisible or problematic characters (others)
- propertyDISALLOWED // should not be included in IDNs
- propertyUNASSIGNED // code points that are not designated in the Unicode Standard
-)
-
-// property stores the property of a code point, as described in RFC 5892,
-// section 1
-type property int
-
-// codePoints list all code points in Unicode Character Database (UCD) Format
-// according to RFC 5892, appendix B.1. Thanks to libidn2 (GNU) -
-// http://www.gnu.org/software/libidn/libidn2/
-var codePoints = []struct {
- start rune
- end rune
- state property
-}{
- {0x0000, 0x002C, propertyDISALLOWED}, // ..COMMA
- {0x002D, 0x0, propertyPVALID}, // HYPHEN-MINUS
- {0x002E, 0x002F, propertyDISALLOWED}, // FULL STOP..SOLIDUS
- {0x0030, 0x0039, propertyPVALID}, // DIGIT ZERO..DIGIT NINE
- {0x003A, 0x0060, propertyDISALLOWED}, // COLON..GRAVE ACCENT
- {0x0041, 0x005A, propertyPVALID}, // LATIN CAPITAL LETTER A..LATIN CAPITAL LETTER Z
- {0x0061, 0x007A, propertyPVALID}, // LATIN SMALL LETTER A..LATIN SMALL LETTER Z
- {0x007B, 0x00B6, propertyDISALLOWED}, // LEFT CURLY BRACKET..PILCROW SIGN
- {0x00B7, 0x0, propertyCONTEXTO}, // MIDDLE DOT
- {0x00B8, 0x00DE, propertyDISALLOWED}, // CEDILLA..LATIN CAPITAL LETTER THORN
- {0x00DF, 0x00F6, propertyPVALID}, // LATIN SMALL LETTER SHARP S..LATIN SMALL LETT
- {0x00F7, 0x0, propertyDISALLOWED}, // DIVISION SIGN
- {0x00F8, 0x00FF, propertyPVALID}, // LATIN SMALL LETTER O WITH STROKE..LATIN SMAL
- {0x0100, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER A WITH MACRON
- {0x0101, 0x0, propertyPVALID}, // LATIN SMALL LETTER A WITH MACRON
- {0x0102, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER A WITH BREVE
- {0x0103, 0x0, propertyPVALID}, // LATIN SMALL LETTER A WITH BREVE
- {0x0104, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER A WITH OGONEK
- {0x0105, 0x0, propertyPVALID}, // LATIN SMALL LETTER A WITH OGONEK
- {0x0106, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER C WITH ACUTE
- {0x0107, 0x0, propertyPVALID}, // LATIN SMALL LETTER C WITH ACUTE
- {0x0108, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER C WITH CIRCUMFLEX
- {0x0109, 0x0, propertyPVALID}, // LATIN SMALL LETTER C WITH CIRCUMFLEX
- {0x010A, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER C WITH DOT ABOVE
- {0x010B, 0x0, propertyPVALID}, // LATIN SMALL LETTER C WITH DOT ABOVE
- {0x010C, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER C WITH CARON
- {0x010D, 0x0, propertyPVALID}, // LATIN SMALL LETTER C WITH CARON
- {0x010E, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER D WITH CARON
- {0x010F, 0x0, propertyPVALID}, // LATIN SMALL LETTER D WITH CARON
- {0x0110, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER D WITH STROKE
- {0x0111, 0x0, propertyPVALID}, // LATIN SMALL LETTER D WITH STROKE
- {0x0112, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER E WITH MACRON
- {0x0113, 0x0, propertyPVALID}, // LATIN SMALL LETTER E WITH MACRON
- {0x0114, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER E WITH BREVE
- {0x0115, 0x0, propertyPVALID}, // LATIN SMALL LETTER E WITH BREVE
- {0x0116, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER E WITH DOT ABOVE
- {0x0117, 0x0, propertyPVALID}, // LATIN SMALL LETTER E WITH DOT ABOVE
- {0x0118, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER E WITH OGONEK
- {0x0119, 0x0, propertyPVALID}, // LATIN SMALL LETTER E WITH OGONEK
- {0x011A, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER E WITH CARON
- {0x011B, 0x0, propertyPVALID}, // LATIN SMALL LETTER E WITH CARON
- {0x011C, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER G WITH CIRCUMFLEX
- {0x011D, 0x0, propertyPVALID}, // LATIN SMALL LETTER G WITH CIRCUMFLEX
- {0x011E, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER G WITH BREVE
- {0x011F, 0x0, propertyPVALID}, // LATIN SMALL LETTER G WITH BREVE
- {0x0120, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER G WITH DOT ABOVE
- {0x0121, 0x0, propertyPVALID}, // LATIN SMALL LETTER G WITH DOT ABOVE
- {0x0122, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER G WITH CEDILLA
- {0x0123, 0x0, propertyPVALID}, // LATIN SMALL LETTER G WITH CEDILLA
- {0x0124, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER H WITH CIRCUMFLEX
- {0x0125, 0x0, propertyPVALID}, // LATIN SMALL LETTER H WITH CIRCUMFLEX
- {0x0126, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER H WITH STROKE
- {0x0127, 0x0, propertyPVALID}, // LATIN SMALL LETTER H WITH STROKE
- {0x0128, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER I WITH TILDE
- {0x0129, 0x0, propertyPVALID}, // LATIN SMALL LETTER I WITH TILDE
- {0x012A, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER I WITH MACRON
- {0x012B, 0x0, propertyPVALID}, // LATIN SMALL LETTER I WITH MACRON
- {0x012C, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER I WITH BREVE
- {0x012D, 0x0, propertyPVALID}, // LATIN SMALL LETTER I WITH BREVE
- {0x012E, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER I WITH OGONEK
- {0x012F, 0x0, propertyPVALID}, // LATIN SMALL LETTER I WITH OGONEK
- {0x0130, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER I WITH DOT ABOVE
- {0x0131, 0x0, propertyPVALID}, // LATIN SMALL LETTER DOTLESS I
- {0x0132, 0x0134, propertyDISALLOWED}, // LATIN CAPITAL LIGATURE IJ..LATIN CAPITAL LET
- {0x0135, 0x0, propertyPVALID}, // LATIN SMALL LETTER J WITH CIRCUMFLEX
- {0x0136, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER K WITH CEDILLA
- {0x0137, 0x0138, propertyPVALID}, // LATIN SMALL LETTER K WITH CEDILLA..LATIN SMA
- {0x0139, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER L WITH ACUTE
- {0x013A, 0x0, propertyPVALID}, // LATIN SMALL LETTER L WITH ACUTE
- {0x013B, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER L WITH CEDILLA
- {0x013C, 0x0, propertyPVALID}, // LATIN SMALL LETTER L WITH CEDILLA
- {0x013D, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER L WITH CARON
- {0x013E, 0x0, propertyPVALID}, // LATIN SMALL LETTER L WITH CARON
- {0x013F, 0x0141, propertyDISALLOWED}, // LATIN CAPITAL LETTER L WITH MIDDLE DOT..LATI
- {0x0142, 0x0, propertyPVALID}, // LATIN SMALL LETTER L WITH STROKE
- {0x0143, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER N WITH ACUTE
- {0x0144, 0x0, propertyPVALID}, // LATIN SMALL LETTER N WITH ACUTE
- {0x0145, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER N WITH CEDILLA
- {0x0146, 0x0, propertyPVALID}, // LATIN SMALL LETTER N WITH CEDILLA
- {0x0147, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER N WITH CARON
- {0x0148, 0x0, propertyPVALID}, // LATIN SMALL LETTER N WITH CARON
- {0x0149, 0x014A, propertyDISALLOWED}, // LATIN SMALL LETTER N PRECEDED BY APOSTROPHE.
- {0x014B, 0x0, propertyPVALID}, // LATIN SMALL LETTER ENG
- {0x014C, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER O WITH MACRON
- {0x014D, 0x0, propertyPVALID}, // LATIN SMALL LETTER O WITH MACRON
- {0x014E, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER O WITH BREVE
- {0x014F, 0x0, propertyPVALID}, // LATIN SMALL LETTER O WITH BREVE
- {0x0150, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER O WITH DOUBLE ACUTE
- {0x0151, 0x0, propertyPVALID}, // LATIN SMALL LETTER O WITH DOUBLE ACUTE
- {0x0152, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LIGATURE OE
- {0x0153, 0x0, propertyPVALID}, // LATIN SMALL LIGATURE OE
- {0x0154, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER R WITH ACUTE
- {0x0155, 0x0, propertyPVALID}, // LATIN SMALL LETTER R WITH ACUTE
- {0x0156, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER R WITH CEDILLA
- {0x0157, 0x0, propertyPVALID}, // LATIN SMALL LETTER R WITH CEDILLA
- {0x0158, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER R WITH CARON
- {0x0159, 0x0, propertyPVALID}, // LATIN SMALL LETTER R WITH CARON
- {0x015A, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER S WITH ACUTE
- {0x015B, 0x0, propertyPVALID}, // LATIN SMALL LETTER S WITH ACUTE
- {0x015C, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER S WITH CIRCUMFLEX
- {0x015D, 0x0, propertyPVALID}, // LATIN SMALL LETTER S WITH CIRCUMFLEX
- {0x015E, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER S WITH CEDILLA
- {0x015F, 0x0, propertyPVALID}, // LATIN SMALL LETTER S WITH CEDILLA
- {0x0160, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER S WITH CARON
- {0x0161, 0x0, propertyPVALID}, // LATIN SMALL LETTER S WITH CARON
- {0x0162, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER T WITH CEDILLA
- {0x0163, 0x0, propertyPVALID}, // LATIN SMALL LETTER T WITH CEDILLA
- {0x0164, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER T WITH CARON
- {0x0165, 0x0, propertyPVALID}, // LATIN SMALL LETTER T WITH CARON
- {0x0166, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER T WITH STROKE
- {0x0167, 0x0, propertyPVALID}, // LATIN SMALL LETTER T WITH STROKE
- {0x0168, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER U WITH TILDE
- {0x0169, 0x0, propertyPVALID}, // LATIN SMALL LETTER U WITH TILDE
- {0x016A, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER U WITH MACRON
- {0x016B, 0x0, propertyPVALID}, // LATIN SMALL LETTER U WITH MACRON
- {0x016C, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER U WITH BREVE
- {0x016D, 0x0, propertyPVALID}, // LATIN SMALL LETTER U WITH BREVE
- {0x016E, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER U WITH RING ABOVE
- {0x016F, 0x0, propertyPVALID}, // LATIN SMALL LETTER U WITH RING ABOVE
- {0x0170, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER U WITH DOUBLE ACUTE
- {0x0171, 0x0, propertyPVALID}, // LATIN SMALL LETTER U WITH DOUBLE ACUTE
- {0x0172, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER U WITH OGONEK
- {0x0173, 0x0, propertyPVALID}, // LATIN SMALL LETTER U WITH OGONEK
- {0x0174, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER W WITH CIRCUMFLEX
- {0x0175, 0x0, propertyPVALID}, // LATIN SMALL LETTER W WITH CIRCUMFLEX
- {0x0176, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER Y WITH CIRCUMFLEX
- {0x0177, 0x0, propertyPVALID}, // LATIN SMALL LETTER Y WITH CIRCUMFLEX
- {0x0178, 0x0179, propertyDISALLOWED}, // LATIN CAPITAL LETTER Y WITH DIAERESIS..LATIN
- {0x017A, 0x0, propertyPVALID}, // LATIN SMALL LETTER Z WITH ACUTE
- {0x017B, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER Z WITH DOT ABOVE
- {0x017C, 0x0, propertyPVALID}, // LATIN SMALL LETTER Z WITH DOT ABOVE
- {0x017D, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER Z WITH CARON
- {0x017E, 0x0, propertyPVALID}, // LATIN SMALL LETTER Z WITH CARON
- {0x017F, 0x0, propertyDISALLOWED}, // LATIN SMALL LETTER LONG S
- {0x0180, 0x0, propertyPVALID}, // LATIN SMALL LETTER B WITH STROKE
- {0x0181, 0x0182, propertyDISALLOWED}, // LATIN CAPITAL LETTER B WITH HOOK..LATIN CAPI
- {0x0183, 0x0, propertyPVALID}, // LATIN SMALL LETTER B WITH TOPBAR
- {0x0184, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER TONE SIX
- {0x0185, 0x0, propertyPVALID}, // LATIN SMALL LETTER TONE SIX
- {0x0186, 0x0187, propertyDISALLOWED}, // LATIN CAPITAL LETTER OPEN O..LATIN CAPITAL L
- {0x0188, 0x0, propertyPVALID}, // LATIN SMALL LETTER C WITH HOOK
- {0x0189, 0x018B, propertyDISALLOWED}, // LATIN CAPITAL LETTER AFRICAN D..LATIN CAPITA
- {0x018C, 0x018D, propertyPVALID}, // LATIN SMALL LETTER D WITH TOPBAR..LATIN SMAL
- {0x018E, 0x0191, propertyDISALLOWED}, // LATIN CAPITAL LETTER REVERSED E..LATIN CAPIT
- {0x0192, 0x0, propertyPVALID}, // LATIN SMALL LETTER F WITH HOOK
- {0x0193, 0x0194, propertyDISALLOWED}, // LATIN CAPITAL LETTER G WITH HOOK..LATIN CAPI
- {0x0195, 0x0, propertyPVALID}, // LATIN SMALL LETTER HV
- {0x0196, 0x0198, propertyDISALLOWED}, // LATIN CAPITAL LETTER IOTA..LATIN CAPITAL LET
- {0x0199, 0x019B, propertyPVALID}, // LATIN SMALL LETTER K WITH HOOK..LATIN SMALL
- {0x019C, 0x019D, propertyDISALLOWED}, // LATIN CAPITAL LETTER TURNED M..LATIN CAPITAL
- {0x019E, 0x0, propertyPVALID}, // LATIN SMALL LETTER N WITH LONG RIGHT LEG
- {0x019F, 0x01A0, propertyDISALLOWED}, // LATIN CAPITAL LETTER O WITH MIDDLE TILDE..LA
- {0x01A1, 0x0, propertyPVALID}, // LATIN SMALL LETTER O WITH HORN
- {0x01A2, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER OI
- {0x01A3, 0x0, propertyPVALID}, // LATIN SMALL LETTER OI
- {0x01A4, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER P WITH HOOK
- {0x01A5, 0x0, propertyPVALID}, // LATIN SMALL LETTER P WITH HOOK
- {0x01A6, 0x01A7, propertyDISALLOWED}, // LATIN LETTER YR..LATIN CAPITAL LETTER TONE T
- {0x01A8, 0x0, propertyPVALID}, // LATIN SMALL LETTER TONE TWO
- {0x01A9, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER ESH
- {0x01AA, 0x01AB, propertyPVALID}, // LATIN LETTER REVERSED ESH LOOP..LATIN SMALL
- {0x01AC, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER T WITH HOOK
- {0x01AD, 0x0, propertyPVALID}, // LATIN SMALL LETTER T WITH HOOK
- {0x01AE, 0x01AF, propertyDISALLOWED}, // LATIN CAPITAL LETTER T WITH RETROFLEX HOOK..
- {0x01B0, 0x0, propertyPVALID}, // LATIN SMALL LETTER U WITH HORN
- {0x01B1, 0x01B3, propertyDISALLOWED}, // LATIN CAPITAL LETTER UPSILON..LATIN CAPITAL
- {0x01B4, 0x0, propertyPVALID}, // LATIN SMALL LETTER Y WITH HOOK
- {0x01B5, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER Z WITH STROKE
- {0x01B6, 0x0, propertyPVALID}, // LATIN SMALL LETTER Z WITH STROKE
- {0x01B7, 0x01B8, propertyDISALLOWED}, // LATIN CAPITAL LETTER EZH..LATIN CAPITAL LETT
- {0x01B9, 0x01BB, propertyPVALID}, // LATIN SMALL LETTER EZH REVERSED..LATIN LETTE
- {0x01BC, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER TONE FIVE
- {0x01BD, 0x01C3, propertyPVALID}, // LATIN SMALL LETTER TONE FIVE..LATIN LETTER R
- {0x01C4, 0x01CD, propertyDISALLOWED}, // LATIN CAPITAL LETTER DZ WITH CARON..LATIN CA
- {0x01CE, 0x0, propertyPVALID}, // LATIN SMALL LETTER A WITH CARON
- {0x01CF, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER I WITH CARON
- {0x01D0, 0x0, propertyPVALID}, // LATIN SMALL LETTER I WITH CARON
- {0x01D1, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER O WITH CARON
- {0x01D2, 0x0, propertyPVALID}, // LATIN SMALL LETTER O WITH CARON
- {0x01D3, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER U WITH CARON
- {0x01D4, 0x0, propertyPVALID}, // LATIN SMALL LETTER U WITH CARON
- {0x01D5, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER U WITH DIAERESIS AND MA
- {0x01D6, 0x0, propertyPVALID}, // LATIN SMALL LETTER U WITH DIAERESIS AND MACR
- {0x01D7, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER U WITH DIAERESIS AND AC
- {0x01D8, 0x0, propertyPVALID}, // LATIN SMALL LETTER U WITH DIAERESIS AND ACUT
- {0x01D9, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER U WITH DIAERESIS AND CA
- {0x01DA, 0x0, propertyPVALID}, // LATIN SMALL LETTER U WITH DIAERESIS AND CARO
- {0x01DB, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER U WITH DIAERESIS AND GR
- {0x01DC, 0x01DD, propertyPVALID}, // LATIN SMALL LETTER U WITH DIAERESIS AND GRAV
- {0x01DE, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER A WITH DIAERESIS AND MA
- {0x01DF, 0x0, propertyPVALID}, // LATIN SMALL LETTER A WITH DIAERESIS AND MACR
- {0x01E0, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER A WITH DOT ABOVE AND MA
- {0x01E1, 0x0, propertyPVALID}, // LATIN SMALL LETTER A WITH DOT ABOVE AND MACR
- {0x01E2, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER AE WITH MACRON
- {0x01E3, 0x0, propertyPVALID}, // LATIN SMALL LETTER AE WITH MACRON
- {0x01E4, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER G WITH STROKE
- {0x01E5, 0x0, propertyPVALID}, // LATIN SMALL LETTER G WITH STROKE
- {0x01E6, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER G WITH CARON
- {0x01E7, 0x0, propertyPVALID}, // LATIN SMALL LETTER G WITH CARON
- {0x01E8, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER K WITH CARON
- {0x01E9, 0x0, propertyPVALID}, // LATIN SMALL LETTER K WITH CARON
- {0x01EA, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER O WITH OGONEK
- {0x01EB, 0x0, propertyPVALID}, // LATIN SMALL LETTER O WITH OGONEK
- {0x01EC, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER O WITH OGONEK AND MACRO
- {0x01ED, 0x0, propertyPVALID}, // LATIN SMALL LETTER O WITH OGONEK AND MACRON
- {0x01EE, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER EZH WITH CARON
- {0x01EF, 0x01F0, propertyPVALID}, // LATIN SMALL LETTER EZH WITH CARON..LATIN SMA
- {0x01F1, 0x01F4, propertyDISALLOWED}, // LATIN CAPITAL LETTER DZ..LATIN CAPITAL LETTE
- {0x01F5, 0x0, propertyPVALID}, // LATIN SMALL LETTER G WITH ACUTE
- {0x01F6, 0x01F8, propertyDISALLOWED}, // LATIN CAPITAL LETTER HWAIR..LATIN CAPITAL LE
- {0x01F9, 0x0, propertyPVALID}, // LATIN SMALL LETTER N WITH GRAVE
- {0x01FA, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER A WITH RING ABOVE AND A
- {0x01FB, 0x0, propertyPVALID}, // LATIN SMALL LETTER A WITH RING ABOVE AND ACU
- {0x01FC, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER AE WITH ACUTE
- {0x01FD, 0x0, propertyPVALID}, // LATIN SMALL LETTER AE WITH ACUTE
- {0x01FE, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER O WITH STROKE AND ACUTE
- {0x01FF, 0x0, propertyPVALID}, // LATIN SMALL LETTER O WITH STROKE AND ACUTE
- {0x0200, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER A WITH DOUBLE GRAVE
- {0x0201, 0x0, propertyPVALID}, // LATIN SMALL LETTER A WITH DOUBLE GRAVE
- {0x0202, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER A WITH INVERTED BREVE
- {0x0203, 0x0, propertyPVALID}, // LATIN SMALL LETTER A WITH INVERTED BREVE
- {0x0204, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER E WITH DOUBLE GRAVE
- {0x0205, 0x0, propertyPVALID}, // LATIN SMALL LETTER E WITH DOUBLE GRAVE
- {0x0206, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER E WITH INVERTED BREVE
- {0x0207, 0x0, propertyPVALID}, // LATIN SMALL LETTER E WITH INVERTED BREVE
- {0x0208, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER I WITH DOUBLE GRAVE
- {0x0209, 0x0, propertyPVALID}, // LATIN SMALL LETTER I WITH DOUBLE GRAVE
- {0x020A, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER I WITH INVERTED BREVE
- {0x020B, 0x0, propertyPVALID}, // LATIN SMALL LETTER I WITH INVERTED BREVE
- {0x020C, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER O WITH DOUBLE GRAVE
- {0x020D, 0x0, propertyPVALID}, // LATIN SMALL LETTER O WITH DOUBLE GRAVE
- {0x020E, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER O WITH INVERTED BREVE
- {0x020F, 0x0, propertyPVALID}, // LATIN SMALL LETTER O WITH INVERTED BREVE
- {0x0210, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER R WITH DOUBLE GRAVE
- {0x0211, 0x0, propertyPVALID}, // LATIN SMALL LETTER R WITH DOUBLE GRAVE
- {0x0212, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER R WITH INVERTED BREVE
- {0x0213, 0x0, propertyPVALID}, // LATIN SMALL LETTER R WITH INVERTED BREVE
- {0x0214, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER U WITH DOUBLE GRAVE
- {0x0215, 0x0, propertyPVALID}, // LATIN SMALL LETTER U WITH DOUBLE GRAVE
- {0x0216, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER U WITH INVERTED BREVE
- {0x0217, 0x0, propertyPVALID}, // LATIN SMALL LETTER U WITH INVERTED BREVE
- {0x0218, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER S WITH COMMA BELOW
- {0x0219, 0x0, propertyPVALID}, // LATIN SMALL LETTER S WITH COMMA BELOW
- {0x021A, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER T WITH COMMA BELOW
- {0x021B, 0x0, propertyPVALID}, // LATIN SMALL LETTER T WITH COMMA BELOW
- {0x021C, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER YOGH
- {0x021D, 0x0, propertyPVALID}, // LATIN SMALL LETTER YOGH
- {0x021E, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER H WITH CARON
- {0x021F, 0x0, propertyPVALID}, // LATIN SMALL LETTER H WITH CARON
- {0x0220, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER N WITH LONG RIGHT LEG
- {0x0221, 0x0, propertyPVALID}, // LATIN SMALL LETTER D WITH CURL
- {0x0222, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER OU
- {0x0223, 0x0, propertyPVALID}, // LATIN SMALL LETTER OU
- {0x0224, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER Z WITH HOOK
- {0x0225, 0x0, propertyPVALID}, // LATIN SMALL LETTER Z WITH HOOK
- {0x0226, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER A WITH DOT ABOVE
- {0x0227, 0x0, propertyPVALID}, // LATIN SMALL LETTER A WITH DOT ABOVE
- {0x0228, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER E WITH CEDILLA
- {0x0229, 0x0, propertyPVALID}, // LATIN SMALL LETTER E WITH CEDILLA
- {0x022A, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER O WITH DIAERESIS AND MA
- {0x022B, 0x0, propertyPVALID}, // LATIN SMALL LETTER O WITH DIAERESIS AND MACR
- {0x022C, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER O WITH TILDE AND MACRON
- {0x022D, 0x0, propertyPVALID}, // LATIN SMALL LETTER O WITH TILDE AND MACRON
- {0x022E, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER O WITH DOT ABOVE
- {0x022F, 0x0, propertyPVALID}, // LATIN SMALL LETTER O WITH DOT ABOVE
- {0x0230, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER O WITH DOT ABOVE AND MA
- {0x0231, 0x0, propertyPVALID}, // LATIN SMALL LETTER O WITH DOT ABOVE AND MACR
- {0x0232, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER Y WITH MACRON
- {0x0233, 0x0239, propertyPVALID}, // LATIN SMALL LETTER Y WITH MACRON..LATIN SMAL
- {0x023A, 0x023B, propertyDISALLOWED}, // LATIN CAPITAL LETTER A WITH STROKE..LATIN CA
- {0x023C, 0x0, propertyPVALID}, // LATIN SMALL LETTER C WITH STROKE
- {0x023D, 0x023E, propertyDISALLOWED}, // LATIN CAPITAL LETTER L WITH BAR..LATIN CAPIT
- {0x023F, 0x0240, propertyPVALID}, // LATIN SMALL LETTER S WITH SWASH TAIL..LATIN
- {0x0241, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER GLOTTAL STOP
- {0x0242, 0x0, propertyPVALID}, // LATIN SMALL LETTER GLOTTAL STOP
- {0x0243, 0x0246, propertyDISALLOWED}, // LATIN CAPITAL LETTER B WITH STROKE..LATIN CA
- {0x0247, 0x0, propertyPVALID}, // LATIN SMALL LETTER E WITH STROKE
- {0x0248, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER J WITH STROKE
- {0x0249, 0x0, propertyPVALID}, // LATIN SMALL LETTER J WITH STROKE
- {0x024A, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER SMALL Q WITH HOOK TAIL
- {0x024B, 0x0, propertyPVALID}, // LATIN SMALL LETTER Q WITH HOOK TAIL
- {0x024C, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER R WITH STROKE
- {0x024D, 0x0, propertyPVALID}, // LATIN SMALL LETTER R WITH STROKE
- {0x024E, 0x0, propertyDISALLOWED}, // LATIN CAPITAL LETTER Y WITH STROKE
- {0x024F, 0x02AF, propertyPVALID}, // LATIN SMALL LETTER Y WITH STROKE..LATIN SMAL
- {0x02B0, 0x02B8, propertyDISALLOWED}, // MODIFIER LETTER SMALL H..MODIFIER LETTER SMA
- {0x02B9, 0x02C1, propertyPVALID}, // MODIFIER LETTER PRIME..MODIFIER LETTER REVER
- {0x02C2, 0x02C5, propertyDISALLOWED}, // MODIFIER LETTER LEFT ARROWHEAD..MODIFIER LET
- {0x02C6, 0x02D1, propertyPVALID}, // MODIFIER LETTER CIRCUMFLEX ACCENT..MODIFIER
- {0x02D2, 0x02EB, propertyDISALLOWED}, // MODIFIER LETTER CENTRED RIGHT HALF RING..MOD
- {0x02EC, 0x0, propertyPVALID}, // MODIFIER LETTER VOICING
- {0x02ED, 0x0, propertyDISALLOWED}, // MODIFIER LETTER UNASPIRATED
- {0x02EE, 0x0, propertyPVALID}, // MODIFIER LETTER DOUBLE APOSTROPHE
- {0x02EF, 0x02FF, propertyDISALLOWED}, // MODIFIER LETTER LOW DOWN ARROWHEAD..MODIFIER
- {0x0300, 0x033F, propertyPVALID}, // COMBINING GRAVE ACCENT..COMBINING DOUBLE OVE
- {0x0340, 0x0341, propertyDISALLOWED}, // COMBINING GRAVE TONE MARK..COMBINING ACUTE T
- {0x0342, 0x0, propertyPVALID}, // COMBINING GREEK PERISPOMENI
- {0x0343, 0x0345, propertyDISALLOWED}, // COMBINING GREEK KORONIS..COMBINING GREEK YPO
- {0x0346, 0x034E, propertyPVALID}, // COMBINING BRIDGE ABOVE..COMBINING UPWARDS AR
- {0x034F, 0x0, propertyDISALLOWED}, // COMBINING GRAPHEME JOINER
- {0x0350, 0x036F, propertyPVALID}, // COMBINING RIGHT ARROWHEAD ABOVE..COMBINING L
- {0x0370, 0x0, propertyDISALLOWED}, // GREEK CAPITAL LETTER HETA
- {0x0371, 0x0, propertyPVALID}, // GREEK SMALL LETTER HETA
- {0x0372, 0x0, propertyDISALLOWED}, // GREEK CAPITAL LETTER ARCHAIC SAMPI
- {0x0373, 0x0, propertyPVALID}, // GREEK SMALL LETTER ARCHAIC SAMPI
- {0x0374, 0x0, propertyDISALLOWED}, // GREEK NUMERAL SIGN
- {0x0375, 0x0, propertyCONTEXTO}, // GREEK LOWER NUMERAL SIGN
- {0x0376, 0x0, propertyDISALLOWED}, // GREEK CAPITAL LETTER PAMPHYLIAN DIGAMMA
- {0x0377, 0x0, propertyPVALID}, // GREEK SMALL LETTER PAMPHYLIAN DIGAMMA
- {0x0378, 0x0379, propertyUNASSIGNED}, // ..
- {0x037A, 0x0, propertyDISALLOWED}, // GREEK YPOGEGRAMMENI
- {0x037B, 0x037D, propertyPVALID}, // GREEK SMALL REVERSED LUNATE SIGMA SYMBOL..GR
- {0x037E, 0x0, propertyDISALLOWED}, // GREEK QUESTION MARK
- {0x037F, 0x0383, propertyUNASSIGNED}, // ..
- {0x0384, 0x038A, propertyDISALLOWED}, // GREEK TONOS..GREEK CAPITAL LETTER IOTA WITH
- {0x038B, 0x0, propertyUNASSIGNED}, //
- {0x038C, 0x0, propertyDISALLOWED}, // GREEK CAPITAL LETTER OMICRON WITH TONOS
- {0x038D, 0x0, propertyUNASSIGNED}, //
- {0x038E, 0x038F, propertyDISALLOWED}, // GREEK CAPITAL LETTER UPSILON WITH TONOS..GRE
- {0x0390, 0x0, propertyPVALID}, // GREEK SMALL LETTER IOTA WITH DIALYTIKA AND T
- {0x0391, 0x03A1, propertyDISALLOWED}, // GREEK CAPITAL LETTER ALPHA..GREEK CAPITAL LE
- {0x03A2, 0x0, propertyUNASSIGNED}, //
- {0x03A3, 0x03AB, propertyDISALLOWED}, // GREEK CAPITAL LETTER SIGMA..GREEK CAPITAL LE
- {0x03AC, 0x03CE, propertyPVALID}, // GREEK SMALL LETTER ALPHA WITH TONOS..GREEK S
- {0x03CF, 0x03D6, propertyDISALLOWED}, // GREEK CAPITAL KAI SYMBOL..GREEK PI SYMBOL
- {0x03D7, 0x0, propertyPVALID}, // GREEK KAI SYMBOL
- {0x03D8, 0x0, propertyDISALLOWED}, // GREEK LETTER ARCHAIC KOPPA
- {0x03D9, 0x0, propertyPVALID}, // GREEK SMALL LETTER ARCHAIC KOPPA
- {0x03DA, 0x0, propertyDISALLOWED}, // GREEK LETTER STIGMA
- {0x03DB, 0x0, propertyPVALID}, // GREEK SMALL LETTER STIGMA
- {0x03DC, 0x0, propertyDISALLOWED}, // GREEK LETTER DIGAMMA
- {0x03DD, 0x0, propertyPVALID}, // GREEK SMALL LETTER DIGAMMA
- {0x03DE, 0x0, propertyDISALLOWED}, // GREEK LETTER KOPPA
- {0x03DF, 0x0, propertyPVALID}, // GREEK SMALL LETTER KOPPA
- {0x03E0, 0x0, propertyDISALLOWED}, // GREEK LETTER SAMPI
- {0x03E1, 0x0, propertyPVALID}, // GREEK SMALL LETTER SAMPI
- {0x03E2, 0x0, propertyDISALLOWED}, // COPTIC CAPITAL LETTER SHEI
- {0x03E3, 0x0, propertyPVALID}, // COPTIC SMALL LETTER SHEI
- {0x03E4, 0x0, propertyDISALLOWED}, // COPTIC CAPITAL LETTER FEI
- {0x03E5, 0x0, propertyPVALID}, // COPTIC SMALL LETTER FEI
- {0x03E6, 0x0, propertyDISALLOWED}, // COPTIC CAPITAL LETTER KHEI
- {0x03E7, 0x0, propertyPVALID}, // COPTIC SMALL LETTER KHEI
- {0x03E8, 0x0, propertyDISALLOWED}, // COPTIC CAPITAL LETTER HORI
- {0x03E9, 0x0, propertyPVALID}, // COPTIC SMALL LETTER HORI
- {0x03EA, 0x0, propertyDISALLOWED}, // COPTIC CAPITAL LETTER GANGIA
- {0x03EB, 0x0, propertyPVALID}, // COPTIC SMALL LETTER GANGIA
- {0x03EC, 0x0, propertyDISALLOWED}, // COPTIC CAPITAL LETTER SHIMA
- {0x03ED, 0x0, propertyPVALID}, // COPTIC SMALL LETTER SHIMA
- {0x03EE, 0x0, propertyDISALLOWED}, // COPTIC CAPITAL LETTER DEI
- {0x03EF, 0x0, propertyPVALID}, // COPTIC SMALL LETTER DEI
- {0x03F0, 0x03F2, propertyDISALLOWED}, // GREEK KAPPA SYMBOL..GREEK LUNATE SIGMA SYMBO
- {0x03F3, 0x0, propertyPVALID}, // GREEK LETTER YOT
- {0x03F4, 0x03F7, propertyDISALLOWED}, // GREEK CAPITAL THETA SYMBOL..GREEK CAPITAL LE
- {0x03F8, 0x0, propertyPVALID}, // GREEK SMALL LETTER SHO
- {0x03F9, 0x03FA, propertyDISALLOWED}, // GREEK CAPITAL LUNATE SIGMA SYMBOL..GREEK CAP
- {0x03FB, 0x03FC, propertyPVALID}, // GREEK SMALL LETTER SAN..GREEK RHO WITH STROK
- {0x03FD, 0x042F, propertyDISALLOWED}, // GREEK CAPITAL REVERSED LUNATE SIGMA SYMBOL..
- {0x0430, 0x045F, propertyPVALID}, // CYRILLIC SMALL LETTER A..CYRILLIC SMALL LETT
- {0x0460, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER OMEGA
- {0x0461, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER OMEGA
- {0x0462, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER YAT
- {0x0463, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER YAT
- {0x0464, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER IOTIFIED E
- {0x0465, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER IOTIFIED E
- {0x0466, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER LITTLE YUS
- {0x0467, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER LITTLE YUS
- {0x0468, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER IOTIFIED LITTLE YUS
- {0x0469, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER IOTIFIED LITTLE YUS
- {0x046A, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER BIG YUS
- {0x046B, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER BIG YUS
- {0x046C, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER IOTIFIED BIG YUS
- {0x046D, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER IOTIFIED BIG YUS
- {0x046E, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER KSI
- {0x046F, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER KSI
- {0x0470, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER PSI
- {0x0471, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER PSI
- {0x0472, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER FITA
- {0x0473, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER FITA
- {0x0474, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER IZHITSA
- {0x0475, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER IZHITSA
- {0x0476, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER IZHITSA WITH DOUBLE
- {0x0477, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER IZHITSA WITH DOUBLE GR
- {0x0478, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER UK
- {0x0479, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER UK
- {0x047A, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER ROUND OMEGA
- {0x047B, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER ROUND OMEGA
- {0x047C, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER OMEGA WITH TITLO
- {0x047D, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER OMEGA WITH TITLO
- {0x047E, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER OT
- {0x047F, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER OT
- {0x0480, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER KOPPA
- {0x0481, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER KOPPA
- {0x0482, 0x0, propertyDISALLOWED}, // CYRILLIC THOUSANDS SIGN
- {0x0483, 0x0487, propertyPVALID}, // COMBINING CYRILLIC TITLO..COMBINING CYRILLIC
- {0x0488, 0x048A, propertyDISALLOWED}, // COMBINING CYRILLIC HUNDRED THOUSANDS SIGN..C
- {0x048B, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER SHORT I WITH TAIL
- {0x048C, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER SEMISOFT SIGN
- {0x048D, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER SEMISOFT SIGN
- {0x048E, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER ER WITH TICK
- {0x048F, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER ER WITH TICK
- {0x0490, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER GHE WITH UPTURN
- {0x0491, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER GHE WITH UPTURN
- {0x0492, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER GHE WITH STROKE
- {0x0493, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER GHE WITH STROKE
- {0x0494, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER GHE WITH MIDDLE HOOK
- {0x0495, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER GHE WITH MIDDLE HOOK
- {0x0496, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER ZHE WITH DESCENDER
- {0x0497, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER ZHE WITH DESCENDER
- {0x0498, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER ZE WITH DESCENDER
- {0x0499, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER ZE WITH DESCENDER
- {0x049A, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER KA WITH DESCENDER
- {0x049B, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER KA WITH DESCENDER
- {0x049C, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER KA WITH VERTICAL STR
- {0x049D, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER KA WITH VERTICAL STROK
- {0x049E, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER KA WITH STROKE
- {0x049F, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER KA WITH STROKE
- {0x04A0, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER BASHKIR KA
- {0x04A1, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER BASHKIR KA
- {0x04A2, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER EN WITH DESCENDER
- {0x04A3, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER EN WITH DESCENDER
- {0x04A4, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LIGATURE EN GHE
- {0x04A5, 0x0, propertyPVALID}, // CYRILLIC SMALL LIGATURE EN GHE
- {0x04A6, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER PE WITH MIDDLE HOOK
- {0x04A7, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER PE WITH MIDDLE HOOK
- {0x04A8, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER ABKHASIAN HA
- {0x04A9, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER ABKHASIAN HA
- {0x04AA, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER ES WITH DESCENDER
- {0x04AB, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER ES WITH DESCENDER
- {0x04AC, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER TE WITH DESCENDER
- {0x04AD, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER TE WITH DESCENDER
- {0x04AE, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER STRAIGHT U
- {0x04AF, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER STRAIGHT U
- {0x04B0, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER STRAIGHT U WITH STRO
- {0x04B1, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER STRAIGHT U WITH STROKE
- {0x04B2, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER HA WITH DESCENDER
- {0x04B3, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER HA WITH DESCENDER
- {0x04B4, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LIGATURE TE TSE
- {0x04B5, 0x0, propertyPVALID}, // CYRILLIC SMALL LIGATURE TE TSE
- {0x04B6, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER CHE WITH DESCENDER
- {0x04B7, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER CHE WITH DESCENDER
- {0x04B8, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER CHE WITH VERTICAL ST
- {0x04B9, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER CHE WITH VERTICAL STRO
- {0x04BA, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER SHHA
- {0x04BB, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER SHHA
- {0x04BC, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER ABKHASIAN CHE
- {0x04BD, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER ABKHASIAN CHE
- {0x04BE, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER ABKHASIAN CHE WITH D
- {0x04BF, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER ABKHASIAN CHE WITH DES
- {0x04C0, 0x04C1, propertyDISALLOWED}, // CYRILLIC LETTER PALOCHKA..CYRILLIC CAPITAL L
- {0x04C2, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER ZHE WITH BREVE
- {0x04C3, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER KA WITH HOOK
- {0x04C4, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER KA WITH HOOK
- {0x04C5, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER EL WITH TAIL
- {0x04C6, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER EL WITH TAIL
- {0x04C7, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER EN WITH HOOK
- {0x04C8, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER EN WITH HOOK
- {0x04C9, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER EN WITH TAIL
- {0x04CA, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER EN WITH TAIL
- {0x04CB, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER KHAKASSIAN CHE
- {0x04CC, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER KHAKASSIAN CHE
- {0x04CD, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER EM WITH TAIL
- {0x04CE, 0x04CF, propertyPVALID}, // CYRILLIC SMALL LETTER EM WITH TAIL..CYRILLIC
- {0x04D0, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER A WITH BREVE
- {0x04D1, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER A WITH BREVE
- {0x04D2, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER A WITH DIAERESIS
- {0x04D3, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER A WITH DIAERESIS
- {0x04D4, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LIGATURE A IE
- {0x04D5, 0x0, propertyPVALID}, // CYRILLIC SMALL LIGATURE A IE
- {0x04D6, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER IE WITH BREVE
- {0x04D7, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER IE WITH BREVE
- {0x04D8, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER SCHWA
- {0x04D9, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER SCHWA
- {0x04DA, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER SCHWA WITH DIAERESIS
- {0x04DB, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER SCHWA WITH DIAERESIS
- {0x04DC, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER ZHE WITH DIAERESIS
- {0x04DD, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER ZHE WITH DIAERESIS
- {0x04DE, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER ZE WITH DIAERESIS
- {0x04DF, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER ZE WITH DIAERESIS
- {0x04E0, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER ABKHASIAN DZE
- {0x04E1, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER ABKHASIAN DZE
- {0x04E2, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER I WITH MACRON
- {0x04E3, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER I WITH MACRON
- {0x04E4, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER I WITH DIAERESIS
- {0x04E5, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER I WITH DIAERESIS
- {0x04E6, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER O WITH DIAERESIS
- {0x04E7, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER O WITH DIAERESIS
- {0x04E8, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER BARRED O
- {0x04E9, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER BARRED O
- {0x04EA, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER BARRED O WITH DIAERE
- {0x04EB, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER BARRED O WITH DIAERESI
- {0x04EC, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER E WITH DIAERESIS
- {0x04ED, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER E WITH DIAERESIS
- {0x04EE, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER U WITH MACRON
- {0x04EF, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER U WITH MACRON
- {0x04F0, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER U WITH DIAERESIS
- {0x04F1, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER U WITH DIAERESIS
- {0x04F2, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER U WITH DOUBLE ACUTE
- {0x04F3, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER U WITH DOUBLE ACUTE
- {0x04F4, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER CHE WITH DIAERESIS
- {0x04F5, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER CHE WITH DIAERESIS
- {0x04F6, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER GHE WITH DESCENDER
- {0x04F7, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER GHE WITH DESCENDER
- {0x04F8, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER YERU WITH DIAERESIS
- {0x04F9, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER YERU WITH DIAERESIS
- {0x04FA, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER GHE WITH STROKE AND
- {0x04FB, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER GHE WITH STROKE AND HO
- {0x04FC, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER HA WITH HOOK
- {0x04FD, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER HA WITH HOOK
- {0x04FE, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER HA WITH STROKE
- {0x04FF, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER HA WITH STROKE
- {0x0500, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER KOMI DE
- {0x0501, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER KOMI DE
- {0x0502, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER KOMI DJE
- {0x0503, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER KOMI DJE
- {0x0504, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER KOMI ZJE
- {0x0505, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER KOMI ZJE
- {0x0506, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER KOMI DZJE
- {0x0507, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER KOMI DZJE
- {0x0508, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER KOMI LJE
- {0x0509, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER KOMI LJE
- {0x050A, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER KOMI NJE
- {0x050B, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER KOMI NJE
- {0x050C, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER KOMI SJE
- {0x050D, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER KOMI SJE
- {0x050E, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER KOMI TJE
- {0x050F, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER KOMI TJE
- {0x0510, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER REVERSED ZE
- {0x0511, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER REVERSED ZE
- {0x0512, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER EL WITH HOOK
- {0x0513, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER EL WITH HOOK
- {0x0514, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER LHA
- {0x0515, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER LHA
- {0x0516, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER RHA
- {0x0517, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER RHA
- {0x0518, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER YAE
- {0x0519, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER YAE
- {0x051A, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER QA
- {0x051B, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER QA
- {0x051C, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER WE
- {0x051D, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER WE
- {0x051E, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER ALEUT KA
- {0x051F, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER ALEUT KA
- {0x0520, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER EL WITH MIDDLE HOOK
- {0x0521, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER EL WITH MIDDLE HOOK
- {0x0522, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER EN WITH MIDDLE HOOK
- {0x0523, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER EN WITH MIDDLE HOOK
- {0x0524, 0x0, propertyDISALLOWED}, // CYRILLIC CAPITAL LETTER PE WITH DESCENDER
- {0x0525, 0x0, propertyPVALID}, // CYRILLIC SMALL LETTER PE WITH DESCENDER
- {0x0526, 0x0530, propertyUNASSIGNED}, // ..
- {0x0531, 0x0556, propertyDISALLOWED}, // ARMENIAN CAPITAL LETTER AYB..ARMENIAN CAPITA
- {0x0557, 0x0558, propertyUNASSIGNED}, // ..
- {0x0559, 0x0, propertyPVALID}, // ARMENIAN MODIFIER LETTER LEFT HALF RING
- {0x055A, 0x055F, propertyDISALLOWED}, // ARMENIAN APOSTROPHE..ARMENIAN ABBREVIATION M
- {0x0560, 0x0, propertyUNASSIGNED}, //
- {0x0561, 0x0586, propertyPVALID}, // ARMENIAN SMALL LETTER AYB..ARMENIAN SMALL LE
- {0x0587, 0x0, propertyDISALLOWED}, // ARMENIAN SMALL LIGATURE ECH YIWN
- {0x0588, 0x0, propertyUNASSIGNED}, //
- {0x0589, 0x058A, propertyDISALLOWED}, // ARMENIAN FULL STOP..ARMENIAN HYPHEN
- {0x058B, 0x0590, propertyUNASSIGNED}, // ..
- {0x0591, 0x05BD, propertyPVALID}, // HEBREW ACCENT ETNAHTA..HEBREW POINT METEG
- {0x05BE, 0x0, propertyDISALLOWED}, // HEBREW PUNCTUATION MAQAF
- {0x05BF, 0x0, propertyPVALID}, // HEBREW POINT RAFE
- {0x05C0, 0x0, propertyDISALLOWED}, // HEBREW PUNCTUATION PASEQ
- {0x05C1, 0x05C2, propertyPVALID}, // HEBREW POINT SHIN DOT..HEBREW POINT SIN DOT
- {0x05C3, 0x0, propertyDISALLOWED}, // HEBREW PUNCTUATION SOF PASUQ
- {0x05C4, 0x05C5, propertyPVALID}, // HEBREW MARK UPPER DOT..HEBREW MARK LOWER DOT
- {0x05C6, 0x0, propertyDISALLOWED}, // HEBREW PUNCTUATION NUN HAFUKHA
- {0x05C7, 0x0, propertyPVALID}, // HEBREW POINT QAMATS QATAN
- {0x05C8, 0x05CF, propertyUNASSIGNED}, // ..
- {0x05D0, 0x05EA, propertyPVALID}, // HEBREW LETTER ALEF..HEBREW LETTER TAV
- {0x05EB, 0x05EF, propertyUNASSIGNED}, // ..
- {0x05F0, 0x05F2, propertyPVALID}, // HEBREW LIGATURE YIDDISH DOUBLE VAV..HEBREW L
- {0x05F3, 0x05F4, propertyCONTEXTO}, // HEBREW PUNCTUATION GERESH..HEBREW PUNCTUATIO
- {0x05F5, 0x05FF, propertyUNASSIGNED}, // ..
- {0x0600, 0x0603, propertyDISALLOWED}, // ARABIC NUMBER SIGN..ARABIC SIGN SAFHA
- {0x0604, 0x0605, propertyUNASSIGNED}, // ..
- {0x0606, 0x060F, propertyDISALLOWED}, // ARABIC-INDIC CUBE ROOT..ARABIC SIGN MISRA
- {0x0610, 0x061A, propertyPVALID}, // ARABIC SIGN SALLALLAHOU ALAYHE WASSALLAM..AR
- {0x061B, 0x0, propertyDISALLOWED}, // ARABIC SEMICOLON
- {0x061C, 0x061D, propertyUNASSIGNED}, // ..
- {0x061E, 0x061F, propertyDISALLOWED}, // ARABIC TRIPLE DOT PUNCTUATION MARK..ARABIC Q
- {0x0620, 0x0, propertyUNASSIGNED}, //
- {0x0621, 0x063F, propertyPVALID}, // ARABIC LETTER HAMZA..ARABIC LETTER FARSI YEH
- {0x0640, 0x0, propertyDISALLOWED}, // ARABIC TATWEEL
- {0x0641, 0x065E, propertyPVALID}, // ARABIC LETTER FEH..ARABIC FATHA WITH TWO DOT
- {0x065F, 0x0, propertyUNASSIGNED}, //
- {0x0660, 0x0669, propertyCONTEXTO}, // ARABIC-INDIC DIGIT ZERO..ARABIC-INDIC DIGIT
- {0x066A, 0x066D, propertyDISALLOWED}, // ARABIC PERCENT SIGN..ARABIC FIVE POINTED STA
- {0x066E, 0x0674, propertyPVALID}, // ARABIC LETTER DOTLESS BEH..ARABIC LETTER HIG
- {0x0675, 0x0678, propertyDISALLOWED}, // ARABIC LETTER HIGH HAMZA ALEF..ARABIC LETTER
- {0x0679, 0x06D3, propertyPVALID}, // ARABIC LETTER TTEH..ARABIC LETTER YEH BARREE
- {0x06D4, 0x0, propertyDISALLOWED}, // ARABIC FULL STOP
- {0x06D5, 0x06DC, propertyPVALID}, // ARABIC LETTER AE..ARABIC SMALL HIGH SEEN
- {0x06DD, 0x06DE, propertyDISALLOWED}, // ARABIC END OF AYAH..ARABIC START OF RUB EL H
- {0x06DF, 0x06E8, propertyPVALID}, // ARABIC SMALL HIGH ROUNDED ZERO..ARABIC SMALL
- {0x06E9, 0x0, propertyDISALLOWED}, // ARABIC PLACE OF SAJDAH
- {0x06EA, 0x06EF, propertyPVALID}, // ARABIC EMPTY CENTRE LOW STOP..ARABIC LETTER
- {0x06F0, 0x06F9, propertyCONTEXTO}, // EXTENDED ARABIC-INDIC DIGIT ZERO..EXTENDED A
- {0x06FA, 0x06FF, propertyPVALID}, // ARABIC LETTER SHEEN WITH DOT BELOW..ARABIC L
- {0x0700, 0x070D, propertyDISALLOWED}, // SYRIAC END OF PARAGRAPH..SYRIAC HARKLEAN AST
- {0x070E, 0x0, propertyUNASSIGNED}, //
- {0x070F, 0x0, propertyDISALLOWED}, // SYRIAC ABBREVIATION MARK
- {0x0710, 0x074A, propertyPVALID}, // SYRIAC LETTER ALAPH..SYRIAC BARREKH
- {0x074B, 0x074C, propertyUNASSIGNED}, // ..
- {0x074D, 0x07B1, propertyPVALID}, // SYRIAC LETTER SOGDIAN ZHAIN..THAANA LETTER N
- {0x07B2, 0x07BF, propertyUNASSIGNED}, // ..
- {0x07C0, 0x07F5, propertyPVALID}, // NKO DIGIT ZERO..NKO LOW TONE APOSTROPHE
- {0x07F6, 0x07FA, propertyDISALLOWED}, // NKO SYMBOL OO DENNEN..NKO LAJANYALAN
- {0x07FB, 0x07FF, propertyUNASSIGNED}, // ..
- {0x0800, 0x082D, propertyPVALID}, // SAMARITAN LETTER ALAF..SAMARITAN MARK NEQUDA
- {0x082E, 0x082F, propertyUNASSIGNED}, // ..
- {0x0830, 0x083E, propertyDISALLOWED}, // SAMARITAN PUNCTUATION NEQUDAA..SAMARITAN PUN
- {0x083F, 0x08FF, propertyUNASSIGNED}, // ..
- {0x0900, 0x0939, propertyPVALID}, // DEVANAGARI SIGN INVERTED CANDRABINDU..DEVANA
- {0x093A, 0x093B, propertyUNASSIGNED}, // ..
- {0x093C, 0x094E, propertyPVALID}, // DEVANAGARI SIGN NUKTA..DEVANAGARI VOWEL SIGN
- {0x094F, 0x0, propertyUNASSIGNED}, //
- {0x0950, 0x0955, propertyPVALID}, // DEVANAGARI OM..DEVANAGARI VOWEL SIGN CANDRA
- {0x0956, 0x0957, propertyUNASSIGNED}, // ..
- {0x0958, 0x095F, propertyDISALLOWED}, // DEVANAGARI LETTER QA..DEVANAGARI LETTER YYA
- {0x0960, 0x0963, propertyPVALID}, // DEVANAGARI LETTER VOCALIC RR..DEVANAGARI VOW
- {0x0964, 0x0965, propertyDISALLOWED}, // DEVANAGARI DANDA..DEVANAGARI DOUBLE DANDA
- {0x0966, 0x096F, propertyPVALID}, // DEVANAGARI DIGIT ZERO..DEVANAGARI DIGIT NINE
- {0x0970, 0x0, propertyDISALLOWED}, // DEVANAGARI ABBREVIATION SIGN
- {0x0971, 0x0972, propertyPVALID}, // DEVANAGARI SIGN HIGH SPACING DOT..DEVANAGARI
- {0x0973, 0x0978, propertyUNASSIGNED}, // ..
- {0x0979, 0x097F, propertyPVALID}, // DEVANAGARI LETTER ZHA..DEVANAGARI LETTER BBA
- {0x0980, 0x0, propertyUNASSIGNED}, //
- {0x0981, 0x0983, propertyPVALID}, // BENGALI SIGN CANDRABINDU..BENGALI SIGN VISAR
- {0x0984, 0x0, propertyUNASSIGNED}, //
- {0x0985, 0x098C, propertyPVALID}, // BENGALI LETTER A..BENGALI LETTER VOCALIC L
- {0x098D, 0x098E, propertyUNASSIGNED}, // ..
- {0x098F, 0x0990, propertyPVALID}, // BENGALI LETTER E..BENGALI LETTER AI
- {0x0991, 0x0992, propertyUNASSIGNED}, // ..
- {0x0993, 0x09A8, propertyPVALID}, // BENGALI LETTER O..BENGALI LETTER NA
- {0x09A9, 0x0, propertyUNASSIGNED}, //
- {0x09AA, 0x09B0, propertyPVALID}, // BENGALI LETTER PA..BENGALI LETTER RA
- {0x09B1, 0x0, propertyUNASSIGNED}, //
- {0x09B2, 0x0, propertyPVALID}, // BENGALI LETTER LA
- {0x09B3, 0x09B5, propertyUNASSIGNED}, // ..
- {0x09B6, 0x09B9, propertyPVALID}, // BENGALI LETTER SHA..BENGALI LETTER HA
- {0x09BA, 0x09BB, propertyUNASSIGNED}, // ..
- {0x09BC, 0x09C4, propertyPVALID}, // BENGALI SIGN NUKTA..BENGALI VOWEL SIGN VOCAL
- {0x09C5, 0x09C6, propertyUNASSIGNED}, // ..
- {0x09C7, 0x09C8, propertyPVALID}, // BENGALI VOWEL SIGN E..BENGALI VOWEL SIGN AI
- {0x09C9, 0x09CA, propertyUNASSIGNED}, // ..
- {0x09CB, 0x09CE, propertyPVALID}, // BENGALI VOWEL SIGN O..BENGALI LETTER KHANDA
- {0x09CF, 0x09D6, propertyUNASSIGNED}, // ..
- {0x09D7, 0x0, propertyPVALID}, // BENGALI AU LENGTH MARK
- {0x09D8, 0x09DB, propertyUNASSIGNED}, // ..
- {0x09DC, 0x09DD, propertyDISALLOWED}, // BENGALI LETTER RRA..BENGALI LETTER RHA
- {0x09DE, 0x0, propertyUNASSIGNED}, //
- {0x09DF, 0x0, propertyDISALLOWED}, // BENGALI LETTER YYA
- {0x09E0, 0x09E3, propertyPVALID}, // BENGALI LETTER VOCALIC RR..BENGALI VOWEL SIG
- {0x09E4, 0x09E5, propertyUNASSIGNED}, // ..
- {0x09E6, 0x09F1, propertyPVALID}, // BENGALI DIGIT ZERO..BENGALI LETTER RA WITH L
- {0x09F2, 0x09FB, propertyDISALLOWED}, // BENGALI RUPEE MARK..BENGALI GANDA MARK
- {0x09FC, 0x0A00, propertyUNASSIGNED}, // ..
- {0x0A01, 0x0A03, propertyPVALID}, // GURMUKHI SIGN ADAK BINDI..GURMUKHI SIGN VISA
- {0x0A04, 0x0, propertyUNASSIGNED}, //
- {0x0A05, 0x0A0A, propertyPVALID}, // GURMUKHI LETTER A..GURMUKHI LETTER UU
- {0x0A0B, 0x0A0E, propertyUNASSIGNED}, // ..
- {0x0A0F, 0x0A10, propertyPVALID}, // GURMUKHI LETTER EE..GURMUKHI LETTER AI
- {0x0A11, 0x0A12, propertyUNASSIGNED}, // ..
- {0x0A13, 0x0A28, propertyPVALID}, // GURMUKHI LETTER OO..GURMUKHI LETTER NA
- {0x0A29, 0x0, propertyUNASSIGNED}, //
- {0x0A2A, 0x0A30, propertyPVALID}, // GURMUKHI LETTER PA..GURMUKHI LETTER RA
- {0x0A31, 0x0, propertyUNASSIGNED}, //
- {0x0A32, 0x0, propertyPVALID}, // GURMUKHI LETTER LA
- {0x0A33, 0x0, propertyDISALLOWED}, // GURMUKHI LETTER LLA
- {0x0A34, 0x0, propertyUNASSIGNED}, //
- {0x0A35, 0x0, propertyPVALID}, // GURMUKHI LETTER VA
- {0x0A36, 0x0, propertyDISALLOWED}, // GURMUKHI LETTER SHA
- {0x0A37, 0x0, propertyUNASSIGNED}, //
- {0x0A38, 0x0A39, propertyPVALID}, // GURMUKHI LETTER SA..GURMUKHI LETTER HA
- {0x0A3A, 0x0A3B, propertyUNASSIGNED}, // ..
- {0x0A3C, 0x0, propertyPVALID}, // GURMUKHI SIGN NUKTA
- {0x0A3D, 0x0, propertyUNASSIGNED}, //
- {0x0A3E, 0x0A42, propertyPVALID}, // GURMUKHI VOWEL SIGN AA..GURMUKHI VOWEL SIGN
- {0x0A43, 0x0A46, propertyUNASSIGNED}, // ..
- {0x0A47, 0x0A48, propertyPVALID}, // GURMUKHI VOWEL SIGN EE..GURMUKHI VOWEL SIGN
- {0x0A49, 0x0A4A, propertyUNASSIGNED}, // ..
- {0x0A4B, 0x0A4D, propertyPVALID}, // GURMUKHI VOWEL SIGN OO..GURMUKHI SIGN VIRAMA
- {0x0A4E, 0x0A50, propertyUNASSIGNED}, // ..
- {0x0A51, 0x0, propertyPVALID}, // GURMUKHI SIGN UDAAT
- {0x0A52, 0x0A58, propertyUNASSIGNED}, // ..
- {0x0A59, 0x0A5B, propertyDISALLOWED}, // GURMUKHI LETTER KHHA..GURMUKHI LETTER ZA
- {0x0A5C, 0x0, propertyPVALID}, // GURMUKHI LETTER RRA
- {0x0A5D, 0x0, propertyUNASSIGNED}, //
- {0x0A5E, 0x0, propertyDISALLOWED}, // GURMUKHI LETTER FA
- {0x0A5F, 0x0A65, propertyUNASSIGNED}, // ..
- {0x0A66, 0x0A75, propertyPVALID}, // GURMUKHI DIGIT ZERO..GURMUKHI SIGN YAKASH
- {0x0A76, 0x0A80, propertyUNASSIGNED}, // ..
- {0x0A81, 0x0A83, propertyPVALID}, // GUJARATI SIGN CANDRABINDU..GUJARATI SIGN VIS
- {0x0A84, 0x0, propertyUNASSIGNED}, //
- {0x0A85, 0x0A8D, propertyPVALID}, // GUJARATI LETTER A..GUJARATI VOWEL CANDRA E
- {0x0A8E, 0x0, propertyUNASSIGNED}, //
- {0x0A8F, 0x0A91, propertyPVALID}, // GUJARATI LETTER E..GUJARATI VOWEL CANDRA O
- {0x0A92, 0x0, propertyUNASSIGNED}, //
- {0x0A93, 0x0AA8, propertyPVALID}, // GUJARATI LETTER O..GUJARATI LETTER NA
- {0x0AA9, 0x0, propertyUNASSIGNED}, //
- {0x0AAA, 0x0AB0, propertyPVALID}, // GUJARATI LETTER PA..GUJARATI LETTER RA
- {0x0AB1, 0x0, propertyUNASSIGNED}, //
- {0x0AB2, 0x0AB3, propertyPVALID}, // GUJARATI LETTER LA..GUJARATI LETTER LLA
- {0x0AB4, 0x0, propertyUNASSIGNED}, //
- {0x0AB5, 0x0AB9, propertyPVALID}, // GUJARATI LETTER VA..GUJARATI LETTER HA
- {0x0ABA, 0x0ABB, propertyUNASSIGNED}, // ..
- {0x0ABC, 0x0AC5, propertyPVALID}, // GUJARATI SIGN NUKTA..GUJARATI VOWEL SIGN CAN
- {0x0AC6, 0x0, propertyUNASSIGNED}, //
- {0x0AC7, 0x0AC9, propertyPVALID}, // GUJARATI VOWEL SIGN E..GUJARATI VOWEL SIGN C
- {0x0ACA, 0x0, propertyUNASSIGNED}, //
- {0x0ACB, 0x0ACD, propertyPVALID}, // GUJARATI VOWEL SIGN O..GUJARATI SIGN VIRAMA
- {0x0ACE, 0x0ACF, propertyUNASSIGNED}, // ..
- {0x0AD0, 0x0, propertyPVALID}, // GUJARATI OM
- {0x0AD1, 0x0ADF, propertyUNASSIGNED}, // ..
- {0x0AE0, 0x0AE3, propertyPVALID}, // GUJARATI LETTER VOCALIC RR..GUJARATI VOWEL S
- {0x0AE4, 0x0AE5, propertyUNASSIGNED}, // ..
- {0x0AE6, 0x0AEF, propertyPVALID}, // GUJARATI DIGIT ZERO..GUJARATI DIGIT NINE
- {0x0AF0, 0x0, propertyUNASSIGNED}, //
- {0x0AF1, 0x0, propertyDISALLOWED}, // GUJARATI RUPEE SIGN
- {0x0AF2, 0x0B00, propertyUNASSIGNED}, // ..
- {0x0B01, 0x0B03, propertyPVALID}, // ORIYA SIGN CANDRABINDU..ORIYA SIGN VISARGA
- {0x0B04, 0x0, propertyUNASSIGNED}, //
- {0x0B05, 0x0B0C, propertyPVALID}, // ORIYA LETTER A..ORIYA LETTER VOCALIC L
- {0x0B0D, 0x0B0E, propertyUNASSIGNED}, // ..
- {0x0B0F, 0x0B10, propertyPVALID}, // ORIYA LETTER E..ORIYA LETTER AI
- {0x0B11, 0x0B12, propertyUNASSIGNED}, // ..
- {0x0B13, 0x0B28, propertyPVALID}, // ORIYA LETTER O..ORIYA LETTER NA
- {0x0B29, 0x0, propertyUNASSIGNED}, //
- {0x0B2A, 0x0B30, propertyPVALID}, // ORIYA LETTER PA..ORIYA LETTER RA
- {0x0B31, 0x0, propertyUNASSIGNED}, //
- {0x0B32, 0x0B33, propertyPVALID}, // ORIYA LETTER LA..ORIYA LETTER LLA
- {0x0B34, 0x0, propertyUNASSIGNED}, //
- {0x0B35, 0x0B39, propertyPVALID}, // ORIYA LETTER VA..ORIYA LETTER HA
- {0x0B3A, 0x0B3B, propertyUNASSIGNED}, // ..
- {0x0B3C, 0x0B44, propertyPVALID}, // ORIYA SIGN NUKTA..ORIYA VOWEL SIGN VOCALIC R
- {0x0B45, 0x0B46, propertyUNASSIGNED}, // ..
- {0x0B47, 0x0B48, propertyPVALID}, // ORIYA VOWEL SIGN E..ORIYA VOWEL SIGN AI
- {0x0B49, 0x0B4A, propertyUNASSIGNED}, // ..
- {0x0B4B, 0x0B4D, propertyPVALID}, // ORIYA VOWEL SIGN O..ORIYA SIGN VIRAMA
- {0x0B4E, 0x0B55, propertyUNASSIGNED}, // ..
- {0x0B56, 0x0B57, propertyPVALID}, // ORIYA AI LENGTH MARK..ORIYA AU LENGTH MARK
- {0x0B58, 0x0B5B, propertyUNASSIGNED}, // ..
- {0x0B5C, 0x0B5D, propertyDISALLOWED}, // ORIYA LETTER RRA..ORIYA LETTER RHA
- {0x0B5E, 0x0, propertyUNASSIGNED}, //
- {0x0B5F, 0x0B63, propertyPVALID}, // ORIYA LETTER YYA..ORIYA VOWEL SIGN VOCALIC L
- {0x0B64, 0x0B65, propertyUNASSIGNED}, // ..
- {0x0B66, 0x0B6F, propertyPVALID}, // ORIYA DIGIT ZERO..ORIYA DIGIT NINE
- {0x0B70, 0x0, propertyDISALLOWED}, // ORIYA ISSHAR
- {0x0B71, 0x0, propertyPVALID}, // ORIYA LETTER WA
- {0x0B72, 0x0B81, propertyUNASSIGNED}, // ..
- {0x0B82, 0x0B83, propertyPVALID}, // TAMIL SIGN ANUSVARA..TAMIL SIGN VISARGA
- {0x0B84, 0x0, propertyUNASSIGNED}, //
- {0x0B85, 0x0B8A, propertyPVALID}, // TAMIL LETTER A..TAMIL LETTER UU
- {0x0B8B, 0x0B8D, propertyUNASSIGNED}, // ..
- {0x0B8E, 0x0B90, propertyPVALID}, // TAMIL LETTER E..TAMIL LETTER AI
- {0x0B91, 0x0, propertyUNASSIGNED}, //
- {0x0B92, 0x0B95, propertyPVALID}, // TAMIL LETTER O..TAMIL LETTER KA
- {0x0B96, 0x0B98, propertyUNASSIGNED}, // ..
- {0x0B99, 0x0B9A, propertyPVALID}, // TAMIL LETTER NGA..TAMIL LETTER CA
- {0x0B9B, 0x0, propertyUNASSIGNED}, //
- {0x0B9C, 0x0, propertyPVALID}, // TAMIL LETTER JA
- {0x0B9D, 0x0, propertyUNASSIGNED}, //
- {0x0B9E, 0x0B9F, propertyPVALID}, // TAMIL LETTER NYA..TAMIL LETTER TTA
- {0x0BA0, 0x0BA2, propertyUNASSIGNED}, // ..
- {0x0BA3, 0x0BA4, propertyPVALID}, // TAMIL LETTER NNA..TAMIL LETTER TA
- {0x0BA5, 0x0BA7, propertyUNASSIGNED}, // ..
- {0x0BA8, 0x0BAA, propertyPVALID}, // TAMIL LETTER NA..TAMIL LETTER PA
- {0x0BAB, 0x0BAD, propertyUNASSIGNED}, // ..
- {0x0BAE, 0x0BB9, propertyPVALID}, // TAMIL LETTER MA..TAMIL LETTER HA
- {0x0BBA, 0x0BBD, propertyUNASSIGNED}, // ..
- {0x0BBE, 0x0BC2, propertyPVALID}, // TAMIL VOWEL SIGN AA..TAMIL VOWEL SIGN UU
- {0x0BC3, 0x0BC5, propertyUNASSIGNED}, // ..
- {0x0BC6, 0x0BC8, propertyPVALID}, // TAMIL VOWEL SIGN E..TAMIL VOWEL SIGN AI
- {0x0BC9, 0x0, propertyUNASSIGNED}, //
- {0x0BCA, 0x0BCD, propertyPVALID}, // TAMIL VOWEL SIGN O..TAMIL SIGN VIRAMA
- {0x0BCE, 0x0BCF, propertyUNASSIGNED}, // ..
- {0x0BD0, 0x0, propertyPVALID}, // TAMIL OM
- {0x0BD1, 0x0BD6, propertyUNASSIGNED}, // ..
- {0x0BD7, 0x0, propertyPVALID}, // TAMIL AU LENGTH MARK
- {0x0BD8, 0x0BE5, propertyUNASSIGNED}, // ..
- {0x0BE6, 0x0BEF, propertyPVALID}, // TAMIL DIGIT ZERO..TAMIL DIGIT NINE
- {0x0BF0, 0x0BFA, propertyDISALLOWED}, // TAMIL NUMBER TEN..TAMIL NUMBER SIGN
- {0x0BFB, 0x0C00, propertyUNASSIGNED}, // ..
- {0x0C01, 0x0C03, propertyPVALID}, // TELUGU SIGN CANDRABINDU..TELUGU SIGN VISARGA
- {0x0C04, 0x0, propertyUNASSIGNED}, //
- {0x0C05, 0x0C0C, propertyPVALID}, // TELUGU LETTER A..TELUGU LETTER VOCALIC L
- {0x0C0D, 0x0, propertyUNASSIGNED}, //
- {0x0C0E, 0x0C10, propertyPVALID}, // TELUGU LETTER E..TELUGU LETTER AI
- {0x0C11, 0x0, propertyUNASSIGNED}, //
- {0x0C12, 0x0C28, propertyPVALID}, // TELUGU LETTER O..TELUGU LETTER NA
- {0x0C29, 0x0, propertyUNASSIGNED}, //
- {0x0C2A, 0x0C33, propertyPVALID}, // TELUGU LETTER PA..TELUGU LETTER LLA
- {0x0C34, 0x0, propertyUNASSIGNED}, //
- {0x0C35, 0x0C39, propertyPVALID}, // TELUGU LETTER VA..TELUGU LETTER HA
- {0x0C3A, 0x0C3C, propertyUNASSIGNED}, // ..
- {0x0C3D, 0x0C44, propertyPVALID}, // TELUGU SIGN AVAGRAHA..TELUGU VOWEL SIGN VOCA
- {0x0C45, 0x0, propertyUNASSIGNED}, //
- {0x0C46, 0x0C48, propertyPVALID}, // TELUGU VOWEL SIGN E..TELUGU VOWEL SIGN AI
- {0x0C49, 0x0, propertyUNASSIGNED}, //
- {0x0C4A, 0x0C4D, propertyPVALID}, // TELUGU VOWEL SIGN O..TELUGU SIGN VIRAMA
- {0x0C4E, 0x0C54, propertyUNASSIGNED}, // ..
- {0x0C55, 0x0C56, propertyPVALID}, // TELUGU LENGTH MARK..TELUGU AI LENGTH MARK
- {0x0C57, 0x0, propertyUNASSIGNED}, //
- {0x0C58, 0x0C59, propertyPVALID}, // TELUGU LETTER TSA..TELUGU LETTER DZA
- {0x0C5A, 0x0C5F, propertyUNASSIGNED}, // ..
- {0x0C60, 0x0C63, propertyPVALID}, // TELUGU LETTER VOCALIC RR..TELUGU VOWEL SIGN
- {0x0C64, 0x0C65, propertyUNASSIGNED}, // ..
- {0x0C66, 0x0C6F, propertyPVALID}, // TELUGU DIGIT ZERO..TELUGU DIGIT NINE
- {0x0C70, 0x0C77, propertyUNASSIGNED}, // ..
- {0x0C78, 0x0C7F, propertyDISALLOWED}, // TELUGU FRACTION DIGIT ZERO FOR ODD POWERS OF
- {0x0C80, 0x0C81, propertyUNASSIGNED}, // ..
- {0x0C82, 0x0C83, propertyPVALID}, // KANNADA SIGN ANUSVARA..KANNADA SIGN VISARGA
- {0x0C84, 0x0, propertyUNASSIGNED}, //
- {0x0C85, 0x0C8C, propertyPVALID}, // KANNADA LETTER A..KANNADA LETTER VOCALIC L
- {0x0C8D, 0x0, propertyUNASSIGNED}, //
- {0x0C8E, 0x0C90, propertyPVALID}, // KANNADA LETTER E..KANNADA LETTER AI
- {0x0C91, 0x0, propertyUNASSIGNED}, //
- {0x0C92, 0x0CA8, propertyPVALID}, // KANNADA LETTER O..KANNADA LETTER NA
- {0x0CA9, 0x0, propertyUNASSIGNED}, //
- {0x0CAA, 0x0CB3, propertyPVALID}, // KANNADA LETTER PA..KANNADA LETTER LLA
- {0x0CB4, 0x0, propertyUNASSIGNED}, //
- {0x0CB5, 0x0CB9, propertyPVALID}, // KANNADA LETTER VA..KANNADA LETTER HA
- {0x0CBA, 0x0CBB, propertyUNASSIGNED}, // ..
- {0x0CBC, 0x0CC4, propertyPVALID}, // KANNADA SIGN NUKTA..KANNADA VOWEL SIGN VOCAL
- {0x0CC5, 0x0, propertyUNASSIGNED}, //
- {0x0CC6, 0x0CC8, propertyPVALID}, // KANNADA VOWEL SIGN E..KANNADA VOWEL SIGN AI
- {0x0CC9, 0x0, propertyUNASSIGNED}, //
- {0x0CCA, 0x0CCD, propertyPVALID}, // KANNADA VOWEL SIGN O..KANNADA SIGN VIRAMA
- {0x0CCE, 0x0CD4, propertyUNASSIGNED}, // ..
- {0x0CD5, 0x0CD6, propertyPVALID}, // KANNADA LENGTH MARK..KANNADA AI LENGTH MARK
- {0x0CD7, 0x0CDD, propertyUNASSIGNED}, // ..
- {0x0CDE, 0x0, propertyPVALID}, // KANNADA LETTER FA
- {0x0CDF, 0x0, propertyUNASSIGNED}, //
- {0x0CE0, 0x0CE3, propertyPVALID}, // KANNADA LETTER VOCALIC RR..KANNADA VOWEL SIG
- {0x0CE4, 0x0CE5, propertyUNASSIGNED}, // ..
- {0x0CE6, 0x0CEF, propertyPVALID}, // KANNADA DIGIT ZERO..KANNADA DIGIT NINE
- {0x0CF0, 0x0, propertyUNASSIGNED}, //
- {0x0CF1, 0x0CF2, propertyDISALLOWED}, // KANNADA SIGN JIHVAMULIYA..KANNADA SIGN UPADH
- {0x0CF3, 0x0D01, propertyUNASSIGNED}, // ..
- {0x0D02, 0x0D03, propertyPVALID}, // MALAYALAM SIGN ANUSVARA..MALAYALAM SIGN VISA
- {0x0D04, 0x0, propertyUNASSIGNED}, //
- {0x0D05, 0x0D0C, propertyPVALID}, // MALAYALAM LETTER A..MALAYALAM LETTER VOCALIC
- {0x0D0D, 0x0, propertyUNASSIGNED}, //
- {0x0D0E, 0x0D10, propertyPVALID}, // MALAYALAM LETTER E..MALAYALAM LETTER AI
- {0x0D11, 0x0, propertyUNASSIGNED}, //
- {0x0D12, 0x0D28, propertyPVALID}, // MALAYALAM LETTER O..MALAYALAM LETTER NA
- {0x0D29, 0x0, propertyUNASSIGNED}, //
- {0x0D2A, 0x0D39, propertyPVALID}, // MALAYALAM LETTER PA..MALAYALAM LETTER HA
- {0x0D3A, 0x0D3C, propertyUNASSIGNED}, // ..
- {0x0D3D, 0x0D44, propertyPVALID}, // MALAYALAM SIGN AVAGRAHA..MALAYALAM VOWEL SIG
- {0x0D45, 0x0, propertyUNASSIGNED}, //
- {0x0D46, 0x0D48, propertyPVALID}, // MALAYALAM VOWEL SIGN E..MALAYALAM VOWEL SIGN
- {0x0D49, 0x0, propertyUNASSIGNED}, //