-#include "util.h"
-
-
-// foward declare without all of Windows.h
-__declspec(dllimport) void __stdcall OutputDebugStringA(char const* lpOutputString);
-
-void debugf(char const* str, ...)
-{
- va_list args;
- va_start(args, str);
-
- char buf[1<<16];
- _vsnprintf_s(buf, sizeof(buf), sizeof(buf), str, args);
- buf[sizeof(buf)-1] = '\0';
- OutputDebugStringA(buf);
-}
diff --git a/vendor/github.com/fatih/color/LICENSE.md b/vendor/github.com/fatih/color/LICENSE.md
deleted file mode 100644
index 25fdaf639d..0000000000
--- a/vendor/github.com/fatih/color/LICENSE.md
+++ /dev/null
@@ -1,20 +0,0 @@
-The MIT License (MIT)
-
-Copyright (c) 2013 Fatih Arslan
-
-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/vendor/github.com/fatih/color/README.md b/vendor/github.com/fatih/color/README.md
deleted file mode 100644
index 25abbca3f8..0000000000
--- a/vendor/github.com/fatih/color/README.md
+++ /dev/null
@@ -1,175 +0,0 @@
-# Color [![GoDoc](http://img.shields.io/badge/go-documentation-blue.svg?style=flat-square)](http://godoc.org/github.com/fatih/color) [![Build Status](http://img.shields.io/travis/fatih/color.svg?style=flat-square)](https://travis-ci.org/fatih/color)
-
-
-
-Color lets you use colorized outputs in terms of [ANSI Escape
-Codes](http://en.wikipedia.org/wiki/ANSI_escape_code#Colors) in Go (Golang). It
-has support for Windows too! The API can be used in several ways, pick one that
-suits you.
-
-
-
-![Color](http://i.imgur.com/c1JI0lA.png)
-
-
-## Install
-
-```bash
-go get github.com/fatih/color
-```
-
-## Examples
-
-### Standard colors
-
-```go
-// Print with default helper functions
-color.Cyan("Prints text in cyan.")
-
-// A newline will be appended automatically
-color.Blue("Prints %s in blue.", "text")
-
-// These are using the default foreground colors
-color.Red("We have red")
-color.Magenta("And many others ..")
-
-```
-
-### Mix and reuse colors
-
-```go
-// Create a new color object
-c := color.New(color.FgCyan).Add(color.Underline)
-c.Println("Prints cyan text with an underline.")
-
-// Or just add them to New()
-d := color.New(color.FgCyan, color.Bold)
-d.Printf("This prints bold cyan %s\n", "too!.")
-
-// Mix up foreground and background colors, create new mixes!
-red := color.New(color.FgRed)
-
-boldRed := red.Add(color.Bold)
-boldRed.Println("This will print text in bold red.")
-
-whiteBackground := red.Add(color.BgWhite)
-whiteBackground.Println("Red text with white background.")
-```
-
-### Use your own output (io.Writer)
-
-```go
-// Use your own io.Writer output
-color.New(color.FgBlue).Fprintln(myWriter, "blue color!")
-
-blue := color.New(color.FgBlue)
-blue.Fprint(writer, "This will print text in blue.")
-```
-
-### Custom print functions (PrintFunc)
-
-```go
-// Create a custom print function for convenience
-red := color.New(color.FgRed).PrintfFunc()
-red("Warning")
-red("Error: %s", err)
-
-// Mix up multiple attributes
-notice := color.New(color.Bold, color.FgGreen).PrintlnFunc()
-notice("Don't forget this...")
-```
-
-### Custom fprint functions (FprintFunc)
-
-```go
-blue := color.New(FgBlue).FprintfFunc()
-blue(myWriter, "important notice: %s", stars)
-
-// Mix up with multiple attributes
-success := color.New(color.Bold, color.FgGreen).FprintlnFunc()
-success(myWriter, "Don't forget this...")
-```
-
-### Insert into noncolor strings (SprintFunc)
-
-```go
-// Create SprintXxx functions to mix strings with other non-colorized strings:
-yellow := color.New(color.FgYellow).SprintFunc()
-red := color.New(color.FgRed).SprintFunc()
-fmt.Printf("This is a %s and this is %s.\n", yellow("warning"), red("error"))
-
-info := color.New(color.FgWhite, color.BgGreen).SprintFunc()
-fmt.Printf("This %s rocks!\n", info("package"))
-
-// Use helper functions
-fmt.Println("This", color.RedString("warning"), "should be not neglected.")
-fmt.Printf("%v %v\n", color.GreenString("Info:"), "an important message.")
-
-// Windows supported too! Just don't forget to change the output to color.Output
-fmt.Fprintf(color.Output, "Windows support: %s", color.GreenString("PASS"))
-```
-
-### Plug into existing code
-
-```go
-// Use handy standard colors
-color.Set(color.FgYellow)
-
-fmt.Println("Existing text will now be in yellow")
-fmt.Printf("This one %s\n", "too")
-
-color.Unset() // Don't forget to unset
-
-// You can mix up parameters
-color.Set(color.FgMagenta, color.Bold)
-defer color.Unset() // Use it in your function
-
-fmt.Println("All text will now be bold magenta.")
-```
-
-### Disable color
-
-There might be a case where you want to disable color output (for example to
-pipe the standard output of your app to somewhere else). `Color` has support to
-disable colors both globally and for single color definition. For example
-suppose you have a CLI app and a `--no-color` bool flag. You can easily disable
-the color output with:
-
-```go
-
-var flagNoColor = flag.Bool("no-color", false, "Disable color output")
-
-if *flagNoColor {
- color.NoColor = true // disables colorized output
-}
-```
-
-It also has support for single color definitions (local). You can
-disable/enable color output on the fly:
-
-```go
-c := color.New(color.FgCyan)
-c.Println("Prints cyan text")
-
-c.DisableColor()
-c.Println("This is printed without any color")
-
-c.EnableColor()
-c.Println("This prints again cyan...")
-```
-
-## Todo
-
-* Save/Return previous values
-* Evaluate fmt.Formatter interface
-
-
-## Credits
-
- * [Fatih Arslan](https://github.com/fatih)
- * Windows support via @mattn: [colorable](https://github.com/mattn/go-colorable)
-
-## License
-
-The MIT License (MIT) - see [`LICENSE.md`](https://github.com/fatih/color/blob/master/LICENSE.md) for more details
-
diff --git a/vendor/github.com/fatih/color/color.go b/vendor/github.com/fatih/color/color.go
deleted file mode 100644
index 34cd8e4c8a..0000000000
--- a/vendor/github.com/fatih/color/color.go
+++ /dev/null
@@ -1,525 +0,0 @@
-package color
-
-import (
- "fmt"
- "io"
- "os"
- "strconv"
- "strings"
- "sync"
-
- "github.com/mattn/go-colorable"
- "github.com/mattn/go-isatty"
-)
-
-var (
- // NoColor defines if the output is colorized or not. It's dynamically set to
- // false or true based on the stdout's file descriptor referring to a terminal
- // or not. This is a global option and affects all colors. For more control
- // over each color block use the methods DisableColor() individually.
- NoColor = !isatty.IsTerminal(os.Stdout.Fd()) || os.Getenv("TERM") == "dumb"
-
- // Output defines the standard output of the print functions. By default
- // os.Stdout is used.
- Output = colorable.NewColorableStdout()
-
- // colorsCache is used to reduce the count of created Color objects and
- // allows to reuse already created objects with required Attribute.
- colorsCache = make(map[Attribute]*Color)
- colorsCacheMu sync.Mutex // protects colorsCache
-)
-
-// Color defines a custom color object which is defined by SGR parameters.
-type Color struct {
- params []Attribute
- noColor *bool
-}
-
-// Attribute defines a single SGR Code
-type Attribute int
-
-const escape = "\x1b"
-
-// Base attributes
-const (
- Reset Attribute = iota
- Bold
- Faint
- Italic
- Underline
- BlinkSlow
- BlinkRapid
- ReverseVideo
- Concealed
- CrossedOut
-)
-
-// Foreground text colors
-const (
- FgBlack Attribute = iota + 30
- FgRed
- FgGreen
- FgYellow
- FgBlue
- FgMagenta
- FgCyan
- FgWhite
-)
-
-// Foreground Hi-Intensity text colors
-const (
- FgHiBlack Attribute = iota + 90
- FgHiRed
- FgHiGreen
- FgHiYellow
- FgHiBlue
- FgHiMagenta
- FgHiCyan
- FgHiWhite
-)
-
-// Background text colors
-const (
- BgBlack Attribute = iota + 40
- BgRed
- BgGreen
- BgYellow
- BgBlue
- BgMagenta
- BgCyan
- BgWhite
-)
-
-// Background Hi-Intensity text colors
-const (
- BgHiBlack Attribute = iota + 100
- BgHiRed
- BgHiGreen
- BgHiYellow
- BgHiBlue
- BgHiMagenta
- BgHiCyan
- BgHiWhite
-)
-
-// New returns a newly created color object.
-func New(value ...Attribute) *Color {
- c := &Color{params: make([]Attribute, 0)}
- c.Add(value...)
- return c
-}
-
-// Set sets the given parameters immediately. It will change the color of
-// output with the given SGR parameters until color.Unset() is called.
-func Set(p ...Attribute) *Color {
- c := New(p...)
- c.Set()
- return c
-}
-
-// Unset resets all escape attributes and clears the output. Usually should
-// be called after Set().
-func Unset() {
- if NoColor {
- return
- }
-
- fmt.Fprintf(Output, "%s[%dm", escape, Reset)
-}
-
-// Set sets the SGR sequence.
-func (c *Color) Set() *Color {
- if c.isNoColorSet() {
- return c
- }
-
- fmt.Fprintf(Output, c.format())
- return c
-}
-
-func (c *Color) unset() {
- if c.isNoColorSet() {
- return
- }
-
- Unset()
-}
-
-func (c *Color) setWriter(w io.Writer) *Color {
- if c.isNoColorSet() {
- return c
- }
-
- fmt.Fprintf(w, c.format())
- return c
-}
-
-func (c *Color) unsetWriter(w io.Writer) {
- if c.isNoColorSet() {
- return
- }
-
- if NoColor {
- return
- }
-
- fmt.Fprintf(w, "%s[%dm", escape, Reset)
-}
-
-// Add is used to chain SGR parameters. Use as many as parameters to combine
-// and create custom color objects. Example: Add(color.FgRed, color.Underline).
-func (c *Color) Add(value ...Attribute) *Color {
- c.params = append(c.params, value...)
- return c
-}
-
-func (c *Color) prepend(value Attribute) {
- c.params = append(c.params, 0)
- copy(c.params[1:], c.params[0:])
- c.params[0] = value
-}
-
-// Fprint formats using the default formats for its operands and writes to w.
-// Spaces are added between operands when neither is a string.
-// It returns the number of bytes written and any write error encountered.
-// On Windows, users should wrap w with colorable.NewColorable() if w is of
-// type *os.File.
-func (c *Color) Fprint(w io.Writer, a ...interface{}) (n int, err error) {
- c.setWriter(w)
- defer c.unsetWriter(w)
-
- return fmt.Fprint(w, a...)
-}
-
-// Print formats using the default formats for its operands and writes to
-// standard output. Spaces are added between operands when neither is a
-// string. It returns the number of bytes written and any write error
-// encountered. This is the standard fmt.Print() method wrapped with the given
-// color.
-func (c *Color) Print(a ...interface{}) (n int, err error) {
- c.Set()
- defer c.unset()
-
- return fmt.Fprint(Output, a...)
-}
-
-// Fprintf formats according to a format specifier and writes to w.
-// It returns the number of bytes written and any write error encountered.
-// On Windows, users should wrap w with colorable.NewColorable() if w is of
-// type *os.File.
-func (c *Color) Fprintf(w io.Writer, format string, a ...interface{}) (n int, err error) {
- c.setWriter(w)
- defer c.unsetWriter(w)
-
- return fmt.Fprintf(w, format, a...)
-}
-
-// Printf formats according to a format specifier and writes to standard output.
-// It returns the number of bytes written and any write error encountered.
-// This is the standard fmt.Printf() method wrapped with the given color.
-func (c *Color) Printf(format string, a ...interface{}) (n int, err error) {
- c.Set()
- defer c.unset()
-
- return fmt.Fprintf(Output, format, a...)
-}
-
-// Fprintln formats using the default formats for its operands and writes to w.
-// Spaces are always added between operands and a newline is appended.
-// On Windows, users should wrap w with colorable.NewColorable() if w is of
-// type *os.File.
-func (c *Color) Fprintln(w io.Writer, a ...interface{}) (n int, err error) {
- c.setWriter(w)
- defer c.unsetWriter(w)
-
- return fmt.Fprintln(w, a...)
-}
-
-// Println formats using the default formats for its operands and writes to
-// standard output. Spaces are always added between operands and a newline is
-// appended. It returns the number of bytes written and any write error
-// encountered. This is the standard fmt.Print() method wrapped with the given
-// color.
-func (c *Color) Println(a ...interface{}) (n int, err error) {
- c.Set()
- defer c.unset()
-
- return fmt.Fprintln(Output, a...)
-}
-
-// Sprint is just like Print, but returns a string instead of printing it.
-func (c *Color) Sprint(a ...interface{}) string {
- return c.wrap(fmt.Sprint(a...))
-}
-
-// Sprintln is just like Println, but returns a string instead of printing it.
-func (c *Color) Sprintln(a ...interface{}) string {
- return c.wrap(fmt.Sprintln(a...))
-}
-
-// Sprintf is just like Printf, but returns a string instead of printing it.
-func (c *Color) Sprintf(format string, a ...interface{}) string {
- return c.wrap(fmt.Sprintf(format, a...))
-}
-
-// FprintFunc returns a new function that prints the passed arguments as
-// colorized with color.Fprint().
-func (c *Color) FprintFunc() func(w io.Writer, a ...interface{}) {
- return func(w io.Writer, a ...interface{}) {
- c.Fprint(w, a...)
- }
-}
-
-// PrintFunc returns a new function that prints the passed arguments as
-// colorized with color.Print().
-func (c *Color) PrintFunc() func(a ...interface{}) {
- return func(a ...interface{}) {
- c.Print(a...)
- }
-}
-
-// FprintfFunc returns a new function that prints the passed arguments as
-// colorized with color.Fprintf().
-func (c *Color) FprintfFunc() func(w io.Writer, format string, a ...interface{}) {
- return func(w io.Writer, format string, a ...interface{}) {
- c.Fprintf(w, format, a...)
- }
-}
-
-// PrintfFunc returns a new function that prints the passed arguments as
-// colorized with color.Printf().
-func (c *Color) PrintfFunc() func(format string, a ...interface{}) {
- return func(format string, a ...interface{}) {
- c.Printf(format, a...)
- }
-}
-
-// FprintlnFunc returns a new function that prints the passed arguments as
-// colorized with color.Fprintln().
-func (c *Color) FprintlnFunc() func(w io.Writer, a ...interface{}) {
- return func(w io.Writer, a ...interface{}) {
- c.Fprintln(w, a...)
- }
-}
-
-// PrintlnFunc returns a new function that prints the passed arguments as
-// colorized with color.Println().
-func (c *Color) PrintlnFunc() func(a ...interface{}) {
- return func(a ...interface{}) {
- c.Println(a...)
- }
-}
-
-// SprintFunc returns a new function that returns colorized strings for the
-// given arguments with fmt.Sprint(). Useful to put into or mix into other
-// string. Windows users should use this in conjunction with color.Output, example:
-//
-// put := New(FgYellow).SprintFunc()
-// fmt.Fprintf(color.Output, "This is a %s", put("warning"))
-func (c *Color) SprintFunc() func(a ...interface{}) string {
- return func(a ...interface{}) string {
- return c.wrap(fmt.Sprint(a...))
- }
-}
-
-// SprintfFunc returns a new function that returns colorized strings for the
-// given arguments with fmt.Sprintf(). Useful to put into or mix into other
-// string. Windows users should use this in conjunction with color.Output.
-func (c *Color) SprintfFunc() func(format string, a ...interface{}) string {
- return func(format string, a ...interface{}) string {
- return c.wrap(fmt.Sprintf(format, a...))
- }
-}
-
-// SprintlnFunc returns a new function that returns colorized strings for the
-// given arguments with fmt.Sprintln(). Useful to put into or mix into other
-// string. Windows users should use this in conjunction with color.Output.
-func (c *Color) SprintlnFunc() func(a ...interface{}) string {
- return func(a ...interface{}) string {
- return c.wrap(fmt.Sprintln(a...))
- }
-}
-
-// sequence returns a formated SGR sequence to be plugged into a "\x1b[...m"
-// an example output might be: "1;36" -> bold cyan
-func (c *Color) sequence() string {
- format := make([]string, len(c.params))
- for i, v := range c.params {
- format[i] = strconv.Itoa(int(v))
- }
-
- return strings.Join(format, ";")
-}
-
-// wrap wraps the s string with the colors attributes. The string is ready to
-// be printed.
-func (c *Color) wrap(s string) string {
- if c.isNoColorSet() {
- return s
- }
-
- return c.format() + s + c.unformat()
-}
-
-func (c *Color) format() string {
- return fmt.Sprintf("%s[%sm", escape, c.sequence())
-}
-
-func (c *Color) unformat() string {
- return fmt.Sprintf("%s[%dm", escape, Reset)
-}
-
-// DisableColor disables the color output. Useful to not change any existing
-// code and still being able to output. Can be used for flags like
-// "--no-color". To enable back use EnableColor() method.
-func (c *Color) DisableColor() {
- c.noColor = boolPtr(true)
-}
-
-// EnableColor enables the color output. Use it in conjunction with
-// DisableColor(). Otherwise this method has no side effects.
-func (c *Color) EnableColor() {
- c.noColor = boolPtr(false)
-}
-
-func (c *Color) isNoColorSet() bool {
- // check first if we have user setted action
- if c.noColor != nil {
- return *c.noColor
- }
-
- // if not return the global option, which is disabled by default
- return NoColor
-}
-
-// Equals returns a boolean value indicating whether two colors are equal.
-func (c *Color) Equals(c2 *Color) bool {
- if len(c.params) != len(c2.params) {
- return false
- }
-
- for _, attr := range c.params {
- if !c2.attrExists(attr) {
- return false
- }
- }
-
- return true
-}
-
-func (c *Color) attrExists(a Attribute) bool {
- for _, attr := range c.params {
- if attr == a {
- return true
- }
- }
-
- return false
-}
-
-func boolPtr(v bool) *bool {
- return &v
-}
-
-func getCachedColor(p Attribute) *Color {
- colorsCacheMu.Lock()
- defer colorsCacheMu.Unlock()
-
- c, ok := colorsCache[p]
- if !ok {
- c = New(p)
- colorsCache[p] = c
- }
-
- return c
-}
-
-func colorPrint(format string, p Attribute, a ...interface{}) {
- c := getCachedColor(p)
-
- if !strings.HasSuffix(format, "\n") {
- format += "\n"
- }
-
- if len(a) == 0 {
- c.Print(format)
- } else {
- c.Printf(format, a...)
- }
-}
-
-func colorString(format string, p Attribute, a ...interface{}) string {
- c := getCachedColor(p)
-
- if len(a) == 0 {
- return c.SprintFunc()(format)
- }
-
- return c.SprintfFunc()(format, a...)
-}
-
-// Black is an convenient helper function to print with black foreground. A
-// newline is appended to format by default.
-func Black(format string, a ...interface{}) { colorPrint(format, FgBlack, a...) }
-
-// Red is an convenient helper function to print with red foreground. A
-// newline is appended to format by default.
-func Red(format string, a ...interface{}) { colorPrint(format, FgRed, a...) }
-
-// Green is an convenient helper function to print with green foreground. A
-// newline is appended to format by default.
-func Green(format string, a ...interface{}) { colorPrint(format, FgGreen, a...) }
-
-// Yellow is an convenient helper function to print with yellow foreground.
-// A newline is appended to format by default.
-func Yellow(format string, a ...interface{}) { colorPrint(format, FgYellow, a...) }
-
-// Blue is an convenient helper function to print with blue foreground. A
-// newline is appended to format by default.
-func Blue(format string, a ...interface{}) { colorPrint(format, FgBlue, a...) }
-
-// Magenta is an convenient helper function to print with magenta foreground.
-// A newline is appended to format by default.
-func Magenta(format string, a ...interface{}) { colorPrint(format, FgMagenta, a...) }
-
-// Cyan is an convenient helper function to print with cyan foreground. A
-// newline is appended to format by default.
-func Cyan(format string, a ...interface{}) { colorPrint(format, FgCyan, a...) }
-
-// White is an convenient helper function to print with white foreground. A
-// newline is appended to format by default.
-func White(format string, a ...interface{}) { colorPrint(format, FgWhite, a...) }
-
-// BlackString is an convenient helper function to return a string with black
-// foreground.
-func BlackString(format string, a ...interface{}) string { return colorString(format, FgBlack, a...) }
-
-// RedString is an convenient helper function to return a string with red
-// foreground.
-func RedString(format string, a ...interface{}) string { return colorString(format, FgRed, a...) }
-
-// GreenString is an convenient helper function to return a string with green
-// foreground.
-func GreenString(format string, a ...interface{}) string { return colorString(format, FgGreen, a...) }
-
-// YellowString is an convenient helper function to return a string with yellow
-// foreground.
-func YellowString(format string, a ...interface{}) string { return colorString(format, FgYellow, a...) }
-
-// BlueString is an convenient helper function to return a string with blue
-// foreground.
-func BlueString(format string, a ...interface{}) string { return colorString(format, FgBlue, a...) }
-
-// MagentaString is an convenient helper function to return a string with magenta
-// foreground.
-func MagentaString(format string, a ...interface{}) string {
- return colorString(format, FgMagenta, a...)
-}
-
-// CyanString is an convenient helper function to return a string with cyan
-// foreground.
-func CyanString(format string, a ...interface{}) string { return colorString(format, FgCyan, a...) }
-
-// WhiteString is an convenient helper function to return a string with white
-// foreground.
-func WhiteString(format string, a ...interface{}) string { return colorString(format, FgWhite, a...) }
diff --git a/vendor/github.com/fatih/color/doc.go b/vendor/github.com/fatih/color/doc.go
deleted file mode 100644
index 1e57812d7c..0000000000
--- a/vendor/github.com/fatih/color/doc.go
+++ /dev/null
@@ -1,128 +0,0 @@
-/*
-Package color is an ANSI color package to output colorized or SGR defined
-output to the standard output. The API can be used in several way, pick one
-that suits you.
-
-Use simple and default helper functions with predefined foreground colors:
-
- color.Cyan("Prints text in cyan.")
-
- // a newline will be appended automatically
- color.Blue("Prints %s in blue.", "text")
-
- // More default foreground colors..
- color.Red("We have red")
- color.Yellow("Yellow color too!")
- color.Magenta("And many others ..")
-
-However there are times where custom color mixes are required. Below are some
-examples to create custom color objects and use the print functions of each
-separate color object.
-
- // Create a new color object
- c := color.New(color.FgCyan).Add(color.Underline)
- c.Println("Prints cyan text with an underline.")
-
- // Or just add them to New()
- d := color.New(color.FgCyan, color.Bold)
- d.Printf("This prints bold cyan %s\n", "too!.")
-
-
- // Mix up foreground and background colors, create new mixes!
- red := color.New(color.FgRed)
-
- boldRed := red.Add(color.Bold)
- boldRed.Println("This will print text in bold red.")
-
- whiteBackground := red.Add(color.BgWhite)
- whiteBackground.Println("Red text with White background.")
-
- // Use your own io.Writer output
- color.New(color.FgBlue).Fprintln(myWriter, "blue color!")
-
- blue := color.New(color.FgBlue)
- blue.Fprint(myWriter, "This will print text in blue.")
-
-You can create PrintXxx functions to simplify even more:
-
- // Create a custom print function for convenient
- red := color.New(color.FgRed).PrintfFunc()
- red("warning")
- red("error: %s", err)
-
- // Mix up multiple attributes
- notice := color.New(color.Bold, color.FgGreen).PrintlnFunc()
- notice("don't forget this...")
-
-You can also FprintXxx functions to pass your own io.Writer:
-
- blue := color.New(FgBlue).FprintfFunc()
- blue(myWriter, "important notice: %s", stars)
-
- // Mix up with multiple attributes
- success := color.New(color.Bold, color.FgGreen).FprintlnFunc()
- success(myWriter, don't forget this...")
-
-
-Or create SprintXxx functions to mix strings with other non-colorized strings:
-
- yellow := New(FgYellow).SprintFunc()
- red := New(FgRed).SprintFunc()
-
- fmt.Printf("this is a %s and this is %s.\n", yellow("warning"), red("error"))
-
- info := New(FgWhite, BgGreen).SprintFunc()
- fmt.Printf("this %s rocks!\n", info("package"))
-
-Windows support is enabled by default. All Print functions works as intended.
-However only for color.SprintXXX functions, user should use fmt.FprintXXX and
-set the output to color.Output:
-
- fmt.Fprintf(color.Output, "Windows support: %s", color.GreenString("PASS"))
-
- info := New(FgWhite, BgGreen).SprintFunc()
- fmt.Fprintf(color.Output, "this %s rocks!\n", info("package"))
-
-Using with existing code is possible. Just use the Set() method to set the
-standard output to the given parameters. That way a rewrite of an existing
-code is not required.
-
- // Use handy standard colors.
- color.Set(color.FgYellow)
-
- fmt.Println("Existing text will be now in Yellow")
- fmt.Printf("This one %s\n", "too")
-
- color.Unset() // don't forget to unset
-
- // You can mix up parameters
- color.Set(color.FgMagenta, color.Bold)
- defer color.Unset() // use it in your function
-
- fmt.Println("All text will be now bold magenta.")
-
-There might be a case where you want to disable color output (for example to
-pipe the standard output of your app to somewhere else). `Color` has support to
-disable colors both globally and for single color definition. For example
-suppose you have a CLI app and a `--no-color` bool flag. You can easily disable
-the color output with:
-
- var flagNoColor = flag.Bool("no-color", false, "Disable color output")
-
- if *flagNoColor {
- color.NoColor = true // disables colorized output
- }
-
-It also has support for single color definitions (local). You can
-disable/enable color output on the fly:
-
- c := color.New(color.FgCyan)
- c.Println("Prints cyan text")
-
- c.DisableColor()
- c.Println("This is printed without any color")
-
- c.EnableColor()
- c.Println("This prints again cyan...")
-*/
-package color
diff --git a/vendor/github.com/fjl/memsize/LICENSE b/vendor/github.com/fjl/memsize/LICENSE
deleted file mode 100644
index 8b80456419..0000000000
--- a/vendor/github.com/fjl/memsize/LICENSE
+++ /dev/null
@@ -1,21 +0,0 @@
-MIT License
-
-Copyright (c) 2018 Felix Lange
-
-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/vendor/github.com/fjl/memsize/bitmap.go b/vendor/github.com/fjl/memsize/bitmap.go
deleted file mode 100644
index 47799ea8d3..0000000000
--- a/vendor/github.com/fjl/memsize/bitmap.go
+++ /dev/null
@@ -1,119 +0,0 @@
-package memsize
-
-import (
- "math/bits"
-)
-
-const (
- uintptrBits = 32 << (uint64(^uintptr(0)) >> 63)
- uintptrBytes = uintptrBits / 8
- bmBlockRange = 1 * 1024 * 1024 // bytes covered by bmBlock
- bmBlockWords = bmBlockRange / uintptrBits
-)
-
-// bitmap is a sparse bitmap.
-type bitmap struct {
- blocks map[uintptr]*bmBlock
-}
-
-func newBitmap() *bitmap {
- return &bitmap{make(map[uintptr]*bmBlock)}
-}
-
-// markRange sets n consecutive bits starting at addr.
-func (b *bitmap) markRange(addr, n uintptr) {
- for end := addr + n; addr < end; {
- block, baddr := b.block(addr)
- for i := baddr; i < bmBlockRange && addr < end; i++ {
- block.mark(i)
- addr++
- }
- }
-}
-
-// isMarked returns the value of the bit at the given address.
-func (b *bitmap) isMarked(addr uintptr) bool {
- block, baddr := b.block(addr)
- return block.isMarked(baddr)
-}
-
-// countRange returns the number of set bits in the range (addr,addr+n).
-func (b *bitmap) countRange(addr, n uintptr) uintptr {
- c := uintptr(0)
- for end := addr + n; addr < end; {
- block, baddr := b.block(addr)
- bend := uintptr(bmBlockRange - 1)
- if baddr+(end-addr) < bmBlockRange {
- bend = baddr + (end - addr)
- }
- c += uintptr(block.count(baddr, bend))
- // Move addr to next block.
- addr += bmBlockRange - baddr
- }
- return c
-}
-
-// block finds the block corresponding to the given memory address.
-// It also returns the block's starting address.
-func (b *bitmap) block(addr uintptr) (*bmBlock, uintptr) {
- index := addr / bmBlockRange
- block := b.blocks[index]
- if block == nil {
- block = new(bmBlock)
- b.blocks[index] = block
- }
- return block, addr % bmBlockRange
-}
-
-// size returns the sum of the byte sizes of all blocks.
-func (b *bitmap) size() uintptr {
- return uintptr(len(b.blocks)) * bmBlockWords * uintptrBytes
-}
-
-// utilization returns the mean percentage of one bits across all blocks.
-func (b *bitmap) utilization() float32 {
- var avg float32
- for _, block := range b.blocks {
- avg += float32(block.count(0, bmBlockRange-1)) / float32(bmBlockRange)
- }
- return avg / float32(len(b.blocks))
-}
-
-// bmBlock is a bitmap block.
-type bmBlock [bmBlockWords]uintptr
-
-// mark sets the i'th bit to one.
-func (b *bmBlock) mark(i uintptr) {
- b[i/uintptrBits] |= 1 << (i % uintptrBits)
-}
-
-// isMarked returns the value of the i'th bit.
-func (b *bmBlock) isMarked(i uintptr) bool {
- return (b[i/uintptrBits] & (1 << (i % uintptrBits))) != 0
-}
-
-// count returns the number of set bits in the range (start,end).
-func (b *bmBlock) count(start, end uintptr) (count int) {
- br := b[start/uintptrBits : end/uintptrBits+1]
- for i, w := range br {
- if i == 0 {
- w &= blockmask(start)
- }
- if i == len(br)-1 {
- w &^= blockmask(end)
- }
- count += onesCountPtr(w)
- }
- return count
-}
-
-func blockmask(x uintptr) uintptr {
- return ^uintptr(0) << (x % uintptrBits)
-}
-
-func onesCountPtr(x uintptr) int {
- if uintptrBits == 64 {
- return bits.OnesCount64(uint64(x))
- }
- return bits.OnesCount32(uint32(x))
-}
diff --git a/vendor/github.com/fjl/memsize/doc.go b/vendor/github.com/fjl/memsize/doc.go
deleted file mode 100644
index 640cfba5eb..0000000000
--- a/vendor/github.com/fjl/memsize/doc.go
+++ /dev/null
@@ -1,16 +0,0 @@
-/*
-Package memsize computes the size of your object graph.
-
-So you made a spiffy algorithm and it works really well, but geez it's using
-way too much memory. Where did it all go? memsize to the rescue!
-
-To get started, find a value that references all your objects and scan it.
-This traverses the graph, counting sizes per type.
-
- sizes := memsize.Scan(myValue)
- fmt.Println(sizes.Total)
-
-memsize can handle cycles just fine and tracks both private and public struct fields.
-Unfortunately function closures cannot be inspected in any way.
-*/
-package memsize
diff --git a/vendor/github.com/fjl/memsize/memsize.go b/vendor/github.com/fjl/memsize/memsize.go
deleted file mode 100644
index 2664e87c46..0000000000
--- a/vendor/github.com/fjl/memsize/memsize.go
+++ /dev/null
@@ -1,243 +0,0 @@
-package memsize
-
-import (
- "bytes"
- "fmt"
- "reflect"
- "sort"
- "strings"
- "text/tabwriter"
- "unsafe"
-)
-
-// Scan traverses all objects reachable from v and counts how much memory
-// is used per type. The value must be a non-nil pointer to any value.
-func Scan(v interface{}) Sizes {
- rv := reflect.ValueOf(v)
- if rv.Kind() != reflect.Ptr || rv.IsNil() {
- panic("value to scan must be non-nil pointer")
- }
-
- stopTheWorld("memsize scan")
- defer startTheWorld()
-
- ctx := newContext()
- ctx.scan(invalidAddr, rv, false)
- ctx.s.BitmapSize = ctx.seen.size()
- ctx.s.BitmapUtilization = ctx.seen.utilization()
- return *ctx.s
-}
-
-// Sizes is the result of a scan.
-type Sizes struct {
- Total uintptr
- ByType map[reflect.Type]*TypeSize
- // Internal stats (for debugging)
- BitmapSize uintptr
- BitmapUtilization float32
-}
-
-type TypeSize struct {
- Total uintptr
- Count uintptr
-}
-
-func newSizes() *Sizes {
- return &Sizes{ByType: make(map[reflect.Type]*TypeSize)}
-}
-
-// Report returns a human-readable report.
-func (s Sizes) Report() string {
- type typLine struct {
- name string
- count uintptr
- total uintptr
- }
- tab := []typLine{{"ALL", 0, s.Total}}
- for _, typ := range s.ByType {
- tab[0].count += typ.Count
- }
- maxname := 0
- for typ, s := range s.ByType {
- line := typLine{typ.String(), s.Count, s.Total}
- tab = append(tab, line)
- if len(line.name) > maxname {
- maxname = len(line.name)
- }
- }
- sort.Slice(tab, func(i, j int) bool { return tab[i].total > tab[j].total })
-
- buf := new(bytes.Buffer)
- w := tabwriter.NewWriter(buf, 0, 0, 0, ' ', tabwriter.AlignRight)
- for _, line := range tab {
- namespace := strings.Repeat(" ", maxname-len(line.name))
- fmt.Fprintf(w, "%s%s\t %v\t %s\t\n", line.name, namespace, line.count, HumanSize(line.total))
- }
- w.Flush()
- return buf.String()
-}
-
-// addValue is called during scan and adds the memory of given object.
-func (s *Sizes) addValue(v reflect.Value, size uintptr) {
- s.Total += size
- rs := s.ByType[v.Type()]
- if rs == nil {
- rs = new(TypeSize)
- s.ByType[v.Type()] = rs
- }
- rs.Total += size
- rs.Count++
-}
-
-type context struct {
- // We track previously scanned objects to prevent infinite loops
- // when scanning cycles and to prevent counting objects more than once.
- seen *bitmap
- tc typCache
- s *Sizes
-}
-
-func newContext() *context {
- return &context{seen: newBitmap(), tc: make(typCache), s: newSizes()}
-}
-
-// scan walks all objects below v, determining their size. All scan* functions return the
-// amount of 'extra' memory (e.g. slice data) that is referenced by the object.
-func (c *context) scan(addr address, v reflect.Value, add bool) (extraSize uintptr) {
- size := v.Type().Size()
- var marked uintptr
- if addr.valid() {
- marked = c.seen.countRange(uintptr(addr), size)
- if marked == size {
- return 0 // Skip if we have already seen the whole object.
- }
- c.seen.markRange(uintptr(addr), size)
- }
- // fmt.Printf("%v: %v ⮑ (marked %d)\n", addr, v.Type(), marked)
- if c.tc.needScan(v.Type()) {
- extraSize = c.scanContent(addr, v)
- }
- // fmt.Printf("%v: %v %d (add %v, size %d, marked %d, extra %d)\n", addr, v.Type(), size+extraSize, add, v.Type().Size(), marked, extraSize)
- if add {
- size -= marked
- size += extraSize
- c.s.addValue(v, size)
- }
- return extraSize
-}
-
-func (c *context) scanContent(addr address, v reflect.Value) uintptr {
- switch v.Kind() {
- case reflect.Array:
- return c.scanArray(addr, v)
- case reflect.Chan:
- return c.scanChan(v)
- case reflect.Func:
- // can't do anything here
- return 0
- case reflect.Interface:
- return c.scanInterface(v)
- case reflect.Map:
- return c.scanMap(v)
- case reflect.Ptr:
- if !v.IsNil() {
- c.scan(address(v.Pointer()), v.Elem(), true)
- }
- return 0
- case reflect.Slice:
- return c.scanSlice(v)
- case reflect.String:
- return uintptr(v.Len())
- case reflect.Struct:
- return c.scanStruct(addr, v)
- default:
- unhandledKind(v.Kind())
- return 0
- }
-}
-
-func (c *context) scanChan(v reflect.Value) uintptr {
- etyp := v.Type().Elem()
- extra := uintptr(0)
- if c.tc.needScan(etyp) {
- // Scan the channel buffer. This is unsafe but doesn't race because
- // the world is stopped during scan.
- hchan := unsafe.Pointer(v.Pointer())
- for i := uint(0); i < uint(v.Cap()); i++ {
- addr := chanbuf(hchan, i)
- elem := reflect.NewAt(etyp, addr).Elem()
- extra += c.scanContent(address(addr), elem)
- }
- }
- return uintptr(v.Cap())*etyp.Size() + extra
-}
-
-func (c *context) scanStruct(base address, v reflect.Value) uintptr {
- extra := uintptr(0)
- for i := 0; i < v.NumField(); i++ {
- f := v.Type().Field(i)
- if c.tc.needScan(f.Type) {
- addr := base.addOffset(f.Offset)
- extra += c.scanContent(addr, v.Field(i))
- }
- }
- return extra
-}
-
-func (c *context) scanArray(addr address, v reflect.Value) uintptr {
- esize := v.Type().Elem().Size()
- extra := uintptr(0)
- for i := 0; i < v.Len(); i++ {
- extra += c.scanContent(addr, v.Index(i))
- addr = addr.addOffset(esize)
- }
- return extra
-}
-
-func (c *context) scanSlice(v reflect.Value) uintptr {
- slice := v.Slice(0, v.Cap())
- esize := slice.Type().Elem().Size()
- base := slice.Pointer()
- // Add size of the unscanned portion of the backing array to extra.
- blen := uintptr(slice.Len()) * esize
- marked := c.seen.countRange(base, blen)
- extra := blen - marked
- c.seen.markRange(uintptr(base), blen)
- if c.tc.needScan(slice.Type().Elem()) {
- // Elements may contain pointers, scan them individually.
- addr := address(base)
- for i := 0; i < slice.Len(); i++ {
- extra += c.scanContent(addr, slice.Index(i))
- addr = addr.addOffset(esize)
- }
- }
- return extra
-}
-
-func (c *context) scanMap(v reflect.Value) uintptr {
- var (
- typ = v.Type()
- len = uintptr(v.Len())
- extra = uintptr(0)
- )
- if c.tc.needScan(typ.Key()) || c.tc.needScan(typ.Elem()) {
- for _, k := range v.MapKeys() {
- extra += c.scan(invalidAddr, k, false)
- extra += c.scan(invalidAddr, v.MapIndex(k), false)
- }
- }
- return len*typ.Key().Size() + len*typ.Elem().Size() + extra
-}
-
-func (c *context) scanInterface(v reflect.Value) uintptr {
- elem := v.Elem()
- if !elem.IsValid() {
- return 0 // nil interface
- }
- c.scan(invalidAddr, elem, false)
- if !c.tc.isPointer(elem.Type()) {
- // Account for non-pointer size of the value.
- return elem.Type().Size()
- }
- return 0
-}
diff --git a/vendor/github.com/fjl/memsize/memsizeui/template.go b/vendor/github.com/fjl/memsize/memsizeui/template.go
deleted file mode 100644
index b60fe6ba54..0000000000
--- a/vendor/github.com/fjl/memsize/memsizeui/template.go
+++ /dev/null
@@ -1,106 +0,0 @@
-package memsizeui
-
-import (
- "html/template"
- "strconv"
- "sync"
-
- "github.com/fjl/memsize"
-)
-
-var (
- base *template.Template // the "base" template
- baseInitOnce sync.Once
-)
-
-func baseInit() {
- base = template.Must(template.New("base").Parse(`
-
-
-
- memsize
-
-
-
- {{template "content" .}}
-
-`))
-
- base.Funcs(template.FuncMap{
- "quote": strconv.Quote,
- "humansize": memsize.HumanSize,
- })
-
- template.Must(base.New("rootbuttons").Parse(`
-Overview
-{{- range $root := .Roots -}}
-
-{{- end -}}`))
-}
-
-func contentTemplate(source string) *template.Template {
- baseInitOnce.Do(baseInit)
- t := template.Must(base.Clone())
- template.Must(t.New("content").Parse(source))
- return t
-}
-
-var rootTemplate = contentTemplate(`
-Memsize
-{{template "rootbuttons" .}}
-
-Reports
-
-`)
-
-var notFoundTemplate = contentTemplate(`
-{{.Data}}
-{{template "rootbuttons" .}}
-`)
-
-var reportTemplate = contentTemplate(`
-{{- $report := .Data -}}
-Memsize Report {{$report.ID}}
-
-
-Root: {{quote $report.RootName}}
-Date: {{$report.Date}}
-Duration: {{$report.Duration}}
-Bitmap Size: {{$report.Sizes.BitmapSize | humansize}}
-Bitmap Utilization: {{$report.Sizes.BitmapUtilization}}
-
-
-
-{{$report.Sizes.Report}}
-
-`)
diff --git a/vendor/github.com/fjl/memsize/memsizeui/ui.go b/vendor/github.com/fjl/memsize/memsizeui/ui.go
deleted file mode 100644
index c48fc53f7f..0000000000
--- a/vendor/github.com/fjl/memsize/memsizeui/ui.go
+++ /dev/null
@@ -1,153 +0,0 @@
-package memsizeui
-
-import (
- "bytes"
- "fmt"
- "html/template"
- "net/http"
- "reflect"
- "sort"
- "strings"
- "sync"
- "time"
-
- "github.com/fjl/memsize"
-)
-
-type Handler struct {
- init sync.Once
- mux http.ServeMux
- mu sync.Mutex
- reports map[int]Report
- roots map[string]interface{}
- reportID int
-}
-
-type Report struct {
- ID int
- Date time.Time
- Duration time.Duration
- RootName string
- Sizes memsize.Sizes
-}
-
-type templateInfo struct {
- Roots []string
- Reports map[int]Report
- PathDepth int
- Data interface{}
-}
-
-func (ti *templateInfo) Link(path ...string) string {
- prefix := strings.Repeat("../", ti.PathDepth)
- return prefix + strings.Join(path, "")
-}
-
-func (h *Handler) Add(name string, v interface{}) {
- rv := reflect.ValueOf(v)
- if rv.Kind() != reflect.Ptr || rv.IsNil() {
- panic("root must be non-nil pointer")
- }
- h.mu.Lock()
- if h.roots == nil {
- h.roots = make(map[string]interface{})
- }
- h.roots[name] = v
- h.mu.Unlock()
-}
-
-func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
- h.init.Do(func() {
- h.reports = make(map[int]Report)
- h.mux.HandleFunc("/", h.handleRoot)
- h.mux.HandleFunc("/scan", h.handleScan)
- h.mux.HandleFunc("/report/", h.handleReport)
- })
- h.mux.ServeHTTP(w, r)
-}
-
-func (h *Handler) templateInfo(r *http.Request, data interface{}) *templateInfo {
- h.mu.Lock()
- roots := make([]string, 0, len(h.roots))
- for name := range h.roots {
- roots = append(roots, name)
- }
- h.mu.Unlock()
- sort.Strings(roots)
-
- return &templateInfo{
- Roots: roots,
- Reports: h.reports,
- PathDepth: strings.Count(r.URL.Path, "/") - 1,
- Data: data,
- }
-}
-
-func (h *Handler) handleRoot(w http.ResponseWriter, r *http.Request) {
- if r.URL.Path != "/" {
- http.NotFound(w, r)
- return
- }
- serveHTML(w, rootTemplate, http.StatusOK, h.templateInfo(r, nil))
-}
-
-func (h *Handler) handleScan(w http.ResponseWriter, r *http.Request) {
- if r.Method != http.MethodPost {
- http.Error(w, "invalid HTTP method, want POST", http.StatusMethodNotAllowed)
- return
- }
- ti := h.templateInfo(r, "Unknown root")
- id, ok := h.scan(r.URL.Query().Get("root"))
- if !ok {
- serveHTML(w, notFoundTemplate, http.StatusNotFound, ti)
- return
- }
- w.Header().Add("Location", ti.Link(fmt.Sprintf("report/%d", id)))
- w.WriteHeader(http.StatusSeeOther)
-}
-
-func (h *Handler) handleReport(w http.ResponseWriter, r *http.Request) {
- var id int
- fmt.Sscan(strings.TrimPrefix(r.URL.Path, "/report/"), &id)
- h.mu.Lock()
- report, ok := h.reports[id]
- h.mu.Unlock()
-
- if !ok {
- serveHTML(w, notFoundTemplate, http.StatusNotFound, h.templateInfo(r, "Report not found"))
- } else {
- serveHTML(w, reportTemplate, http.StatusOK, h.templateInfo(r, report))
- }
-}
-
-func (h *Handler) scan(root string) (int, bool) {
- h.mu.Lock()
- defer h.mu.Unlock()
-
- val, ok := h.roots[root]
- if !ok {
- return 0, false
- }
- id := h.reportID
- start := time.Now()
- sizes := memsize.Scan(val)
- h.reports[id] = Report{
- ID: id,
- RootName: root,
- Date: start.Truncate(1 * time.Second),
- Duration: time.Since(start),
- Sizes: sizes,
- }
- h.reportID++
- return id, true
-}
-
-func serveHTML(w http.ResponseWriter, tpl *template.Template, status int, ti *templateInfo) {
- w.Header().Set("content-type", "text/html")
- var buf bytes.Buffer
- if err := tpl.Execute(&buf, ti); err != nil {
- http.Error(w, err.Error(), http.StatusInternalServerError)
- return
- }
- buf.WriteTo(w)
-}
diff --git a/vendor/github.com/fjl/memsize/runtimefunc.go b/vendor/github.com/fjl/memsize/runtimefunc.go
deleted file mode 100644
index 912a3e768d..0000000000
--- a/vendor/github.com/fjl/memsize/runtimefunc.go
+++ /dev/null
@@ -1,14 +0,0 @@
-package memsize
-
-import "unsafe"
-
-var _ = unsafe.Pointer(nil)
-
-//go:linkname stopTheWorld runtime.stopTheWorld
-func stopTheWorld(reason string)
-
-//go:linkname startTheWorld runtime.startTheWorld
-func startTheWorld()
-
-//go:linkname chanbuf runtime.chanbuf
-func chanbuf(ch unsafe.Pointer, i uint) unsafe.Pointer
diff --git a/vendor/github.com/fjl/memsize/runtimefunc.s b/vendor/github.com/fjl/memsize/runtimefunc.s
deleted file mode 100644
index a091e2fa72..0000000000
--- a/vendor/github.com/fjl/memsize/runtimefunc.s
+++ /dev/null
@@ -1 +0,0 @@
-// This file is required to make stub function declarations work.
diff --git a/vendor/github.com/fjl/memsize/type.go b/vendor/github.com/fjl/memsize/type.go
deleted file mode 100644
index 5d6f59e9ff..0000000000
--- a/vendor/github.com/fjl/memsize/type.go
+++ /dev/null
@@ -1,119 +0,0 @@
-package memsize
-
-import (
- "fmt"
- "reflect"
-)
-
-// address is a memory location.
-//
-// Code dealing with uintptr is oblivious to the zero address.
-// Code dealing with address is not: it treats the zero address
-// as invalid. Offsetting an invalid address doesn't do anything.
-//
-// This distinction is useful because there are objects that we can't
-// get the pointer to.
-type address uintptr
-
-const invalidAddr = address(0)
-
-func (a address) valid() bool {
- return a != 0
-}
-
-func (a address) addOffset(off uintptr) address {
- if !a.valid() {
- return invalidAddr
- }
- return a + address(off)
-}
-
-func (a address) String() string {
- if uintptrBits == 32 {
- return fmt.Sprintf("%#0.8x", uintptr(a))
- }
- return fmt.Sprintf("%#0.16x", uintptr(a))
-}
-
-type typCache map[reflect.Type]typInfo
-
-type typInfo struct {
- isPointer bool
- needScan bool
-}
-
-// isPointer returns true for pointer-ish values. The notion of
-// pointer includes everything but plain values, i.e. slices, maps
-// channels, interfaces are 'pointer', too.
-func (tc *typCache) isPointer(typ reflect.Type) bool {
- return tc.info(typ).isPointer
-}
-
-// needScan reports whether a value of the type needs to be scanned
-// recursively because it may contain pointers.
-func (tc *typCache) needScan(typ reflect.Type) bool {
- return tc.info(typ).needScan
-}
-
-func (tc *typCache) info(typ reflect.Type) typInfo {
- info, found := (*tc)[typ]
- switch {
- case found:
- return info
- case isPointer(typ):
- info = typInfo{true, true}
- default:
- info = typInfo{false, tc.checkNeedScan(typ)}
- }
- (*tc)[typ] = info
- return info
-}
-
-func (tc *typCache) checkNeedScan(typ reflect.Type) bool {
- switch k := typ.Kind(); k {
- case reflect.Struct:
- // Structs don't need scan if none of their fields need it.
- for i := 0; i < typ.NumField(); i++ {
- if tc.needScan(typ.Field(i).Type) {
- return true
- }
- }
- case reflect.Array:
- // Arrays don't need scan if their element type doesn't.
- return tc.needScan(typ.Elem())
- }
- return false
-}
-
-func isPointer(typ reflect.Type) bool {
- k := typ.Kind()
- switch {
- case k <= reflect.Complex128:
- return false
- case k == reflect.Array:
- return false
- case k >= reflect.Chan && k <= reflect.String:
- return true
- case k == reflect.Struct || k == reflect.UnsafePointer:
- return false
- default:
- unhandledKind(k)
- return false
- }
-}
-
-func unhandledKind(k reflect.Kind) {
- panic("unhandled kind " + k.String())
-}
-
-// HumanSize formats the given number of bytes as a readable string.
-func HumanSize(bytes uintptr) string {
- switch {
- case bytes < 1024:
- return fmt.Sprintf("%d B", bytes)
- case bytes < 1024*1024:
- return fmt.Sprintf("%.3f KB", float64(bytes)/1024)
- default:
- return fmt.Sprintf("%.3f MB", float64(bytes)/1024/1024)
- }
-}
diff --git a/vendor/github.com/gballet/go-libpcsclite/LICENSE b/vendor/github.com/gballet/go-libpcsclite/LICENSE
deleted file mode 100644
index 52d9e62b07..0000000000
--- a/vendor/github.com/gballet/go-libpcsclite/LICENSE
+++ /dev/null
@@ -1,29 +0,0 @@
-BSD 3-Clause License
-
-Copyright (c) 2019, Guillaume Ballet
-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 copyright holder 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.
diff --git a/vendor/github.com/gballet/go-libpcsclite/README.md b/vendor/github.com/gballet/go-libpcsclite/README.md
deleted file mode 100644
index 182398e39d..0000000000
--- a/vendor/github.com/gballet/go-libpcsclite/README.md
+++ /dev/null
@@ -1,73 +0,0 @@
-# go-libpcsclite
-
-A golang implementation of the [libpcpsclite](http://github.com/LudovicRousseau/PCSC) client. It connects to the `pcscd` daemon over sockets.
-
-## Purpose
-
-The goal is for major open source projects to distribute a single binary that doesn't depend on `libpcsclite`. It provides an extra function `CheckPCSCDaemon` that will tell the user if `pcscd` is running.
-
-## Example
-
-```golang
-func main() {
- client, err := EstablishContext(2)
- if err != nil {
- fmt.Printf("Error establishing context: %v\n", err)
- os.Exit(1)
- }
-
- _, err = client.ListReaders()
- if err != nil {
- fmt.Printf("Error getting the list of readers: %v\n", err)
- os.Exit(1)
- }
-
- card, err := client.Connect(client.readerStateDescriptors[0].Name, ShareShared, ProtocolT0|ProtocolT1)
- if err != nil {
- fmt.Printf("Error connecting: %v\n", err)
- os.Exit(1)
- }
-
- resp, _, err := card.Transmit([]byte{0, 0xa4, 4, 0, 0xA0, 0, 0, 8, 4, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0})
-
- card.Disconnect(LeaveCard)
-}
-```
-
-## TODO
-
- - [x] Finish this README
- - [x] Lock context
- - [ ] implement missing functions
-
-## License
-
-BSD 3-Clause License
-
-Copyright (c) 2019, Guillaume Ballet
-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 copyright holder 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.
diff --git a/vendor/github.com/gballet/go-libpcsclite/doc.go b/vendor/github.com/gballet/go-libpcsclite/doc.go
deleted file mode 100644
index 0f28c0c9c4..0000000000
--- a/vendor/github.com/gballet/go-libpcsclite/doc.go
+++ /dev/null
@@ -1,95 +0,0 @@
-// BSD 3-Clause License
-//
-// Copyright (c) 2019, Guillaume Ballet
-// 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 copyright holder 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 pcsc
-
-const (
- AutoAllocate = -1 /* see SCardFreeMemory() */
- ScopeUser = 0x0000 /* Scope in user space */
- ScopeTerminal = 0x0001 /* Scope in terminal */
- ScopeSystem = 0x0002 /* Scope in system */
- ScopeGlobal = 0x0003 /* Scope is global */
-
- ProtocolUndefined = 0x0000 /* protocol not set */
- ProtocolUnSet = ProtocolUndefined /* backward compat */
- ProtocolT0 = 0x0001 /* T=0 active protocol. */
- ProtocolT1 = 0x0002 /* T=1 active protocol. */
- ProtocolRaw = 0x0004 /* Raw active protocol. */
- ProtocolT15 = 0x0008 /* T=15 protocol. */
- ProtocolAny = (ProtocolT0 | ProtocolT1) /* IFD determines prot. */
-
- ShareExclusive = 0x0001 /* Exclusive mode only */
- ShareShared = 0x0002 /* Shared mode only */
- ShareDirect = 0x0003 /* Raw mode only */
-
- LeaveCard = 0x0000 /* Do nothing on close */
- ResetCard = 0x0001 /* Reset on close */
- UnpowerCard = 0x0002 /* Power down on close */
- EjectCard = 0x0003 /* Eject on close */
-
- SCardUnknown = 0x0001 /* Unknown state */
- SCardAbsent = 0x0002 /* Card is absent */
- SCardPresent = 0x0004 /* Card is present */
- SCardSwallowed = 0x0008 /* Card not powered */
- SCardPowever = 0x0010 /* Card is powered */
- SCardNegotiable = 0x0020 /* Ready for PTS */
- SCardSpecific = 0x0040 /* PTS has been set */
-)
-
-// List of commands to send to the daemon
-const (
- _ = iota
- SCardEstablishContext /* used by SCardEstablishContext() */
- SCardReleaseContext /* used by SCardReleaseContext() */
- SCardListReaders /* used by SCardListReaders() */
- SCardConnect /* used by SCardConnect() */
- SCardReConnect /* used by SCardReconnect() */
- SCardDisConnect /* used by SCardDisconnect() */
- SCardBeginTransaction /* used by SCardBeginTransaction() */
- SCardEndTransaction /* used by SCardEndTransaction() */
- SCardTransmit /* used by SCardTransmit() */
- SCardControl /* used by SCardControl() */
- SCardStatus /* used by SCardStatus() */
- SCardGetStatusChange /* not used */
- SCardCancel /* used by SCardCancel() */
- SCardCancelTransaction /* not used */
- SCardGetAttrib /* used by SCardGetAttrib() */
- SCardSetAttrib /* used by SCardSetAttrib() */
- CommandVersion /* get the client/server protocol version */
- CommandGetReaderState /* get the readers state */
- CommandWaitReaderStateChange /* wait for a reader state change */
- CommandStopWaitingReaderStateChange /* stop waiting for a reader state change */
-)
-
-// Protocol information
-const (
- ProtocolVersionMajor = uint32(4) /* IPC major */
- ProtocolVersionMinor = uint32(3) /* IPC minor */
-)
diff --git a/vendor/github.com/gballet/go-libpcsclite/doc_bsd.go b/vendor/github.com/gballet/go-libpcsclite/doc_bsd.go
deleted file mode 100644
index 672c672e4f..0000000000
--- a/vendor/github.com/gballet/go-libpcsclite/doc_bsd.go
+++ /dev/null
@@ -1,35 +0,0 @@
-// BSD 3-Clause License
-//
-// Copyright (c) 2019, Guillaume Ballet
-// 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 copyright holder 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.
-
-// +build dragonfly freebsd netbsd openbsd solaris
-
-package pcsc
-
-const PCSCDSockName string = "/var/run/pcscd/pcscd.comm"
diff --git a/vendor/github.com/gballet/go-libpcsclite/doc_darwin.go b/vendor/github.com/gballet/go-libpcsclite/doc_darwin.go
deleted file mode 100644
index 3dec7c79b4..0000000000
--- a/vendor/github.com/gballet/go-libpcsclite/doc_darwin.go
+++ /dev/null
@@ -1,35 +0,0 @@
-// BSD 3-Clause License
-//
-// Copyright (c) 2019, Guillaume Ballet
-// 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 copyright holder 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.
-
-// +build darwin
-
-package pcsc
-
-const PCSCDSockName string = ""
diff --git a/vendor/github.com/gballet/go-libpcsclite/doc_linux.go b/vendor/github.com/gballet/go-libpcsclite/doc_linux.go
deleted file mode 100644
index becbf16775..0000000000
--- a/vendor/github.com/gballet/go-libpcsclite/doc_linux.go
+++ /dev/null
@@ -1,35 +0,0 @@
-// BSD 3-Clause License
-//
-// Copyright (c) 2019, Guillaume Ballet
-// 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 copyright holder 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.
-
-// +build linux
-
-package pcsc
-
-const PCSCDSockName string = "/run/pcscd/pcscd.comm"
\ No newline at end of file
diff --git a/vendor/github.com/gballet/go-libpcsclite/doc_windows.go b/vendor/github.com/gballet/go-libpcsclite/doc_windows.go
deleted file mode 100644
index 9bd6bd333f..0000000000
--- a/vendor/github.com/gballet/go-libpcsclite/doc_windows.go
+++ /dev/null
@@ -1,35 +0,0 @@
-// BSD 3-Clause License
-//
-// Copyright (c) 2019, Guillaume Ballet
-// 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 copyright holder 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.
-
-// +build windows
-
-package pcsc
-
-const PCSCDSockName string = ""
diff --git a/vendor/github.com/gballet/go-libpcsclite/error.go b/vendor/github.com/gballet/go-libpcsclite/error.go
deleted file mode 100644
index 4710de5e60..0000000000
--- a/vendor/github.com/gballet/go-libpcsclite/error.go
+++ /dev/null
@@ -1,246 +0,0 @@
-// BSD 3-Clause License
-//
-// Copyright (c) 2019, Guillaume Ballet
-// 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 copyright holder 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 pcsc
-
-import "fmt"
-
-type ErrorCode uint32
-
-const (
- SCardSuccess ErrorCode = 0x00000000 /* No error was encountered. */
- ErrSCardInternal = 0x80100001 /* An internal consistency check failed. */
- ErrSCardCancelled = 0x80100002 /* The action was cancelled by an SCardCancel request. */
- ErrSCardInvalidHandle = 0x80100003 /* The supplied handle was invalid. */
- ErrSCardInvalidParameter = 0x80100004 /* One or more of the supplied parameters could not be properly interpreted. */
- ErrSCardInvalidTarget = 0x80100005 /* Registry startup information is missing or invalid. */
- ErrSCardNoMemory = 0x80100006 /* Not enough memory available to complete this command. */
- ErrSCardWaitedTooLong = 0x80100007 /* An internal consistency timer has expired. */
- ErrSCardInsufficientBuffer = 0x80100008 /* The data buffer to receive returned data is too small for the returned data. */
- ErrScardUnknownReader = 0x80100009 /* The specified reader name is not recognized. */
- ErrSCardTimeout = 0x8010000A /* The user-specified timeout value has expired. */
- ErrSCardSharingViolation = 0x8010000B /* The smart card cannot be accessed because of other connections outstanding. */
- ErrSCardNoSmartCard = 0x8010000C /* The operation requires a Smart Card, but no Smart Card is currently in the device. */
- ErrSCardUnknownCard = 0x8010000D /* The specified smart card name is not recognized. */
- ErrSCardCannotDispose = 0x8010000E /* The system could not dispose of the media in the requested manner. */
- ErrSCardProtoMismatch = 0x8010000F /* The requested protocols are incompatible with the protocol currently in use with the smart card. */
- ErrSCardNotReady = 0x80100010 /* The reader or smart card is not ready to accept commands. */
- ErrSCardInvalidValue = 0x80100011 /* One or more of the supplied parameters values could not be properly interpreted. */
- ErrSCardSystemCancelled = 0x80100012 /* The action was cancelled by the system, presumably to log off or shut down. */
- ErrSCardCommError = 0x80100013 /* An internal communications error has been detected. */
- ErrScardUnknownError = 0x80100014 /* An internal error has been detected, but the source is unknown. */
- ErrSCardInvalidATR = 0x80100015 /* An ATR obtained from the registry is not a valid ATR string. */
- ErrSCardNotTransacted = 0x80100016 /* An attempt was made to end a non-existent transaction. */
- ErrSCardReaderUnavailable = 0x80100017 /* The specified reader is not currently available for use. */
- ErrSCardShutdown = 0x80100018 /* The operation has been aborted to allow the server application to exit. */
- ErrSCardPCITooSmall = 0x80100019 /* The PCI Receive buffer was too small. */
- ErrSCardReaderUnsupported = 0x8010001A /* The reader driver does not meet minimal requirements for support. */
- ErrSCardDuplicateReader = 0x8010001B /* The reader driver did not produce a unique reader name. */
- ErrSCardCardUnsupported = 0x8010001C /* The smart card does not meet minimal requirements for support. */
- ErrScardNoService = 0x8010001D /* The Smart card resource manager is not running. */
- ErrSCardServiceStopped = 0x8010001E /* The Smart card resource manager has shut down. */
- ErrSCardUnexpected = 0x8010001F /* An unexpected card error has occurred. */
- ErrSCardUnsupportedFeature = 0x8010001F /* This smart card does not support the requested feature. */
- ErrSCardICCInstallation = 0x80100020 /* No primary provider can be found for the smart card. */
- ErrSCardICCCreateOrder = 0x80100021 /* The requested order of object creation is not supported. */
- ErrSCardDirNotFound = 0x80100023 /* The identified directory does not exist in the smart card. */
- ErrSCardFileNotFound = 0x80100024 /* The identified file does not exist in the smart card. */
- ErrSCardNoDir = 0x80100025 /* The supplied path does not represent a smart card directory. */
- ErrSCardNoFile = 0x80100026 /* The supplied path does not represent a smart card file. */
- ErrScardNoAccess = 0x80100027 /* Access is denied to this file. */
- ErrSCardWriteTooMany = 0x80100028 /* The smart card does not have enough memory to store the information. */
- ErrSCardBadSeek = 0x80100029 /* There was an error trying to set the smart card file object pointer. */
- ErrSCardInvalidCHV = 0x8010002A /* The supplied PIN is incorrect. */
- ErrSCardUnknownResMNG = 0x8010002B /* An unrecognized error code was returned from a layered component. */
- ErrSCardNoSuchCertificate = 0x8010002C /* The requested certificate does not exist. */
- ErrSCardCertificateUnavailable = 0x8010002D /* The requested certificate could not be obtained. */
- ErrSCardNoReadersAvailable = 0x8010002E /* Cannot find a smart card reader. */
- ErrSCardCommDataLost = 0x8010002F /* A communications error with the smart card has been detected. Retry the operation. */
- ErrScardNoKeyContainer = 0x80100030 /* The requested key container does not exist on the smart card. */
- ErrSCardServerTooBusy = 0x80100031 /* The Smart Card Resource Manager is too busy to complete this operation. */
- ErrSCardUnsupportedCard = 0x80100065 /* The reader cannot communicate with the card, due to ATR string configuration conflicts. */
- ErrSCardUnresponsiveCard = 0x80100066 /* The smart card is not responding to a reset. */
- ErrSCardUnpoweredCard = 0x80100067 /* Power has been removed from the smart card, so that further communication is not possible. */
- ErrSCardResetCard = 0x80100068 /* The smart card has been reset, so any shared state information is invalid. */
- ErrSCardRemovedCard = 0x80100069 /* The smart card has been removed, so further communication is not possible. */
- ErrSCardSecurityViolation = 0x8010006A /* Access was denied because of a security violation. */
- ErrSCardWrongCHV = 0x8010006B /* The card cannot be accessed because the wrong PIN was presented. */
- ErrSCardCHVBlocked = 0x8010006C /* The card cannot be accessed because the maximum number of PIN entry attempts has been reached. */
- ErrSCardEOF = 0x8010006D /* The end of the smart card file has been reached. */
- ErrSCardCancelledByUser = 0x8010006E /* The user pressed "Cancel" on a Smart Card Selection Dialog. */
- ErrSCardCardNotAuthenticated = 0x8010006F /* No PIN was presented to the smart card. */
-)
-
-// Code returns the error code, with an uint32 type to be used in PutUInt32
-func (code ErrorCode) Code() uint32 {
- return uint32(code)
-}
-
-func (code ErrorCode) Error() error {
- switch code {
- case SCardSuccess:
- return fmt.Errorf("Command successful")
-
- case ErrSCardInternal:
- return fmt.Errorf("Internal error")
-
- case ErrSCardCancelled:
- return fmt.Errorf("Command cancelled")
-
- case ErrSCardInvalidHandle:
- return fmt.Errorf("Invalid handle")
-
- case ErrSCardInvalidParameter:
- return fmt.Errorf("Invalid parameter given")
-
- case ErrSCardInvalidTarget:
- return fmt.Errorf("Invalid target given")
-
- case ErrSCardNoMemory:
- return fmt.Errorf("Not enough memory")
-
- case ErrSCardWaitedTooLong:
- return fmt.Errorf("Waited too long")
-
- case ErrSCardInsufficientBuffer:
- return fmt.Errorf("Insufficient buffer")
-
- case ErrScardUnknownReader:
- return fmt.Errorf("Unknown reader specified")
-
- case ErrSCardTimeout:
- return fmt.Errorf("Command timeout")
-
- case ErrSCardSharingViolation:
- return fmt.Errorf("Sharing violation")
-
- case ErrSCardNoSmartCard:
- return fmt.Errorf("No smart card inserted")
-
- case ErrSCardUnknownCard:
- return fmt.Errorf("Unknown card")
-
- case ErrSCardCannotDispose:
- return fmt.Errorf("Cannot dispose handle")
-
- case ErrSCardProtoMismatch:
- return fmt.Errorf("Card protocol mismatch")
-
- case ErrSCardNotReady:
- return fmt.Errorf("Subsystem not ready")
-
- case ErrSCardInvalidValue:
- return fmt.Errorf("Invalid value given")
-
- case ErrSCardSystemCancelled:
- return fmt.Errorf("System cancelled")
-
- case ErrSCardCommError:
- return fmt.Errorf("RPC transport error")
-
- case ErrScardUnknownError:
- return fmt.Errorf("Unknown error")
-
- case ErrSCardInvalidATR:
- return fmt.Errorf("Invalid ATR")
-
- case ErrSCardNotTransacted:
- return fmt.Errorf("Transaction failed")
-
- case ErrSCardReaderUnavailable:
- return fmt.Errorf("Reader is unavailable")
-
- /* case SCARD_P_SHUTDOWN: */
- case ErrSCardPCITooSmall:
- return fmt.Errorf("PCI struct too small")
-
- case ErrSCardReaderUnsupported:
- return fmt.Errorf("Reader is unsupported")
-
- case ErrSCardDuplicateReader:
- return fmt.Errorf("Reader already exists")
-
- case ErrSCardCardUnsupported:
- return fmt.Errorf("Card is unsupported")
-
- case ErrScardNoService:
- return fmt.Errorf("Service not available")
-
- case ErrSCardServiceStopped:
- return fmt.Errorf("Service was stopped")
-
- /* case SCARD_E_UNEXPECTED: */
- /* case SCARD_E_ICC_CREATEORDER: */
- /* case SCARD_E_UNSUPPORTED_FEATURE: */
- /* case SCARD_E_DIR_NOT_FOUND: */
- /* case SCARD_E_NO_DIR: */
- /* case SCARD_E_NO_FILE: */
- /* case SCARD_E_NO_ACCESS: */
- /* case SCARD_E_WRITE_TOO_MANY: */
- /* case SCARD_E_BAD_SEEK: */
- /* case SCARD_E_INVALID_CHV: */
- /* case SCARD_E_UNKNOWN_RES_MNG: */
- /* case SCARD_E_NO_SUCH_CERTIFICATE: */
- /* case SCARD_E_CERTIFICATE_UNAVAILABLE: */
- case ErrSCardNoReadersAvailable:
- return fmt.Errorf("Cannot find a smart card reader")
-
- /* case SCARD_E_COMM_DATA_LOST: */
- /* case SCARD_E_NO_KEY_CONTAINER: */
- /* case SCARD_E_SERVER_TOO_BUSY: */
- case ErrSCardUnsupportedCard:
- return fmt.Errorf("Card is not supported")
-
- case ErrSCardUnresponsiveCard:
- return fmt.Errorf("Card is unresponsive")
-
- case ErrSCardUnpoweredCard:
- return fmt.Errorf("Card is unpowered")
-
- case ErrSCardResetCard:
- return fmt.Errorf("Card was reset")
-
- case ErrSCardRemovedCard:
- return fmt.Errorf("Card was removed")
-
- /* case SCARD_W_SECURITY_VIOLATION: */
- /* case SCARD_W_WRONG_CHV: */
- /* case SCARD_W_CHV_BLOCKED: */
- /* case SCARD_W_EOF: */
- /* case SCARD_W_CANCELLED_BY_USER: */
- /* case SCARD_W_CARD_NOT_AUTHENTICATED: */
-
- case ErrSCardUnsupportedFeature:
- return fmt.Errorf("Feature not supported")
-
- default:
- return fmt.Errorf("unknown error: %08x", code)
- }
-}
diff --git a/vendor/github.com/gballet/go-libpcsclite/go.mod b/vendor/github.com/gballet/go-libpcsclite/go.mod
deleted file mode 100644
index e97f46b7fe..0000000000
--- a/vendor/github.com/gballet/go-libpcsclite/go.mod
+++ /dev/null
@@ -1 +0,0 @@
-module github.com/gballet/go-libpcsclite
diff --git a/vendor/github.com/gballet/go-libpcsclite/msg.go b/vendor/github.com/gballet/go-libpcsclite/msg.go
deleted file mode 100644
index 1377082b14..0000000000
--- a/vendor/github.com/gballet/go-libpcsclite/msg.go
+++ /dev/null
@@ -1,82 +0,0 @@
-// BSD 3-Clause License
-//
-// Copyright (c) 2019, Guillaume Ballet
-// 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 copyright holder 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 pcsc
-
-import (
- "encoding/binary"
- "net"
-)
-
-/**
- * @brief Wrapper for the MessageSend() function.
- *
- * Called by clients to send messages to the server.
- * The parameters \p command and \p data are set in the \c sharedSegmentMsg
- * struct in order to be sent.
- *
- * @param[in] command Command to be sent.
- * @param[in] dwClientID Client socket handle.
- * @param[in] size Size of the message (\p data).
- * @param[in] data_void Data to be sent.
- *
- * @return Same error codes as MessageSend().
- */
-func messageSendWithHeader(command uint32, conn net.Conn, data []byte) error {
- /* Translate header into bytes */
- msgData := make([]byte, 8+len(data))
- binary.LittleEndian.PutUint32(msgData[4:], command)
- binary.LittleEndian.PutUint32(msgData, uint32(len(data)))
-
- /* Copy payload */
- copy(msgData[8:], data)
-
- _, err := conn.Write(msgData)
- return err
-}
-
-// clientSetupSession prepares a communication channel for the client to talk to the server.
-// This is called by the application to create a socket for local IPC with the
-// server. The socket is associated to the file \c PCSCLITE_CSOCK_NAME.
-/*
- * @param[out] pdwClientID Client Connection ID.
- *
- * @retval 0 Success.
- * @retval -1 Can not create the socket.
- * @retval -1 The socket can not open a connection.
- * @retval -1 Can not set the socket to non-blocking.
- */
-func clientSetupSession(daemonPath string) (net.Conn, error) {
- path := PCSCDSockName
- if len(daemonPath) > 0 {
- path = daemonPath
- }
- return net.Dial("unix", path)
-}
diff --git a/vendor/github.com/gballet/go-libpcsclite/winscard.go b/vendor/github.com/gballet/go-libpcsclite/winscard.go
deleted file mode 100644
index b916db1621..0000000000
--- a/vendor/github.com/gballet/go-libpcsclite/winscard.go
+++ /dev/null
@@ -1,402 +0,0 @@
-// BSD 3-Clause License
-//
-// Copyright (c) 2019, Guillaume Ballet
-// 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 copyright holder 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 pcsc
-
-import (
- "encoding/binary"
- "fmt"
- "net"
- "sync"
- "unsafe"
-)
-
-// Client contains all the information needed to establish
-// and maintain a connection to the deamon/card.
-type Client struct {
- conn net.Conn
-
- minor uint32
- major uint32
-
- ctx uint32
-
- mutex sync.Mutex
-
- readerStateDescriptors [MaxReaderStateDescriptors]ReaderState
-}
-
-// EstablishContext asks the PCSC daemon to create a context
-// handle for further communication with connected cards and
-// readers.
-func EstablishContext(path string, scope uint32) (*Client, error) {
- client := &Client{}
-
- conn, err := clientSetupSession(path)
- if err != nil {
- return nil, err
- }
- client.conn = conn
-
- payload := make([]byte, 12)
- response := make([]byte, 12)
-
- var code uint32
- var minor uint32
- for minor = ProtocolVersionMinor; minor <= ProtocolVersionMinor+1; minor++ {
- /* Exchange version information */
- binary.LittleEndian.PutUint32(payload, ProtocolVersionMajor)
- binary.LittleEndian.PutUint32(payload[4:], minor)
- binary.LittleEndian.PutUint32(payload[8:], SCardSuccess.Code())
- err = messageSendWithHeader(CommandVersion, conn, payload)
- if err != nil {
- return nil, err
- }
- n, err := conn.Read(response)
- if err != nil {
- return nil, err
- }
- if n != len(response) {
- return nil, fmt.Errorf("invalid response length: expected %d, got %d", len(response), n)
- }
- code = binary.LittleEndian.Uint32(response[8:])
- if code != SCardSuccess.Code() {
- continue
- }
- client.major = binary.LittleEndian.Uint32(response)
- client.minor = binary.LittleEndian.Uint32(response[4:])
- if client.major != ProtocolVersionMajor || client.minor != minor {
- continue
- }
- break
- }
-
- if code != SCardSuccess.Code() {
- return nil, fmt.Errorf("invalid response code: expected %d, got %d (%v)", SCardSuccess, code, ErrorCode(code).Error())
- }
- if client.major != ProtocolVersionMajor || (client.minor != minor && client.minor+1 != minor) {
- return nil, fmt.Errorf("invalid version found: expected %d.%d, got %d.%d", ProtocolVersionMajor, ProtocolVersionMinor, client.major, client.minor)
- }
-
- /* Establish the context proper */
- binary.LittleEndian.PutUint32(payload, scope)
- binary.LittleEndian.PutUint32(payload[4:], 0)
- binary.LittleEndian.PutUint32(payload[8:], SCardSuccess.Code())
- err = messageSendWithHeader(SCardEstablishContext, conn, payload)
- if err != nil {
- return nil, err
- }
- response = make([]byte, 12)
- n, err := conn.Read(response)
- if err != nil {
- return nil, err
- }
- if n != len(response) {
- return nil, fmt.Errorf("invalid response length: expected %d, got %d", len(response), n)
- }
- code = binary.LittleEndian.Uint32(response[8:])
- if code != SCardSuccess.Code() {
- return nil, fmt.Errorf("invalid response code: expected %d, got %d (%v)", SCardSuccess, code, ErrorCode(code).Error())
- }
- client.ctx = binary.LittleEndian.Uint32(response[4:])
-
- return client, nil
-}
-
-// ReleaseContext tells the daemon that the client will no longer
-// need the context.
-func (client *Client) ReleaseContext() error {
- client.mutex.Lock()
- defer client.mutex.Unlock()
-
- data := [8]byte{}
- binary.LittleEndian.PutUint32(data[:], client.ctx)
- binary.LittleEndian.PutUint32(data[4:], SCardSuccess.Code())
- err := messageSendWithHeader(SCardReleaseContext, client.conn, data[:])
- if err != nil {
- return err
- }
- total := 0
- for total < len(data) {
- n, err := client.conn.Read(data[total:])
- if err != nil {
- return err
- }
- total += n
- }
- code := binary.LittleEndian.Uint32(data[4:])
- if code != SCardSuccess.Code() {
- return fmt.Errorf("invalid return code: %x, %v", code, ErrorCode(code).Error())
- }
-
- return nil
-}
-
-// Constants related to the reader state structure
-const (
- ReaderStateNameLength = 128
- ReaderStateMaxAtrSizeLength = 33
- // NOTE: ATR is 32-byte aligned in the C version, which means it's
- // actually 36 byte long and not 33.
- ReaderStateDescriptorLength = ReaderStateNameLength + ReaderStateMaxAtrSizeLength + 5*4 + 3
-
- MaxReaderStateDescriptors = 16
-)
-
-// ReaderState represent the state of a single reader, as reported
-// by the PCSC daemon.
-type ReaderState struct {
- Name string /* reader name */
- eventCounter uint32 /* number of card events */
- readerState uint32 /* SCARD_* bit field */
- readerSharing uint32 /* PCSCLITE_SHARING_* sharing status */
-
- cardAtr [ReaderStateMaxAtrSizeLength]byte /* ATR */
- cardAtrLength uint32 /* ATR length */
- cardProtocol uint32 /* SCARD_PROTOCOL_* value */
-}
-
-func getReaderState(data []byte) (ReaderState, error) {
- ret := ReaderState{}
- if len(data) < ReaderStateDescriptorLength {
- return ret, fmt.Errorf("could not unmarshall data of length %d < %d", len(data), ReaderStateDescriptorLength)
- }
-
- ret.Name = string(data[:ReaderStateNameLength])
- ret.eventCounter = binary.LittleEndian.Uint32(data[unsafe.Offsetof(ret.eventCounter):])
- ret.readerState = binary.LittleEndian.Uint32(data[unsafe.Offsetof(ret.readerState):])
- ret.readerSharing = binary.LittleEndian.Uint32(data[unsafe.Offsetof(ret.readerSharing):])
- copy(ret.cardAtr[:], data[unsafe.Offsetof(ret.cardAtr):unsafe.Offsetof(ret.cardAtr)+ReaderStateMaxAtrSizeLength])
- ret.cardAtrLength = binary.LittleEndian.Uint32(data[unsafe.Offsetof(ret.cardAtrLength):])
- ret.cardProtocol = binary.LittleEndian.Uint32(data[unsafe.Offsetof(ret.cardProtocol):])
-
- return ret, nil
-}
-
-// ListReaders gets the list of readers from the daemon
-func (client *Client) ListReaders() ([]string, error) {
- client.mutex.Lock()
- defer client.mutex.Unlock()
-
- err := messageSendWithHeader(CommandGetReaderState, client.conn, []byte{})
- if err != nil {
- return nil, err
- }
- response := make([]byte, ReaderStateDescriptorLength*MaxReaderStateDescriptors)
- total := 0
- for total < len(response) {
- n, err := client.conn.Read(response[total:])
- if err != nil {
- return nil, err
- }
- total += n
- }
-
- var names []string
- for i := range client.readerStateDescriptors {
- desc, err := getReaderState(response[i*ReaderStateDescriptorLength:])
- if err != nil {
- return nil, err
- }
- client.readerStateDescriptors[i] = desc
- if desc.Name[0] == 0 {
- break
- }
- names = append(names, desc.Name)
- }
-
- return names, nil
-}
-
-// Offsets into the Connect request/response packet
-const (
- SCardConnectReaderNameOffset = 4
- SCardConnectShareModeOffset = SCardConnectReaderNameOffset + ReaderStateNameLength
- SCardConnectPreferredProtocolOffset = SCardConnectShareModeOffset + 4
- SCardConnectReturnValueOffset = SCardConnectPreferredProtocolOffset + 12
-)
-
-// Card represents the connection to a card
-type Card struct {
- handle uint32
- activeProto uint32
- client *Client
-}
-
-// Connect asks the daemon to connect to the card
-func (client *Client) Connect(name string, shareMode uint32, preferredProtocol uint32) (*Card, error) {
- client.mutex.Lock()
- defer client.mutex.Unlock()
-
- request := make([]byte, ReaderStateNameLength+4*6)
- binary.LittleEndian.PutUint32(request, client.ctx)
- copy(request[SCardConnectReaderNameOffset:], []byte(name))
- binary.LittleEndian.PutUint32(request[SCardConnectShareModeOffset:], shareMode)
- binary.LittleEndian.PutUint32(request[SCardConnectPreferredProtocolOffset:], preferredProtocol)
- binary.LittleEndian.PutUint32(request[SCardConnectReturnValueOffset:], SCardSuccess.Code())
-
- err := messageSendWithHeader(SCardConnect, client.conn, request)
- if err != nil {
- return nil, err
- }
- response := make([]byte, ReaderStateNameLength+4*6)
- total := 0
- for total < len(response) {
- n, err := client.conn.Read(response[total:])
- if err != nil {
- return nil, err
- }
- // fmt.Println("total, n", total, n, response)
- total += n
- }
- code := binary.LittleEndian.Uint32(response[148:])
- if code != SCardSuccess.Code() {
- return nil, fmt.Errorf("invalid return code: %x (%v)", code, ErrorCode(code).Error())
- }
- handle := binary.LittleEndian.Uint32(response[140:])
- active := binary.LittleEndian.Uint32(response[SCardConnectPreferredProtocolOffset:])
-
- return &Card{handle: handle, activeProto: active, client: client}, nil
-}
-
-/**
-* @brief contained in \ref SCARD_TRANSMIT Messages.
-*
-* These data are passed throw the field \c sharedSegmentMsg.data.
- */
-type transmit struct {
- hCard uint32
- ioSendPciProtocol uint32
- ioSendPciLength uint32
- cbSendLength uint32
- ioRecvPciProtocol uint32
- ioRecvPciLength uint32
- pcbRecvLength uint32
- rv uint32
-}
-
-// SCardIoRequest contains the info needed for performing an IO request
-type SCardIoRequest struct {
- proto uint32
- length uint32
-}
-
-const (
- TransmitRequestLength = 32
-)
-
-// Transmit sends request data to a card and returns the response
-func (card *Card) Transmit(adpu []byte) ([]byte, *SCardIoRequest, error) {
- card.client.mutex.Lock()
- defer card.client.mutex.Unlock()
-
- request := [TransmitRequestLength]byte{}
- binary.LittleEndian.PutUint32(request[:], card.handle)
- binary.LittleEndian.PutUint32(request[4:] /*card.activeProto*/, 2)
- binary.LittleEndian.PutUint32(request[8:], 8)
- binary.LittleEndian.PutUint32(request[12:], uint32(len(adpu)))
- binary.LittleEndian.PutUint32(request[16:], 0)
- binary.LittleEndian.PutUint32(request[20:], 0)
- binary.LittleEndian.PutUint32(request[24:], 0x10000)
- binary.LittleEndian.PutUint32(request[28:], SCardSuccess.Code())
- err := messageSendWithHeader(SCardTransmit, card.client.conn, request[:])
- if err != nil {
- return nil, nil, err
- }
- // Add the ADPU payload after the transmit descriptor
- n, err := card.client.conn.Write(adpu)
- if err != nil {
- return nil, nil, err
- }
- if n != len(adpu) {
- return nil, nil, fmt.Errorf("Invalid number of bytes written: expected %d, got %d", len(adpu), n)
- }
- response := [TransmitRequestLength]byte{}
- total := 0
- for total < len(response) {
- n, err = card.client.conn.Read(response[total:])
- if err != nil {
- return nil, nil, err
- }
- total += n
- }
-
- code := binary.LittleEndian.Uint32(response[28:])
- if code != SCardSuccess.Code() {
- return nil, nil, fmt.Errorf("invalid return code: %x (%v)", code, ErrorCode(code).Error())
- }
-
- // Recover the response data
- recvProto := binary.LittleEndian.Uint32(response[16:])
- recvLength := binary.LittleEndian.Uint32(response[20:])
- recv := &SCardIoRequest{proto: recvProto, length: recvLength}
- recvLength = binary.LittleEndian.Uint32(response[24:])
- recvData := make([]byte, recvLength)
- total = 0
- for uint32(total) < recvLength {
- n, err := card.client.conn.Read(recvData[total:])
- if err != nil {
- return nil, nil, err
- }
- total += n
- }
-
- return recvData, recv, nil
-}
-
-// Disconnect tells the PCSC daemon that the client is no longer
-// interested in communicating with the card.
-func (card *Card) Disconnect(disposition uint32) error {
- card.client.mutex.Lock()
- defer card.client.mutex.Unlock()
-
- data := [12]byte{}
- binary.LittleEndian.PutUint32(data[:], card.handle)
- binary.LittleEndian.PutUint32(data[4:], disposition)
- binary.LittleEndian.PutUint32(data[8:], SCardSuccess.Code())
- err := messageSendWithHeader(SCardDisConnect, card.client.conn, data[:])
- if err != nil {
- return err
- }
- total := 0
- for total < len(data) {
- n, err := card.client.conn.Read(data[total:])
- if err != nil {
- return err
- }
- total += n
- }
- code := binary.LittleEndian.Uint32(data[8:])
- if code != SCardSuccess.Code() {
- return fmt.Errorf("invalid return code: %x (%v)", code, ErrorCode(code).Error())
- }
-
- return nil
-}
diff --git a/vendor/github.com/go-ole/go-ole/ChangeLog.md b/vendor/github.com/go-ole/go-ole/ChangeLog.md
deleted file mode 100644
index 4ba6a8c64d..0000000000
--- a/vendor/github.com/go-ole/go-ole/ChangeLog.md
+++ /dev/null
@@ -1,49 +0,0 @@
-# Version 1.x.x
-
-* **Add more test cases and reference new test COM server project.** (Placeholder for future additions)
-
-# Version 1.2.0-alphaX
-
-**Minimum supported version is now Go 1.4. Go 1.1 support is deprecated, but should still build.**
-
- * Added CI configuration for Travis-CI and AppVeyor.
- * Added test InterfaceID and ClassID for the COM Test Server project.
- * Added more inline documentation (#83).
- * Added IEnumVARIANT implementation (#88).
- * Added IEnumVARIANT test cases (#99, #100, #101).
- * Added support for retrieving `time.Time` from VARIANT (#92).
- * Added test case for IUnknown (#64).
- * Added test case for IDispatch (#64).
- * Added test cases for scalar variants (#64, #76).
-
-# Version 1.1.1
-
- * Fixes for Linux build.
- * Fixes for Windows build.
-
-# Version 1.1.0
-
-The change to provide building on all platforms is a new feature. The increase in minor version reflects that and allows those who wish to stay on 1.0.x to continue to do so. Support for 1.0.x will be limited to bug fixes.
-
- * Move GUID out of variables.go into its own file to make new documentation available.
- * Move OleError out of ole.go into its own file to make new documentation available.
- * Add documentation to utility functions.
- * Add documentation to variant receiver functions.
- * Add documentation to ole structures.
- * Make variant available to other systems outside of Windows.
- * Make OLE structures available to other systems outside of Windows.
-
-## New Features
-
- * Library should now be built on all platforms supported by Go. Library will NOOP on any platform that is not Windows.
- * More functions are now documented and available on godoc.org.
-
-# Version 1.0.1
-
- 1. Fix package references from repository location change.
-
-# Version 1.0.0
-
-This version is stable enough for use. The COM API is still incomplete, but provides enough functionality for accessing COM servers using IDispatch interface.
-
-There is no changelog for this version. Check commits for history.
diff --git a/vendor/github.com/go-ole/go-ole/LICENSE b/vendor/github.com/go-ole/go-ole/LICENSE
deleted file mode 100644
index 623ec06f91..0000000000
--- a/vendor/github.com/go-ole/go-ole/LICENSE
+++ /dev/null
@@ -1,21 +0,0 @@
-The MIT License (MIT)
-
-Copyright © 2013-2017 Yasuhiro Matsumoto,
-
-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/vendor/github.com/go-ole/go-ole/README.md b/vendor/github.com/go-ole/go-ole/README.md
deleted file mode 100644
index 0ea9db33c7..0000000000
--- a/vendor/github.com/go-ole/go-ole/README.md
+++ /dev/null
@@ -1,46 +0,0 @@
-#Go OLE
-
-[![Build status](https://ci.appveyor.com/api/projects/status/qr0u2sf7q43us9fj?svg=true)](https://ci.appveyor.com/project/jacobsantos/go-ole-jgs28)
-[![Build Status](https://travis-ci.org/go-ole/go-ole.svg?branch=master)](https://travis-ci.org/go-ole/go-ole)
-[![GoDoc](https://godoc.org/github.com/go-ole/go-ole?status.svg)](https://godoc.org/github.com/go-ole/go-ole)
-
-Go bindings for Windows COM using shared libraries instead of cgo.
-
-By Yasuhiro Matsumoto.
-
-## Install
-
-To experiment with go-ole, you can just compile and run the example program:
-
-```
-go get github.com/go-ole/go-ole
-cd /path/to/go-ole/
-go test
-
-cd /path/to/go-ole/example/excel
-go run excel.go
-```
-
-## Continuous Integration
-
-Continuous integration configuration has been added for both Travis-CI and AppVeyor. You will have to add these to your own account for your fork in order for it to run.
-
-**Travis-CI**
-
-Travis-CI was added to check builds on Linux to ensure that `go get` works when cross building. Currently, Travis-CI is not used to test cross-building, but this may be changed in the future. It is also not currently possible to test the library on Linux, since COM API is specific to Windows and it is not currently possible to run a COM server on Linux or even connect to a remote COM server.
-
-**AppVeyor**
-
-AppVeyor is used to build on Windows using the (in-development) test COM server. It is currently only used to test the build and ensure that the code works on Windows. It will be used to register a COM server and then run the test cases based on the test COM server.
-
-The tests currently do run and do pass and this should be maintained with commits.
-
-##Versioning
-
-Go OLE uses [semantic versioning](http://semver.org) for version numbers, which is similar to the version contract of the Go language. Which means that the major version will always maintain backwards compatibility with minor versions. Minor versions will only add new additions and changes. Fixes will always be in patch.
-
-This contract should allow you to upgrade to new minor and patch versions without breakage or modifications to your existing code. Leave a ticket, if there is breakage, so that it could be fixed.
-
-##LICENSE
-
-Under the MIT License: http://mattn.mit-license.org/2013
diff --git a/vendor/github.com/go-ole/go-ole/appveyor.yml b/vendor/github.com/go-ole/go-ole/appveyor.yml
deleted file mode 100644
index 0d557ac2ff..0000000000
--- a/vendor/github.com/go-ole/go-ole/appveyor.yml
+++ /dev/null
@@ -1,54 +0,0 @@
-# Notes:
-# - Minimal appveyor.yml file is an empty file. All sections are optional.
-# - Indent each level of configuration with 2 spaces. Do not use tabs!
-# - All section names are case-sensitive.
-# - Section names should be unique on each level.
-
-version: "1.3.0.{build}-alpha-{branch}"
-
-os: Windows Server 2012 R2
-
-branches:
- only:
- - master
- - v1.2
- - v1.1
- - v1.0
-
-skip_tags: true
-
-clone_folder: c:\gopath\src\github.com\go-ole\go-ole
-
-environment:
- GOPATH: c:\gopath
- matrix:
- - GOARCH: amd64
- GOVERSION: 1.5
- GOROOT: c:\go
- DOWNLOADPLATFORM: "x64"
-
-install:
- - choco install mingw
- - SET PATH=c:\tools\mingw64\bin;%PATH%
- # - Download COM Server
- - ps: Start-FileDownload "https://github.com/go-ole/test-com-server/releases/download/v1.0.2/test-com-server-${env:DOWNLOADPLATFORM}.zip"
- - 7z e test-com-server-%DOWNLOADPLATFORM%.zip -oc:\gopath\src\github.com\go-ole\go-ole > NUL
- - c:\gopath\src\github.com\go-ole\go-ole\build\register-assembly.bat
- # - set
- - go version
- - go env
- - go get -u golang.org/x/tools/cmd/cover
- - go get -u golang.org/x/tools/cmd/godoc
- - go get -u golang.org/x/tools/cmd/stringer
-
-build_script:
- - cd c:\gopath\src\github.com\go-ole\go-ole
- - go get -v -t ./...
- - go build
- - go test -v -cover ./...
-
-# disable automatic tests
-test: off
-
-# disable deployment
-deploy: off
diff --git a/vendor/github.com/go-ole/go-ole/com.go b/vendor/github.com/go-ole/go-ole/com.go
deleted file mode 100644
index 75ebbf13f6..0000000000
--- a/vendor/github.com/go-ole/go-ole/com.go
+++ /dev/null
@@ -1,329 +0,0 @@
-// +build windows
-
-package ole
-
-import (
- "errors"
- "syscall"
- "time"
- "unicode/utf16"
- "unsafe"
-)
-
-var (
- procCoInitialize, _ = modole32.FindProc("CoInitialize")
- procCoInitializeEx, _ = modole32.FindProc("CoInitializeEx")
- procCoUninitialize, _ = modole32.FindProc("CoUninitialize")
- procCoCreateInstance, _ = modole32.FindProc("CoCreateInstance")
- procCoTaskMemFree, _ = modole32.FindProc("CoTaskMemFree")
- procCLSIDFromProgID, _ = modole32.FindProc("CLSIDFromProgID")
- procCLSIDFromString, _ = modole32.FindProc("CLSIDFromString")
- procStringFromCLSID, _ = modole32.FindProc("StringFromCLSID")
- procStringFromIID, _ = modole32.FindProc("StringFromIID")
- procIIDFromString, _ = modole32.FindProc("IIDFromString")
- procGetUserDefaultLCID, _ = modkernel32.FindProc("GetUserDefaultLCID")
- procCopyMemory, _ = modkernel32.FindProc("RtlMoveMemory")
- procVariantInit, _ = modoleaut32.FindProc("VariantInit")
- procVariantClear, _ = modoleaut32.FindProc("VariantClear")
- procVariantTimeToSystemTime, _ = modoleaut32.FindProc("VariantTimeToSystemTime")
- procSysAllocString, _ = modoleaut32.FindProc("SysAllocString")
- procSysAllocStringLen, _ = modoleaut32.FindProc("SysAllocStringLen")
- procSysFreeString, _ = modoleaut32.FindProc("SysFreeString")
- procSysStringLen, _ = modoleaut32.FindProc("SysStringLen")
- procCreateDispTypeInfo, _ = modoleaut32.FindProc("CreateDispTypeInfo")
- procCreateStdDispatch, _ = modoleaut32.FindProc("CreateStdDispatch")
- procGetActiveObject, _ = modoleaut32.FindProc("GetActiveObject")
-
- procGetMessageW, _ = moduser32.FindProc("GetMessageW")
- procDispatchMessageW, _ = moduser32.FindProc("DispatchMessageW")
-)
-
-// coInitialize initializes COM library on current thread.
-//
-// MSDN documentation suggests that this function should not be called. Call
-// CoInitializeEx() instead. The reason has to do with threading and this
-// function is only for single-threaded apartments.
-//
-// That said, most users of the library have gotten away with just this
-// function. If you are experiencing threading issues, then use
-// CoInitializeEx().
-func coInitialize() (err error) {
- // http://msdn.microsoft.com/en-us/library/windows/desktop/ms678543(v=vs.85).aspx
- // Suggests that no value should be passed to CoInitialized.
- // Could just be Call() since the parameter is optional. <-- Needs testing to be sure.
- hr, _, _ := procCoInitialize.Call(uintptr(0))
- if hr != 0 {
- err = NewError(hr)
- }
- return
-}
-
-// coInitializeEx initializes COM library with concurrency model.
-func coInitializeEx(coinit uint32) (err error) {
- // http://msdn.microsoft.com/en-us/library/windows/desktop/ms695279(v=vs.85).aspx
- // Suggests that the first parameter is not only optional but should always be NULL.
- hr, _, _ := procCoInitializeEx.Call(uintptr(0), uintptr(coinit))
- if hr != 0 {
- err = NewError(hr)
- }
- return
-}
-
-// CoInitialize initializes COM library on current thread.
-//
-// MSDN documentation suggests that this function should not be called. Call
-// CoInitializeEx() instead. The reason has to do with threading and this
-// function is only for single-threaded apartments.
-//
-// That said, most users of the library have gotten away with just this
-// function. If you are experiencing threading issues, then use
-// CoInitializeEx().
-func CoInitialize(p uintptr) (err error) {
- // p is ignored and won't be used.
- // Avoid any variable not used errors.
- p = uintptr(0)
- return coInitialize()
-}
-
-// CoInitializeEx initializes COM library with concurrency model.
-func CoInitializeEx(p uintptr, coinit uint32) (err error) {
- // Avoid any variable not used errors.
- p = uintptr(0)
- return coInitializeEx(coinit)
-}
-
-// CoUninitialize uninitializes COM Library.
-func CoUninitialize() {
- procCoUninitialize.Call()
-}
-
-// CoTaskMemFree frees memory pointer.
-func CoTaskMemFree(memptr uintptr) {
- procCoTaskMemFree.Call(memptr)
-}
-
-// CLSIDFromProgID retrieves Class Identifier with the given Program Identifier.
-//
-// The Programmatic Identifier must be registered, because it will be looked up
-// in the Windows Registry. The registry entry has the following keys: CLSID,
-// Insertable, Protocol and Shell
-// (https://msdn.microsoft.com/en-us/library/dd542719(v=vs.85).aspx).
-//
-// programID identifies the class id with less precision and is not guaranteed
-// to be unique. These are usually found in the registry under
-// HKEY_LOCAL_MACHINE\SOFTWARE\Classes, usually with the format of
-// "Program.Component.Version" with version being optional.
-//
-// CLSIDFromProgID in Windows API.
-func CLSIDFromProgID(progId string) (clsid *GUID, err error) {
- var guid GUID
- lpszProgID := uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(progId)))
- hr, _, _ := procCLSIDFromProgID.Call(lpszProgID, uintptr(unsafe.Pointer(&guid)))
- if hr != 0 {
- err = NewError(hr)
- }
- clsid = &guid
- return
-}
-
-// CLSIDFromString retrieves Class ID from string representation.
-//
-// This is technically the string version of the GUID and will convert the
-// string to object.
-//
-// CLSIDFromString in Windows API.
-func CLSIDFromString(str string) (clsid *GUID, err error) {
- var guid GUID
- lpsz := uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(str)))
- hr, _, _ := procCLSIDFromString.Call(lpsz, uintptr(unsafe.Pointer(&guid)))
- if hr != 0 {
- err = NewError(hr)
- }
- clsid = &guid
- return
-}
-
-// StringFromCLSID returns GUID formated string from GUID object.
-func StringFromCLSID(clsid *GUID) (str string, err error) {
- var p *uint16
- hr, _, _ := procStringFromCLSID.Call(uintptr(unsafe.Pointer(clsid)), uintptr(unsafe.Pointer(&p)))
- if hr != 0 {
- err = NewError(hr)
- }
- str = LpOleStrToString(p)
- return
-}
-
-// IIDFromString returns GUID from program ID.
-func IIDFromString(progId string) (clsid *GUID, err error) {
- var guid GUID
- lpsz := uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(progId)))
- hr, _, _ := procIIDFromString.Call(lpsz, uintptr(unsafe.Pointer(&guid)))
- if hr != 0 {
- err = NewError(hr)
- }
- clsid = &guid
- return
-}
-
-// StringFromIID returns GUID formatted string from GUID object.
-func StringFromIID(iid *GUID) (str string, err error) {
- var p *uint16
- hr, _, _ := procStringFromIID.Call(uintptr(unsafe.Pointer(iid)), uintptr(unsafe.Pointer(&p)))
- if hr != 0 {
- err = NewError(hr)
- }
- str = LpOleStrToString(p)
- return
-}
-
-// CreateInstance of single uninitialized object with GUID.
-func CreateInstance(clsid *GUID, iid *GUID) (unk *IUnknown, err error) {
- if iid == nil {
- iid = IID_IUnknown
- }
- hr, _, _ := procCoCreateInstance.Call(
- uintptr(unsafe.Pointer(clsid)),
- 0,
- CLSCTX_SERVER,
- uintptr(unsafe.Pointer(iid)),
- uintptr(unsafe.Pointer(&unk)))
- if hr != 0 {
- err = NewError(hr)
- }
- return
-}
-
-// GetActiveObject retrieves pointer to active object.
-func GetActiveObject(clsid *GUID, iid *GUID) (unk *IUnknown, err error) {
- if iid == nil {
- iid = IID_IUnknown
- }
- hr, _, _ := procGetActiveObject.Call(
- uintptr(unsafe.Pointer(clsid)),
- uintptr(unsafe.Pointer(iid)),
- uintptr(unsafe.Pointer(&unk)))
- if hr != 0 {
- err = NewError(hr)
- }
- return
-}
-
-// VariantInit initializes variant.
-func VariantInit(v *VARIANT) (err error) {
- hr, _, _ := procVariantInit.Call(uintptr(unsafe.Pointer(v)))
- if hr != 0 {
- err = NewError(hr)
- }
- return
-}
-
-// VariantClear clears value in Variant settings to VT_EMPTY.
-func VariantClear(v *VARIANT) (err error) {
- hr, _, _ := procVariantClear.Call(uintptr(unsafe.Pointer(v)))
- if hr != 0 {
- err = NewError(hr)
- }
- return
-}
-
-// SysAllocString allocates memory for string and copies string into memory.
-func SysAllocString(v string) (ss *int16) {
- pss, _, _ := procSysAllocString.Call(uintptr(unsafe.Pointer(syscall.StringToUTF16Ptr(v))))
- ss = (*int16)(unsafe.Pointer(pss))
- return
-}
-
-// SysAllocStringLen copies up to length of given string returning pointer.
-func SysAllocStringLen(v string) (ss *int16) {
- utf16 := utf16.Encode([]rune(v + "\x00"))
- ptr := &utf16[0]
-
- pss, _, _ := procSysAllocStringLen.Call(uintptr(unsafe.Pointer(ptr)), uintptr(len(utf16)-1))
- ss = (*int16)(unsafe.Pointer(pss))
- return
-}
-
-// SysFreeString frees string system memory. This must be called with SysAllocString.
-func SysFreeString(v *int16) (err error) {
- hr, _, _ := procSysFreeString.Call(uintptr(unsafe.Pointer(v)))
- if hr != 0 {
- err = NewError(hr)
- }
- return
-}
-
-// SysStringLen is the length of the system allocated string.
-func SysStringLen(v *int16) uint32 {
- l, _, _ := procSysStringLen.Call(uintptr(unsafe.Pointer(v)))
- return uint32(l)
-}
-
-// CreateStdDispatch provides default IDispatch implementation for IUnknown.
-//
-// This handles default IDispatch implementation for objects. It haves a few
-// limitations with only supporting one language. It will also only return
-// default exception codes.
-func CreateStdDispatch(unk *IUnknown, v uintptr, ptinfo *IUnknown) (disp *IDispatch, err error) {
- hr, _, _ := procCreateStdDispatch.Call(
- uintptr(unsafe.Pointer(unk)),
- v,
- uintptr(unsafe.Pointer(ptinfo)),
- uintptr(unsafe.Pointer(&disp)))
- if hr != 0 {
- err = NewError(hr)
- }
- return
-}
-
-// CreateDispTypeInfo provides default ITypeInfo implementation for IDispatch.
-//
-// This will not handle the full implementation of the interface.
-func CreateDispTypeInfo(idata *INTERFACEDATA) (pptinfo *IUnknown, err error) {
- hr, _, _ := procCreateDispTypeInfo.Call(
- uintptr(unsafe.Pointer(idata)),
- uintptr(GetUserDefaultLCID()),
- uintptr(unsafe.Pointer(&pptinfo)))
- if hr != 0 {
- err = NewError(hr)
- }
- return
-}
-
-// copyMemory moves location of a block of memory.
-func copyMemory(dest unsafe.Pointer, src unsafe.Pointer, length uint32) {
- procCopyMemory.Call(uintptr(dest), uintptr(src), uintptr(length))
-}
-
-// GetUserDefaultLCID retrieves current user default locale.
-func GetUserDefaultLCID() (lcid uint32) {
- ret, _, _ := procGetUserDefaultLCID.Call()
- lcid = uint32(ret)
- return
-}
-
-// GetMessage in message queue from runtime.
-//
-// This function appears to block. PeekMessage does not block.
-func GetMessage(msg *Msg, hwnd uint32, MsgFilterMin uint32, MsgFilterMax uint32) (ret int32, err error) {
- r0, _, err := procGetMessageW.Call(uintptr(unsafe.Pointer(msg)), uintptr(hwnd), uintptr(MsgFilterMin), uintptr(MsgFilterMax))
- ret = int32(r0)
- return
-}
-
-// DispatchMessage to window procedure.
-func DispatchMessage(msg *Msg) (ret int32) {
- r0, _, _ := procDispatchMessageW.Call(uintptr(unsafe.Pointer(msg)))
- ret = int32(r0)
- return
-}
-
-// GetVariantDate converts COM Variant Time value to Go time.Time.
-func GetVariantDate(value float64) (time.Time, error) {
- var st syscall.Systemtime
- r, _, _ := procVariantTimeToSystemTime.Call(uintptr(value), uintptr(unsafe.Pointer(&st)))
- if r != 0 {
- return time.Date(int(st.Year), time.Month(st.Month), int(st.Day), int(st.Hour), int(st.Minute), int(st.Second), int(st.Milliseconds/1000), time.UTC), nil
- }
- return time.Now(), errors.New("Could not convert to time, passing current time.")
-}
diff --git a/vendor/github.com/go-ole/go-ole/com_func.go b/vendor/github.com/go-ole/go-ole/com_func.go
deleted file mode 100644
index 425aad3233..0000000000
--- a/vendor/github.com/go-ole/go-ole/com_func.go
+++ /dev/null
@@ -1,174 +0,0 @@
-// +build !windows
-
-package ole
-
-import (
- "time"
- "unsafe"
-)
-
-// coInitialize initializes COM library on current thread.
-//
-// MSDN documentation suggests that this function should not be called. Call
-// CoInitializeEx() instead. The reason has to do with threading and this
-// function is only for single-threaded apartments.
-//
-// That said, most users of the library have gotten away with just this
-// function. If you are experiencing threading issues, then use
-// CoInitializeEx().
-func coInitialize() error {
- return NewError(E_NOTIMPL)
-}
-
-// coInitializeEx initializes COM library with concurrency model.
-func coInitializeEx(coinit uint32) error {
- return NewError(E_NOTIMPL)
-}
-
-// CoInitialize initializes COM library on current thread.
-//
-// MSDN documentation suggests that this function should not be called. Call
-// CoInitializeEx() instead. The reason has to do with threading and this
-// function is only for single-threaded apartments.
-//
-// That said, most users of the library have gotten away with just this
-// function. If you are experiencing threading issues, then use
-// CoInitializeEx().
-func CoInitialize(p uintptr) error {
- return NewError(E_NOTIMPL)
-}
-
-// CoInitializeEx initializes COM library with concurrency model.
-func CoInitializeEx(p uintptr, coinit uint32) error {
- return NewError(E_NOTIMPL)
-}
-
-// CoUninitialize uninitializes COM Library.
-func CoUninitialize() {}
-
-// CoTaskMemFree frees memory pointer.
-func CoTaskMemFree(memptr uintptr) {}
-
-// CLSIDFromProgID retrieves Class Identifier with the given Program Identifier.
-//
-// The Programmatic Identifier must be registered, because it will be looked up
-// in the Windows Registry. The registry entry has the following keys: CLSID,
-// Insertable, Protocol and Shell
-// (https://msdn.microsoft.com/en-us/library/dd542719(v=vs.85).aspx).
-//
-// programID identifies the class id with less precision and is not guaranteed
-// to be unique. These are usually found in the registry under
-// HKEY_LOCAL_MACHINE\SOFTWARE\Classes, usually with the format of
-// "Program.Component.Version" with version being optional.
-//
-// CLSIDFromProgID in Windows API.
-func CLSIDFromProgID(progId string) (*GUID, error) {
- return nil, NewError(E_NOTIMPL)
-}
-
-// CLSIDFromString retrieves Class ID from string representation.
-//
-// This is technically the string version of the GUID and will convert the
-// string to object.
-//
-// CLSIDFromString in Windows API.
-func CLSIDFromString(str string) (*GUID, error) {
- return nil, NewError(E_NOTIMPL)
-}
-
-// StringFromCLSID returns GUID formated string from GUID object.
-func StringFromCLSID(clsid *GUID) (string, error) {
- return "", NewError(E_NOTIMPL)
-}
-
-// IIDFromString returns GUID from program ID.
-func IIDFromString(progId string) (*GUID, error) {
- return nil, NewError(E_NOTIMPL)
-}
-
-// StringFromIID returns GUID formatted string from GUID object.
-func StringFromIID(iid *GUID) (string, error) {
- return "", NewError(E_NOTIMPL)
-}
-
-// CreateInstance of single uninitialized object with GUID.
-func CreateInstance(clsid *GUID, iid *GUID) (*IUnknown, error) {
- return nil, NewError(E_NOTIMPL)
-}
-
-// GetActiveObject retrieves pointer to active object.
-func GetActiveObject(clsid *GUID, iid *GUID) (*IUnknown, error) {
- return nil, NewError(E_NOTIMPL)
-}
-
-// VariantInit initializes variant.
-func VariantInit(v *VARIANT) error {
- return NewError(E_NOTIMPL)
-}
-
-// VariantClear clears value in Variant settings to VT_EMPTY.
-func VariantClear(v *VARIANT) error {
- return NewError(E_NOTIMPL)
-}
-
-// SysAllocString allocates memory for string and copies string into memory.
-func SysAllocString(v string) *int16 {
- u := int16(0)
- return &u
-}
-
-// SysAllocStringLen copies up to length of given string returning pointer.
-func SysAllocStringLen(v string) *int16 {
- u := int16(0)
- return &u
-}
-
-// SysFreeString frees string system memory. This must be called with SysAllocString.
-func SysFreeString(v *int16) error {
- return NewError(E_NOTIMPL)
-}
-
-// SysStringLen is the length of the system allocated string.
-func SysStringLen(v *int16) uint32 {
- return uint32(0)
-}
-
-// CreateStdDispatch provides default IDispatch implementation for IUnknown.
-//
-// This handles default IDispatch implementation for objects. It haves a few
-// limitations with only supporting one language. It will also only return
-// default exception codes.
-func CreateStdDispatch(unk *IUnknown, v uintptr, ptinfo *IUnknown) (*IDispatch, error) {
- return nil, NewError(E_NOTIMPL)
-}
-
-// CreateDispTypeInfo provides default ITypeInfo implementation for IDispatch.
-//
-// This will not handle the full implementation of the interface.
-func CreateDispTypeInfo(idata *INTERFACEDATA) (*IUnknown, error) {
- return nil, NewError(E_NOTIMPL)
-}
-
-// copyMemory moves location of a block of memory.
-func copyMemory(dest unsafe.Pointer, src unsafe.Pointer, length uint32) {}
-
-// GetUserDefaultLCID retrieves current user default locale.
-func GetUserDefaultLCID() uint32 {
- return uint32(0)
-}
-
-// GetMessage in message queue from runtime.
-//
-// This function appears to block. PeekMessage does not block.
-func GetMessage(msg *Msg, hwnd uint32, MsgFilterMin uint32, MsgFilterMax uint32) (int32, error) {
- return int32(0), NewError(E_NOTIMPL)
-}
-
-// DispatchMessage to window procedure.
-func DispatchMessage(msg *Msg) int32 {
- return int32(0)
-}
-
-func GetVariantDate(value float64) (time.Time, error) {
- return time.Now(), NewError(E_NOTIMPL)
-}
diff --git a/vendor/github.com/go-ole/go-ole/connect.go b/vendor/github.com/go-ole/go-ole/connect.go
deleted file mode 100644
index b2ac2ec67a..0000000000
--- a/vendor/github.com/go-ole/go-ole/connect.go
+++ /dev/null
@@ -1,192 +0,0 @@
-package ole
-
-// Connection contains IUnknown for fluent interface interaction.
-//
-// Deprecated. Use oleutil package instead.
-type Connection struct {
- Object *IUnknown // Access COM
-}
-
-// Initialize COM.
-func (*Connection) Initialize() (err error) {
- return coInitialize()
-}
-
-// Uninitialize COM.
-func (*Connection) Uninitialize() {
- CoUninitialize()
-}
-
-// Create IUnknown object based first on ProgId and then from String.
-func (c *Connection) Create(progId string) (err error) {
- var clsid *GUID
- clsid, err = CLSIDFromProgID(progId)
- if err != nil {
- clsid, err = CLSIDFromString(progId)
- if err != nil {
- return
- }
- }
-
- unknown, err := CreateInstance(clsid, IID_IUnknown)
- if err != nil {
- return
- }
- c.Object = unknown
-
- return
-}
-
-// Release IUnknown object.
-func (c *Connection) Release() {
- c.Object.Release()
-}
-
-// Load COM object from list of programIDs or strings.
-func (c *Connection) Load(names ...string) (errors []error) {
- var tempErrors []error = make([]error, len(names))
- var numErrors int = 0
- for _, name := range names {
- err := c.Create(name)
- if err != nil {
- tempErrors = append(tempErrors, err)
- numErrors += 1
- continue
- }
- break
- }
-
- copy(errors, tempErrors[0:numErrors])
- return
-}
-
-// Dispatch returns Dispatch object.
-func (c *Connection) Dispatch() (object *Dispatch, err error) {
- dispatch, err := c.Object.QueryInterface(IID_IDispatch)
- if err != nil {
- return
- }
- object = &Dispatch{dispatch}
- return
-}
-
-// Dispatch stores IDispatch object.
-type Dispatch struct {
- Object *IDispatch // Dispatch object.
-}
-
-// Call method on IDispatch with parameters.
-func (d *Dispatch) Call(method string, params ...interface{}) (result *VARIANT, err error) {
- id, err := d.GetId(method)
- if err != nil {
- return
- }
-
- result, err = d.Invoke(id, DISPATCH_METHOD, params)
- return
-}
-
-// MustCall method on IDispatch with parameters.
-func (d *Dispatch) MustCall(method string, params ...interface{}) (result *VARIANT) {
- id, err := d.GetId(method)
- if err != nil {
- panic(err)
- }
-
- result, err = d.Invoke(id, DISPATCH_METHOD, params)
- if err != nil {
- panic(err)
- }
-
- return
-}
-
-// Get property on IDispatch with parameters.
-func (d *Dispatch) Get(name string, params ...interface{}) (result *VARIANT, err error) {
- id, err := d.GetId(name)
- if err != nil {
- return
- }
- result, err = d.Invoke(id, DISPATCH_PROPERTYGET, params)
- return
-}
-
-// MustGet property on IDispatch with parameters.
-func (d *Dispatch) MustGet(name string, params ...interface{}) (result *VARIANT) {
- id, err := d.GetId(name)
- if err != nil {
- panic(err)
- }
-
- result, err = d.Invoke(id, DISPATCH_PROPERTYGET, params)
- if err != nil {
- panic(err)
- }
- return
-}
-
-// Set property on IDispatch with parameters.
-func (d *Dispatch) Set(name string, params ...interface{}) (result *VARIANT, err error) {
- id, err := d.GetId(name)
- if err != nil {
- return
- }
- result, err = d.Invoke(id, DISPATCH_PROPERTYPUT, params)
- return
-}
-
-// MustSet property on IDispatch with parameters.
-func (d *Dispatch) MustSet(name string, params ...interface{}) (result *VARIANT) {
- id, err := d.GetId(name)
- if err != nil {
- panic(err)
- }
-
- result, err = d.Invoke(id, DISPATCH_PROPERTYPUT, params)
- if err != nil {
- panic(err)
- }
- return
-}
-
-// GetId retrieves ID of name on IDispatch.
-func (d *Dispatch) GetId(name string) (id int32, err error) {
- var dispid []int32
- dispid, err = d.Object.GetIDsOfName([]string{name})
- if err != nil {
- return
- }
- id = dispid[0]
- return
-}
-
-// GetIds retrieves all IDs of names on IDispatch.
-func (d *Dispatch) GetIds(names ...string) (dispid []int32, err error) {
- dispid, err = d.Object.GetIDsOfName(names)
- return
-}
-
-// Invoke IDispatch on DisplayID of dispatch type with parameters.
-//
-// There have been problems where if send cascading params..., it would error
-// out because the parameters would be empty.
-func (d *Dispatch) Invoke(id int32, dispatch int16, params []interface{}) (result *VARIANT, err error) {
- if len(params) < 1 {
- result, err = d.Object.Invoke(id, dispatch)
- } else {
- result, err = d.Object.Invoke(id, dispatch, params...)
- }
- return
-}
-
-// Release IDispatch object.
-func (d *Dispatch) Release() {
- d.Object.Release()
-}
-
-// Connect initializes COM and attempts to load IUnknown based on given names.
-func Connect(names ...string) (connection *Connection) {
- connection.Initialize()
- connection.Load(names...)
- return
-}
diff --git a/vendor/github.com/go-ole/go-ole/constants.go b/vendor/github.com/go-ole/go-ole/constants.go
deleted file mode 100644
index fd0c6d74b0..0000000000
--- a/vendor/github.com/go-ole/go-ole/constants.go
+++ /dev/null
@@ -1,153 +0,0 @@
-package ole
-
-const (
- CLSCTX_INPROC_SERVER = 1
- CLSCTX_INPROC_HANDLER = 2
- CLSCTX_LOCAL_SERVER = 4
- CLSCTX_INPROC_SERVER16 = 8
- CLSCTX_REMOTE_SERVER = 16
- CLSCTX_ALL = CLSCTX_INPROC_SERVER | CLSCTX_INPROC_HANDLER | CLSCTX_LOCAL_SERVER
- CLSCTX_INPROC = CLSCTX_INPROC_SERVER | CLSCTX_INPROC_HANDLER
- CLSCTX_SERVER = CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER | CLSCTX_REMOTE_SERVER
-)
-
-const (
- COINIT_APARTMENTTHREADED = 0x2
- COINIT_MULTITHREADED = 0x0
- COINIT_DISABLE_OLE1DDE = 0x4
- COINIT_SPEED_OVER_MEMORY = 0x8
-)
-
-const (
- DISPATCH_METHOD = 1
- DISPATCH_PROPERTYGET = 2
- DISPATCH_PROPERTYPUT = 4
- DISPATCH_PROPERTYPUTREF = 8
-)
-
-const (
- S_OK = 0x00000000
- E_UNEXPECTED = 0x8000FFFF
- E_NOTIMPL = 0x80004001
- E_OUTOFMEMORY = 0x8007000E
- E_INVALIDARG = 0x80070057
- E_NOINTERFACE = 0x80004002
- E_POINTER = 0x80004003
- E_HANDLE = 0x80070006
- E_ABORT = 0x80004004
- E_FAIL = 0x80004005
- E_ACCESSDENIED = 0x80070005
- E_PENDING = 0x8000000A
-
- CO_E_CLASSSTRING = 0x800401F3
-)
-
-const (
- CC_FASTCALL = iota
- CC_CDECL
- CC_MSCPASCAL
- CC_PASCAL = CC_MSCPASCAL
- CC_MACPASCAL
- CC_STDCALL
- CC_FPFASTCALL
- CC_SYSCALL
- CC_MPWCDECL
- CC_MPWPASCAL
- CC_MAX = CC_MPWPASCAL
-)
-
-type VT uint16
-
-const (
- VT_EMPTY VT = 0x0
- VT_NULL VT = 0x1
- VT_I2 VT = 0x2
- VT_I4 VT = 0x3
- VT_R4 VT = 0x4
- VT_R8 VT = 0x5
- VT_CY VT = 0x6
- VT_DATE VT = 0x7
- VT_BSTR VT = 0x8
- VT_DISPATCH VT = 0x9
- VT_ERROR VT = 0xa
- VT_BOOL VT = 0xb
- VT_VARIANT VT = 0xc
- VT_UNKNOWN VT = 0xd
- VT_DECIMAL VT = 0xe
- VT_I1 VT = 0x10
- VT_UI1 VT = 0x11
- VT_UI2 VT = 0x12
- VT_UI4 VT = 0x13
- VT_I8 VT = 0x14
- VT_UI8 VT = 0x15
- VT_INT VT = 0x16
- VT_UINT VT = 0x17
- VT_VOID VT = 0x18
- VT_HRESULT VT = 0x19
- VT_PTR VT = 0x1a
- VT_SAFEARRAY VT = 0x1b
- VT_CARRAY VT = 0x1c
- VT_USERDEFINED VT = 0x1d
- VT_LPSTR VT = 0x1e
- VT_LPWSTR VT = 0x1f
- VT_RECORD VT = 0x24
- VT_INT_PTR VT = 0x25
- VT_UINT_PTR VT = 0x26
- VT_FILETIME VT = 0x40
- VT_BLOB VT = 0x41
- VT_STREAM VT = 0x42
- VT_STORAGE VT = 0x43
- VT_STREAMED_OBJECT VT = 0x44
- VT_STORED_OBJECT VT = 0x45
- VT_BLOB_OBJECT VT = 0x46
- VT_CF VT = 0x47
- VT_CLSID VT = 0x48
- VT_BSTR_BLOB VT = 0xfff
- VT_VECTOR VT = 0x1000
- VT_ARRAY VT = 0x2000
- VT_BYREF VT = 0x4000
- VT_RESERVED VT = 0x8000
- VT_ILLEGAL VT = 0xffff
- VT_ILLEGALMASKED VT = 0xfff
- VT_TYPEMASK VT = 0xfff
-)
-
-const (
- DISPID_UNKNOWN = -1
- DISPID_VALUE = 0
- DISPID_PROPERTYPUT = -3
- DISPID_NEWENUM = -4
- DISPID_EVALUATE = -5
- DISPID_CONSTRUCTOR = -6
- DISPID_DESTRUCTOR = -7
- DISPID_COLLECT = -8
-)
-
-const (
- TKIND_ENUM = 1
- TKIND_RECORD = 2
- TKIND_MODULE = 3
- TKIND_INTERFACE = 4
- TKIND_DISPATCH = 5
- TKIND_COCLASS = 6
- TKIND_ALIAS = 7
- TKIND_UNION = 8
- TKIND_MAX = 9
-)
-
-// Safe Array Feature Flags
-
-const (
- FADF_AUTO = 0x0001
- FADF_STATIC = 0x0002
- FADF_EMBEDDED = 0x0004
- FADF_FIXEDSIZE = 0x0010
- FADF_RECORD = 0x0020
- FADF_HAVEIID = 0x0040
- FADF_HAVEVARTYPE = 0x0080
- FADF_BSTR = 0x0100
- FADF_UNKNOWN = 0x0200
- FADF_DISPATCH = 0x0400
- FADF_VARIANT = 0x0800
- FADF_RESERVED = 0xF008
-)
diff --git a/vendor/github.com/go-ole/go-ole/error.go b/vendor/github.com/go-ole/go-ole/error.go
deleted file mode 100644
index 096b456d3a..0000000000
--- a/vendor/github.com/go-ole/go-ole/error.go
+++ /dev/null
@@ -1,51 +0,0 @@
-package ole
-
-// OleError stores COM errors.
-type OleError struct {
- hr uintptr
- description string
- subError error
-}
-
-// NewError creates new error with HResult.
-func NewError(hr uintptr) *OleError {
- return &OleError{hr: hr}
-}
-
-// NewErrorWithDescription creates new COM error with HResult and description.
-func NewErrorWithDescription(hr uintptr, description string) *OleError {
- return &OleError{hr: hr, description: description}
-}
-
-// NewErrorWithSubError creates new COM error with parent error.
-func NewErrorWithSubError(hr uintptr, description string, err error) *OleError {
- return &OleError{hr: hr, description: description, subError: err}
-}
-
-// Code is the HResult.
-func (v *OleError) Code() uintptr {
- return uintptr(v.hr)
-}
-
-// String description, either manually set or format message with error code.
-func (v *OleError) String() string {
- if v.description != "" {
- return errstr(int(v.hr)) + " (" + v.description + ")"
- }
- return errstr(int(v.hr))
-}
-
-// Error implements error interface.
-func (v *OleError) Error() string {
- return v.String()
-}
-
-// Description retrieves error summary, if there is one.
-func (v *OleError) Description() string {
- return v.description
-}
-
-// SubError returns parent error, if there is one.
-func (v *OleError) SubError() error {
- return v.subError
-}
diff --git a/vendor/github.com/go-ole/go-ole/error_func.go b/vendor/github.com/go-ole/go-ole/error_func.go
deleted file mode 100644
index 8a2ffaa272..0000000000
--- a/vendor/github.com/go-ole/go-ole/error_func.go
+++ /dev/null
@@ -1,8 +0,0 @@
-// +build !windows
-
-package ole
-
-// errstr converts error code to string.
-func errstr(errno int) string {
- return ""
-}
diff --git a/vendor/github.com/go-ole/go-ole/error_windows.go b/vendor/github.com/go-ole/go-ole/error_windows.go
deleted file mode 100644
index d0e8e68595..0000000000
--- a/vendor/github.com/go-ole/go-ole/error_windows.go
+++ /dev/null
@@ -1,24 +0,0 @@
-// +build windows
-
-package ole
-
-import (
- "fmt"
- "syscall"
- "unicode/utf16"
-)
-
-// errstr converts error code to string.
-func errstr(errno int) string {
- // ask windows for the remaining errors
- var flags uint32 = syscall.FORMAT_MESSAGE_FROM_SYSTEM | syscall.FORMAT_MESSAGE_ARGUMENT_ARRAY | syscall.FORMAT_MESSAGE_IGNORE_INSERTS
- b := make([]uint16, 300)
- n, err := syscall.FormatMessage(flags, 0, uint32(errno), 0, b, nil)
- if err != nil {
- return fmt.Sprintf("error %d (FormatMessage failed with: %v)", errno, err)
- }
- // trim terminating \r and \n
- for ; n > 0 && (b[n-1] == '\n' || b[n-1] == '\r'); n-- {
- }
- return string(utf16.Decode(b[:n]))
-}
diff --git a/vendor/github.com/go-ole/go-ole/guid.go b/vendor/github.com/go-ole/go-ole/guid.go
deleted file mode 100644
index 8d20f68fbf..0000000000
--- a/vendor/github.com/go-ole/go-ole/guid.go
+++ /dev/null
@@ -1,284 +0,0 @@
-package ole
-
-var (
- // IID_NULL is null Interface ID, used when no other Interface ID is known.
- IID_NULL = NewGUID("{00000000-0000-0000-0000-000000000000}")
-
- // IID_IUnknown is for IUnknown interfaces.
- IID_IUnknown = NewGUID("{00000000-0000-0000-C000-000000000046}")
-
- // IID_IDispatch is for IDispatch interfaces.
- IID_IDispatch = NewGUID("{00020400-0000-0000-C000-000000000046}")
-
- // IID_IEnumVariant is for IEnumVariant interfaces
- IID_IEnumVariant = NewGUID("{00020404-0000-0000-C000-000000000046}")
-
- // IID_IConnectionPointContainer is for IConnectionPointContainer interfaces.
- IID_IConnectionPointContainer = NewGUID("{B196B284-BAB4-101A-B69C-00AA00341D07}")
-
- // IID_IConnectionPoint is for IConnectionPoint interfaces.
- IID_IConnectionPoint = NewGUID("{B196B286-BAB4-101A-B69C-00AA00341D07}")
-
- // IID_IInspectable is for IInspectable interfaces.
- IID_IInspectable = NewGUID("{AF86E2E0-B12D-4C6A-9C5A-D7AA65101E90}")
-
- // IID_IProvideClassInfo is for IProvideClassInfo interfaces.
- IID_IProvideClassInfo = NewGUID("{B196B283-BAB4-101A-B69C-00AA00341D07}")
-)
-
-// These are for testing and not part of any library.
-var (
- // IID_ICOMTestString is for ICOMTestString interfaces.
- //
- // {E0133EB4-C36F-469A-9D3D-C66B84BE19ED}
- IID_ICOMTestString = NewGUID("{E0133EB4-C36F-469A-9D3D-C66B84BE19ED}")
-
- // IID_ICOMTestInt8 is for ICOMTestInt8 interfaces.
- //
- // {BEB06610-EB84-4155-AF58-E2BFF53680B4}
- IID_ICOMTestInt8 = NewGUID("{BEB06610-EB84-4155-AF58-E2BFF53680B4}")
-
- // IID_ICOMTestInt16 is for ICOMTestInt16 interfaces.
- //
- // {DAA3F9FA-761E-4976-A860-8364CE55F6FC}
- IID_ICOMTestInt16 = NewGUID("{DAA3F9FA-761E-4976-A860-8364CE55F6FC}")
-
- // IID_ICOMTestInt32 is for ICOMTestInt32 interfaces.
- //
- // {E3DEDEE7-38A2-4540-91D1-2EEF1D8891B0}
- IID_ICOMTestInt32 = NewGUID("{E3DEDEE7-38A2-4540-91D1-2EEF1D8891B0}")
-
- // IID_ICOMTestInt64 is for ICOMTestInt64 interfaces.
- //
- // {8D437CBC-B3ED-485C-BC32-C336432A1623}
- IID_ICOMTestInt64 = NewGUID("{8D437CBC-B3ED-485C-BC32-C336432A1623}")
-
- // IID_ICOMTestFloat is for ICOMTestFloat interfaces.
- //
- // {BF1ED004-EA02-456A-AA55-2AC8AC6B054C}
- IID_ICOMTestFloat = NewGUID("{BF1ED004-EA02-456A-AA55-2AC8AC6B054C}")
-
- // IID_ICOMTestDouble is for ICOMTestDouble interfaces.
- //
- // {BF908A81-8687-4E93-999F-D86FAB284BA0}
- IID_ICOMTestDouble = NewGUID("{BF908A81-8687-4E93-999F-D86FAB284BA0}")
-
- // IID_ICOMTestBoolean is for ICOMTestBoolean interfaces.
- //
- // {D530E7A6-4EE8-40D1-8931-3D63B8605010}
- IID_ICOMTestBoolean = NewGUID("{D530E7A6-4EE8-40D1-8931-3D63B8605010}")
-
- // IID_ICOMEchoTestObject is for ICOMEchoTestObject interfaces.
- //
- // {6485B1EF-D780-4834-A4FE-1EBB51746CA3}
- IID_ICOMEchoTestObject = NewGUID("{6485B1EF-D780-4834-A4FE-1EBB51746CA3}")
-
- // IID_ICOMTestTypes is for ICOMTestTypes interfaces.
- //
- // {CCA8D7AE-91C0-4277-A8B3-FF4EDF28D3C0}
- IID_ICOMTestTypes = NewGUID("{CCA8D7AE-91C0-4277-A8B3-FF4EDF28D3C0}")
-
- // CLSID_COMEchoTestObject is for COMEchoTestObject class.
- //
- // {3C24506A-AE9E-4D50-9157-EF317281F1B0}
- CLSID_COMEchoTestObject = NewGUID("{3C24506A-AE9E-4D50-9157-EF317281F1B0}")
-
- // CLSID_COMTestScalarClass is for COMTestScalarClass class.
- //
- // {865B85C5-0334-4AC6-9EF6-AACEC8FC5E86}
- CLSID_COMTestScalarClass = NewGUID("{865B85C5-0334-4AC6-9EF6-AACEC8FC5E86}")
-)
-
-const hextable = "0123456789ABCDEF"
-const emptyGUID = "{00000000-0000-0000-0000-000000000000}"
-
-// GUID is Windows API specific GUID type.
-//
-// This exists to match Windows GUID type for direct passing for COM.
-// Format is in xxxxxxxx-xxxx-xxxx-xxxxxxxxxxxxxxxx.
-type GUID struct {
- Data1 uint32
- Data2 uint16
- Data3 uint16
- Data4 [8]byte
-}
-
-// NewGUID converts the given string into a globally unique identifier that is
-// compliant with the Windows API.
-//
-// The supplied string may be in any of these formats:
-//
-// XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
-// XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
-// {XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}
-//
-// The conversion of the supplied string is not case-sensitive.
-func NewGUID(guid string) *GUID {
- d := []byte(guid)
- var d1, d2, d3, d4a, d4b []byte
-
- switch len(d) {
- case 38:
- if d[0] != '{' || d[37] != '}' {
- return nil
- }
- d = d[1:37]
- fallthrough
- case 36:
- if d[8] != '-' || d[13] != '-' || d[18] != '-' || d[23] != '-' {
- return nil
- }
- d1 = d[0:8]
- d2 = d[9:13]
- d3 = d[14:18]
- d4a = d[19:23]
- d4b = d[24:36]
- case 32:
- d1 = d[0:8]
- d2 = d[8:12]
- d3 = d[12:16]
- d4a = d[16:20]
- d4b = d[20:32]
- default:
- return nil
- }
-
- var g GUID
- var ok1, ok2, ok3, ok4 bool
- g.Data1, ok1 = decodeHexUint32(d1)
- g.Data2, ok2 = decodeHexUint16(d2)
- g.Data3, ok3 = decodeHexUint16(d3)
- g.Data4, ok4 = decodeHexByte64(d4a, d4b)
- if ok1 && ok2 && ok3 && ok4 {
- return &g
- }
- return nil
-}
-
-func decodeHexUint32(src []byte) (value uint32, ok bool) {
- var b1, b2, b3, b4 byte
- var ok1, ok2, ok3, ok4 bool
- b1, ok1 = decodeHexByte(src[0], src[1])
- b2, ok2 = decodeHexByte(src[2], src[3])
- b3, ok3 = decodeHexByte(src[4], src[5])
- b4, ok4 = decodeHexByte(src[6], src[7])
- value = (uint32(b1) << 24) | (uint32(b2) << 16) | (uint32(b3) << 8) | uint32(b4)
- ok = ok1 && ok2 && ok3 && ok4
- return
-}
-
-func decodeHexUint16(src []byte) (value uint16, ok bool) {
- var b1, b2 byte
- var ok1, ok2 bool
- b1, ok1 = decodeHexByte(src[0], src[1])
- b2, ok2 = decodeHexByte(src[2], src[3])
- value = (uint16(b1) << 8) | uint16(b2)
- ok = ok1 && ok2
- return
-}
-
-func decodeHexByte64(s1 []byte, s2 []byte) (value [8]byte, ok bool) {
- var ok1, ok2, ok3, ok4, ok5, ok6, ok7, ok8 bool
- value[0], ok1 = decodeHexByte(s1[0], s1[1])
- value[1], ok2 = decodeHexByte(s1[2], s1[3])
- value[2], ok3 = decodeHexByte(s2[0], s2[1])
- value[3], ok4 = decodeHexByte(s2[2], s2[3])
- value[4], ok5 = decodeHexByte(s2[4], s2[5])
- value[5], ok6 = decodeHexByte(s2[6], s2[7])
- value[6], ok7 = decodeHexByte(s2[8], s2[9])
- value[7], ok8 = decodeHexByte(s2[10], s2[11])
- ok = ok1 && ok2 && ok3 && ok4 && ok5 && ok6 && ok7 && ok8
- return
-}
-
-func decodeHexByte(c1, c2 byte) (value byte, ok bool) {
- var n1, n2 byte
- var ok1, ok2 bool
- n1, ok1 = decodeHexChar(c1)
- n2, ok2 = decodeHexChar(c2)
- value = (n1 << 4) | n2
- ok = ok1 && ok2
- return
-}
-
-func decodeHexChar(c byte) (byte, bool) {
- switch {
- case '0' <= c && c <= '9':
- return c - '0', true
- case 'a' <= c && c <= 'f':
- return c - 'a' + 10, true
- case 'A' <= c && c <= 'F':
- return c - 'A' + 10, true
- }
-
- return 0, false
-}
-
-// String converts the GUID to string form. It will adhere to this pattern:
-//
-// {XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}
-//
-// If the GUID is nil, the string representation of an empty GUID is returned:
-//
-// {00000000-0000-0000-0000-000000000000}
-func (guid *GUID) String() string {
- if guid == nil {
- return emptyGUID
- }
-
- var c [38]byte
- c[0] = '{'
- putUint32Hex(c[1:9], guid.Data1)
- c[9] = '-'
- putUint16Hex(c[10:14], guid.Data2)
- c[14] = '-'
- putUint16Hex(c[15:19], guid.Data3)
- c[19] = '-'
- putByteHex(c[20:24], guid.Data4[0:2])
- c[24] = '-'
- putByteHex(c[25:37], guid.Data4[2:8])
- c[37] = '}'
- return string(c[:])
-}
-
-func putUint32Hex(b []byte, v uint32) {
- b[0] = hextable[byte(v>>24)>>4]
- b[1] = hextable[byte(v>>24)&0x0f]
- b[2] = hextable[byte(v>>16)>>4]
- b[3] = hextable[byte(v>>16)&0x0f]
- b[4] = hextable[byte(v>>8)>>4]
- b[5] = hextable[byte(v>>8)&0x0f]
- b[6] = hextable[byte(v)>>4]
- b[7] = hextable[byte(v)&0x0f]
-}
-
-func putUint16Hex(b []byte, v uint16) {
- b[0] = hextable[byte(v>>8)>>4]
- b[1] = hextable[byte(v>>8)&0x0f]
- b[2] = hextable[byte(v)>>4]
- b[3] = hextable[byte(v)&0x0f]
-}
-
-func putByteHex(dst, src []byte) {
- for i := 0; i < len(src); i++ {
- dst[i*2] = hextable[src[i]>>4]
- dst[i*2+1] = hextable[src[i]&0x0f]
- }
-}
-
-// IsEqualGUID compares two GUID.
-//
-// Not constant time comparison.
-func IsEqualGUID(guid1 *GUID, guid2 *GUID) bool {
- return guid1.Data1 == guid2.Data1 &&
- guid1.Data2 == guid2.Data2 &&
- guid1.Data3 == guid2.Data3 &&
- guid1.Data4[0] == guid2.Data4[0] &&
- guid1.Data4[1] == guid2.Data4[1] &&
- guid1.Data4[2] == guid2.Data4[2] &&
- guid1.Data4[3] == guid2.Data4[3] &&
- guid1.Data4[4] == guid2.Data4[4] &&
- guid1.Data4[5] == guid2.Data4[5] &&
- guid1.Data4[6] == guid2.Data4[6] &&
- guid1.Data4[7] == guid2.Data4[7]
-}
diff --git a/vendor/github.com/go-ole/go-ole/iconnectionpoint.go b/vendor/github.com/go-ole/go-ole/iconnectionpoint.go
deleted file mode 100644
index 9e6c49f41f..0000000000
--- a/vendor/github.com/go-ole/go-ole/iconnectionpoint.go
+++ /dev/null
@@ -1,20 +0,0 @@
-package ole
-
-import "unsafe"
-
-type IConnectionPoint struct {
- IUnknown
-}
-
-type IConnectionPointVtbl struct {
- IUnknownVtbl
- GetConnectionInterface uintptr
- GetConnectionPointContainer uintptr
- Advise uintptr
- Unadvise uintptr
- EnumConnections uintptr
-}
-
-func (v *IConnectionPoint) VTable() *IConnectionPointVtbl {
- return (*IConnectionPointVtbl)(unsafe.Pointer(v.RawVTable))
-}
diff --git a/vendor/github.com/go-ole/go-ole/iconnectionpoint_func.go b/vendor/github.com/go-ole/go-ole/iconnectionpoint_func.go
deleted file mode 100644
index 5414dc3cd3..0000000000
--- a/vendor/github.com/go-ole/go-ole/iconnectionpoint_func.go
+++ /dev/null
@@ -1,21 +0,0 @@
-// +build !windows
-
-package ole
-
-import "unsafe"
-
-func (v *IConnectionPoint) GetConnectionInterface(piid **GUID) int32 {
- return int32(0)
-}
-
-func (v *IConnectionPoint) Advise(unknown *IUnknown) (uint32, error) {
- return uint32(0), NewError(E_NOTIMPL)
-}
-
-func (v *IConnectionPoint) Unadvise(cookie uint32) error {
- return NewError(E_NOTIMPL)
-}
-
-func (v *IConnectionPoint) EnumConnections(p *unsafe.Pointer) (err error) {
- return NewError(E_NOTIMPL)
-}
diff --git a/vendor/github.com/go-ole/go-ole/iconnectionpoint_windows.go b/vendor/github.com/go-ole/go-ole/iconnectionpoint_windows.go
deleted file mode 100644
index 32bc183248..0000000000
--- a/vendor/github.com/go-ole/go-ole/iconnectionpoint_windows.go
+++ /dev/null
@@ -1,43 +0,0 @@
-// +build windows
-
-package ole
-
-import (
- "syscall"
- "unsafe"
-)
-
-func (v *IConnectionPoint) GetConnectionInterface(piid **GUID) int32 {
- // XXX: This doesn't look like it does what it's supposed to
- return release((*IUnknown)(unsafe.Pointer(v)))
-}
-
-func (v *IConnectionPoint) Advise(unknown *IUnknown) (cookie uint32, err error) {
- hr, _, _ := syscall.Syscall(
- v.VTable().Advise,
- 3,
- uintptr(unsafe.Pointer(v)),
- uintptr(unsafe.Pointer(unknown)),
- uintptr(unsafe.Pointer(&cookie)))
- if hr != 0 {
- err = NewError(hr)
- }
- return
-}
-
-func (v *IConnectionPoint) Unadvise(cookie uint32) (err error) {
- hr, _, _ := syscall.Syscall(
- v.VTable().Unadvise,
- 2,
- uintptr(unsafe.Pointer(v)),
- uintptr(cookie),
- 0)
- if hr != 0 {
- err = NewError(hr)
- }
- return
-}
-
-func (v *IConnectionPoint) EnumConnections(p *unsafe.Pointer) error {
- return NewError(E_NOTIMPL)
-}
diff --git a/vendor/github.com/go-ole/go-ole/iconnectionpointcontainer.go b/vendor/github.com/go-ole/go-ole/iconnectionpointcontainer.go
deleted file mode 100644
index 165860d199..0000000000
--- a/vendor/github.com/go-ole/go-ole/iconnectionpointcontainer.go
+++ /dev/null
@@ -1,17 +0,0 @@
-package ole
-
-import "unsafe"
-
-type IConnectionPointContainer struct {
- IUnknown
-}
-
-type IConnectionPointContainerVtbl struct {
- IUnknownVtbl
- EnumConnectionPoints uintptr
- FindConnectionPoint uintptr
-}
-
-func (v *IConnectionPointContainer) VTable() *IConnectionPointContainerVtbl {
- return (*IConnectionPointContainerVtbl)(unsafe.Pointer(v.RawVTable))
-}
diff --git a/vendor/github.com/go-ole/go-ole/iconnectionpointcontainer_func.go b/vendor/github.com/go-ole/go-ole/iconnectionpointcontainer_func.go
deleted file mode 100644
index 5dfa42aaeb..0000000000
--- a/vendor/github.com/go-ole/go-ole/iconnectionpointcontainer_func.go
+++ /dev/null
@@ -1,11 +0,0 @@
-// +build !windows
-
-package ole
-
-func (v *IConnectionPointContainer) EnumConnectionPoints(points interface{}) error {
- return NewError(E_NOTIMPL)
-}
-
-func (v *IConnectionPointContainer) FindConnectionPoint(iid *GUID, point **IConnectionPoint) error {
- return NewError(E_NOTIMPL)
-}
diff --git a/vendor/github.com/go-ole/go-ole/iconnectionpointcontainer_windows.go b/vendor/github.com/go-ole/go-ole/iconnectionpointcontainer_windows.go
deleted file mode 100644
index ad30d79efc..0000000000
--- a/vendor/github.com/go-ole/go-ole/iconnectionpointcontainer_windows.go
+++ /dev/null
@@ -1,25 +0,0 @@
-// +build windows
-
-package ole
-
-import (
- "syscall"
- "unsafe"
-)
-
-func (v *IConnectionPointContainer) EnumConnectionPoints(points interface{}) error {
- return NewError(E_NOTIMPL)
-}
-
-func (v *IConnectionPointContainer) FindConnectionPoint(iid *GUID, point **IConnectionPoint) (err error) {
- hr, _, _ := syscall.Syscall(
- v.VTable().FindConnectionPoint,
- 3,
- uintptr(unsafe.Pointer(v)),
- uintptr(unsafe.Pointer(iid)),
- uintptr(unsafe.Pointer(point)))
- if hr != 0 {
- err = NewError(hr)
- }
- return
-}
diff --git a/vendor/github.com/go-ole/go-ole/idispatch.go b/vendor/github.com/go-ole/go-ole/idispatch.go
deleted file mode 100644
index d4af124092..0000000000
--- a/vendor/github.com/go-ole/go-ole/idispatch.go
+++ /dev/null
@@ -1,94 +0,0 @@
-package ole
-
-import "unsafe"
-
-type IDispatch struct {
- IUnknown
-}
-
-type IDispatchVtbl struct {
- IUnknownVtbl
- GetTypeInfoCount uintptr
- GetTypeInfo uintptr
- GetIDsOfNames uintptr
- Invoke uintptr
-}
-
-func (v *IDispatch) VTable() *IDispatchVtbl {
- return (*IDispatchVtbl)(unsafe.Pointer(v.RawVTable))
-}
-
-func (v *IDispatch) GetIDsOfName(names []string) (dispid []int32, err error) {
- dispid, err = getIDsOfName(v, names)
- return
-}
-
-func (v *IDispatch) Invoke(dispid int32, dispatch int16, params ...interface{}) (result *VARIANT, err error) {
- result, err = invoke(v, dispid, dispatch, params...)
- return
-}
-
-func (v *IDispatch) GetTypeInfoCount() (c uint32, err error) {
- c, err = getTypeInfoCount(v)
- return
-}
-
-func (v *IDispatch) GetTypeInfo() (tinfo *ITypeInfo, err error) {
- tinfo, err = getTypeInfo(v)
- return
-}
-
-// GetSingleIDOfName is a helper that returns single display ID for IDispatch name.
-//
-// This replaces the common pattern of attempting to get a single name from the list of available
-// IDs. It gives the first ID, if it is available.
-func (v *IDispatch) GetSingleIDOfName(name string) (displayID int32, err error) {
- var displayIDs []int32
- displayIDs, err = v.GetIDsOfName([]string{name})
- if err != nil {
- return
- }
- displayID = displayIDs[0]
- return
-}
-
-// InvokeWithOptionalArgs accepts arguments as an array, works like Invoke.
-//
-// Accepts name and will attempt to retrieve Display ID to pass to Invoke.
-//
-// Passing params as an array is a workaround that could be fixed in later versions of Go that
-// prevent passing empty params. During testing it was discovered that this is an acceptable way of
-// getting around not being able to pass params normally.
-func (v *IDispatch) InvokeWithOptionalArgs(name string, dispatch int16, params []interface{}) (result *VARIANT, err error) {
- displayID, err := v.GetSingleIDOfName(name)
- if err != nil {
- return
- }
-
- if len(params) < 1 {
- result, err = v.Invoke(displayID, dispatch)
- } else {
- result, err = v.Invoke(displayID, dispatch, params...)
- }
-
- return
-}
-
-// CallMethod invokes named function with arguments on object.
-func (v *IDispatch) CallMethod(name string, params ...interface{}) (*VARIANT, error) {
- return v.InvokeWithOptionalArgs(name, DISPATCH_METHOD, params)
-}
-
-// GetProperty retrieves the property with the name with the ability to pass arguments.
-//
-// Most of the time you will not need to pass arguments as most objects do not allow for this
-// feature. Or at least, should not allow for this feature. Some servers don't follow best practices
-// and this is provided for those edge cases.
-func (v *IDispatch) GetProperty(name string, params ...interface{}) (*VARIANT, error) {
- return v.InvokeWithOptionalArgs(name, DISPATCH_PROPERTYGET, params)
-}
-
-// PutProperty attempts to mutate a property in the object.
-func (v *IDispatch) PutProperty(name string, params ...interface{}) (*VARIANT, error) {
- return v.InvokeWithOptionalArgs(name, DISPATCH_PROPERTYPUT, params)
-}
diff --git a/vendor/github.com/go-ole/go-ole/idispatch_func.go b/vendor/github.com/go-ole/go-ole/idispatch_func.go
deleted file mode 100644
index b8fbbe319f..0000000000
--- a/vendor/github.com/go-ole/go-ole/idispatch_func.go
+++ /dev/null
@@ -1,19 +0,0 @@
-// +build !windows
-
-package ole
-
-func getIDsOfName(disp *IDispatch, names []string) ([]int32, error) {
- return []int32{}, NewError(E_NOTIMPL)
-}
-
-func getTypeInfoCount(disp *IDispatch) (uint32, error) {
- return uint32(0), NewError(E_NOTIMPL)
-}
-
-func getTypeInfo(disp *IDispatch) (*ITypeInfo, error) {
- return nil, NewError(E_NOTIMPL)
-}
-
-func invoke(disp *IDispatch, dispid int32, dispatch int16, params ...interface{}) (*VARIANT, error) {
- return nil, NewError(E_NOTIMPL)
-}
diff --git a/vendor/github.com/go-ole/go-ole/idispatch_windows.go b/vendor/github.com/go-ole/go-ole/idispatch_windows.go
deleted file mode 100644
index 020e4f51b0..0000000000
--- a/vendor/github.com/go-ole/go-ole/idispatch_windows.go
+++ /dev/null
@@ -1,197 +0,0 @@
-// +build windows
-
-package ole
-
-import (
- "syscall"
- "time"
- "unsafe"
-)
-
-func getIDsOfName(disp *IDispatch, names []string) (dispid []int32, err error) {
- wnames := make([]*uint16, len(names))
- for i := 0; i < len(names); i++ {
- wnames[i] = syscall.StringToUTF16Ptr(names[i])
- }
- dispid = make([]int32, len(names))
- namelen := uint32(len(names))
- hr, _, _ := syscall.Syscall6(
- disp.VTable().GetIDsOfNames,
- 6,
- uintptr(unsafe.Pointer(disp)),
- uintptr(unsafe.Pointer(IID_NULL)),
- uintptr(unsafe.Pointer(&wnames[0])),
- uintptr(namelen),
- uintptr(GetUserDefaultLCID()),
- uintptr(unsafe.Pointer(&dispid[0])))
- if hr != 0 {
- err = NewError(hr)
- }
- return
-}
-
-func getTypeInfoCount(disp *IDispatch) (c uint32, err error) {
- hr, _, _ := syscall.Syscall(
- disp.VTable().GetTypeInfoCount,
- 2,
- uintptr(unsafe.Pointer(disp)),
- uintptr(unsafe.Pointer(&c)),
- 0)
- if hr != 0 {
- err = NewError(hr)
- }
- return
-}
-
-func getTypeInfo(disp *IDispatch) (tinfo *ITypeInfo, err error) {
- hr, _, _ := syscall.Syscall(
- disp.VTable().GetTypeInfo,
- 3,
- uintptr(unsafe.Pointer(disp)),
- uintptr(GetUserDefaultLCID()),
- uintptr(unsafe.Pointer(&tinfo)))
- if hr != 0 {
- err = NewError(hr)
- }
- return
-}
-
-func invoke(disp *IDispatch, dispid int32, dispatch int16, params ...interface{}) (result *VARIANT, err error) {
- var dispparams DISPPARAMS
-
- if dispatch&DISPATCH_PROPERTYPUT != 0 {
- dispnames := [1]int32{DISPID_PROPERTYPUT}
- dispparams.rgdispidNamedArgs = uintptr(unsafe.Pointer(&dispnames[0]))
- dispparams.cNamedArgs = 1
- } else if dispatch&DISPATCH_PROPERTYPUTREF != 0 {
- dispnames := [1]int32{DISPID_PROPERTYPUT}
- dispparams.rgdispidNamedArgs = uintptr(unsafe.Pointer(&dispnames[0]))
- dispparams.cNamedArgs = 1
- }
- var vargs []VARIANT
- if len(params) > 0 {
- vargs = make([]VARIANT, len(params))
- for i, v := range params {
- //n := len(params)-i-1
- n := len(params) - i - 1
- VariantInit(&vargs[n])
- switch vv := v.(type) {
- case bool:
- if vv {
- vargs[n] = NewVariant(VT_BOOL, 0xffff)
- } else {
- vargs[n] = NewVariant(VT_BOOL, 0)
- }
- case *bool:
- vargs[n] = NewVariant(VT_BOOL|VT_BYREF, int64(uintptr(unsafe.Pointer(v.(*bool)))))
- case uint8:
- vargs[n] = NewVariant(VT_I1, int64(v.(uint8)))
- case *uint8:
- vargs[n] = NewVariant(VT_I1|VT_BYREF, int64(uintptr(unsafe.Pointer(v.(*uint8)))))
- case int8:
- vargs[n] = NewVariant(VT_I1, int64(v.(int8)))
- case *int8:
- vargs[n] = NewVariant(VT_I1|VT_BYREF, int64(uintptr(unsafe.Pointer(v.(*uint8)))))
- case int16:
- vargs[n] = NewVariant(VT_I2, int64(v.(int16)))
- case *int16:
- vargs[n] = NewVariant(VT_I2|VT_BYREF, int64(uintptr(unsafe.Pointer(v.(*int16)))))
- case uint16:
- vargs[n] = NewVariant(VT_UI2, int64(v.(uint16)))
- case *uint16:
- vargs[n] = NewVariant(VT_UI2|VT_BYREF, int64(uintptr(unsafe.Pointer(v.(*uint16)))))
- case int32:
- vargs[n] = NewVariant(VT_I4, int64(v.(int32)))
- case *int32:
- vargs[n] = NewVariant(VT_I4|VT_BYREF, int64(uintptr(unsafe.Pointer(v.(*int32)))))
- case uint32:
- vargs[n] = NewVariant(VT_UI4, int64(v.(uint32)))
- case *uint32:
- vargs[n] = NewVariant(VT_UI4|VT_BYREF, int64(uintptr(unsafe.Pointer(v.(*uint32)))))
- case int64:
- vargs[n] = NewVariant(VT_I8, int64(v.(int64)))
- case *int64:
- vargs[n] = NewVariant(VT_I8|VT_BYREF, int64(uintptr(unsafe.Pointer(v.(*int64)))))
- case uint64:
- vargs[n] = NewVariant(VT_UI8, int64(uintptr(v.(uint64))))
- case *uint64:
- vargs[n] = NewVariant(VT_UI8|VT_BYREF, int64(uintptr(unsafe.Pointer(v.(*uint64)))))
- case int:
- vargs[n] = NewVariant(VT_I4, int64(v.(int)))
- case *int:
- vargs[n] = NewVariant(VT_I4|VT_BYREF, int64(uintptr(unsafe.Pointer(v.(*int)))))
- case uint:
- vargs[n] = NewVariant(VT_UI4, int64(v.(uint)))
- case *uint:
- vargs[n] = NewVariant(VT_UI4|VT_BYREF, int64(uintptr(unsafe.Pointer(v.(*uint)))))
- case float32:
- vargs[n] = NewVariant(VT_R4, *(*int64)(unsafe.Pointer(&vv)))
- case *float32:
- vargs[n] = NewVariant(VT_R4|VT_BYREF, int64(uintptr(unsafe.Pointer(v.(*float32)))))
- case float64:
- vargs[n] = NewVariant(VT_R8, *(*int64)(unsafe.Pointer(&vv)))
- case *float64:
- vargs[n] = NewVariant(VT_R8|VT_BYREF, int64(uintptr(unsafe.Pointer(v.(*float64)))))
- case string:
- vargs[n] = NewVariant(VT_BSTR, int64(uintptr(unsafe.Pointer(SysAllocStringLen(v.(string))))))
- case *string:
- vargs[n] = NewVariant(VT_BSTR|VT_BYREF, int64(uintptr(unsafe.Pointer(v.(*string)))))
- case time.Time:
- s := vv.Format("2006-01-02 15:04:05")
- vargs[n] = NewVariant(VT_BSTR, int64(uintptr(unsafe.Pointer(SysAllocStringLen(s)))))
- case *time.Time:
- s := vv.Format("2006-01-02 15:04:05")
- vargs[n] = NewVariant(VT_BSTR|VT_BYREF, int64(uintptr(unsafe.Pointer(&s))))
- case *IDispatch:
- vargs[n] = NewVariant(VT_DISPATCH, int64(uintptr(unsafe.Pointer(v.(*IDispatch)))))
- case **IDispatch:
- vargs[n] = NewVariant(VT_DISPATCH|VT_BYREF, int64(uintptr(unsafe.Pointer(v.(**IDispatch)))))
- case nil:
- vargs[n] = NewVariant(VT_NULL, 0)
- case *VARIANT:
- vargs[n] = NewVariant(VT_VARIANT|VT_BYREF, int64(uintptr(unsafe.Pointer(v.(*VARIANT)))))
- case []byte:
- safeByteArray := safeArrayFromByteSlice(v.([]byte))
- vargs[n] = NewVariant(VT_ARRAY|VT_UI1, int64(uintptr(unsafe.Pointer(safeByteArray))))
- defer VariantClear(&vargs[n])
- case []string:
- safeByteArray := safeArrayFromStringSlice(v.([]string))
- vargs[n] = NewVariant(VT_ARRAY|VT_BSTR, int64(uintptr(unsafe.Pointer(safeByteArray))))
- defer VariantClear(&vargs[n])
- default:
- panic("unknown type")
- }
- }
- dispparams.rgvarg = uintptr(unsafe.Pointer(&vargs[0]))
- dispparams.cArgs = uint32(len(params))
- }
-
- result = new(VARIANT)
- var excepInfo EXCEPINFO
- VariantInit(result)
- hr, _, _ := syscall.Syscall9(
- disp.VTable().Invoke,
- 9,
- uintptr(unsafe.Pointer(disp)),
- uintptr(dispid),
- uintptr(unsafe.Pointer(IID_NULL)),
- uintptr(GetUserDefaultLCID()),
- uintptr(dispatch),
- uintptr(unsafe.Pointer(&dispparams)),
- uintptr(unsafe.Pointer(result)),
- uintptr(unsafe.Pointer(&excepInfo)),
- 0)
- if hr != 0 {
- err = NewErrorWithSubError(hr, BstrToString(excepInfo.bstrDescription), excepInfo)
- }
- for i, varg := range vargs {
- n := len(params) - i - 1
- if varg.VT == VT_BSTR && varg.Val != 0 {
- SysFreeString(((*int16)(unsafe.Pointer(uintptr(varg.Val)))))
- }
- if varg.VT == (VT_BSTR|VT_BYREF) && varg.Val != 0 {
- *(params[n].(*string)) = LpOleStrToString(*(**uint16)(unsafe.Pointer(uintptr(varg.Val))))
- }
- }
- return
-}
diff --git a/vendor/github.com/go-ole/go-ole/ienumvariant.go b/vendor/github.com/go-ole/go-ole/ienumvariant.go
deleted file mode 100644
index 2433897544..0000000000
--- a/vendor/github.com/go-ole/go-ole/ienumvariant.go
+++ /dev/null
@@ -1,19 +0,0 @@
-package ole
-
-import "unsafe"
-
-type IEnumVARIANT struct {
- IUnknown
-}
-
-type IEnumVARIANTVtbl struct {
- IUnknownVtbl
- Next uintptr
- Skip uintptr
- Reset uintptr
- Clone uintptr
-}
-
-func (v *IEnumVARIANT) VTable() *IEnumVARIANTVtbl {
- return (*IEnumVARIANTVtbl)(unsafe.Pointer(v.RawVTable))
-}
diff --git a/vendor/github.com/go-ole/go-ole/ienumvariant_func.go b/vendor/github.com/go-ole/go-ole/ienumvariant_func.go
deleted file mode 100644
index c14848199c..0000000000
--- a/vendor/github.com/go-ole/go-ole/ienumvariant_func.go
+++ /dev/null
@@ -1,19 +0,0 @@
-// +build !windows
-
-package ole
-
-func (enum *IEnumVARIANT) Clone() (*IEnumVARIANT, error) {
- return nil, NewError(E_NOTIMPL)
-}
-
-func (enum *IEnumVARIANT) Reset() error {
- return NewError(E_NOTIMPL)
-}
-
-func (enum *IEnumVARIANT) Skip(celt uint) error {
- return NewError(E_NOTIMPL)
-}
-
-func (enum *IEnumVARIANT) Next(celt uint) (VARIANT, uint, error) {
- return NewVariant(VT_NULL, int64(0)), 0, NewError(E_NOTIMPL)
-}
diff --git a/vendor/github.com/go-ole/go-ole/ienumvariant_windows.go b/vendor/github.com/go-ole/go-ole/ienumvariant_windows.go
deleted file mode 100644
index 4781f3b8b0..0000000000
--- a/vendor/github.com/go-ole/go-ole/ienumvariant_windows.go
+++ /dev/null
@@ -1,63 +0,0 @@
-// +build windows
-
-package ole
-
-import (
- "syscall"
- "unsafe"
-)
-
-func (enum *IEnumVARIANT) Clone() (cloned *IEnumVARIANT, err error) {
- hr, _, _ := syscall.Syscall(
- enum.VTable().Clone,
- 2,
- uintptr(unsafe.Pointer(enum)),
- uintptr(unsafe.Pointer(&cloned)),
- 0)
- if hr != 0 {
- err = NewError(hr)
- }
- return
-}
-
-func (enum *IEnumVARIANT) Reset() (err error) {
- hr, _, _ := syscall.Syscall(
- enum.VTable().Reset,
- 1,
- uintptr(unsafe.Pointer(enum)),
- 0,
- 0)
- if hr != 0 {
- err = NewError(hr)
- }
- return
-}
-
-func (enum *IEnumVARIANT) Skip(celt uint) (err error) {
- hr, _, _ := syscall.Syscall(
- enum.VTable().Skip,
- 2,
- uintptr(unsafe.Pointer(enum)),
- uintptr(celt),
- 0)
- if hr != 0 {
- err = NewError(hr)
- }
- return
-}
-
-func (enum *IEnumVARIANT) Next(celt uint) (array VARIANT, length uint, err error) {
- hr, _, _ := syscall.Syscall6(
- enum.VTable().Next,
- 4,
- uintptr(unsafe.Pointer(enum)),
- uintptr(celt),
- uintptr(unsafe.Pointer(&array)),
- uintptr(unsafe.Pointer(&length)),
- 0,
- 0)
- if hr != 0 {
- err = NewError(hr)
- }
- return
-}
diff --git a/vendor/github.com/go-ole/go-ole/iinspectable.go b/vendor/github.com/go-ole/go-ole/iinspectable.go
deleted file mode 100644
index f4a19e253a..0000000000
--- a/vendor/github.com/go-ole/go-ole/iinspectable.go
+++ /dev/null
@@ -1,18 +0,0 @@
-package ole
-
-import "unsafe"
-
-type IInspectable struct {
- IUnknown
-}
-
-type IInspectableVtbl struct {
- IUnknownVtbl
- GetIIds uintptr
- GetRuntimeClassName uintptr
- GetTrustLevel uintptr
-}
-
-func (v *IInspectable) VTable() *IInspectableVtbl {
- return (*IInspectableVtbl)(unsafe.Pointer(v.RawVTable))
-}
diff --git a/vendor/github.com/go-ole/go-ole/iinspectable_func.go b/vendor/github.com/go-ole/go-ole/iinspectable_func.go
deleted file mode 100644
index 348829bf06..0000000000
--- a/vendor/github.com/go-ole/go-ole/iinspectable_func.go
+++ /dev/null
@@ -1,15 +0,0 @@
-// +build !windows
-
-package ole
-
-func (v *IInspectable) GetIids() ([]*GUID, error) {
- return []*GUID{}, NewError(E_NOTIMPL)
-}
-
-func (v *IInspectable) GetRuntimeClassName() (string, error) {
- return "", NewError(E_NOTIMPL)
-}
-
-func (v *IInspectable) GetTrustLevel() (uint32, error) {
- return uint32(0), NewError(E_NOTIMPL)
-}
diff --git a/vendor/github.com/go-ole/go-ole/iinspectable_windows.go b/vendor/github.com/go-ole/go-ole/iinspectable_windows.go
deleted file mode 100644
index 4519a4aa44..0000000000
--- a/vendor/github.com/go-ole/go-ole/iinspectable_windows.go
+++ /dev/null
@@ -1,72 +0,0 @@
-// +build windows
-
-package ole
-
-import (
- "bytes"
- "encoding/binary"
- "reflect"
- "syscall"
- "unsafe"
-)
-
-func (v *IInspectable) GetIids() (iids []*GUID, err error) {
- var count uint32
- var array uintptr
- hr, _, _ := syscall.Syscall(
- v.VTable().GetIIds,
- 3,
- uintptr(unsafe.Pointer(v)),
- uintptr(unsafe.Pointer(&count)),
- uintptr(unsafe.Pointer(&array)))
- if hr != 0 {
- err = NewError(hr)
- return
- }
- defer CoTaskMemFree(array)
-
- iids = make([]*GUID, count)
- byteCount := count * uint32(unsafe.Sizeof(GUID{}))
- slicehdr := reflect.SliceHeader{Data: array, Len: int(byteCount), Cap: int(byteCount)}
- byteSlice := *(*[]byte)(unsafe.Pointer(&slicehdr))
- reader := bytes.NewReader(byteSlice)
- for i := range iids {
- guid := GUID{}
- err = binary.Read(reader, binary.LittleEndian, &guid)
- if err != nil {
- return
- }
- iids[i] = &guid
- }
- return
-}
-
-func (v *IInspectable) GetRuntimeClassName() (s string, err error) {
- var hstring HString
- hr, _, _ := syscall.Syscall(
- v.VTable().GetRuntimeClassName,
- 2,
- uintptr(unsafe.Pointer(v)),
- uintptr(unsafe.Pointer(&hstring)),
- 0)
- if hr != 0 {
- err = NewError(hr)
- return
- }
- s = hstring.String()
- DeleteHString(hstring)
- return
-}
-
-func (v *IInspectable) GetTrustLevel() (level uint32, err error) {
- hr, _, _ := syscall.Syscall(
- v.VTable().GetTrustLevel,
- 2,
- uintptr(unsafe.Pointer(v)),
- uintptr(unsafe.Pointer(&level)),
- 0)
- if hr != 0 {
- err = NewError(hr)
- }
- return
-}
diff --git a/vendor/github.com/go-ole/go-ole/iprovideclassinfo.go b/vendor/github.com/go-ole/go-ole/iprovideclassinfo.go
deleted file mode 100644
index 25f3a6f24a..0000000000
--- a/vendor/github.com/go-ole/go-ole/iprovideclassinfo.go
+++ /dev/null
@@ -1,21 +0,0 @@
-package ole
-
-import "unsafe"
-
-type IProvideClassInfo struct {
- IUnknown
-}
-
-type IProvideClassInfoVtbl struct {
- IUnknownVtbl
- GetClassInfo uintptr
-}
-
-func (v *IProvideClassInfo) VTable() *IProvideClassInfoVtbl {
- return (*IProvideClassInfoVtbl)(unsafe.Pointer(v.RawVTable))
-}
-
-func (v *IProvideClassInfo) GetClassInfo() (cinfo *ITypeInfo, err error) {
- cinfo, err = getClassInfo(v)
- return
-}
diff --git a/vendor/github.com/go-ole/go-ole/iprovideclassinfo_func.go b/vendor/github.com/go-ole/go-ole/iprovideclassinfo_func.go
deleted file mode 100644
index 7e3cb63ea7..0000000000
--- a/vendor/github.com/go-ole/go-ole/iprovideclassinfo_func.go
+++ /dev/null
@@ -1,7 +0,0 @@
-// +build !windows
-
-package ole
-
-func getClassInfo(disp *IProvideClassInfo) (tinfo *ITypeInfo, err error) {
- return nil, NewError(E_NOTIMPL)
-}
diff --git a/vendor/github.com/go-ole/go-ole/iprovideclassinfo_windows.go b/vendor/github.com/go-ole/go-ole/iprovideclassinfo_windows.go
deleted file mode 100644
index 2ad0163949..0000000000
--- a/vendor/github.com/go-ole/go-ole/iprovideclassinfo_windows.go
+++ /dev/null
@@ -1,21 +0,0 @@
-// +build windows
-
-package ole
-
-import (
- "syscall"
- "unsafe"
-)
-
-func getClassInfo(disp *IProvideClassInfo) (tinfo *ITypeInfo, err error) {
- hr, _, _ := syscall.Syscall(
- disp.VTable().GetClassInfo,
- 2,
- uintptr(unsafe.Pointer(disp)),
- uintptr(unsafe.Pointer(&tinfo)),
- 0)
- if hr != 0 {
- err = NewError(hr)
- }
- return
-}
diff --git a/vendor/github.com/go-ole/go-ole/itypeinfo.go b/vendor/github.com/go-ole/go-ole/itypeinfo.go
deleted file mode 100644
index dd3c5e21bb..0000000000
--- a/vendor/github.com/go-ole/go-ole/itypeinfo.go
+++ /dev/null
@@ -1,34 +0,0 @@
-package ole
-
-import "unsafe"
-
-type ITypeInfo struct {
- IUnknown
-}
-
-type ITypeInfoVtbl struct {
- IUnknownVtbl
- GetTypeAttr uintptr
- GetTypeComp uintptr
- GetFuncDesc uintptr
- GetVarDesc uintptr
- GetNames uintptr
- GetRefTypeOfImplType uintptr
- GetImplTypeFlags uintptr
- GetIDsOfNames uintptr
- Invoke uintptr
- GetDocumentation uintptr
- GetDllEntry uintptr
- GetRefTypeInfo uintptr
- AddressOfMember uintptr
- CreateInstance uintptr
- GetMops uintptr
- GetContainingTypeLib uintptr
- ReleaseTypeAttr uintptr
- ReleaseFuncDesc uintptr
- ReleaseVarDesc uintptr
-}
-
-func (v *ITypeInfo) VTable() *ITypeInfoVtbl {
- return (*ITypeInfoVtbl)(unsafe.Pointer(v.RawVTable))
-}
diff --git a/vendor/github.com/go-ole/go-ole/itypeinfo_func.go b/vendor/github.com/go-ole/go-ole/itypeinfo_func.go
deleted file mode 100644
index 8364a659ba..0000000000
--- a/vendor/github.com/go-ole/go-ole/itypeinfo_func.go
+++ /dev/null
@@ -1,7 +0,0 @@
-// +build !windows
-
-package ole
-
-func (v *ITypeInfo) GetTypeAttr() (*TYPEATTR, error) {
- return nil, NewError(E_NOTIMPL)
-}
diff --git a/vendor/github.com/go-ole/go-ole/itypeinfo_windows.go b/vendor/github.com/go-ole/go-ole/itypeinfo_windows.go
deleted file mode 100644
index 54782b3da5..0000000000
--- a/vendor/github.com/go-ole/go-ole/itypeinfo_windows.go
+++ /dev/null
@@ -1,21 +0,0 @@
-// +build windows
-
-package ole
-
-import (
- "syscall"
- "unsafe"
-)
-
-func (v *ITypeInfo) GetTypeAttr() (tattr *TYPEATTR, err error) {
- hr, _, _ := syscall.Syscall(
- uintptr(v.VTable().GetTypeAttr),
- 2,
- uintptr(unsafe.Pointer(v)),
- uintptr(unsafe.Pointer(&tattr)),
- 0)
- if hr != 0 {
- err = NewError(hr)
- }
- return
-}
diff --git a/vendor/github.com/go-ole/go-ole/iunknown.go b/vendor/github.com/go-ole/go-ole/iunknown.go
deleted file mode 100644
index 108f28ea61..0000000000
--- a/vendor/github.com/go-ole/go-ole/iunknown.go
+++ /dev/null
@@ -1,57 +0,0 @@
-package ole
-
-import "unsafe"
-
-type IUnknown struct {
- RawVTable *interface{}
-}
-
-type IUnknownVtbl struct {
- QueryInterface uintptr
- AddRef uintptr
- Release uintptr
-}
-
-type UnknownLike interface {
- QueryInterface(iid *GUID) (disp *IDispatch, err error)
- AddRef() int32
- Release() int32
-}
-
-func (v *IUnknown) VTable() *IUnknownVtbl {
- return (*IUnknownVtbl)(unsafe.Pointer(v.RawVTable))
-}
-
-func (v *IUnknown) PutQueryInterface(interfaceID *GUID, obj interface{}) error {
- return reflectQueryInterface(v, v.VTable().QueryInterface, interfaceID, obj)
-}
-
-func (v *IUnknown) IDispatch(interfaceID *GUID) (dispatch *IDispatch, err error) {
- err = v.PutQueryInterface(interfaceID, &dispatch)
- return
-}
-
-func (v *IUnknown) IEnumVARIANT(interfaceID *GUID) (enum *IEnumVARIANT, err error) {
- err = v.PutQueryInterface(interfaceID, &enum)
- return
-}
-
-func (v *IUnknown) QueryInterface(iid *GUID) (*IDispatch, error) {
- return queryInterface(v, iid)
-}
-
-func (v *IUnknown) MustQueryInterface(iid *GUID) (disp *IDispatch) {
- unk, err := queryInterface(v, iid)
- if err != nil {
- panic(err)
- }
- return unk
-}
-
-func (v *IUnknown) AddRef() int32 {
- return addRef(v)
-}
-
-func (v *IUnknown) Release() int32 {
- return release(v)
-}
diff --git a/vendor/github.com/go-ole/go-ole/iunknown_func.go b/vendor/github.com/go-ole/go-ole/iunknown_func.go
deleted file mode 100644
index d0a62cfd73..0000000000
--- a/vendor/github.com/go-ole/go-ole/iunknown_func.go
+++ /dev/null
@@ -1,19 +0,0 @@
-// +build !windows
-
-package ole
-
-func reflectQueryInterface(self interface{}, method uintptr, interfaceID *GUID, obj interface{}) (err error) {
- return NewError(E_NOTIMPL)
-}
-
-func queryInterface(unk *IUnknown, iid *GUID) (disp *IDispatch, err error) {
- return nil, NewError(E_NOTIMPL)
-}
-
-func addRef(unk *IUnknown) int32 {
- return 0
-}
-
-func release(unk *IUnknown) int32 {
- return 0
-}
diff --git a/vendor/github.com/go-ole/go-ole/iunknown_windows.go b/vendor/github.com/go-ole/go-ole/iunknown_windows.go
deleted file mode 100644
index ede5bb8c17..0000000000
--- a/vendor/github.com/go-ole/go-ole/iunknown_windows.go
+++ /dev/null
@@ -1,58 +0,0 @@
-// +build windows
-
-package ole
-
-import (
- "reflect"
- "syscall"
- "unsafe"
-)
-
-func reflectQueryInterface(self interface{}, method uintptr, interfaceID *GUID, obj interface{}) (err error) {
- selfValue := reflect.ValueOf(self).Elem()
- objValue := reflect.ValueOf(obj).Elem()
-
- hr, _, _ := syscall.Syscall(
- method,
- 3,
- selfValue.UnsafeAddr(),
- uintptr(unsafe.Pointer(interfaceID)),
- objValue.Addr().Pointer())
- if hr != 0 {
- err = NewError(hr)
- }
- return
-}
-
-func queryInterface(unk *IUnknown, iid *GUID) (disp *IDispatch, err error) {
- hr, _, _ := syscall.Syscall(
- unk.VTable().QueryInterface,
- 3,
- uintptr(unsafe.Pointer(unk)),
- uintptr(unsafe.Pointer(iid)),
- uintptr(unsafe.Pointer(&disp)))
- if hr != 0 {
- err = NewError(hr)
- }
- return
-}
-
-func addRef(unk *IUnknown) int32 {
- ret, _, _ := syscall.Syscall(
- unk.VTable().AddRef,
- 1,
- uintptr(unsafe.Pointer(unk)),
- 0,
- 0)
- return int32(ret)
-}
-
-func release(unk *IUnknown) int32 {
- ret, _, _ := syscall.Syscall(
- unk.VTable().Release,
- 1,
- uintptr(unsafe.Pointer(unk)),
- 0,
- 0)
- return int32(ret)
-}
diff --git a/vendor/github.com/go-ole/go-ole/ole.go b/vendor/github.com/go-ole/go-ole/ole.go
deleted file mode 100644
index e2ae4f4bbf..0000000000
--- a/vendor/github.com/go-ole/go-ole/ole.go
+++ /dev/null
@@ -1,157 +0,0 @@
-package ole
-
-import (
- "fmt"
- "strings"
-)
-
-// DISPPARAMS are the arguments that passed to methods or property.
-type DISPPARAMS struct {
- rgvarg uintptr
- rgdispidNamedArgs uintptr
- cArgs uint32
- cNamedArgs uint32
-}
-
-// EXCEPINFO defines exception info.
-type EXCEPINFO struct {
- wCode uint16
- wReserved uint16
- bstrSource *uint16
- bstrDescription *uint16
- bstrHelpFile *uint16
- dwHelpContext uint32
- pvReserved uintptr
- pfnDeferredFillIn uintptr
- scode uint32
-}
-
-// WCode return wCode in EXCEPINFO.
-func (e EXCEPINFO) WCode() uint16 {
- return e.wCode
-}
-
-// SCODE return scode in EXCEPINFO.
-func (e EXCEPINFO) SCODE() uint32 {
- return e.scode
-}
-
-// String convert EXCEPINFO to string.
-func (e EXCEPINFO) String() string {
- var src, desc, hlp string
- if e.bstrSource == nil {
- src = ""
- } else {
- src = BstrToString(e.bstrSource)
- }
-
- if e.bstrDescription == nil {
- desc = ""
- } else {
- desc = BstrToString(e.bstrDescription)
- }
-
- if e.bstrHelpFile == nil {
- hlp = ""
- } else {
- hlp = BstrToString(e.bstrHelpFile)
- }
-
- return fmt.Sprintf(
- "wCode: %#x, bstrSource: %v, bstrDescription: %v, bstrHelpFile: %v, dwHelpContext: %#x, scode: %#x",
- e.wCode, src, desc, hlp, e.dwHelpContext, e.scode,
- )
-}
-
-// Error implements error interface and returns error string.
-func (e EXCEPINFO) Error() string {
- if e.bstrDescription != nil {
- return strings.TrimSpace(BstrToString(e.bstrDescription))
- }
-
- src := "Unknown"
- if e.bstrSource != nil {
- src = BstrToString(e.bstrSource)
- }
-
- code := e.scode
- if e.wCode != 0 {
- code = uint32(e.wCode)
- }
-
- return fmt.Sprintf("%v: %#x", src, code)
-}
-
-// PARAMDATA defines parameter data type.
-type PARAMDATA struct {
- Name *int16
- Vt uint16
-}
-
-// METHODDATA defines method info.
-type METHODDATA struct {
- Name *uint16
- Data *PARAMDATA
- Dispid int32
- Meth uint32
- CC int32
- CArgs uint32
- Flags uint16
- VtReturn uint32
-}
-
-// INTERFACEDATA defines interface info.
-type INTERFACEDATA struct {
- MethodData *METHODDATA
- CMembers uint32
-}
-
-// Point is 2D vector type.
-type Point struct {
- X int32
- Y int32
-}
-
-// Msg is message between processes.
-type Msg struct {
- Hwnd uint32
- Message uint32
- Wparam int32
- Lparam int32
- Time uint32
- Pt Point
-}
-
-// TYPEDESC defines data type.
-type TYPEDESC struct {
- Hreftype uint32
- VT uint16
-}
-
-// IDLDESC defines IDL info.
-type IDLDESC struct {
- DwReserved uint32
- WIDLFlags uint16
-}
-
-// TYPEATTR defines type info.
-type TYPEATTR struct {
- Guid GUID
- Lcid uint32
- dwReserved uint32
- MemidConstructor int32
- MemidDestructor int32
- LpstrSchema *uint16
- CbSizeInstance uint32
- Typekind int32
- CFuncs uint16
- CVars uint16
- CImplTypes uint16
- CbSizeVft uint16
- CbAlignment uint16
- WTypeFlags uint16
- WMajorVerNum uint16
- WMinorVerNum uint16
- TdescAlias TYPEDESC
- IdldescType IDLDESC
-}
diff --git a/vendor/github.com/go-ole/go-ole/oleutil/connection.go b/vendor/github.com/go-ole/go-ole/oleutil/connection.go
deleted file mode 100644
index 60df73cda0..0000000000
--- a/vendor/github.com/go-ole/go-ole/oleutil/connection.go
+++ /dev/null
@@ -1,100 +0,0 @@
-// +build windows
-
-package oleutil
-
-import (
- "reflect"
- "unsafe"
-
- ole "github.com/go-ole/go-ole"
-)
-
-type stdDispatch struct {
- lpVtbl *stdDispatchVtbl
- ref int32
- iid *ole.GUID
- iface interface{}
- funcMap map[string]int32
-}
-
-type stdDispatchVtbl struct {
- pQueryInterface uintptr
- pAddRef uintptr
- pRelease uintptr
- pGetTypeInfoCount uintptr
- pGetTypeInfo uintptr
- pGetIDsOfNames uintptr
- pInvoke uintptr
-}
-
-func dispQueryInterface(this *ole.IUnknown, iid *ole.GUID, punk **ole.IUnknown) uint32 {
- pthis := (*stdDispatch)(unsafe.Pointer(this))
- *punk = nil
- if ole.IsEqualGUID(iid, ole.IID_IUnknown) ||
- ole.IsEqualGUID(iid, ole.IID_IDispatch) {
- dispAddRef(this)
- *punk = this
- return ole.S_OK
- }
- if ole.IsEqualGUID(iid, pthis.iid) {
- dispAddRef(this)
- *punk = this
- return ole.S_OK
- }
- return ole.E_NOINTERFACE
-}
-
-func dispAddRef(this *ole.IUnknown) int32 {
- pthis := (*stdDispatch)(unsafe.Pointer(this))
- pthis.ref++
- return pthis.ref
-}
-
-func dispRelease(this *ole.IUnknown) int32 {
- pthis := (*stdDispatch)(unsafe.Pointer(this))
- pthis.ref--
- return pthis.ref
-}
-
-func dispGetIDsOfNames(this *ole.IUnknown, iid *ole.GUID, wnames []*uint16, namelen int, lcid int, pdisp []int32) uintptr {
- pthis := (*stdDispatch)(unsafe.Pointer(this))
- names := make([]string, len(wnames))
- for i := 0; i < len(names); i++ {
- names[i] = ole.LpOleStrToString(wnames[i])
- }
- for n := 0; n < namelen; n++ {
- if id, ok := pthis.funcMap[names[n]]; ok {
- pdisp[n] = id
- }
- }
- return ole.S_OK
-}
-
-func dispGetTypeInfoCount(pcount *int) uintptr {
- if pcount != nil {
- *pcount = 0
- }
- return ole.S_OK
-}
-
-func dispGetTypeInfo(ptypeif *uintptr) uintptr {
- return ole.E_NOTIMPL
-}
-
-func dispInvoke(this *ole.IDispatch, dispid int32, riid *ole.GUID, lcid int, flags int16, dispparams *ole.DISPPARAMS, result *ole.VARIANT, pexcepinfo *ole.EXCEPINFO, nerr *uint) uintptr {
- pthis := (*stdDispatch)(unsafe.Pointer(this))
- found := ""
- for name, id := range pthis.funcMap {
- if id == dispid {
- found = name
- }
- }
- if found != "" {
- rv := reflect.ValueOf(pthis.iface).Elem()
- rm := rv.MethodByName(found)
- rr := rm.Call([]reflect.Value{})
- println(len(rr))
- return ole.S_OK
- }
- return ole.E_NOTIMPL
-}
diff --git a/vendor/github.com/go-ole/go-ole/oleutil/connection_func.go b/vendor/github.com/go-ole/go-ole/oleutil/connection_func.go
deleted file mode 100644
index 8818fb8275..0000000000
--- a/vendor/github.com/go-ole/go-ole/oleutil/connection_func.go
+++ /dev/null
@@ -1,10 +0,0 @@
-// +build !windows
-
-package oleutil
-
-import ole "github.com/go-ole/go-ole"
-
-// ConnectObject creates a connection point between two services for communication.
-func ConnectObject(disp *ole.IDispatch, iid *ole.GUID, idisp interface{}) (uint32, error) {
- return 0, ole.NewError(ole.E_NOTIMPL)
-}
diff --git a/vendor/github.com/go-ole/go-ole/oleutil/connection_windows.go b/vendor/github.com/go-ole/go-ole/oleutil/connection_windows.go
deleted file mode 100644
index ab9c0d8dcb..0000000000
--- a/vendor/github.com/go-ole/go-ole/oleutil/connection_windows.go
+++ /dev/null
@@ -1,58 +0,0 @@
-// +build windows
-
-package oleutil
-
-import (
- "reflect"
- "syscall"
- "unsafe"
-
- ole "github.com/go-ole/go-ole"
-)
-
-// ConnectObject creates a connection point between two services for communication.
-func ConnectObject(disp *ole.IDispatch, iid *ole.GUID, idisp interface{}) (cookie uint32, err error) {
- unknown, err := disp.QueryInterface(ole.IID_IConnectionPointContainer)
- if err != nil {
- return
- }
-
- container := (*ole.IConnectionPointContainer)(unsafe.Pointer(unknown))
- var point *ole.IConnectionPoint
- err = container.FindConnectionPoint(iid, &point)
- if err != nil {
- return
- }
- if edisp, ok := idisp.(*ole.IUnknown); ok {
- cookie, err = point.Advise(edisp)
- container.Release()
- if err != nil {
- return
- }
- }
- rv := reflect.ValueOf(disp).Elem()
- if rv.Type().Kind() == reflect.Struct {
- dest := &stdDispatch{}
- dest.lpVtbl = &stdDispatchVtbl{}
- dest.lpVtbl.pQueryInterface = syscall.NewCallback(dispQueryInterface)
- dest.lpVtbl.pAddRef = syscall.NewCallback(dispAddRef)
- dest.lpVtbl.pRelease = syscall.NewCallback(dispRelease)
- dest.lpVtbl.pGetTypeInfoCount = syscall.NewCallback(dispGetTypeInfoCount)
- dest.lpVtbl.pGetTypeInfo = syscall.NewCallback(dispGetTypeInfo)
- dest.lpVtbl.pGetIDsOfNames = syscall.NewCallback(dispGetIDsOfNames)
- dest.lpVtbl.pInvoke = syscall.NewCallback(dispInvoke)
- dest.iface = disp
- dest.iid = iid
- cookie, err = point.Advise((*ole.IUnknown)(unsafe.Pointer(dest)))
- container.Release()
- if err != nil {
- point.Release()
- return
- }
- return
- }
-
- container.Release()
-
- return 0, ole.NewError(ole.E_INVALIDARG)
-}
diff --git a/vendor/github.com/go-ole/go-ole/oleutil/go-get.go b/vendor/github.com/go-ole/go-ole/oleutil/go-get.go
deleted file mode 100644
index 58347628f2..0000000000
--- a/vendor/github.com/go-ole/go-ole/oleutil/go-get.go
+++ /dev/null
@@ -1,6 +0,0 @@
-// This file is here so go get succeeds as without it errors with:
-// no buildable Go source files in ...
-//
-// +build !windows
-
-package oleutil
diff --git a/vendor/github.com/go-ole/go-ole/oleutil/oleutil.go b/vendor/github.com/go-ole/go-ole/oleutil/oleutil.go
deleted file mode 100644
index f7803c1e30..0000000000
--- a/vendor/github.com/go-ole/go-ole/oleutil/oleutil.go
+++ /dev/null
@@ -1,127 +0,0 @@
-package oleutil
-
-import ole "github.com/go-ole/go-ole"
-
-// ClassIDFrom retrieves class ID whether given is program ID or application string.
-func ClassIDFrom(programID string) (classID *ole.GUID, err error) {
- return ole.ClassIDFrom(programID)
-}
-
-// CreateObject creates object from programID based on interface type.
-//
-// Only supports IUnknown.
-//
-// Program ID can be either program ID or application string.
-func CreateObject(programID string) (unknown *ole.IUnknown, err error) {
- classID, err := ole.ClassIDFrom(programID)
- if err != nil {
- return
- }
-
- unknown, err = ole.CreateInstance(classID, ole.IID_IUnknown)
- if err != nil {
- return
- }
-
- return
-}
-
-// GetActiveObject retrieves active object for program ID and interface ID based
-// on interface type.
-//
-// Only supports IUnknown.
-//
-// Program ID can be either program ID or application string.
-func GetActiveObject(programID string) (unknown *ole.IUnknown, err error) {
- classID, err := ole.ClassIDFrom(programID)
- if err != nil {
- return
- }
-
- unknown, err = ole.GetActiveObject(classID, ole.IID_IUnknown)
- if err != nil {
- return
- }
-
- return
-}
-
-// CallMethod calls method on IDispatch with parameters.
-func CallMethod(disp *ole.IDispatch, name string, params ...interface{}) (result *ole.VARIANT, err error) {
- return disp.InvokeWithOptionalArgs(name, ole.DISPATCH_METHOD, params)
-}
-
-// MustCallMethod calls method on IDispatch with parameters or panics.
-func MustCallMethod(disp *ole.IDispatch, name string, params ...interface{}) (result *ole.VARIANT) {
- r, err := CallMethod(disp, name, params...)
- if err != nil {
- panic(err.Error())
- }
- return r
-}
-
-// GetProperty retrieves property from IDispatch.
-func GetProperty(disp *ole.IDispatch, name string, params ...interface{}) (result *ole.VARIANT, err error) {
- return disp.InvokeWithOptionalArgs(name, ole.DISPATCH_PROPERTYGET, params)
-}
-
-// MustGetProperty retrieves property from IDispatch or panics.
-func MustGetProperty(disp *ole.IDispatch, name string, params ...interface{}) (result *ole.VARIANT) {
- r, err := GetProperty(disp, name, params...)
- if err != nil {
- panic(err.Error())
- }
- return r
-}
-
-// PutProperty mutates property.
-func PutProperty(disp *ole.IDispatch, name string, params ...interface{}) (result *ole.VARIANT, err error) {
- return disp.InvokeWithOptionalArgs(name, ole.DISPATCH_PROPERTYPUT, params)
-}
-
-// MustPutProperty mutates property or panics.
-func MustPutProperty(disp *ole.IDispatch, name string, params ...interface{}) (result *ole.VARIANT) {
- r, err := PutProperty(disp, name, params...)
- if err != nil {
- panic(err.Error())
- }
- return r
-}
-
-// PutPropertyRef mutates property reference.
-func PutPropertyRef(disp *ole.IDispatch, name string, params ...interface{}) (result *ole.VARIANT, err error) {
- return disp.InvokeWithOptionalArgs(name, ole.DISPATCH_PROPERTYPUTREF, params)
-}
-
-// MustPutPropertyRef mutates property reference or panics.
-func MustPutPropertyRef(disp *ole.IDispatch, name string, params ...interface{}) (result *ole.VARIANT) {
- r, err := PutPropertyRef(disp, name, params...)
- if err != nil {
- panic(err.Error())
- }
- return r
-}
-
-func ForEach(disp *ole.IDispatch, f func(v *ole.VARIANT) error) error {
- newEnum, err := disp.GetProperty("_NewEnum")
- if err != nil {
- return err
- }
- defer newEnum.Clear()
-
- enum, err := newEnum.ToIUnknown().IEnumVARIANT(ole.IID_IEnumVariant)
- if err != nil {
- return err
- }
- defer enum.Release()
-
- for item, length, err := enum.Next(1); length > 0; item, length, err = enum.Next(1) {
- if err != nil {
- return err
- }
- if ferr := f(&item); ferr != nil {
- return ferr
- }
- }
- return nil
-}
diff --git a/vendor/github.com/go-ole/go-ole/safearray.go b/vendor/github.com/go-ole/go-ole/safearray.go
deleted file mode 100644
index a5201b56c3..0000000000
--- a/vendor/github.com/go-ole/go-ole/safearray.go
+++ /dev/null
@@ -1,27 +0,0 @@
-// Package is meant to retrieve and process safe array data returned from COM.
-
-package ole
-
-// SafeArrayBound defines the SafeArray boundaries.
-type SafeArrayBound struct {
- Elements uint32
- LowerBound int32
-}
-
-// SafeArray is how COM handles arrays.
-type SafeArray struct {
- Dimensions uint16
- FeaturesFlag uint16
- ElementsSize uint32
- LocksAmount uint32
- Data uint32
- Bounds [16]byte
-}
-
-// SAFEARRAY is obsolete, exists for backwards compatibility.
-// Use SafeArray
-type SAFEARRAY SafeArray
-
-// SAFEARRAYBOUND is obsolete, exists for backwards compatibility.
-// Use SafeArrayBound
-type SAFEARRAYBOUND SafeArrayBound
diff --git a/vendor/github.com/go-ole/go-ole/safearray_func.go b/vendor/github.com/go-ole/go-ole/safearray_func.go
deleted file mode 100644
index 8ff0baa41d..0000000000
--- a/vendor/github.com/go-ole/go-ole/safearray_func.go
+++ /dev/null
@@ -1,211 +0,0 @@
-// +build !windows
-
-package ole
-
-import (
- "unsafe"
-)
-
-// safeArrayAccessData returns raw array pointer.
-//
-// AKA: SafeArrayAccessData in Windows API.
-func safeArrayAccessData(safearray *SafeArray) (uintptr, error) {
- return uintptr(0), NewError(E_NOTIMPL)
-}
-
-// safeArrayUnaccessData releases raw array.
-//
-// AKA: SafeArrayUnaccessData in Windows API.
-func safeArrayUnaccessData(safearray *SafeArray) error {
- return NewError(E_NOTIMPL)
-}
-
-// safeArrayAllocData allocates SafeArray.
-//
-// AKA: SafeArrayAllocData in Windows API.
-func safeArrayAllocData(safearray *SafeArray) error {
- return NewError(E_NOTIMPL)
-}
-
-// safeArrayAllocDescriptor allocates SafeArray.
-//
-// AKA: SafeArrayAllocDescriptor in Windows API.
-func safeArrayAllocDescriptor(dimensions uint32) (*SafeArray, error) {
- return nil, NewError(E_NOTIMPL)
-}
-
-// safeArrayAllocDescriptorEx allocates SafeArray.
-//
-// AKA: SafeArrayAllocDescriptorEx in Windows API.
-func safeArrayAllocDescriptorEx(variantType VT, dimensions uint32) (*SafeArray, error) {
- return nil, NewError(E_NOTIMPL)
-}
-
-// safeArrayCopy returns copy of SafeArray.
-//
-// AKA: SafeArrayCopy in Windows API.
-func safeArrayCopy(original *SafeArray) (*SafeArray, error) {
- return nil, NewError(E_NOTIMPL)
-}
-
-// safeArrayCopyData duplicates SafeArray into another SafeArray object.
-//
-// AKA: SafeArrayCopyData in Windows API.
-func safeArrayCopyData(original *SafeArray, duplicate *SafeArray) error {
- return NewError(E_NOTIMPL)
-}
-
-// safeArrayCreate creates SafeArray.
-//
-// AKA: SafeArrayCreate in Windows API.
-func safeArrayCreate(variantType VT, dimensions uint32, bounds *SafeArrayBound) (*SafeArray, error) {
- return nil, NewError(E_NOTIMPL)
-}
-
-// safeArrayCreateEx creates SafeArray.
-//
-// AKA: SafeArrayCreateEx in Windows API.
-func safeArrayCreateEx(variantType VT, dimensions uint32, bounds *SafeArrayBound, extra uintptr) (*SafeArray, error) {
- return nil, NewError(E_NOTIMPL)
-}
-
-// safeArrayCreateVector creates SafeArray.
-//
-// AKA: SafeArrayCreateVector in Windows API.
-func safeArrayCreateVector(variantType VT, lowerBound int32, length uint32) (*SafeArray, error) {
- return nil, NewError(E_NOTIMPL)
-}
-
-// safeArrayCreateVectorEx creates SafeArray.
-//
-// AKA: SafeArrayCreateVectorEx in Windows API.
-func safeArrayCreateVectorEx(variantType VT, lowerBound int32, length uint32, extra uintptr) (*SafeArray, error) {
- return nil, NewError(E_NOTIMPL)
-}
-
-// safeArrayDestroy destroys SafeArray object.
-//
-// AKA: SafeArrayDestroy in Windows API.
-func safeArrayDestroy(safearray *SafeArray) error {
- return NewError(E_NOTIMPL)
-}
-
-// safeArrayDestroyData destroys SafeArray object.
-//
-// AKA: SafeArrayDestroyData in Windows API.
-func safeArrayDestroyData(safearray *SafeArray) error {
- return NewError(E_NOTIMPL)
-}
-
-// safeArrayDestroyDescriptor destroys SafeArray object.
-//
-// AKA: SafeArrayDestroyDescriptor in Windows API.
-func safeArrayDestroyDescriptor(safearray *SafeArray) error {
- return NewError(E_NOTIMPL)
-}
-
-// safeArrayGetDim is the amount of dimensions in the SafeArray.
-//
-// SafeArrays may have multiple dimensions. Meaning, it could be
-// multidimensional array.
-//
-// AKA: SafeArrayGetDim in Windows API.
-func safeArrayGetDim(safearray *SafeArray) (*uint32, error) {
- u := uint32(0)
- return &u, NewError(E_NOTIMPL)
-}
-
-// safeArrayGetElementSize is the element size in bytes.
-//
-// AKA: SafeArrayGetElemsize in Windows API.
-func safeArrayGetElementSize(safearray *SafeArray) (*uint32, error) {
- u := uint32(0)
- return &u, NewError(E_NOTIMPL)
-}
-
-// safeArrayGetElement retrieves element at given index.
-func safeArrayGetElement(safearray *SafeArray, index int64, pv unsafe.Pointer) error {
- return NewError(E_NOTIMPL)
-}
-
-// safeArrayGetElement retrieves element at given index and converts to string.
-func safeArrayGetElementString(safearray *SafeArray, index int64) (string, error) {
- return "", NewError(E_NOTIMPL)
-}
-
-// safeArrayGetIID is the InterfaceID of the elements in the SafeArray.
-//
-// AKA: SafeArrayGetIID in Windows API.
-func safeArrayGetIID(safearray *SafeArray) (*GUID, error) {
- return nil, NewError(E_NOTIMPL)
-}
-
-// safeArrayGetLBound returns lower bounds of SafeArray.
-//
-// SafeArrays may have multiple dimensions. Meaning, it could be
-// multidimensional array.
-//
-// AKA: SafeArrayGetLBound in Windows API.
-func safeArrayGetLBound(safearray *SafeArray, dimension uint32) (int64, error) {
- return int64(0), NewError(E_NOTIMPL)
-}
-
-// safeArrayGetUBound returns upper bounds of SafeArray.
-//
-// SafeArrays may have multiple dimensions. Meaning, it could be
-// multidimensional array.
-//
-// AKA: SafeArrayGetUBound in Windows API.
-func safeArrayGetUBound(safearray *SafeArray, dimension uint32) (int64, error) {
- return int64(0), NewError(E_NOTIMPL)
-}
-
-// safeArrayGetVartype returns data type of SafeArray.
-//
-// AKA: SafeArrayGetVartype in Windows API.
-func safeArrayGetVartype(safearray *SafeArray) (uint16, error) {
- return uint16(0), NewError(E_NOTIMPL)
-}
-
-// safeArrayLock locks SafeArray for reading to modify SafeArray.
-//
-// This must be called during some calls to ensure that another process does not
-// read or write to the SafeArray during editing.
-//
-// AKA: SafeArrayLock in Windows API.
-func safeArrayLock(safearray *SafeArray) error {
- return NewError(E_NOTIMPL)
-}
-
-// safeArrayUnlock unlocks SafeArray for reading.
-//
-// AKA: SafeArrayUnlock in Windows API.
-func safeArrayUnlock(safearray *SafeArray) error {
- return NewError(E_NOTIMPL)
-}
-
-// safeArrayPutElement stores the data element at the specified location in the
-// array.
-//
-// AKA: SafeArrayPutElement in Windows API.
-func safeArrayPutElement(safearray *SafeArray, index int64, element uintptr) error {
- return NewError(E_NOTIMPL)
-}
-
-// safeArrayGetRecordInfo accesses IRecordInfo info for custom types.
-//
-// AKA: SafeArrayGetRecordInfo in Windows API.
-//
-// XXX: Must implement IRecordInfo interface for this to return.
-func safeArrayGetRecordInfo(safearray *SafeArray) (interface{}, error) {
- return nil, NewError(E_NOTIMPL)
-}
-
-// safeArraySetRecordInfo mutates IRecordInfo info for custom types.
-//
-// AKA: SafeArraySetRecordInfo in Windows API.
-//
-// XXX: Must implement IRecordInfo interface for this to return.
-func safeArraySetRecordInfo(safearray *SafeArray, recordInfo interface{}) error {
- return NewError(E_NOTIMPL)
-}
diff --git a/vendor/github.com/go-ole/go-ole/safearray_windows.go b/vendor/github.com/go-ole/go-ole/safearray_windows.go
deleted file mode 100644
index b27936e24e..0000000000
--- a/vendor/github.com/go-ole/go-ole/safearray_windows.go
+++ /dev/null
@@ -1,337 +0,0 @@
-// +build windows
-
-package ole
-
-import (
- "unsafe"
-)
-
-var (
- procSafeArrayAccessData, _ = modoleaut32.FindProc("SafeArrayAccessData")
- procSafeArrayAllocData, _ = modoleaut32.FindProc("SafeArrayAllocData")
- procSafeArrayAllocDescriptor, _ = modoleaut32.FindProc("SafeArrayAllocDescriptor")
- procSafeArrayAllocDescriptorEx, _ = modoleaut32.FindProc("SafeArrayAllocDescriptorEx")
- procSafeArrayCopy, _ = modoleaut32.FindProc("SafeArrayCopy")
- procSafeArrayCopyData, _ = modoleaut32.FindProc("SafeArrayCopyData")
- procSafeArrayCreate, _ = modoleaut32.FindProc("SafeArrayCreate")
- procSafeArrayCreateEx, _ = modoleaut32.FindProc("SafeArrayCreateEx")
- procSafeArrayCreateVector, _ = modoleaut32.FindProc("SafeArrayCreateVector")
- procSafeArrayCreateVectorEx, _ = modoleaut32.FindProc("SafeArrayCreateVectorEx")
- procSafeArrayDestroy, _ = modoleaut32.FindProc("SafeArrayDestroy")
- procSafeArrayDestroyData, _ = modoleaut32.FindProc("SafeArrayDestroyData")
- procSafeArrayDestroyDescriptor, _ = modoleaut32.FindProc("SafeArrayDestroyDescriptor")
- procSafeArrayGetDim, _ = modoleaut32.FindProc("SafeArrayGetDim")
- procSafeArrayGetElement, _ = modoleaut32.FindProc("SafeArrayGetElement")
- procSafeArrayGetElemsize, _ = modoleaut32.FindProc("SafeArrayGetElemsize")
- procSafeArrayGetIID, _ = modoleaut32.FindProc("SafeArrayGetIID")
- procSafeArrayGetLBound, _ = modoleaut32.FindProc("SafeArrayGetLBound")
- procSafeArrayGetUBound, _ = modoleaut32.FindProc("SafeArrayGetUBound")
- procSafeArrayGetVartype, _ = modoleaut32.FindProc("SafeArrayGetVartype")
- procSafeArrayLock, _ = modoleaut32.FindProc("SafeArrayLock")
- procSafeArrayPtrOfIndex, _ = modoleaut32.FindProc("SafeArrayPtrOfIndex")
- procSafeArrayUnaccessData, _ = modoleaut32.FindProc("SafeArrayUnaccessData")
- procSafeArrayUnlock, _ = modoleaut32.FindProc("SafeArrayUnlock")
- procSafeArrayPutElement, _ = modoleaut32.FindProc("SafeArrayPutElement")
- //procSafeArrayRedim, _ = modoleaut32.FindProc("SafeArrayRedim") // TODO
- //procSafeArraySetIID, _ = modoleaut32.FindProc("SafeArraySetIID") // TODO
- procSafeArrayGetRecordInfo, _ = modoleaut32.FindProc("SafeArrayGetRecordInfo")
- procSafeArraySetRecordInfo, _ = modoleaut32.FindProc("SafeArraySetRecordInfo")
-)
-
-// safeArrayAccessData returns raw array pointer.
-//
-// AKA: SafeArrayAccessData in Windows API.
-// Todo: Test
-func safeArrayAccessData(safearray *SafeArray) (element uintptr, err error) {
- err = convertHresultToError(
- procSafeArrayAccessData.Call(
- uintptr(unsafe.Pointer(safearray)),
- uintptr(unsafe.Pointer(&element))))
- return
-}
-
-// safeArrayUnaccessData releases raw array.
-//
-// AKA: SafeArrayUnaccessData in Windows API.
-func safeArrayUnaccessData(safearray *SafeArray) (err error) {
- err = convertHresultToError(procSafeArrayUnaccessData.Call(uintptr(unsafe.Pointer(safearray))))
- return
-}
-
-// safeArrayAllocData allocates SafeArray.
-//
-// AKA: SafeArrayAllocData in Windows API.
-func safeArrayAllocData(safearray *SafeArray) (err error) {
- err = convertHresultToError(procSafeArrayAllocData.Call(uintptr(unsafe.Pointer(safearray))))
- return
-}
-
-// safeArrayAllocDescriptor allocates SafeArray.
-//
-// AKA: SafeArrayAllocDescriptor in Windows API.
-func safeArrayAllocDescriptor(dimensions uint32) (safearray *SafeArray, err error) {
- err = convertHresultToError(
- procSafeArrayAllocDescriptor.Call(uintptr(dimensions), uintptr(unsafe.Pointer(&safearray))))
- return
-}
-
-// safeArrayAllocDescriptorEx allocates SafeArray.
-//
-// AKA: SafeArrayAllocDescriptorEx in Windows API.
-func safeArrayAllocDescriptorEx(variantType VT, dimensions uint32) (safearray *SafeArray, err error) {
- err = convertHresultToError(
- procSafeArrayAllocDescriptorEx.Call(
- uintptr(variantType),
- uintptr(dimensions),
- uintptr(unsafe.Pointer(&safearray))))
- return
-}
-
-// safeArrayCopy returns copy of SafeArray.
-//
-// AKA: SafeArrayCopy in Windows API.
-func safeArrayCopy(original *SafeArray) (safearray *SafeArray, err error) {
- err = convertHresultToError(
- procSafeArrayCopy.Call(
- uintptr(unsafe.Pointer(original)),
- uintptr(unsafe.Pointer(&safearray))))
- return
-}
-
-// safeArrayCopyData duplicates SafeArray into another SafeArray object.
-//
-// AKA: SafeArrayCopyData in Windows API.
-func safeArrayCopyData(original *SafeArray, duplicate *SafeArray) (err error) {
- err = convertHresultToError(
- procSafeArrayCopyData.Call(
- uintptr(unsafe.Pointer(original)),
- uintptr(unsafe.Pointer(duplicate))))
- return
-}
-
-// safeArrayCreate creates SafeArray.
-//
-// AKA: SafeArrayCreate in Windows API.
-func safeArrayCreate(variantType VT, dimensions uint32, bounds *SafeArrayBound) (safearray *SafeArray, err error) {
- sa, _, err := procSafeArrayCreate.Call(
- uintptr(variantType),
- uintptr(dimensions),
- uintptr(unsafe.Pointer(bounds)))
- safearray = (*SafeArray)(unsafe.Pointer(&sa))
- return
-}
-
-// safeArrayCreateEx creates SafeArray.
-//
-// AKA: SafeArrayCreateEx in Windows API.
-func safeArrayCreateEx(variantType VT, dimensions uint32, bounds *SafeArrayBound, extra uintptr) (safearray *SafeArray, err error) {
- sa, _, err := procSafeArrayCreateEx.Call(
- uintptr(variantType),
- uintptr(dimensions),
- uintptr(unsafe.Pointer(bounds)),
- extra)
- safearray = (*SafeArray)(unsafe.Pointer(sa))
- return
-}
-
-// safeArrayCreateVector creates SafeArray.
-//
-// AKA: SafeArrayCreateVector in Windows API.
-func safeArrayCreateVector(variantType VT, lowerBound int32, length uint32) (safearray *SafeArray, err error) {
- sa, _, err := procSafeArrayCreateVector.Call(
- uintptr(variantType),
- uintptr(lowerBound),
- uintptr(length))
- safearray = (*SafeArray)(unsafe.Pointer(sa))
- return
-}
-
-// safeArrayCreateVectorEx creates SafeArray.
-//
-// AKA: SafeArrayCreateVectorEx in Windows API.
-func safeArrayCreateVectorEx(variantType VT, lowerBound int32, length uint32, extra uintptr) (safearray *SafeArray, err error) {
- sa, _, err := procSafeArrayCreateVectorEx.Call(
- uintptr(variantType),
- uintptr(lowerBound),
- uintptr(length),
- extra)
- safearray = (*SafeArray)(unsafe.Pointer(sa))
- return
-}
-
-// safeArrayDestroy destroys SafeArray object.
-//
-// AKA: SafeArrayDestroy in Windows API.
-func safeArrayDestroy(safearray *SafeArray) (err error) {
- err = convertHresultToError(procSafeArrayDestroy.Call(uintptr(unsafe.Pointer(safearray))))
- return
-}
-
-// safeArrayDestroyData destroys SafeArray object.
-//
-// AKA: SafeArrayDestroyData in Windows API.
-func safeArrayDestroyData(safearray *SafeArray) (err error) {
- err = convertHresultToError(procSafeArrayDestroyData.Call(uintptr(unsafe.Pointer(safearray))))
- return
-}
-
-// safeArrayDestroyDescriptor destroys SafeArray object.
-//
-// AKA: SafeArrayDestroyDescriptor in Windows API.
-func safeArrayDestroyDescriptor(safearray *SafeArray) (err error) {
- err = convertHresultToError(procSafeArrayDestroyDescriptor.Call(uintptr(unsafe.Pointer(safearray))))
- return
-}
-
-// safeArrayGetDim is the amount of dimensions in the SafeArray.
-//
-// SafeArrays may have multiple dimensions. Meaning, it could be
-// multidimensional array.
-//
-// AKA: SafeArrayGetDim in Windows API.
-func safeArrayGetDim(safearray *SafeArray) (dimensions *uint32, err error) {
- l, _, err := procSafeArrayGetDim.Call(uintptr(unsafe.Pointer(safearray)))
- dimensions = (*uint32)(unsafe.Pointer(l))
- return
-}
-
-// safeArrayGetElementSize is the element size in bytes.
-//
-// AKA: SafeArrayGetElemsize in Windows API.
-func safeArrayGetElementSize(safearray *SafeArray) (length *uint32, err error) {
- l, _, err := procSafeArrayGetElemsize.Call(uintptr(unsafe.Pointer(safearray)))
- length = (*uint32)(unsafe.Pointer(l))
- return
-}
-
-// safeArrayGetElement retrieves element at given index.
-func safeArrayGetElement(safearray *SafeArray, index int64, pv unsafe.Pointer) error {
- return convertHresultToError(
- procSafeArrayGetElement.Call(
- uintptr(unsafe.Pointer(safearray)),
- uintptr(unsafe.Pointer(&index)),
- uintptr(pv)))
-}
-
-// safeArrayGetElementString retrieves element at given index and converts to string.
-func safeArrayGetElementString(safearray *SafeArray, index int64) (str string, err error) {
- var element *int16
- err = convertHresultToError(
- procSafeArrayGetElement.Call(
- uintptr(unsafe.Pointer(safearray)),
- uintptr(unsafe.Pointer(&index)),
- uintptr(unsafe.Pointer(&element))))
- str = BstrToString(*(**uint16)(unsafe.Pointer(&element)))
- SysFreeString(element)
- return
-}
-
-// safeArrayGetIID is the InterfaceID of the elements in the SafeArray.
-//
-// AKA: SafeArrayGetIID in Windows API.
-func safeArrayGetIID(safearray *SafeArray) (guid *GUID, err error) {
- err = convertHresultToError(
- procSafeArrayGetIID.Call(
- uintptr(unsafe.Pointer(safearray)),
- uintptr(unsafe.Pointer(&guid))))
- return
-}
-
-// safeArrayGetLBound returns lower bounds of SafeArray.
-//
-// SafeArrays may have multiple dimensions. Meaning, it could be
-// multidimensional array.
-//
-// AKA: SafeArrayGetLBound in Windows API.
-func safeArrayGetLBound(safearray *SafeArray, dimension uint32) (lowerBound int64, err error) {
- err = convertHresultToError(
- procSafeArrayGetLBound.Call(
- uintptr(unsafe.Pointer(safearray)),
- uintptr(dimension),
- uintptr(unsafe.Pointer(&lowerBound))))
- return
-}
-
-// safeArrayGetUBound returns upper bounds of SafeArray.
-//
-// SafeArrays may have multiple dimensions. Meaning, it could be
-// multidimensional array.
-//
-// AKA: SafeArrayGetUBound in Windows API.
-func safeArrayGetUBound(safearray *SafeArray, dimension uint32) (upperBound int64, err error) {
- err = convertHresultToError(
- procSafeArrayGetUBound.Call(
- uintptr(unsafe.Pointer(safearray)),
- uintptr(dimension),
- uintptr(unsafe.Pointer(&upperBound))))
- return
-}
-
-// safeArrayGetVartype returns data type of SafeArray.
-//
-// AKA: SafeArrayGetVartype in Windows API.
-func safeArrayGetVartype(safearray *SafeArray) (varType uint16, err error) {
- err = convertHresultToError(
- procSafeArrayGetVartype.Call(
- uintptr(unsafe.Pointer(safearray)),
- uintptr(unsafe.Pointer(&varType))))
- return
-}
-
-// safeArrayLock locks SafeArray for reading to modify SafeArray.
-//
-// This must be called during some calls to ensure that another process does not
-// read or write to the SafeArray during editing.
-//
-// AKA: SafeArrayLock in Windows API.
-func safeArrayLock(safearray *SafeArray) (err error) {
- err = convertHresultToError(procSafeArrayLock.Call(uintptr(unsafe.Pointer(safearray))))
- return
-}
-
-// safeArrayUnlock unlocks SafeArray for reading.
-//
-// AKA: SafeArrayUnlock in Windows API.
-func safeArrayUnlock(safearray *SafeArray) (err error) {
- err = convertHresultToError(procSafeArrayUnlock.Call(uintptr(unsafe.Pointer(safearray))))
- return
-}
-
-// safeArrayPutElement stores the data element at the specified location in the
-// array.
-//
-// AKA: SafeArrayPutElement in Windows API.
-func safeArrayPutElement(safearray *SafeArray, index int64, element uintptr) (err error) {
- err = convertHresultToError(
- procSafeArrayPutElement.Call(
- uintptr(unsafe.Pointer(safearray)),
- uintptr(unsafe.Pointer(&index)),
- uintptr(unsafe.Pointer(element))))
- return
-}
-
-// safeArrayGetRecordInfo accesses IRecordInfo info for custom types.
-//
-// AKA: SafeArrayGetRecordInfo in Windows API.
-//
-// XXX: Must implement IRecordInfo interface for this to return.
-func safeArrayGetRecordInfo(safearray *SafeArray) (recordInfo interface{}, err error) {
- err = convertHresultToError(
- procSafeArrayGetRecordInfo.Call(
- uintptr(unsafe.Pointer(safearray)),
- uintptr(unsafe.Pointer(&recordInfo))))
- return
-}
-
-// safeArraySetRecordInfo mutates IRecordInfo info for custom types.
-//
-// AKA: SafeArraySetRecordInfo in Windows API.
-//
-// XXX: Must implement IRecordInfo interface for this to return.
-func safeArraySetRecordInfo(safearray *SafeArray, recordInfo interface{}) (err error) {
- err = convertHresultToError(
- procSafeArraySetRecordInfo.Call(
- uintptr(unsafe.Pointer(safearray)),
- uintptr(unsafe.Pointer(&recordInfo))))
- return
-}
diff --git a/vendor/github.com/go-ole/go-ole/safearrayconversion.go b/vendor/github.com/go-ole/go-ole/safearrayconversion.go
deleted file mode 100644
index ffeb2b97b0..0000000000
--- a/vendor/github.com/go-ole/go-ole/safearrayconversion.go
+++ /dev/null
@@ -1,140 +0,0 @@
-// Helper for converting SafeArray to array of objects.
-
-package ole
-
-import (
- "unsafe"
-)
-
-type SafeArrayConversion struct {
- Array *SafeArray
-}
-
-func (sac *SafeArrayConversion) ToStringArray() (strings []string) {
- totalElements, _ := sac.TotalElements(0)
- strings = make([]string, totalElements)
-
- for i := int64(0); i < totalElements; i++ {
- strings[int32(i)], _ = safeArrayGetElementString(sac.Array, i)
- }
-
- return
-}
-
-func (sac *SafeArrayConversion) ToByteArray() (bytes []byte) {
- totalElements, _ := sac.TotalElements(0)
- bytes = make([]byte, totalElements)
-
- for i := int64(0); i < totalElements; i++ {
- safeArrayGetElement(sac.Array, i, unsafe.Pointer(&bytes[int32(i)]))
- }
-
- return
-}
-
-func (sac *SafeArrayConversion) ToValueArray() (values []interface{}) {
- totalElements, _ := sac.TotalElements(0)
- values = make([]interface{}, totalElements)
- vt, _ := safeArrayGetVartype(sac.Array)
-
- for i := 0; i < int(totalElements); i++ {
- switch VT(vt) {
- case VT_BOOL:
- var v bool
- safeArrayGetElement(sac.Array, int64(i), unsafe.Pointer(&v))
- values[i] = v
- case VT_I1:
- var v int8
- safeArrayGetElement(sac.Array, int64(i), unsafe.Pointer(&v))
- values[i] = v
- case VT_I2:
- var v int16
- safeArrayGetElement(sac.Array, int64(i), unsafe.Pointer(&v))
- values[i] = v
- case VT_I4:
- var v int32
- safeArrayGetElement(sac.Array, int64(i), unsafe.Pointer(&v))
- values[i] = v
- case VT_I8:
- var v int64
- safeArrayGetElement(sac.Array, int64(i), unsafe.Pointer(&v))
- values[i] = v
- case VT_UI1:
- var v uint8
- safeArrayGetElement(sac.Array, int64(i), unsafe.Pointer(&v))
- values[i] = v
- case VT_UI2:
- var v uint16
- safeArrayGetElement(sac.Array, int64(i), unsafe.Pointer(&v))
- values[i] = v
- case VT_UI4:
- var v uint32
- safeArrayGetElement(sac.Array, int64(i), unsafe.Pointer(&v))
- values[i] = v
- case VT_UI8:
- var v uint64
- safeArrayGetElement(sac.Array, int64(i), unsafe.Pointer(&v))
- values[i] = v
- case VT_R4:
- var v float32
- safeArrayGetElement(sac.Array, int64(i), unsafe.Pointer(&v))
- values[i] = v
- case VT_R8:
- var v float64
- safeArrayGetElement(sac.Array, int64(i), unsafe.Pointer(&v))
- values[i] = v
- case VT_BSTR:
- var v string
- safeArrayGetElement(sac.Array, int64(i), unsafe.Pointer(&v))
- values[i] = v
- case VT_VARIANT:
- var v VARIANT
- safeArrayGetElement(sac.Array, int64(i), unsafe.Pointer(&v))
- values[i] = v.Value()
- default:
- // TODO
- }
- }
-
- return
-}
-
-func (sac *SafeArrayConversion) GetType() (varType uint16, err error) {
- return safeArrayGetVartype(sac.Array)
-}
-
-func (sac *SafeArrayConversion) GetDimensions() (dimensions *uint32, err error) {
- return safeArrayGetDim(sac.Array)
-}
-
-func (sac *SafeArrayConversion) GetSize() (length *uint32, err error) {
- return safeArrayGetElementSize(sac.Array)
-}
-
-func (sac *SafeArrayConversion) TotalElements(index uint32) (totalElements int64, err error) {
- if index < 1 {
- index = 1
- }
-
- // Get array bounds
- var LowerBounds int64
- var UpperBounds int64
-
- LowerBounds, err = safeArrayGetLBound(sac.Array, index)
- if err != nil {
- return
- }
-
- UpperBounds, err = safeArrayGetUBound(sac.Array, index)
- if err != nil {
- return
- }
-
- totalElements = UpperBounds - LowerBounds + 1
- return
-}
-
-// Release Safe Array memory
-func (sac *SafeArrayConversion) Release() {
- safeArrayDestroy(sac.Array)
-}
diff --git a/vendor/github.com/go-ole/go-ole/safearrayslices.go b/vendor/github.com/go-ole/go-ole/safearrayslices.go
deleted file mode 100644
index a9fa885f1d..0000000000
--- a/vendor/github.com/go-ole/go-ole/safearrayslices.go
+++ /dev/null
@@ -1,33 +0,0 @@
-// +build windows
-
-package ole
-
-import (
- "unsafe"
-)
-
-func safeArrayFromByteSlice(slice []byte) *SafeArray {
- array, _ := safeArrayCreateVector(VT_UI1, 0, uint32(len(slice)))
-
- if array == nil {
- panic("Could not convert []byte to SAFEARRAY")
- }
-
- for i, v := range slice {
- safeArrayPutElement(array, int64(i), uintptr(unsafe.Pointer(&v)))
- }
- return array
-}
-
-func safeArrayFromStringSlice(slice []string) *SafeArray {
- array, _ := safeArrayCreateVector(VT_BSTR, 0, uint32(len(slice)))
-
- if array == nil {
- panic("Could not convert []string to SAFEARRAY")
- }
- // SysAllocStringLen(s)
- for i, v := range slice {
- safeArrayPutElement(array, int64(i), uintptr(unsafe.Pointer(SysAllocStringLen(v))))
- }
- return array
-}
diff --git a/vendor/github.com/go-ole/go-ole/utility.go b/vendor/github.com/go-ole/go-ole/utility.go
deleted file mode 100644
index 99ee82dc34..0000000000
--- a/vendor/github.com/go-ole/go-ole/utility.go
+++ /dev/null
@@ -1,101 +0,0 @@
-package ole
-
-import (
- "unicode/utf16"
- "unsafe"
-)
-
-// ClassIDFrom retrieves class ID whether given is program ID or application string.
-//
-// Helper that provides check against both Class ID from Program ID and Class ID from string. It is
-// faster, if you know which you are using, to use the individual functions, but this will check
-// against available functions for you.
-func ClassIDFrom(programID string) (classID *GUID, err error) {
- classID, err = CLSIDFromProgID(programID)
- if err != nil {
- classID, err = CLSIDFromString(programID)
- if err != nil {
- return
- }
- }
- return
-}
-
-// BytePtrToString converts byte pointer to a Go string.
-func BytePtrToString(p *byte) string {
- a := (*[10000]uint8)(unsafe.Pointer(p))
- i := 0
- for a[i] != 0 {
- i++
- }
- return string(a[:i])
-}
-
-// UTF16PtrToString is alias for LpOleStrToString.
-//
-// Kept for compatibility reasons.
-func UTF16PtrToString(p *uint16) string {
- return LpOleStrToString(p)
-}
-
-// LpOleStrToString converts COM Unicode to Go string.
-func LpOleStrToString(p *uint16) string {
- if p == nil {
- return ""
- }
-
- length := lpOleStrLen(p)
- a := make([]uint16, length)
-
- ptr := unsafe.Pointer(p)
-
- for i := 0; i < int(length); i++ {
- a[i] = *(*uint16)(ptr)
- ptr = unsafe.Pointer(uintptr(ptr) + 2)
- }
-
- return string(utf16.Decode(a))
-}
-
-// BstrToString converts COM binary string to Go string.
-func BstrToString(p *uint16) string {
- if p == nil {
- return ""
- }
- length := SysStringLen((*int16)(unsafe.Pointer(p)))
- a := make([]uint16, length)
-
- ptr := unsafe.Pointer(p)
-
- for i := 0; i < int(length); i++ {
- a[i] = *(*uint16)(ptr)
- ptr = unsafe.Pointer(uintptr(ptr) + 2)
- }
- return string(utf16.Decode(a))
-}
-
-// lpOleStrLen returns the length of Unicode string.
-func lpOleStrLen(p *uint16) (length int64) {
- if p == nil {
- return 0
- }
-
- ptr := unsafe.Pointer(p)
-
- for i := 0; ; i++ {
- if 0 == *(*uint16)(ptr) {
- length = int64(i)
- break
- }
- ptr = unsafe.Pointer(uintptr(ptr) + 2)
- }
- return
-}
-
-// convertHresultToError converts syscall to error, if call is unsuccessful.
-func convertHresultToError(hr uintptr, r2 uintptr, ignore error) (err error) {
- if hr != 0 {
- err = NewError(hr)
- }
- return
-}
diff --git a/vendor/github.com/go-ole/go-ole/variables.go b/vendor/github.com/go-ole/go-ole/variables.go
deleted file mode 100644
index ebe00f1cfc..0000000000
--- a/vendor/github.com/go-ole/go-ole/variables.go
+++ /dev/null
@@ -1,16 +0,0 @@
-// +build windows
-
-package ole
-
-import (
- "syscall"
-)
-
-var (
- modcombase = syscall.NewLazyDLL("combase.dll")
- modkernel32, _ = syscall.LoadDLL("kernel32.dll")
- modole32, _ = syscall.LoadDLL("ole32.dll")
- modoleaut32, _ = syscall.LoadDLL("oleaut32.dll")
- modmsvcrt, _ = syscall.LoadDLL("msvcrt.dll")
- moduser32, _ = syscall.LoadDLL("user32.dll")
-)
diff --git a/vendor/github.com/go-ole/go-ole/variant.go b/vendor/github.com/go-ole/go-ole/variant.go
deleted file mode 100644
index 36969725eb..0000000000
--- a/vendor/github.com/go-ole/go-ole/variant.go
+++ /dev/null
@@ -1,105 +0,0 @@
-package ole
-
-import "unsafe"
-
-// NewVariant returns new variant based on type and value.
-func NewVariant(vt VT, val int64) VARIANT {
- return VARIANT{VT: vt, Val: val}
-}
-
-// ToIUnknown converts Variant to Unknown object.
-func (v *VARIANT) ToIUnknown() *IUnknown {
- if v.VT != VT_UNKNOWN {
- return nil
- }
- return (*IUnknown)(unsafe.Pointer(uintptr(v.Val)))
-}
-
-// ToIDispatch converts variant to dispatch object.
-func (v *VARIANT) ToIDispatch() *IDispatch {
- if v.VT != VT_DISPATCH {
- return nil
- }
- return (*IDispatch)(unsafe.Pointer(uintptr(v.Val)))
-}
-
-// ToArray converts variant to SafeArray helper.
-func (v *VARIANT) ToArray() *SafeArrayConversion {
- if v.VT != VT_SAFEARRAY {
- if v.VT&VT_ARRAY == 0 {
- return nil
- }
- }
- var safeArray *SafeArray = (*SafeArray)(unsafe.Pointer(uintptr(v.Val)))
- return &SafeArrayConversion{safeArray}
-}
-
-// ToString converts variant to Go string.
-func (v *VARIANT) ToString() string {
- if v.VT != VT_BSTR {
- return ""
- }
- return BstrToString(*(**uint16)(unsafe.Pointer(&v.Val)))
-}
-
-// Clear the memory of variant object.
-func (v *VARIANT) Clear() error {
- return VariantClear(v)
-}
-
-// Value returns variant value based on its type.
-//
-// Currently supported types: 2- and 4-byte integers, strings, bools.
-// Note that 64-bit integers, datetimes, and other types are stored as strings
-// and will be returned as strings.
-//
-// Needs to be further converted, because this returns an interface{}.
-func (v *VARIANT) Value() interface{} {
- switch v.VT {
- case VT_I1:
- return int8(v.Val)
- case VT_UI1:
- return uint8(v.Val)
- case VT_I2:
- return int16(v.Val)
- case VT_UI2:
- return uint16(v.Val)
- case VT_I4:
- return int32(v.Val)
- case VT_UI4:
- return uint32(v.Val)
- case VT_I8:
- return int64(v.Val)
- case VT_UI8:
- return uint64(v.Val)
- case VT_INT:
- return int(v.Val)
- case VT_UINT:
- return uint(v.Val)
- case VT_INT_PTR:
- return uintptr(v.Val) // TODO
- case VT_UINT_PTR:
- return uintptr(v.Val)
- case VT_R4:
- return *(*float32)(unsafe.Pointer(&v.Val))
- case VT_R8:
- return *(*float64)(unsafe.Pointer(&v.Val))
- case VT_BSTR:
- return v.ToString()
- case VT_DATE:
- // VT_DATE type will either return float64 or time.Time.
- d := float64(v.Val)
- date, err := GetVariantDate(d)
- if err != nil {
- return d
- }
- return date
- case VT_UNKNOWN:
- return v.ToIUnknown()
- case VT_DISPATCH:
- return v.ToIDispatch()
- case VT_BOOL:
- return v.Val != 0
- }
- return nil
-}
diff --git a/vendor/github.com/go-ole/go-ole/variant_386.go b/vendor/github.com/go-ole/go-ole/variant_386.go
deleted file mode 100644
index e73736bf39..0000000000
--- a/vendor/github.com/go-ole/go-ole/variant_386.go
+++ /dev/null
@@ -1,11 +0,0 @@
-// +build 386
-
-package ole
-
-type VARIANT struct {
- VT VT // 2
- wReserved1 uint16 // 4
- wReserved2 uint16 // 6
- wReserved3 uint16 // 8
- Val int64 // 16
-}
diff --git a/vendor/github.com/go-ole/go-ole/variant_amd64.go b/vendor/github.com/go-ole/go-ole/variant_amd64.go
deleted file mode 100644
index dccdde1323..0000000000
--- a/vendor/github.com/go-ole/go-ole/variant_amd64.go
+++ /dev/null
@@ -1,12 +0,0 @@
-// +build amd64
-
-package ole
-
-type VARIANT struct {
- VT VT // 2
- wReserved1 uint16 // 4
- wReserved2 uint16 // 6
- wReserved3 uint16 // 8
- Val int64 // 16
- _ [8]byte // 24
-}
diff --git a/vendor/github.com/go-ole/go-ole/variant_s390x.go b/vendor/github.com/go-ole/go-ole/variant_s390x.go
deleted file mode 100644
index 9874ca66b4..0000000000
--- a/vendor/github.com/go-ole/go-ole/variant_s390x.go
+++ /dev/null
@@ -1,12 +0,0 @@
-// +build s390x
-
-package ole
-
-type VARIANT struct {
- VT VT // 2
- wReserved1 uint16 // 4
- wReserved2 uint16 // 6
- wReserved3 uint16 // 8
- Val int64 // 16
- _ [8]byte // 24
-}
diff --git a/vendor/github.com/go-ole/go-ole/vt_string.go b/vendor/github.com/go-ole/go-ole/vt_string.go
deleted file mode 100644
index 729b4a04dd..0000000000
--- a/vendor/github.com/go-ole/go-ole/vt_string.go
+++ /dev/null
@@ -1,58 +0,0 @@
-// generated by stringer -output vt_string.go -type VT; DO NOT EDIT
-
-package ole
-
-import "fmt"
-
-const (
- _VT_name_0 = "VT_EMPTYVT_NULLVT_I2VT_I4VT_R4VT_R8VT_CYVT_DATEVT_BSTRVT_DISPATCHVT_ERRORVT_BOOLVT_VARIANTVT_UNKNOWNVT_DECIMAL"
- _VT_name_1 = "VT_I1VT_UI1VT_UI2VT_UI4VT_I8VT_UI8VT_INTVT_UINTVT_VOIDVT_HRESULTVT_PTRVT_SAFEARRAYVT_CARRAYVT_USERDEFINEDVT_LPSTRVT_LPWSTR"
- _VT_name_2 = "VT_RECORDVT_INT_PTRVT_UINT_PTR"
- _VT_name_3 = "VT_FILETIMEVT_BLOBVT_STREAMVT_STORAGEVT_STREAMED_OBJECTVT_STORED_OBJECTVT_BLOB_OBJECTVT_CFVT_CLSID"
- _VT_name_4 = "VT_BSTR_BLOBVT_VECTOR"
- _VT_name_5 = "VT_ARRAY"
- _VT_name_6 = "VT_BYREF"
- _VT_name_7 = "VT_RESERVED"
- _VT_name_8 = "VT_ILLEGAL"
-)
-
-var (
- _VT_index_0 = [...]uint8{0, 8, 15, 20, 25, 30, 35, 40, 47, 54, 65, 73, 80, 90, 100, 110}
- _VT_index_1 = [...]uint8{0, 5, 11, 17, 23, 28, 34, 40, 47, 54, 64, 70, 82, 91, 105, 113, 122}
- _VT_index_2 = [...]uint8{0, 9, 19, 30}
- _VT_index_3 = [...]uint8{0, 11, 18, 27, 37, 55, 71, 85, 90, 98}
- _VT_index_4 = [...]uint8{0, 12, 21}
- _VT_index_5 = [...]uint8{0, 8}
- _VT_index_6 = [...]uint8{0, 8}
- _VT_index_7 = [...]uint8{0, 11}
- _VT_index_8 = [...]uint8{0, 10}
-)
-
-func (i VT) String() string {
- switch {
- case 0 <= i && i <= 14:
- return _VT_name_0[_VT_index_0[i]:_VT_index_0[i+1]]
- case 16 <= i && i <= 31:
- i -= 16
- return _VT_name_1[_VT_index_1[i]:_VT_index_1[i+1]]
- case 36 <= i && i <= 38:
- i -= 36
- return _VT_name_2[_VT_index_2[i]:_VT_index_2[i+1]]
- case 64 <= i && i <= 72:
- i -= 64
- return _VT_name_3[_VT_index_3[i]:_VT_index_3[i+1]]
- case 4095 <= i && i <= 4096:
- i -= 4095
- return _VT_name_4[_VT_index_4[i]:_VT_index_4[i+1]]
- case i == 8192:
- return _VT_name_5
- case i == 16384:
- return _VT_name_6
- case i == 32768:
- return _VT_name_7
- case i == 65535:
- return _VT_name_8
- default:
- return fmt.Sprintf("VT(%d)", i)
- }
-}
diff --git a/vendor/github.com/go-ole/go-ole/winrt.go b/vendor/github.com/go-ole/go-ole/winrt.go
deleted file mode 100644
index 4e9eca7324..0000000000
--- a/vendor/github.com/go-ole/go-ole/winrt.go
+++ /dev/null
@@ -1,99 +0,0 @@
-// +build windows
-
-package ole
-
-import (
- "reflect"
- "syscall"
- "unicode/utf8"
- "unsafe"
-)
-
-var (
- procRoInitialize = modcombase.NewProc("RoInitialize")
- procRoActivateInstance = modcombase.NewProc("RoActivateInstance")
- procRoGetActivationFactory = modcombase.NewProc("RoGetActivationFactory")
- procWindowsCreateString = modcombase.NewProc("WindowsCreateString")
- procWindowsDeleteString = modcombase.NewProc("WindowsDeleteString")
- procWindowsGetStringRawBuffer = modcombase.NewProc("WindowsGetStringRawBuffer")
-)
-
-func RoInitialize(thread_type uint32) (err error) {
- hr, _, _ := procRoInitialize.Call(uintptr(thread_type))
- if hr != 0 {
- err = NewError(hr)
- }
- return
-}
-
-func RoActivateInstance(clsid string) (ins *IInspectable, err error) {
- hClsid, err := NewHString(clsid)
- if err != nil {
- return nil, err
- }
- defer DeleteHString(hClsid)
-
- hr, _, _ := procRoActivateInstance.Call(
- uintptr(unsafe.Pointer(hClsid)),
- uintptr(unsafe.Pointer(&ins)))
- if hr != 0 {
- err = NewError(hr)
- }
- return
-}
-
-func RoGetActivationFactory(clsid string, iid *GUID) (ins *IInspectable, err error) {
- hClsid, err := NewHString(clsid)
- if err != nil {
- return nil, err
- }
- defer DeleteHString(hClsid)
-
- hr, _, _ := procRoGetActivationFactory.Call(
- uintptr(unsafe.Pointer(hClsid)),
- uintptr(unsafe.Pointer(iid)),
- uintptr(unsafe.Pointer(&ins)))
- if hr != 0 {
- err = NewError(hr)
- }
- return
-}
-
-// HString is handle string for pointers.
-type HString uintptr
-
-// NewHString returns a new HString for Go string.
-func NewHString(s string) (hstring HString, err error) {
- u16 := syscall.StringToUTF16Ptr(s)
- len := uint32(utf8.RuneCountInString(s))
- hr, _, _ := procWindowsCreateString.Call(
- uintptr(unsafe.Pointer(u16)),
- uintptr(len),
- uintptr(unsafe.Pointer(&hstring)))
- if hr != 0 {
- err = NewError(hr)
- }
- return
-}
-
-// DeleteHString deletes HString.
-func DeleteHString(hstring HString) (err error) {
- hr, _, _ := procWindowsDeleteString.Call(uintptr(hstring))
- if hr != 0 {
- err = NewError(hr)
- }
- return
-}
-
-// String returns Go string value of HString.
-func (h HString) String() string {
- var u16buf uintptr
- var u16len uint32
- u16buf, _, _ = procWindowsGetStringRawBuffer.Call(
- uintptr(h),
- uintptr(unsafe.Pointer(&u16len)))
-
- u16hdr := reflect.SliceHeader{Data: u16buf, Len: int(u16len), Cap: int(u16len)}
- u16 := *(*[]uint16)(unsafe.Pointer(&u16hdr))
- return syscall.UTF16ToString(u16)
-}
diff --git a/vendor/github.com/go-ole/go-ole/winrt_doc.go b/vendor/github.com/go-ole/go-ole/winrt_doc.go
deleted file mode 100644
index 52e6d74c9a..0000000000
--- a/vendor/github.com/go-ole/go-ole/winrt_doc.go
+++ /dev/null
@@ -1,36 +0,0 @@
-// +build !windows
-
-package ole
-
-// RoInitialize
-func RoInitialize(thread_type uint32) (err error) {
- return NewError(E_NOTIMPL)
-}
-
-// RoActivateInstance
-func RoActivateInstance(clsid string) (ins *IInspectable, err error) {
- return nil, NewError(E_NOTIMPL)
-}
-
-// RoGetActivationFactory
-func RoGetActivationFactory(clsid string, iid *GUID) (ins *IInspectable, err error) {
- return nil, NewError(E_NOTIMPL)
-}
-
-// HString is handle string for pointers.
-type HString uintptr
-
-// NewHString returns a new HString for Go string.
-func NewHString(s string) (hstring HString, err error) {
- return HString(uintptr(0)), NewError(E_NOTIMPL)
-}
-
-// DeleteHString deletes HString.
-func DeleteHString(hstring HString) (err error) {
- return NewError(E_NOTIMPL)
-}
-
-// String returns Go string value of HString.
-func (h HString) String() string {
- return ""
-}
diff --git a/vendor/github.com/go-stack/stack/LICENSE.md b/vendor/github.com/go-stack/stack/LICENSE.md
deleted file mode 100644
index 2abf98ea83..0000000000
--- a/vendor/github.com/go-stack/stack/LICENSE.md
+++ /dev/null
@@ -1,21 +0,0 @@
-The MIT License (MIT)
-
-Copyright (c) 2014 Chris Hines
-
-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/vendor/github.com/go-stack/stack/README.md b/vendor/github.com/go-stack/stack/README.md
deleted file mode 100644
index f11ccccaa4..0000000000
--- a/vendor/github.com/go-stack/stack/README.md
+++ /dev/null
@@ -1,38 +0,0 @@
-[![GoDoc](https://godoc.org/github.com/go-stack/stack?status.svg)](https://godoc.org/github.com/go-stack/stack)
-[![Go Report Card](https://goreportcard.com/badge/go-stack/stack)](https://goreportcard.com/report/go-stack/stack)
-[![TravisCI](https://travis-ci.org/go-stack/stack.svg?branch=master)](https://travis-ci.org/go-stack/stack)
-[![Coverage Status](https://coveralls.io/repos/github/go-stack/stack/badge.svg?branch=master)](https://coveralls.io/github/go-stack/stack?branch=master)
-
-# stack
-
-Package stack implements utilities to capture, manipulate, and format call
-stacks. It provides a simpler API than package runtime.
-
-The implementation takes care of the minutia and special cases of interpreting
-the program counter (pc) values returned by runtime.Callers.
-
-## Versioning
-
-Package stack publishes releases via [semver](http://semver.org/) compatible Git
-tags prefixed with a single 'v'. The master branch always contains the latest
-release. The develop branch contains unreleased commits.
-
-## Formatting
-
-Package stack's types implement fmt.Formatter, which provides a simple and
-flexible way to declaratively configure formatting when used with logging or
-error tracking packages.
-
-```go
-func DoTheThing() {
- c := stack.Caller(0)
- log.Print(c) // "source.go:10"
- log.Printf("%+v", c) // "pkg/path/source.go:10"
- log.Printf("%n", c) // "DoTheThing"
-
- s := stack.Trace().TrimRuntime()
- log.Print(s) // "[source.go:15 caller.go:42 main.go:14]"
-}
-```
-
-See the docs for all of the supported formatting options.
diff --git a/vendor/github.com/go-stack/stack/stack.go b/vendor/github.com/go-stack/stack/stack.go
deleted file mode 100644
index 8033c4013a..0000000000
--- a/vendor/github.com/go-stack/stack/stack.go
+++ /dev/null
@@ -1,322 +0,0 @@
-// Package stack implements utilities to capture, manipulate, and format call
-// stacks. It provides a simpler API than package runtime.
-//
-// The implementation takes care of the minutia and special cases of
-// interpreting the program counter (pc) values returned by runtime.Callers.
-//
-// Package stack's types implement fmt.Formatter, which provides a simple and
-// flexible way to declaratively configure formatting when used with logging
-// or error tracking packages.
-package stack
-
-import (
- "bytes"
- "errors"
- "fmt"
- "io"
- "runtime"
- "strconv"
- "strings"
-)
-
-// Call records a single function invocation from a goroutine stack.
-type Call struct {
- fn *runtime.Func
- pc uintptr
-}
-
-// Caller returns a Call from the stack of the current goroutine. The argument
-// skip is the number of stack frames to ascend, with 0 identifying the
-// calling function.
-func Caller(skip int) Call {
- var pcs [2]uintptr
- n := runtime.Callers(skip+1, pcs[:])
-
- var c Call
-
- if n < 2 {
- return c
- }
-
- c.pc = pcs[1]
- if runtime.FuncForPC(pcs[0]).Name() != "runtime.sigpanic" {
- c.pc--
- }
- c.fn = runtime.FuncForPC(c.pc)
- return c
-}
-
-// String implements fmt.Stinger. It is equivalent to fmt.Sprintf("%v", c).
-func (c Call) String() string {
- return fmt.Sprint(c)
-}
-
-// MarshalText implements encoding.TextMarshaler. It formats the Call the same
-// as fmt.Sprintf("%v", c).
-func (c Call) MarshalText() ([]byte, error) {
- if c.fn == nil {
- return nil, ErrNoFunc
- }
- buf := bytes.Buffer{}
- fmt.Fprint(&buf, c)
- return buf.Bytes(), nil
-}
-
-// ErrNoFunc means that the Call has a nil *runtime.Func. The most likely
-// cause is a Call with the zero value.
-var ErrNoFunc = errors.New("no call stack information")
-
-// Format implements fmt.Formatter with support for the following verbs.
-//
-// %s source file
-// %d line number
-// %n function name
-// %v equivalent to %s:%d
-//
-// It accepts the '+' and '#' flags for most of the verbs as follows.
-//
-// %+s path of source file relative to the compile time GOPATH
-// %#s full path of source file
-// %+n import path qualified function name
-// %+v equivalent to %+s:%d
-// %#v equivalent to %#s:%d
-func (c Call) Format(s fmt.State, verb rune) {
- if c.fn == nil {
- fmt.Fprintf(s, "%%!%c(NOFUNC)", verb)
- return
- }
-
- switch verb {
- case 's', 'v':
- file, line := c.fn.FileLine(c.pc)
- switch {
- case s.Flag('#'):
- // done
- case s.Flag('+'):
- file = file[pkgIndex(file, c.fn.Name()):]
- default:
- const sep = "/"
- if i := strings.LastIndex(file, sep); i != -1 {
- file = file[i+len(sep):]
- }
- }
- io.WriteString(s, file)
- if verb == 'v' {
- buf := [7]byte{':'}
- s.Write(strconv.AppendInt(buf[:1], int64(line), 10))
- }
-
- case 'd':
- _, line := c.fn.FileLine(c.pc)
- buf := [6]byte{}
- s.Write(strconv.AppendInt(buf[:0], int64(line), 10))
-
- case 'n':
- name := c.fn.Name()
- if !s.Flag('+') {
- const pathSep = "/"
- if i := strings.LastIndex(name, pathSep); i != -1 {
- name = name[i+len(pathSep):]
- }
- const pkgSep = "."
- if i := strings.Index(name, pkgSep); i != -1 {
- name = name[i+len(pkgSep):]
- }
- }
- io.WriteString(s, name)
- }
-}
-
-// PC returns the program counter for this call frame; multiple frames may
-// have the same PC value.
-func (c Call) PC() uintptr {
- return c.pc
-}
-
-// name returns the import path qualified name of the function containing the
-// call.
-func (c Call) name() string {
- if c.fn == nil {
- return "???"
- }
- return c.fn.Name()
-}
-
-func (c Call) file() string {
- if c.fn == nil {
- return "???"
- }
- file, _ := c.fn.FileLine(c.pc)
- return file
-}
-
-func (c Call) line() int {
- if c.fn == nil {
- return 0
- }
- _, line := c.fn.FileLine(c.pc)
- return line
-}
-
-// CallStack records a sequence of function invocations from a goroutine
-// stack.
-type CallStack []Call
-
-// String implements fmt.Stinger. It is equivalent to fmt.Sprintf("%v", cs).
-func (cs CallStack) String() string {
- return fmt.Sprint(cs)
-}
-
-var (
- openBracketBytes = []byte("[")
- closeBracketBytes = []byte("]")
- spaceBytes = []byte(" ")
-)
-
-// MarshalText implements encoding.TextMarshaler. It formats the CallStack the
-// same as fmt.Sprintf("%v", cs).
-func (cs CallStack) MarshalText() ([]byte, error) {
- buf := bytes.Buffer{}
- buf.Write(openBracketBytes)
- for i, pc := range cs {
- if pc.fn == nil {
- return nil, ErrNoFunc
- }
- if i > 0 {
- buf.Write(spaceBytes)
- }
- fmt.Fprint(&buf, pc)
- }
- buf.Write(closeBracketBytes)
- return buf.Bytes(), nil
-}
-
-// Format implements fmt.Formatter by printing the CallStack as square brackets
-// ([, ]) surrounding a space separated list of Calls each formatted with the
-// supplied verb and options.
-func (cs CallStack) Format(s fmt.State, verb rune) {
- s.Write(openBracketBytes)
- for i, pc := range cs {
- if i > 0 {
- s.Write(spaceBytes)
- }
- pc.Format(s, verb)
- }
- s.Write(closeBracketBytes)
-}
-
-// Trace returns a CallStack for the current goroutine with element 0
-// identifying the calling function.
-func Trace() CallStack {
- var pcs [512]uintptr
- n := runtime.Callers(2, pcs[:])
- cs := make([]Call, n)
-
- for i, pc := range pcs[:n] {
- pcFix := pc
- if i > 0 && cs[i-1].fn.Name() != "runtime.sigpanic" {
- pcFix--
- }
- cs[i] = Call{
- fn: runtime.FuncForPC(pcFix),
- pc: pcFix,
- }
- }
-
- return cs
-}
-
-// TrimBelow returns a slice of the CallStack with all entries below c
-// removed.
-func (cs CallStack) TrimBelow(c Call) CallStack {
- for len(cs) > 0 && cs[0].pc != c.pc {
- cs = cs[1:]
- }
- return cs
-}
-
-// TrimAbove returns a slice of the CallStack with all entries above c
-// removed.
-func (cs CallStack) TrimAbove(c Call) CallStack {
- for len(cs) > 0 && cs[len(cs)-1].pc != c.pc {
- cs = cs[:len(cs)-1]
- }
- return cs
-}
-
-// pkgIndex returns the index that results in file[index:] being the path of
-// file relative to the compile time GOPATH, and file[:index] being the
-// $GOPATH/src/ portion of file. funcName must be the name of a function in
-// file as returned by runtime.Func.Name.
-func pkgIndex(file, funcName string) int {
- // As of Go 1.6.2 there is no direct way to know the compile time GOPATH
- // at runtime, but we can infer the number of path segments in the GOPATH.
- // We note that runtime.Func.Name() returns the function name qualified by
- // the import path, which does not include the GOPATH. Thus we can trim
- // segments from the beginning of the file path until the number of path
- // separators remaining is one more than the number of path separators in
- // the function name. For example, given:
- //
- // GOPATH /home/user
- // file /home/user/src/pkg/sub/file.go
- // fn.Name() pkg/sub.Type.Method
- //
- // We want to produce:
- //
- // file[:idx] == /home/user/src/
- // file[idx:] == pkg/sub/file.go
- //
- // From this we can easily see that fn.Name() has one less path separator
- // than our desired result for file[idx:]. We count separators from the
- // end of the file path until it finds two more than in the function name
- // and then move one character forward to preserve the initial path
- // segment without a leading separator.
- const sep = "/"
- i := len(file)
- for n := strings.Count(funcName, sep) + 2; n > 0; n-- {
- i = strings.LastIndex(file[:i], sep)
- if i == -1 {
- i = -len(sep)
- break
- }
- }
- // get back to 0 or trim the leading separator
- return i + len(sep)
-}
-
-var runtimePath string
-
-func init() {
- var pcs [1]uintptr
- runtime.Callers(0, pcs[:])
- fn := runtime.FuncForPC(pcs[0])
- file, _ := fn.FileLine(pcs[0])
-
- idx := pkgIndex(file, fn.Name())
-
- runtimePath = file[:idx]
- if runtime.GOOS == "windows" {
- runtimePath = strings.ToLower(runtimePath)
- }
-}
-
-func inGoroot(c Call) bool {
- file := c.file()
- if len(file) == 0 || file[0] == '?' {
- return true
- }
- if runtime.GOOS == "windows" {
- file = strings.ToLower(file)
- }
- return strings.HasPrefix(file, runtimePath) || strings.HasSuffix(file, "/_testmain.go")
-}
-
-// TrimRuntime returns a slice of the CallStack with the topmost entries from
-// the go runtime removed. It considers any calls originating from unknown
-// files, files under GOROOT, or _testmain.go as part of the runtime.
-func (cs CallStack) TrimRuntime() CallStack {
- for len(cs) > 0 && inGoroot(cs[len(cs)-1]) {
- cs = cs[:len(cs)-1]
- }
- return cs
-}
diff --git a/vendor/github.com/golang/protobuf/LICENSE b/vendor/github.com/golang/protobuf/LICENSE
deleted file mode 100644
index 0f646931a4..0000000000
--- a/vendor/github.com/golang/protobuf/LICENSE
+++ /dev/null
@@ -1,28 +0,0 @@
-Copyright 2010 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/vendor/github.com/golang/protobuf/proto/clone.go b/vendor/github.com/golang/protobuf/proto/clone.go
deleted file mode 100644
index 3cd3249f70..0000000000
--- a/vendor/github.com/golang/protobuf/proto/clone.go
+++ /dev/null
@@ -1,253 +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: RawMessage.
-
-package proto
-
-import (
- "fmt"
- "log"
- "reflect"
- "strings"
-)
-
-// Clone returns a deep copy of a protocol buffer.
-func Clone(src Message) Message {
- in := reflect.ValueOf(src)
- if in.IsNil() {
- return src
- }
- out := reflect.New(in.Type().Elem())
- dst := out.Interface().(Message)
- Merge(dst, src)
- return dst
-}
-
-// Merger is the interface representing objects that can merge messages of the same type.
-type Merger interface {
- // Merge merges src into this message.
- // 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 may panic if called with a different argument type than the receiver.
- Merge(src Message)
-}
-
-// generatedMerger is the custom merge method that generated protos will have.
-// We must add this method since a generate Merge method will conflict with
-// many existing protos that have a Merge data field already defined.
-type generatedMerger interface {
- XXX_Merge(src 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) {
- if m, ok := dst.(Merger); ok {
- m.Merge(src)
- return
- }
-
- in := reflect.ValueOf(src)
- out := reflect.ValueOf(dst)
- if out.IsNil() {
- panic("proto: nil destination")
- }
- if in.Type() != out.Type() {
- panic(fmt.Sprintf("proto.Merge(%T, %T) type mismatch", dst, src))
- }
- if in.IsNil() {
- return // Merge from nil src is a noop
- }
- if m, ok := dst.(generatedMerger); ok {
- m.XXX_Merge(src)
- 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, err := extendable(in.Addr().Interface()); err == nil {
- emOut, _ := extendable(out.Addr().Interface())
- mIn, muIn := emIn.extensionsRead()
- if mIn != nil {
- mOut := emOut.extensionsWrite()
- muIn.Lock()
- mergeExtension(mOut, mIn)
- muIn.Unlock()
- }
- }
-
- uf := in.FieldByName("XXX_unrecognized")
- if !uf.IsValid() {
- return
- }
- uin := uf.Bytes()
- if len(uin) > 0 {
- out.FieldByName("XXX_unrecognized").SetBytes(append([]byte(nil), uin...))
- }
-}
-
-// mergeAny performs a merge between two values of the same type.
-// viaPtr indicates whether the values were indirected through a pointer (implying proto2).
-// prop is set if this is a struct field (it may be nil).
-func mergeAny(out, in reflect.Value, viaPtr bool, prop *Properties) {
- if in.Type() == protoMessageType {
- if !in.IsNil() {
- if out.IsNil() {
- out.Set(reflect.ValueOf(Clone(in.Interface().(Message))))
- } else {
- Merge(out.Interface().(Message), in.Interface().(Message))
- }
- }
- return
- }
- switch in.Kind() {
- case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int32, reflect.Int64,
- reflect.String, reflect.Uint32, reflect.Uint64:
- if !viaPtr && isProto3Zero(in) {
- return
- }
- out.Set(in)
- case reflect.Interface:
- // Probably a oneof field; copy non-nil values.
- if in.IsNil() {
- return
- }
- // Allocate destination if it is not set, or set to a different type.
- // Otherwise we will merge as normal.
- if out.IsNil() || out.Elem().Type() != in.Elem().Type() {
- out.Set(reflect.New(in.Elem().Elem().Type())) // interface -> *T -> T -> new(T)
- }
- mergeAny(out.Elem(), in.Elem(), false, nil)
- case reflect.Map:
- if in.Len() == 0 {
- return
- }
- if out.IsNil() {
- out.Set(reflect.MakeMap(in.Type()))
- }
- // For maps with value types of *T or []byte we need to deep copy each value.
- elemKind := in.Type().Elem().Kind()
- for _, key := range in.MapKeys() {
- var val reflect.Value
- switch elemKind {
- case reflect.Ptr:
- val = reflect.New(in.Type().Elem().Elem())
- mergeAny(val, in.MapIndex(key), false, nil)
- case reflect.Slice:
- val = in.MapIndex(key)
- val = reflect.ValueOf(append([]byte{}, val.Bytes()...))
- default:
- val = in.MapIndex(key)
- }
- out.SetMapIndex(key, val)
- }
- case reflect.Ptr:
- if in.IsNil() {
- return
- }
- if out.IsNil() {
- out.Set(reflect.New(in.Elem().Type()))
- }
- mergeAny(out.Elem(), in.Elem(), true, nil)
- case reflect.Slice:
- if in.IsNil() {
- return
- }
- if in.Type().Elem().Kind() == reflect.Uint8 {
- // []byte is a scalar bytes field, not a repeated field.
-
- // Edge case: if this is in a proto3 message, a zero length
- // bytes field is considered the zero value, and should not
- // be merged.
- if prop != nil && prop.proto3 && in.Len() == 0 {
- return
- }
-
- // Make a deep copy.
- // Append to []byte{} instead of []byte(nil) so that we never end up
- // with a nil result.
- out.SetBytes(append([]byte{}, in.Bytes()...))
- return
- }
- n := in.Len()
- if out.IsNil() {
- out.Set(reflect.MakeSlice(in.Type(), 0, n))
- }
- switch in.Type().Elem().Kind() {
- case reflect.Bool, reflect.Float32, reflect.Float64, reflect.Int32, reflect.Int64,
- reflect.String, reflect.Uint32, reflect.Uint64:
- out.Set(reflect.AppendSlice(out, in))
- default:
- for i := 0; i < n; i++ {
- x := reflect.Indirect(reflect.New(in.Type().Elem()))
- mergeAny(x, in.Index(i), false, nil)
- out.Set(reflect.Append(out, x))
- }
- }
- case reflect.Struct:
- mergeStruct(out, in)
- default:
- // unknown type, so not a protocol buffer
- log.Printf("proto: don't know how to copy %v", in)
- }
-}
-
-func mergeExtension(out, in map[int32]Extension) {
- for extNum, eIn := range in {
- eOut := Extension{desc: eIn.desc}
- if eIn.value != nil {
- v := reflect.New(reflect.TypeOf(eIn.value)).Elem()
- mergeAny(v, reflect.ValueOf(eIn.value), false, nil)
- eOut.value = v.Interface()
- }
- if eIn.enc != nil {
- eOut.enc = make([]byte, len(eIn.enc))
- copy(eOut.enc, eIn.enc)
- }
-
- out[extNum] = eOut
- }
-}
diff --git a/vendor/github.com/golang/protobuf/proto/decode.go b/vendor/github.com/golang/protobuf/proto/decode.go
deleted file mode 100644
index 63b0f08bef..0000000000
--- a/vendor/github.com/golang/protobuf/proto/decode.go
+++ /dev/null
@@ -1,427 +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"
-)
-
-// errOverflow is returned when an integer is too large to be represented.
-var errOverflow = errors.New("proto: integer overflow")
-
-// ErrInternalBadWireType is returned by generated code when an incorrect
-// wire type is encountered. It does not get returned to user code.
-var ErrInternalBadWireType = errors.New("proto: internal error: bad wiretype for oneof")
-
-// DecodeVarint reads a varint-encoded integer from the slice.
-// It returns the integer and the number of bytes consumed, or
-// zero if there is not enough.
-// This is the format for the
-// int32, int64, uint32, uint64, bool, and enum
-// protocol buffer types.
-func DecodeVarint(buf []byte) (x uint64, n int) {
- for shift := uint(0); shift < 64; shift += 7 {
- if n >= len(buf) {
- return 0, 0
- }
- b := uint64(buf[n])
- n++
- x |= (b & 0x7F) << shift
- if (b & 0x80) == 0 {
- return x, n
- }
- }
-
- // The number is too large to represent in a 64-bit value.
- return 0, 0
-}
-
-func (p *Buffer) decodeVarintSlow() (x uint64, err error) {
- i := p.index
- l := len(p.buf)
-
- for shift := uint(0); shift < 64; shift += 7 {
- if i >= l {
- err = io.ErrUnexpectedEOF
- return
- }
- b := p.buf[i]
- i++
- x |= (uint64(b) & 0x7F) << shift
- if b < 0x80 {
- p.index = i
- return
- }
- }
-
- // The number is too large to represent in a 64-bit value.
- err = errOverflow
- return
-}
-
-// DecodeVarint reads a varint-encoded integer from the Buffer.
-// This is the format for the
-// int32, int64, uint32, uint64, bool, and enum
-// protocol buffer types.
-func (p *Buffer) DecodeVarint() (x uint64, err error) {
- i := p.index
- buf := p.buf
-
- if i >= len(buf) {
- return 0, io.ErrUnexpectedEOF
- } else if buf[i] < 0x80 {
- p.index++
- return uint64(buf[i]), nil
- } else if len(buf)-i < 10 {
- return p.decodeVarintSlow()
- }
-
- var b uint64
- // we already checked the first byte
- x = uint64(buf[i]) - 0x80
- i++
-
- b = uint64(buf[i])
- i++
- x += b << 7
- if b&0x80 == 0 {
- goto done
- }
- x -= 0x80 << 7
-
- b = uint64(buf[i])
- i++
- x += b << 14
- if b&0x80 == 0 {
- goto done
- }
- x -= 0x80 << 14
-
- b = uint64(buf[i])
- i++
- x += b << 21
- if b&0x80 == 0 {
- goto done
- }
- x -= 0x80 << 21
-
- b = uint64(buf[i])
- i++
- x += b << 28
- if b&0x80 == 0 {
- goto done
- }
- x -= 0x80 << 28
-
- b = uint64(buf[i])
- i++
- x += b << 35
- if b&0x80 == 0 {
- goto done
- }
- x -= 0x80 << 35
-
- b = uint64(buf[i])
- i++
- x += b << 42
- if b&0x80 == 0 {
- goto done
- }
- x -= 0x80 << 42
-
- b = uint64(buf[i])
- i++
- x += b << 49
- if b&0x80 == 0 {
- goto done
- }
- x -= 0x80 << 49
-
- b = uint64(buf[i])
- i++
- x += b << 56
- if b&0x80 == 0 {
- goto done
- }
- x -= 0x80 << 56
-
- b = uint64(buf[i])
- i++
- x += b << 63
- if b&0x80 == 0 {
- goto done
- }
-
- return 0, errOverflow
-
-done:
- p.index = i
- return x, nil
-}
-
-// DecodeFixed64 reads a 64-bit integer from the Buffer.
-// This is the format for the
-// fixed64, sfixed64, and double protocol buffer types.
-func (p *Buffer) DecodeFixed64() (x uint64, err error) {
- // x, err already 0
- i := p.index + 8
- if i < 0 || i > len(p.buf) {
- err = io.ErrUnexpectedEOF
- return
- }
- p.index = i
-
- x = uint64(p.buf[i-8])
- x |= uint64(p.buf[i-7]) << 8
- x |= uint64(p.buf[i-6]) << 16
- x |= uint64(p.buf[i-5]) << 24
- x |= uint64(p.buf[i-4]) << 32
- x |= uint64(p.buf[i-3]) << 40
- x |= uint64(p.buf[i-2]) << 48
- x |= uint64(p.buf[i-1]) << 56
- return
-}
-
-// DecodeFixed32 reads a 32-bit integer from the Buffer.
-// This is the format for the
-// fixed32, sfixed32, and float protocol buffer types.
-func (p *Buffer) DecodeFixed32() (x uint64, err error) {
- // x, err already 0
- i := p.index + 4
- if i < 0 || i > len(p.buf) {
- err = io.ErrUnexpectedEOF
- return
- }
- p.index = i
-
- x = uint64(p.buf[i-4])
- x |= uint64(p.buf[i-3]) << 8
- x |= uint64(p.buf[i-2]) << 16
- x |= uint64(p.buf[i-1]) << 24
- return
-}
-
-// DecodeZigzag64 reads a zigzag-encoded 64-bit integer
-// from the Buffer.
-// This is the format used for the sint64 protocol buffer type.
-func (p *Buffer) DecodeZigzag64() (x uint64, err error) {
- x, err = p.DecodeVarint()
- if err != nil {
- return
- }
- x = (x >> 1) ^ uint64((int64(x&1)<<63)>>63)
- return
-}
-
-// DecodeZigzag32 reads a zigzag-encoded 32-bit integer
-// from the Buffer.
-// This is the format used for the sint32 protocol buffer type.
-func (p *Buffer) DecodeZigzag32() (x uint64, err error) {
- x, err = p.DecodeVarint()
- if err != nil {
- return
- }
- x = uint64((uint32(x) >> 1) ^ uint32((int32(x&1)<<31)>>31))
- return
-}
-
-// 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
-}
-
-// Unmarshaler is the interface representing objects that can
-// unmarshal themselves. The argument points to data that may be
-// overwritten, so implementations should not keep references to the
-// buffer.
-// Unmarshal implementations should not clear the receiver.
-// Any unmarshaled data should be merged into the receiver.
-// Callers of Unmarshal that do not want to retain existing data
-// should Reset the receiver before calling Unmarshal.
-type Unmarshaler interface {
- Unmarshal([]byte) error
-}
-
-// newUnmarshaler is the interface representing objects that can
-// unmarshal themselves. The semantics are identical to Unmarshaler.
-//
-// This exists to support protoc-gen-go generated messages.
-// The proto package will stop type-asserting to this interface in the future.
-//
-// DO NOT DEPEND ON THIS.
-type newUnmarshaler interface {
- XXX_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()
- if u, ok := pb.(newUnmarshaler); ok {
- return u.XXX_Unmarshal(buf)
- }
- if u, ok := pb.(Unmarshaler); ok {
- return u.Unmarshal(buf)
- }
- return NewBuffer(buf).Unmarshal(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 u, ok := pb.(newUnmarshaler); ok {
- return u.XXX_Unmarshal(buf)
- }
- if u, ok := pb.(Unmarshaler); ok {
- // NOTE: The history of proto have unfortunately been inconsistent
- // whether Unmarshaler should or should not implicitly clear itself.
- // Some implementations do, most do not.
- // Thus, calling this here may or may not do what people want.
- //
- // See https://github.com/golang/protobuf/issues/424
- return u.Unmarshal(buf)
- }
- return NewBuffer(buf).Unmarshal(pb)
-}
-
-// DecodeMessage reads a count-delimited message from the Buffer.
-func (p *Buffer) DecodeMessage(pb Message) error {
- enc, err := p.DecodeRawBytes(false)
- if err != nil {
- return err
- }
- return NewBuffer(enc).Unmarshal(pb)
-}
-
-// DecodeGroup reads a tag-delimited group from the Buffer.
-// StartGroup tag is already consumed. This function consumes
-// EndGroup tag.
-func (p *Buffer) DecodeGroup(pb Message) error {
- b := p.buf[p.index:]
- x, y := findEndGroup(b)
- if x < 0 {
- return io.ErrUnexpectedEOF
- }
- err := Unmarshal(b[:x], pb)
- p.index += y
- return err
-}
-
-// Unmarshal parses the protocol buffer representation in the
-// Buffer and places the decoded result in pb. If the struct
-// underlying pb does not match the data in the buffer, the results can be
-// unpredictable.
-//
-// Unlike proto.Unmarshal, this does not reset pb before starting to unmarshal.
-func (p *Buffer) Unmarshal(pb Message) error {
- // If the object can unmarshal itself, let it.
- if u, ok := pb.(newUnmarshaler); ok {
- err := u.XXX_Unmarshal(p.buf[p.index:])
- p.index = len(p.buf)
- return err
- }
- if u, ok := pb.(Unmarshaler); ok {
- // NOTE: The history of proto have unfortunately been inconsistent
- // whether Unmarshaler should or should not implicitly clear itself.
- // Some implementations do, most do not.
- // Thus, calling this here may or may not do what people want.
- //
- // See https://github.com/golang/protobuf/issues/424
- err := u.Unmarshal(p.buf[p.index:])
- p.index = len(p.buf)
- return err
- }
-
- // Slow workaround for messages that aren't Unmarshalers.
- // This includes some hand-coded .pb.go files and
- // bootstrap protos.
- // TODO: fix all of those and then add Unmarshal to
- // the Message interface. Then:
- // The cast above and code below can be deleted.
- // The old unmarshaler can be deleted.
- // Clients can call Unmarshal directly (can already do that, actually).
- var info InternalMessageInfo
- err := info.Unmarshal(pb, p.buf[p.index:])
- p.index = len(p.buf)
- return err
-}
diff --git a/vendor/github.com/golang/protobuf/proto/deprecated.go b/vendor/github.com/golang/protobuf/proto/deprecated.go
deleted file mode 100644
index 35b882c09a..0000000000
--- a/vendor/github.com/golang/protobuf/proto/deprecated.go
+++ /dev/null
@@ -1,63 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2018 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 "errors"
-
-// Deprecated: do not use.
-type Stats struct{ Emalloc, Dmalloc, Encode, Decode, Chit, Cmiss, Size uint64 }
-
-// Deprecated: do not use.
-func GetStats() Stats { return Stats{} }
-
-// Deprecated: do not use.
-func MarshalMessageSet(interface{}) ([]byte, error) {
- return nil, errors.New("proto: not implemented")
-}
-
-// Deprecated: do not use.
-func UnmarshalMessageSet([]byte, interface{}) error {
- return errors.New("proto: not implemented")
-}
-
-// Deprecated: do not use.
-func MarshalMessageSetJSON(interface{}) ([]byte, error) {
- return nil, errors.New("proto: not implemented")
-}
-
-// Deprecated: do not use.
-func UnmarshalMessageSetJSON([]byte, interface{}) error {
- return errors.New("proto: not implemented")
-}
-
-// Deprecated: do not use.
-func RegisterMessageSetType(Message, int32, string) {}
diff --git a/vendor/github.com/golang/protobuf/proto/discard.go b/vendor/github.com/golang/protobuf/proto/discard.go
deleted file mode 100644
index dea2617ced..0000000000
--- a/vendor/github.com/golang/protobuf/proto/discard.go
+++ /dev/null
@@ -1,350 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2017 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-package proto
-
-import (
- "fmt"
- "reflect"
- "strings"
- "sync"
- "sync/atomic"
-)
-
-type generatedDiscarder interface {
- XXX_DiscardUnknown()
-}
-
-// DiscardUnknown recursively discards all unknown fields from this message
-// and all embedded messages.
-//
-// When unmarshaling a message with unrecognized fields, the tags and values
-// of such fields are preserved in the Message. This allows a later call to
-// marshal to be able to produce a message that continues to have those
-// unrecognized fields. To avoid this, DiscardUnknown is used to
-// explicitly clear the unknown fields after unmarshaling.
-//
-// For proto2 messages, the unknown fields of message extensions are only
-// discarded from messages that have been accessed via GetExtension.
-func DiscardUnknown(m Message) {
- if m, ok := m.(generatedDiscarder); ok {
- m.XXX_DiscardUnknown()
- return
- }
- // TODO: Dynamically populate a InternalMessageInfo for legacy messages,
- // but the master branch has no implementation for InternalMessageInfo,
- // so it would be more work to replicate that approach.
- discardLegacy(m)
-}
-
-// DiscardUnknown recursively discards all unknown fields.
-func (a *InternalMessageInfo) DiscardUnknown(m Message) {
- di := atomicLoadDiscardInfo(&a.discard)
- if di == nil {
- di = getDiscardInfo(reflect.TypeOf(m).Elem())
- atomicStoreDiscardInfo(&a.discard, di)
- }
- di.discard(toPointer(&m))
-}
-
-type discardInfo struct {
- typ reflect.Type
-
- initialized int32 // 0: only typ is valid, 1: everything is valid
- lock sync.Mutex
-
- fields []discardFieldInfo
- unrecognized field
-}
-
-type discardFieldInfo struct {
- field field // Offset of field, guaranteed to be valid
- discard func(src pointer)
-}
-
-var (
- discardInfoMap = map[reflect.Type]*discardInfo{}
- discardInfoLock sync.Mutex
-)
-
-func getDiscardInfo(t reflect.Type) *discardInfo {
- discardInfoLock.Lock()
- defer discardInfoLock.Unlock()
- di := discardInfoMap[t]
- if di == nil {
- di = &discardInfo{typ: t}
- discardInfoMap[t] = di
- }
- return di
-}
-
-func (di *discardInfo) discard(src pointer) {
- if src.isNil() {
- return // Nothing to do.
- }
-
- if atomic.LoadInt32(&di.initialized) == 0 {
- di.computeDiscardInfo()
- }
-
- for _, fi := range di.fields {
- sfp := src.offset(fi.field)
- fi.discard(sfp)
- }
-
- // For proto2 messages, only discard unknown fields in message extensions
- // that have been accessed via GetExtension.
- if em, err := extendable(src.asPointerTo(di.typ).Interface()); err == nil {
- // Ignore lock since DiscardUnknown is not concurrency safe.
- emm, _ := em.extensionsRead()
- for _, mx := range emm {
- if m, ok := mx.value.(Message); ok {
- DiscardUnknown(m)
- }
- }
- }
-
- if di.unrecognized.IsValid() {
- *src.offset(di.unrecognized).toBytes() = nil
- }
-}
-
-func (di *discardInfo) computeDiscardInfo() {
- di.lock.Lock()
- defer di.lock.Unlock()
- if di.initialized != 0 {
- return
- }
- t := di.typ
- n := t.NumField()
-
- for i := 0; i < n; i++ {
- f := t.Field(i)
- if strings.HasPrefix(f.Name, "XXX_") {
- continue
- }
-
- dfi := discardFieldInfo{field: toField(&f)}
- tf := f.Type
-
- // Unwrap tf to get its most basic type.
- var isPointer, isSlice bool
- if tf.Kind() == reflect.Slice && tf.Elem().Kind() != reflect.Uint8 {
- isSlice = true
- tf = tf.Elem()
- }
- if tf.Kind() == reflect.Ptr {
- isPointer = true
- tf = tf.Elem()
- }
- if isPointer && isSlice && tf.Kind() != reflect.Struct {
- panic(fmt.Sprintf("%v.%s cannot be a slice of pointers to primitive types", t, f.Name))
- }
-
- switch tf.Kind() {
- case reflect.Struct:
- switch {
- case !isPointer:
- panic(fmt.Sprintf("%v.%s cannot be a direct struct value", t, f.Name))
- case isSlice: // E.g., []*pb.T
- di := getDiscardInfo(tf)
- dfi.discard = func(src pointer) {
- sps := src.getPointerSlice()
- for _, sp := range sps {
- if !sp.isNil() {
- di.discard(sp)
- }
- }
- }
- default: // E.g., *pb.T
- di := getDiscardInfo(tf)
- dfi.discard = func(src pointer) {
- sp := src.getPointer()
- if !sp.isNil() {
- di.discard(sp)
- }
- }
- }
- case reflect.Map:
- switch {
- case isPointer || isSlice:
- panic(fmt.Sprintf("%v.%s cannot be a pointer to a map or a slice of map values", t, f.Name))
- default: // E.g., map[K]V
- if tf.Elem().Kind() == reflect.Ptr { // Proto struct (e.g., *T)
- dfi.discard = func(src pointer) {
- sm := src.asPointerTo(tf).Elem()
- if sm.Len() == 0 {
- return
- }
- for _, key := range sm.MapKeys() {
- val := sm.MapIndex(key)
- DiscardUnknown(val.Interface().(Message))
- }
- }
- } else {
- dfi.discard = func(pointer) {} // Noop
- }
- }
- case reflect.Interface:
- // Must be oneof field.
- switch {
- case isPointer || isSlice:
- panic(fmt.Sprintf("%v.%s cannot be a pointer to a interface or a slice of interface values", t, f.Name))
- default: // E.g., interface{}
- // TODO: Make this faster?
- dfi.discard = func(src pointer) {
- su := src.asPointerTo(tf).Elem()
- if !su.IsNil() {
- sv := su.Elem().Elem().Field(0)
- if sv.Kind() == reflect.Ptr && sv.IsNil() {
- return
- }
- switch sv.Type().Kind() {
- case reflect.Ptr: // Proto struct (e.g., *T)
- DiscardUnknown(sv.Interface().(Message))
- }
- }
- }
- }
- default:
- continue
- }
- di.fields = append(di.fields, dfi)
- }
-
- di.unrecognized = invalidField
- if f, ok := t.FieldByName("XXX_unrecognized"); ok {
- if f.Type != reflect.TypeOf([]byte{}) {
- panic("expected XXX_unrecognized to be of type []byte")
- }
- di.unrecognized = toField(&f)
- }
-
- atomic.StoreInt32(&di.initialized, 1)
-}
-
-func discardLegacy(m Message) {
- v := reflect.ValueOf(m)
- if v.Kind() != reflect.Ptr || v.IsNil() {
- return
- }
- v = v.Elem()
- if v.Kind() != reflect.Struct {
- return
- }
- t := v.Type()
-
- for i := 0; i < v.NumField(); i++ {
- f := t.Field(i)
- if strings.HasPrefix(f.Name, "XXX_") {
- continue
- }
- vf := v.Field(i)
- tf := f.Type
-
- // Unwrap tf to get its most basic type.
- var isPointer, isSlice bool
- if tf.Kind() == reflect.Slice && tf.Elem().Kind() != reflect.Uint8 {
- isSlice = true
- tf = tf.Elem()
- }
- if tf.Kind() == reflect.Ptr {
- isPointer = true
- tf = tf.Elem()
- }
- if isPointer && isSlice && tf.Kind() != reflect.Struct {
- panic(fmt.Sprintf("%T.%s cannot be a slice of pointers to primitive types", m, f.Name))
- }
-
- switch tf.Kind() {
- case reflect.Struct:
- switch {
- case !isPointer:
- panic(fmt.Sprintf("%T.%s cannot be a direct struct value", m, f.Name))
- case isSlice: // E.g., []*pb.T
- for j := 0; j < vf.Len(); j++ {
- discardLegacy(vf.Index(j).Interface().(Message))
- }
- default: // E.g., *pb.T
- discardLegacy(vf.Interface().(Message))
- }
- case reflect.Map:
- switch {
- case isPointer || isSlice:
- panic(fmt.Sprintf("%T.%s cannot be a pointer to a map or a slice of map values", m, f.Name))
- default: // E.g., map[K]V
- tv := vf.Type().Elem()
- if tv.Kind() == reflect.Ptr && tv.Implements(protoMessageType) { // Proto struct (e.g., *T)
- for _, key := range vf.MapKeys() {
- val := vf.MapIndex(key)
- discardLegacy(val.Interface().(Message))
- }
- }
- }
- case reflect.Interface:
- // Must be oneof field.
- switch {
- case isPointer || isSlice:
- panic(fmt.Sprintf("%T.%s cannot be a pointer to a interface or a slice of interface values", m, f.Name))
- default: // E.g., test_proto.isCommunique_Union interface
- if !vf.IsNil() && f.Tag.Get("protobuf_oneof") != "" {
- vf = vf.Elem() // E.g., *test_proto.Communique_Msg
- if !vf.IsNil() {
- vf = vf.Elem() // E.g., test_proto.Communique_Msg
- vf = vf.Field(0) // E.g., Proto struct (e.g., *T) or primitive value
- if vf.Kind() == reflect.Ptr {
- discardLegacy(vf.Interface().(Message))
- }
- }
- }
- }
- }
- }
-
- if vf := v.FieldByName("XXX_unrecognized"); vf.IsValid() {
- if vf.Type() != reflect.TypeOf([]byte{}) {
- panic("expected XXX_unrecognized to be of type []byte")
- }
- vf.Set(reflect.ValueOf([]byte(nil)))
- }
-
- // For proto2 messages, only discard unknown fields in message extensions
- // that have been accessed via GetExtension.
- if em, err := extendable(m); err == nil {
- // Ignore lock since discardLegacy is not concurrency safe.
- emm, _ := em.extensionsRead()
- for _, mx := range emm {
- if m, ok := mx.value.(Message); ok {
- discardLegacy(m)
- }
- }
- }
-}
diff --git a/vendor/github.com/golang/protobuf/proto/encode.go b/vendor/github.com/golang/protobuf/proto/encode.go
deleted file mode 100644
index 3abfed2cff..0000000000
--- a/vendor/github.com/golang/protobuf/proto/encode.go
+++ /dev/null
@@ -1,203 +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"
- "reflect"
-)
-
-var (
- // errRepeatedHasNil is the error returned if Marshal is called with
- // a struct with a repeated field containing a nil element.
- errRepeatedHasNil = errors.New("proto: repeated field has nil element")
-
- // errOneofHasNil is the error returned if Marshal is called with
- // a struct with a oneof field containing a nil element.
- errOneofHasNil = errors.New("proto: oneof field has nil value")
-
- // ErrNil is the error returned if Marshal is called with nil.
- ErrNil = errors.New("proto: Marshal called with nil")
-
- // ErrTooLarge is the error returned if Marshal is called with a
- // message that encodes to >2GB.
- ErrTooLarge = errors.New("proto: message encodes to over 2 GB")
-)
-
-// The fundamental encoders that put bytes on the wire.
-// Those that take integer types all accept uint64 and are
-// therefore of type valueEncoder.
-
-const maxVarintBytes = 10 // maximum length of a varint
-
-// EncodeVarint returns the varint encoding of x.
-// This is the format for the
-// int32, int64, uint32, uint64, bool, and enum
-// protocol buffer types.
-// Not used by the package itself, but helpful to clients
-// wishing to use the same encoding.
-func EncodeVarint(x uint64) []byte {
- var buf [maxVarintBytes]byte
- var n int
- for n = 0; x > 127; n++ {
- buf[n] = 0x80 | uint8(x&0x7F)
- x >>= 7
- }
- buf[n] = uint8(x)
- n++
- return buf[0:n]
-}
-
-// EncodeVarint writes a varint-encoded integer to the Buffer.
-// This is the format for the
-// int32, int64, uint32, uint64, bool, and enum
-// protocol buffer types.
-func (p *Buffer) EncodeVarint(x uint64) error {
- for x >= 1<<7 {
- p.buf = append(p.buf, uint8(x&0x7f|0x80))
- x >>= 7
- }
- p.buf = append(p.buf, uint8(x))
- return nil
-}
-
-// SizeVarint returns the varint encoding size of an integer.
-func SizeVarint(x uint64) int {
- switch {
- case x < 1<<7:
- return 1
- case x < 1<<14:
- return 2
- case x < 1<<21:
- return 3
- case x < 1<<28:
- return 4
- case x < 1<<35:
- return 5
- case x < 1<<42:
- return 6
- case x < 1<<49:
- return 7
- case x < 1<<56:
- return 8
- case x < 1<<63:
- return 9
- }
- return 10
-}
-
-// 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
-}
-
-// 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
-}
-
-// 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))))
-}
-
-// 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))))
-}
-
-// 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
-}
-
-// 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
-}
-
-// Marshaler is the interface representing objects that can marshal themselves.
-type Marshaler interface {
- Marshal() ([]byte, error)
-}
-
-// EncodeMessage writes the protocol buffer to the Buffer,
-// prefixed by a varint-encoded length.
-func (p *Buffer) EncodeMessage(pb Message) error {
- siz := Size(pb)
- p.EncodeVarint(uint64(siz))
- return p.Marshal(pb)
-}
-
-// 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
-}
diff --git a/vendor/github.com/golang/protobuf/proto/equal.go b/vendor/github.com/golang/protobuf/proto/equal.go
deleted file mode 100644
index f9b6e41b3c..0000000000
--- a/vendor/github.com/golang/protobuf/proto/equal.go
+++ /dev/null
@@ -1,301 +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.
-
-package proto
-
-import (
- "bytes"
- "log"
- "reflect"
- "strings"
-)
-
-/*
-Equal returns true iff protocol buffers a and b are equal.
-The arguments must both be pointers to protocol buffer structs.
-
-Equality is defined in this way:
- - Two messages are equal iff they are the same type,
- corresponding fields are equal, unknown field sets
- are equal, and extensions sets are equal.
- - Two set scalar fields are equal iff their values are equal.
- If the fields are of a floating-point type, remember that
- NaN != x for all x, including NaN. If the message is defined
- in a proto3 .proto file, fields are not "set"; specifically,
- zero length proto3 "bytes" fields are equal (nil == {}).
- - Two repeated fields are equal iff their lengths are the same,
- and their corresponding elements are equal. Note a "bytes" field,
- although represented by []byte, is not a repeated field and the
- rule for the scalar fields described above applies.
- - Two unset fields are equal.
- - Two unknown field sets are equal if their current
- encoded state is equal.
- - Two extension sets are equal iff they have corresponding
- elements that are pairwise equal.
- - Two map fields are equal iff their lengths are the same,
- and they contain the same set of elements. Zero-length map
- fields are equal.
- - Every other combination of things are not equal.
-
-The return value is undefined if a and b are not protocol buffers.
-*/
-func Equal(a, b Message) bool {
- if a == nil || b == nil {
- return a == b
- }
- v1, v2 := reflect.ValueOf(a), reflect.ValueOf(b)
- if v1.Type() != v2.Type() {
- return false
- }
- if v1.Kind() == reflect.Ptr {
- if v1.IsNil() {
- return v2.IsNil()
- }
- if v2.IsNil() {
- return false
- }
- v1, v2 = v1.Elem(), v2.Elem()
- }
- if v1.Kind() != reflect.Struct {
- return false
- }
- return equalStruct(v1, v2)
-}
-
-// v1 and v2 are known to have the same type.
-func equalStruct(v1, v2 reflect.Value) bool {
- sprop := GetProperties(v1.Type())
- for i := 0; i < v1.NumField(); i++ {
- f := v1.Type().Field(i)
- if strings.HasPrefix(f.Name, "XXX_") {
- continue
- }
- f1, f2 := v1.Field(i), v2.Field(i)
- if f.Type.Kind() == reflect.Ptr {
- if n1, n2 := f1.IsNil(), f2.IsNil(); n1 && n2 {
- // both unset
- continue
- } else if n1 != n2 {
- // set/unset mismatch
- return false
- }
- f1, f2 = f1.Elem(), f2.Elem()
- }
- if !equalAny(f1, f2, sprop.Prop[i]) {
- return false
- }
- }
-
- if em1 := v1.FieldByName("XXX_InternalExtensions"); em1.IsValid() {
- em2 := v2.FieldByName("XXX_InternalExtensions")
- if !equalExtensions(v1.Type(), em1.Interface().(XXX_InternalExtensions), em2.Interface().(XXX_InternalExtensions)) {
- return false
- }
- }
-
- if em1 := v1.FieldByName("XXX_extensions"); em1.IsValid() {
- em2 := v2.FieldByName("XXX_extensions")
- if !equalExtMap(v1.Type(), em1.Interface().(map[int32]Extension), em2.Interface().(map[int32]Extension)) {
- return false
- }
- }
-
- uf := v1.FieldByName("XXX_unrecognized")
- if !uf.IsValid() {
- return true
- }
-
- u1 := uf.Bytes()
- u2 := v2.FieldByName("XXX_unrecognized").Bytes()
- return bytes.Equal(u1, u2)
-}
-
-// v1 and v2 are known to have the same type.
-// prop may be nil.
-func equalAny(v1, v2 reflect.Value, prop *Properties) bool {
- if v1.Type() == protoMessageType {
- m1, _ := v1.Interface().(Message)
- m2, _ := v2.Interface().(Message)
- return Equal(m1, m2)
- }
- switch v1.Kind() {
- case reflect.Bool:
- return v1.Bool() == v2.Bool()
- case reflect.Float32, reflect.Float64:
- return v1.Float() == v2.Float()
- case reflect.Int32, reflect.Int64:
- return v1.Int() == v2.Int()
- case reflect.Interface:
- // Probably a oneof field; compare the inner values.
- n1, n2 := v1.IsNil(), v2.IsNil()
- if n1 || n2 {
- return n1 == n2
- }
- e1, e2 := v1.Elem(), v2.Elem()
- if e1.Type() != e2.Type() {
- return false
- }
- return equalAny(e1, e2, nil)
- case reflect.Map:
- if v1.Len() != v2.Len() {
- return false
- }
- for _, key := range v1.MapKeys() {
- val2 := v2.MapIndex(key)
- if !val2.IsValid() {
- // This key was not found in the second map.
- return false
- }
- if !equalAny(v1.MapIndex(key), val2, nil) {
- return false
- }
- }
- return true
- case reflect.Ptr:
- // Maps may have nil values in them, so check for nil.
- if v1.IsNil() && v2.IsNil() {
- return true
- }
- if v1.IsNil() != v2.IsNil() {
- return false
- }
- return equalAny(v1.Elem(), v2.Elem(), prop)
- case reflect.Slice:
- if v1.Type().Elem().Kind() == reflect.Uint8 {
- // short circuit: []byte
-
- // Edge case: if this is in a proto3 message, a zero length
- // bytes field is considered the zero value.
- if prop != nil && prop.proto3 && v1.Len() == 0 && v2.Len() == 0 {
- return true
- }
- if v1.IsNil() != v2.IsNil() {
- return false
- }
- return bytes.Equal(v1.Interface().([]byte), v2.Interface().([]byte))
- }
-
- if v1.Len() != v2.Len() {
- return false
- }
- for i := 0; i < v1.Len(); i++ {
- if !equalAny(v1.Index(i), v2.Index(i), prop) {
- return false
- }
- }
- return true
- case reflect.String:
- return v1.Interface().(string) == v2.Interface().(string)
- case reflect.Struct:
- return equalStruct(v1, v2)
- case reflect.Uint32, reflect.Uint64:
- return v1.Uint() == v2.Uint()
- }
-
- // unknown type, so not a protocol buffer
- log.Printf("proto: don't know how to compare %v", v1)
- return false
-}
-
-// base is the struct type that the extensions are based on.
-// x1 and x2 are InternalExtensions.
-func equalExtensions(base reflect.Type, x1, x2 XXX_InternalExtensions) bool {
- em1, _ := x1.extensionsRead()
- em2, _ := x2.extensionsRead()
- return equalExtMap(base, em1, em2)
-}
-
-func equalExtMap(base reflect.Type, em1, em2 map[int32]Extension) bool {
- if len(em1) != len(em2) {
- return false
- }
-
- for extNum, e1 := range em1 {
- e2, ok := em2[extNum]
- if !ok {
- return false
- }
-
- m1 := extensionAsLegacyType(e1.value)
- m2 := extensionAsLegacyType(e2.value)
-
- if m1 == nil && m2 == nil {
- // Both have only encoded form.
- if bytes.Equal(e1.enc, e2.enc) {
- continue
- }
- // The bytes are different, but the extensions might still be
- // equal. We need to decode them to compare.
- }
-
- if m1 != nil && m2 != nil {
- // Both are unencoded.
- if !equalAny(reflect.ValueOf(m1), reflect.ValueOf(m2), nil) {
- return false
- }
- continue
- }
-
- // At least one is encoded. To do a semantically correct comparison
- // we need to unmarshal them first.
- var desc *ExtensionDesc
- if m := extensionMaps[base]; m != nil {
- desc = m[extNum]
- }
- if desc == nil {
- // If both have only encoded form and the bytes are the same,
- // it is handled above. We get here when the bytes are different.
- // We don't know how to decode it, so just compare them as byte
- // slices.
- log.Printf("proto: don't know how to compare extension %d of %v", extNum, base)
- return false
- }
- var err error
- if m1 == nil {
- m1, err = decodeExtension(e1.enc, desc)
- }
- if m2 == nil && err == nil {
- m2, err = decodeExtension(e2.enc, desc)
- }
- if err != nil {
- // The encoded form is invalid.
- log.Printf("proto: badly encoded extension %d of %v: %v", extNum, base, err)
- return false
- }
- if !equalAny(reflect.ValueOf(m1), reflect.ValueOf(m2), nil) {
- return false
- }
- }
-
- return true
-}
diff --git a/vendor/github.com/golang/protobuf/proto/extensions.go b/vendor/github.com/golang/protobuf/proto/extensions.go
deleted file mode 100644
index fa88add30a..0000000000
--- a/vendor/github.com/golang/protobuf/proto/extensions.go
+++ /dev/null
@@ -1,607 +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"
- "io"
- "reflect"
- "strconv"
- "sync"
-)
-
-// ErrMissingExtension is the error returned by GetExtension if the named extension is not in the message.
-var ErrMissingExtension = errors.New("proto: missing extension")
-
-// ExtensionRange represents a range of message extensions for a protocol buffer.
-// Used in code generated by the protocol compiler.
-type ExtensionRange struct {
- Start, End int32 // both inclusive
-}
-
-// extendableProto is an interface implemented by any protocol buffer generated by the current
-// proto compiler that may be extended.
-type extendableProto interface {
- Message
- ExtensionRangeArray() []ExtensionRange
- extensionsWrite() map[int32]Extension
- extensionsRead() (map[int32]Extension, sync.Locker)
-}
-
-// extendableProtoV1 is an interface implemented by a protocol buffer generated by the previous
-// version of the proto compiler that may be extended.
-type extendableProtoV1 interface {
- Message
- ExtensionRangeArray() []ExtensionRange
- ExtensionMap() map[int32]Extension
-}
-
-// extensionAdapter is a wrapper around extendableProtoV1 that implements extendableProto.
-type extensionAdapter struct {
- extendableProtoV1
-}
-
-func (e extensionAdapter) extensionsWrite() map[int32]Extension {
- return e.ExtensionMap()
-}
-
-func (e extensionAdapter) extensionsRead() (map[int32]Extension, sync.Locker) {
- return e.ExtensionMap(), notLocker{}
-}
-
-// notLocker is a sync.Locker whose Lock and Unlock methods are nops.
-type notLocker struct{}
-
-func (n notLocker) Lock() {}
-func (n notLocker) Unlock() {}
-
-// extendable returns the extendableProto interface for the given generated proto message.
-// If the proto message has the old extension format, it returns a wrapper that implements
-// the extendableProto interface.
-func extendable(p interface{}) (extendableProto, error) {
- switch p := p.(type) {
- case extendableProto:
- if isNilPtr(p) {
- return nil, fmt.Errorf("proto: nil %T is not extendable", p)
- }
- return p, nil
- case extendableProtoV1:
- if isNilPtr(p) {
- return nil, fmt.Errorf("proto: nil %T is not extendable", p)
- }
- return extensionAdapter{p}, nil
- }
- // Don't allocate a specific error containing %T:
- // this is the hot path for Clone and MarshalText.
- return nil, errNotExtendable
-}
-
-var errNotExtendable = errors.New("proto: not an extendable proto.Message")
-
-func isNilPtr(x interface{}) bool {
- v := reflect.ValueOf(x)
- return v.Kind() == reflect.Ptr && v.IsNil()
-}
-
-// XXX_InternalExtensions is an internal representation of proto extensions.
-//
-// Each generated message struct type embeds an anonymous XXX_InternalExtensions field,
-// thus gaining the unexported 'extensions' method, which can be called only from the proto package.
-//
-// The methods of XXX_InternalExtensions are not concurrency safe in general,
-// but calls to logically read-only methods such as has and get may be executed concurrently.
-type XXX_InternalExtensions struct {
- // The struct must be indirect so that if a user inadvertently copies a
- // generated message and its embedded XXX_InternalExtensions, they
- // avoid the mayhem of a copied mutex.
- //
- // The mutex serializes all logically read-only operations to p.extensionMap.
- // It is up to the client to ensure that write operations to p.extensionMap are
- // mutually exclusive with other accesses.
- p *struct {
- mu sync.Mutex
- extensionMap map[int32]Extension
- }
-}
-
-// extensionsWrite returns the extension map, creating it on first use.
-func (e *XXX_InternalExtensions) extensionsWrite() map[int32]Extension {
- if e.p == nil {
- e.p = new(struct {
- mu sync.Mutex
- extensionMap map[int32]Extension
- })
- e.p.extensionMap = make(map[int32]Extension)
- }
- return e.p.extensionMap
-}
-
-// extensionsRead returns the extensions map for read-only use. It may be nil.
-// The caller must hold the returned mutex's lock when accessing Elements within the map.
-func (e *XXX_InternalExtensions) extensionsRead() (map[int32]Extension, sync.Locker) {
- if e.p == nil {
- return nil, nil
- }
- return e.p.extensionMap, &e.p.mu
-}
-
-// ExtensionDesc represents an extension specification.
-// Used in generated code from the protocol compiler.
-type ExtensionDesc struct {
- ExtendedType Message // nil pointer to the type that is being extended
- ExtensionType interface{} // nil pointer to the extension type
- Field int32 // field number
- Name string // fully-qualified name of extension, for text formatting
- Tag string // protobuf tag style
- Filename string // name of the file in which the extension is defined
-}
-
-func (ed *ExtensionDesc) repeated() bool {
- t := reflect.TypeOf(ed.ExtensionType)
- return t.Kind() == reflect.Slice && t.Elem().Kind() != reflect.Uint8
-}
-
-// Extension represents an extension in a message.
-type Extension struct {
- // When an extension is stored in a message using SetExtension
- // only desc and value are set. When the message is marshaled
- // enc will be set to the encoded form of the message.
- //
- // When a message is unmarshaled and contains extensions, each
- // extension will have only enc set. When such an extension is
- // accessed using GetExtension (or GetExtensions) desc and value
- // will be set.
- desc *ExtensionDesc
-
- // value is a concrete value for the extension field. Let the type of
- // desc.ExtensionType be the "API type" and the type of Extension.value
- // be the "storage type". The API type and storage type are the same except:
- // * For scalars (except []byte), the API type uses *T,
- // while the storage type uses T.
- // * For repeated fields, the API type uses []T, while the storage type
- // uses *[]T.
- //
- // The reason for the divergence is so that the storage type more naturally
- // matches what is expected of when retrieving the values through the
- // protobuf reflection APIs.
- //
- // The value may only be populated if desc is also populated.
- value interface{}
-
- // enc is the raw bytes for the extension field.
- enc []byte
-}
-
-// SetRawExtension is for testing only.
-func SetRawExtension(base Message, id int32, b []byte) {
- epb, err := extendable(base)
- if err != nil {
- return
- }
- extmap := epb.extensionsWrite()
- extmap[id] = Extension{enc: b}
-}
-
-// isExtensionField returns true iff the given field number is in an extension range.
-func isExtensionField(pb extendableProto, field int32) bool {
- for _, er := range pb.ExtensionRangeArray() {
- if er.Start <= field && field <= er.End {
- return true
- }
- }
- return false
-}
-
-// checkExtensionTypes checks that the given extension is valid for pb.
-func checkExtensionTypes(pb extendableProto, extension *ExtensionDesc) error {
- var pbi interface{} = pb
- // Check the extended type.
- if ea, ok := pbi.(extensionAdapter); ok {
- pbi = ea.extendableProtoV1
- }
- if a, b := reflect.TypeOf(pbi), reflect.TypeOf(extension.ExtendedType); a != b {
- return fmt.Errorf("proto: bad extended type; %v does not extend %v", b, a)
- }
- // 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
-}
-
-// HasExtension returns whether the given extension is present in pb.
-func HasExtension(pb Message, extension *ExtensionDesc) bool {
- // TODO: Check types, field numbers, etc.?
- epb, err := extendable(pb)
- if err != nil {
- return false
- }
- extmap, mu := epb.extensionsRead()
- if extmap == nil {
- return false
- }
- mu.Lock()
- _, ok := extmap[extension.Field]
- mu.Unlock()
- return ok
-}
-
-// ClearExtension removes the given extension from pb.
-func ClearExtension(pb Message, extension *ExtensionDesc) {
- epb, err := extendable(pb)
- if err != nil {
- return
- }
- // TODO: Check types, field numbers, etc.?
- extmap := epb.extensionsWrite()
- delete(extmap, extension.Field)
-}
-
-// GetExtension retrieves a proto2 extended field from pb.
-//
-// If the descriptor is type complete (i.e., ExtensionDesc.ExtensionType is non-nil),
-// then GetExtension parses the encoded field and returns a Go value of the specified type.
-// If the field is not present, then the default value is returned (if one is specified),
-// otherwise ErrMissingExtension is reported.
-//
-// If the descriptor is not type complete (i.e., ExtensionDesc.ExtensionType is nil),
-// then GetExtension returns the raw encoded bytes of the field extension.
-func GetExtension(pb Message, extension *ExtensionDesc) (interface{}, error) {
- epb, err := extendable(pb)
- if err != nil {
- return nil, err
- }
-
- if extension.ExtendedType != nil {
- // can only check type if this is a complete descriptor
- if err := checkExtensionTypes(epb, extension); err != nil {
- return nil, err
- }
- }
-
- emap, mu := epb.extensionsRead()
- if emap == nil {
- return defaultExtensionValue(extension)
- }
- mu.Lock()
- defer mu.Unlock()
- e, ok := emap[extension.Field]
- if !ok {
- // defaultExtensionValue returns the default value or
- // ErrMissingExtension if there is no default.
- return defaultExtensionValue(extension)
- }
-
- if e.value != nil {
- // Already decoded. Check the descriptor, though.
- if e.desc != extension {
- // This shouldn't happen. If it does, it means that
- // GetExtension was called twice with two different
- // descriptors with the same field number.
- return nil, errors.New("proto: descriptor conflict")
- }
- return extensionAsLegacyType(e.value), nil
- }
-
- if extension.ExtensionType == nil {
- // incomplete descriptor
- return e.enc, 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 = extensionAsStorageType(v)
- e.desc = extension
- e.enc = nil
- emap[extension.Field] = e
- return extensionAsLegacyType(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) {
- if extension.ExtensionType == nil {
- // incomplete descriptor, so no default
- return nil, ErrMissingExtension
- }
-
- 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) {
- t := reflect.TypeOf(extension.ExtensionType)
- unmarshal := typeUnmarshaler(t, extension.Tag)
-
- // t is a pointer to a struct, pointer to basic type or a slice.
- // Allocate space to store the pointer/slice.
- value := reflect.New(t).Elem()
-
- var err error
- for {
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- wire := int(x) & 7
-
- b, err = unmarshal(b, valToPointer(value.Addr()), wire)
- if err != nil {
- return nil, err
- }
-
- if len(b) == 0 {
- 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, err := extendable(pb)
- if err != nil {
- return nil, err
- }
- extensions = make([]interface{}, len(es))
- for i, e := range es {
- extensions[i], err = GetExtension(epb, e)
- if err == ErrMissingExtension {
- err = nil
- }
- if err != nil {
- return
- }
- }
- return
-}
-
-// ExtensionDescs returns a new slice containing pb's extension descriptors, in undefined order.
-// For non-registered extensions, ExtensionDescs returns an incomplete descriptor containing
-// just the Field field, which defines the extension's field number.
-func ExtensionDescs(pb Message) ([]*ExtensionDesc, error) {
- epb, err := extendable(pb)
- if err != nil {
- return nil, err
- }
- registeredExtensions := RegisteredExtensions(pb)
-
- emap, mu := epb.extensionsRead()
- if emap == nil {
- return nil, nil
- }
- mu.Lock()
- defer mu.Unlock()
- extensions := make([]*ExtensionDesc, 0, len(emap))
- for extid, e := range emap {
- desc := e.desc
- if desc == nil {
- desc = registeredExtensions[extid]
- if desc == nil {
- desc = &ExtensionDesc{Field: extid}
- }
- }
-
- extensions = append(extensions, desc)
- }
- return extensions, nil
-}
-
-// SetExtension sets the specified extension of pb to the specified value.
-func SetExtension(pb Message, extension *ExtensionDesc, value interface{}) error {
- epb, err := extendable(pb)
- if err != nil {
- return err
- }
- if err := checkExtensionTypes(epb, extension); err != nil {
- return err
- }
- typ := reflect.TypeOf(extension.ExtensionType)
- if typ != reflect.TypeOf(value) {
- return fmt.Errorf("proto: bad extension value type. got: %T, want: %T", value, extension.ExtensionType)
- }
- // nil extension values need to be caught early, because the
- // encoder can't distinguish an ErrNil due to a nil extension
- // from an ErrNil due to a missing field. Extensions are
- // always optional, so the encoder would just swallow the error
- // and drop all the extensions from the encoded message.
- if reflect.ValueOf(value).IsNil() {
- return fmt.Errorf("proto: SetExtension called with nil value of type %T", value)
- }
-
- extmap := epb.extensionsWrite()
- extmap[extension.Field] = Extension{desc: extension, value: extensionAsStorageType(value)}
- return nil
-}
-
-// ClearAllExtensions clears all extensions from pb.
-func ClearAllExtensions(pb Message) {
- epb, err := extendable(pb)
- if err != nil {
- return
- }
- m := epb.extensionsWrite()
- for k := range m {
- delete(m, k)
- }
-}
-
-// A global registry of extensions.
-// The generated code will register the generated descriptors by calling RegisterExtension.
-
-var extensionMaps = make(map[reflect.Type]map[int32]*ExtensionDesc)
-
-// RegisterExtension is called from the generated code.
-func RegisterExtension(desc *ExtensionDesc) {
- st := reflect.TypeOf(desc.ExtendedType).Elem()
- m := extensionMaps[st]
- if m == nil {
- m = make(map[int32]*ExtensionDesc)
- extensionMaps[st] = m
- }
- if _, ok := m[desc.Field]; ok {
- panic("proto: duplicate extension registered: " + st.String() + " " + strconv.Itoa(int(desc.Field)))
- }
- m[desc.Field] = desc
-}
-
-// RegisteredExtensions returns a map of the registered extensions of a
-// protocol buffer struct, indexed by the extension number.
-// The argument pb should be a nil pointer to the struct type.
-func RegisteredExtensions(pb Message) map[int32]*ExtensionDesc {
- return extensionMaps[reflect.TypeOf(pb).Elem()]
-}
-
-// extensionAsLegacyType converts an value in the storage type as the API type.
-// See Extension.value.
-func extensionAsLegacyType(v interface{}) interface{} {
- switch rv := reflect.ValueOf(v); rv.Kind() {
- case reflect.Bool, reflect.Int32, reflect.Int64, reflect.Uint32, reflect.Uint64, reflect.Float32, reflect.Float64, reflect.String:
- // Represent primitive types as a pointer to the value.
- rv2 := reflect.New(rv.Type())
- rv2.Elem().Set(rv)
- v = rv2.Interface()
- case reflect.Ptr:
- // Represent slice types as the value itself.
- switch rv.Type().Elem().Kind() {
- case reflect.Slice:
- if rv.IsNil() {
- v = reflect.Zero(rv.Type().Elem()).Interface()
- } else {
- v = rv.Elem().Interface()
- }
- }
- }
- return v
-}
-
-// extensionAsStorageType converts an value in the API type as the storage type.
-// See Extension.value.
-func extensionAsStorageType(v interface{}) interface{} {
- switch rv := reflect.ValueOf(v); rv.Kind() {
- case reflect.Ptr:
- // Represent slice types as the value itself.
- switch rv.Type().Elem().Kind() {
- case reflect.Bool, reflect.Int32, reflect.Int64, reflect.Uint32, reflect.Uint64, reflect.Float32, reflect.Float64, reflect.String:
- if rv.IsNil() {
- v = reflect.Zero(rv.Type().Elem()).Interface()
- } else {
- v = rv.Elem().Interface()
- }
- }
- case reflect.Slice:
- // Represent slice types as a pointer to the value.
- if rv.Type().Elem().Kind() != reflect.Uint8 {
- rv2 := reflect.New(rv.Type())
- rv2.Elem().Set(rv)
- v = rv2.Interface()
- }
- }
- return v
-}
diff --git a/vendor/github.com/golang/protobuf/proto/lib.go b/vendor/github.com/golang/protobuf/proto/lib.go
deleted file mode 100644
index fdd328bb7f..0000000000
--- a/vendor/github.com/golang/protobuf/proto/lib.go
+++ /dev/null
@@ -1,965 +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.
- - Oneof field sets are given a single field in their message,
- with distinguished wrapper types for each possible field value.
- - Marshal and Unmarshal are functions to encode and decode the wire format.
-
-When the .proto file specifies `syntax="proto3"`, there are some differences:
-
- - Non-repeated fields of non-message type are values instead of pointers.
- - Enum types do not get an Enum method.
-
-The simplest way to describe this is to see an example.
-Given file test.proto, containing
-
- package example;
-
- enum FOO { X = 17; }
-
- message Test {
- required string label = 1;
- optional int32 type = 2 [default=77];
- repeated int64 reps = 3;
- optional group OptionalGroup = 4 {
- required string RequiredField = 5;
- }
- oneof union {
- int32 number = 6;
- string name = 7;
- }
- }
-
-The resulting file, test.pb.go, is:
-
- package example
-
- import proto "github.com/golang/protobuf/proto"
- import math "math"
-
- type FOO int32
- const (
- FOO_X FOO = 17
- )
- var FOO_name = map[int32]string{
- 17: "X",
- }
- var FOO_value = map[string]int32{
- "X": 17,
- }
-
- func (x FOO) Enum() *FOO {
- p := new(FOO)
- *p = x
- return p
- }
- func (x FOO) String() string {
- return proto.EnumName(FOO_name, int32(x))
- }
- func (x *FOO) UnmarshalJSON(data []byte) error {
- value, err := proto.UnmarshalJSONEnum(FOO_value, data)
- if err != nil {
- return err
- }
- *x = FOO(value)
- return nil
- }
-
- type Test struct {
- Label *string `protobuf:"bytes,1,req,name=label" json:"label,omitempty"`
- Type *int32 `protobuf:"varint,2,opt,name=type,def=77" json:"type,omitempty"`
- Reps []int64 `protobuf:"varint,3,rep,name=reps" json:"reps,omitempty"`
- Optionalgroup *Test_OptionalGroup `protobuf:"group,4,opt,name=OptionalGroup" json:"optionalgroup,omitempty"`
- // Types that are valid to be assigned to Union:
- // *Test_Number
- // *Test_Name
- Union isTest_Union `protobuf_oneof:"union"`
- XXX_unrecognized []byte `json:"-"`
- }
- func (m *Test) Reset() { *m = Test{} }
- func (m *Test) String() string { return proto.CompactTextString(m) }
- func (*Test) ProtoMessage() {}
-
- type isTest_Union interface {
- isTest_Union()
- }
-
- type Test_Number struct {
- Number int32 `protobuf:"varint,6,opt,name=number"`
- }
- type Test_Name struct {
- Name string `protobuf:"bytes,7,opt,name=name"`
- }
-
- func (*Test_Number) isTest_Union() {}
- func (*Test_Name) isTest_Union() {}
-
- func (m *Test) GetUnion() isTest_Union {
- if m != nil {
- return m.Union
- }
- return nil
- }
- const Default_Test_Type int32 = 77
-
- func (m *Test) GetLabel() string {
- if m != nil && m.Label != nil {
- return *m.Label
- }
- return ""
- }
-
- func (m *Test) GetType() int32 {
- if m != nil && m.Type != nil {
- return *m.Type
- }
- return Default_Test_Type
- }
-
- func (m *Test) GetOptionalgroup() *Test_OptionalGroup {
- if m != nil {
- return m.Optionalgroup
- }
- return nil
- }
-
- type Test_OptionalGroup struct {
- RequiredField *string `protobuf:"bytes,5,req" json:"RequiredField,omitempty"`
- }
- func (m *Test_OptionalGroup) Reset() { *m = Test_OptionalGroup{} }
- func (m *Test_OptionalGroup) String() string { return proto.CompactTextString(m) }
-
- func (m *Test_OptionalGroup) GetRequiredField() string {
- if m != nil && m.RequiredField != nil {
- return *m.RequiredField
- }
- return ""
- }
-
- func (m *Test) GetNumber() int32 {
- if x, ok := m.GetUnion().(*Test_Number); ok {
- return x.Number
- }
- return 0
- }
-
- func (m *Test) GetName() string {
- if x, ok := m.GetUnion().(*Test_Name); ok {
- return x.Name
- }
- return ""
- }
-
- func init() {
- proto.RegisterEnum("example.FOO", FOO_name, FOO_value)
- }
-
-To create and play with a Test object:
-
- package main
-
- import (
- "log"
-
- "github.com/golang/protobuf/proto"
- pb "./example.pb"
- )
-
- func main() {
- test := &pb.Test{
- Label: proto.String("hello"),
- Type: proto.Int32(17),
- Reps: []int64{1, 2, 3},
- Optionalgroup: &pb.Test_OptionalGroup{
- RequiredField: proto.String("good bye"),
- },
- Union: &pb.Test_Name{"fred"},
- }
- data, err := proto.Marshal(test)
- if err != nil {
- log.Fatal("marshaling error: ", err)
- }
- newTest := &pb.Test{}
- err = proto.Unmarshal(data, newTest)
- if err != nil {
- log.Fatal("unmarshaling error: ", err)
- }
- // Now test and newTest contain the same data.
- if test.GetLabel() != newTest.GetLabel() {
- log.Fatalf("data mismatch %q != %q", test.GetLabel(), newTest.GetLabel())
- }
- // Use a type switch to determine which oneof was set.
- switch u := test.Union.(type) {
- case *pb.Test_Number: // u.Number contains the number.
- case *pb.Test_Name: // u.Name contains the string.
- }
- // etc.
- }
-*/
-package proto
-
-import (
- "encoding/json"
- "fmt"
- "log"
- "reflect"
- "sort"
- "strconv"
- "sync"
-)
-
-// RequiredNotSetError is an error type returned by either Marshal or Unmarshal.
-// Marshal reports this when a required field is not initialized.
-// Unmarshal reports this when a required field is missing from the wire data.
-type RequiredNotSetError struct{ field string }
-
-func (e *RequiredNotSetError) Error() string {
- if e.field == "" {
- return fmt.Sprintf("proto: required field not set")
- }
- return fmt.Sprintf("proto: required field %q not set", e.field)
-}
-func (e *RequiredNotSetError) RequiredNotSet() bool {
- return true
-}
-
-type invalidUTF8Error struct{ field string }
-
-func (e *invalidUTF8Error) Error() string {
- if e.field == "" {
- return "proto: invalid UTF-8 detected"
- }
- return fmt.Sprintf("proto: field %q contains invalid UTF-8", e.field)
-}
-func (e *invalidUTF8Error) InvalidUTF8() bool {
- return true
-}
-
-// errInvalidUTF8 is a sentinel error to identify fields with invalid UTF-8.
-// This error should not be exposed to the external API as such errors should
-// be recreated with the field information.
-var errInvalidUTF8 = &invalidUTF8Error{}
-
-// isNonFatal reports whether the error is either a RequiredNotSet error
-// or a InvalidUTF8 error.
-func isNonFatal(err error) bool {
- if re, ok := err.(interface{ RequiredNotSet() bool }); ok && re.RequiredNotSet() {
- return true
- }
- if re, ok := err.(interface{ InvalidUTF8() bool }); ok && re.InvalidUTF8() {
- return true
- }
- return false
-}
-
-type nonFatal struct{ E error }
-
-// Merge merges err into nf and reports whether it was successful.
-// Otherwise it returns false for any fatal non-nil errors.
-func (nf *nonFatal) Merge(err error) (ok bool) {
- if err == nil {
- return true // not an error
- }
- if !isNonFatal(err) {
- return false // fatal error
- }
- if nf.E == nil {
- nf.E = err // store first instance of non-fatal error
- }
- return true
-}
-
-// Message is implemented by generated protocol buffer messages.
-type Message interface {
- Reset()
- String() string
- ProtoMessage()
-}
-
-// A Buffer is a buffer manager for marshaling and unmarshaling
-// protocol buffers. It may be reused between invocations to
-// reduce memory usage. It is not necessary to use a Buffer;
-// the global functions Marshal and Unmarshal create a
-// temporary Buffer and are fine for most applications.
-type Buffer struct {
- buf []byte // encode/decode byte stream
- index int // read point
-
- deterministic bool
-}
-
-// 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 }
-
-// SetDeterministic sets whether to use deterministic serialization.
-//
-// Deterministic serialization guarantees that for a given binary, equal
-// messages will always be serialized to the same bytes. This implies:
-//
-// - Repeated serialization of a message will return the same bytes.
-// - Different processes of the same binary (which may be executing on
-// different machines) will serialize equal messages to the same bytes.
-//
-// Note that the deterministic serialization is NOT canonical across
-// languages. It is not guaranteed to remain stable over time. It is unstable
-// across different builds with schema changes due to unknown fields.
-// Users who need canonical serialization (e.g., persistent storage in a
-// canonical form, fingerprinting, etc.) should define their own
-// canonicalization specification and implement their own serializer rather
-// than relying on this API.
-//
-// If deterministic serialization is requested, map entries will be sorted
-// by keys in lexographical order. This is an implementation detail and
-// subject to change.
-func (p *Buffer) SetDeterministic(deterministic bool) {
- p.deterministic = deterministic
-}
-
-/*
- * Helper routines for simplifying the creation of optional fields of basic type.
- */
-
-// Bool is a helper routine that allocates a new bool value
-// to store v and returns a pointer to it.
-func Bool(v bool) *bool {
- return &v
-}
-
-// Int32 is a helper routine that allocates a new int32 value
-// to store v and returns a pointer to it.
-func Int32(v int32) *int32 {
- return &v
-}
-
-// Int is a helper routine that allocates a new int32 value
-// to store v and returns a pointer to it, but unlike Int32
-// its argument value is an int.
-func Int(v int) *int32 {
- p := new(int32)
- *p = int32(v)
- return p
-}
-
-// Int64 is a helper routine that allocates a new int64 value
-// to store v and returns a pointer to it.
-func Int64(v int64) *int64 {
- return &v
-}
-
-// Float32 is a helper routine that allocates a new float32 value
-// to store v and returns a pointer to it.
-func Float32(v float32) *float32 {
- return &v
-}
-
-// Float64 is a helper routine that allocates a new float64 value
-// to store v and returns a pointer to it.
-func Float64(v float64) *float64 {
- return &v
-}
-
-// Uint32 is a helper routine that allocates a new uint32 value
-// to store v and returns a pointer to it.
-func Uint32(v uint32) *uint32 {
- return &v
-}
-
-// Uint64 is a helper routine that allocates a new uint64 value
-// to store v and returns a pointer to it.
-func Uint64(v uint64) *uint64 {
- return &v
-}
-
-// String is a helper routine that allocates a new string value
-// to store v and returns a pointer to it.
-func String(v string) *string {
- return &v
-}
-
-// EnumName is a helper function to simplify printing protocol buffer enums
-// by name. Given an enum map and a value, it returns a useful string.
-func EnumName(m map[int32]string, v int32) string {
- s, ok := m[v]
- if ok {
- return s
- }
- return strconv.Itoa(int(v))
-}
-
-// UnmarshalJSONEnum is a helper function to simplify recovering enum int values
-// from their JSON-encoded representation. Given a map from the enum's symbolic
-// names to its int values, and a byte buffer containing the JSON-encoded
-// value, it returns an int32 that can be cast to the enum type by the caller.
-//
-// The function can deal with both JSON representations, numeric and symbolic.
-func UnmarshalJSONEnum(m map[string]int32, data []byte, enumName string) (int32, error) {
- if data[0] == '"' {
- // New style: enums are strings.
- var repr string
- if err := json.Unmarshal(data, &repr); err != nil {
- return -1, err
- }
- val, ok := m[repr]
- if !ok {
- return 0, fmt.Errorf("unrecognized enum %s value %q", enumName, repr)
- }
- return val, nil
- }
- // Old style: enums are ints.
- var val int32
- if err := json.Unmarshal(data, &val); err != nil {
- return 0, fmt.Errorf("cannot unmarshal %#q into enum %s", data, enumName)
- }
- return val, nil
-}
-
-// DebugPrint dumps the encoded data in b in a debugging format with a header
-// including the string s. Used in testing but made available for general debugging.
-func (p *Buffer) DebugPrint(s string, b []byte) {
- var u uint64
-
- obuf := p.buf
- index := p.index
- p.buf = b
- p.index = 0
- depth := 0
-
- fmt.Printf("\n--- %s ---\n", s)
-
-out:
- for {
- for i := 0; i < depth; i++ {
- fmt.Print(" ")
- }
-
- index := p.index
- if index == len(p.buf) {
- break
- }
-
- op, err := p.DecodeVarint()
- if err != nil {
- fmt.Printf("%3d: fetching op err %v\n", index, err)
- break out
- }
- tag := op >> 3
- wire := op & 7
-
- switch wire {
- default:
- fmt.Printf("%3d: t=%3d unknown wire=%d\n",
- index, tag, wire)
- break out
-
- case WireBytes:
- var r []byte
-
- r, err = p.DecodeRawBytes(false)
- if err != nil {
- break out
- }
- fmt.Printf("%3d: t=%3d bytes [%d]", index, tag, len(r))
- if len(r) <= 6 {
- for i := 0; i < len(r); i++ {
- fmt.Printf(" %.2x", r[i])
- }
- } else {
- for i := 0; i < 3; i++ {
- fmt.Printf(" %.2x", r[i])
- }
- fmt.Printf(" ..")
- for i := len(r) - 3; i < len(r); i++ {
- fmt.Printf(" %.2x", r[i])
- }
- }
- fmt.Printf("\n")
-
- case WireFixed32:
- u, err = p.DecodeFixed32()
- if err != nil {
- fmt.Printf("%3d: t=%3d fix32 err %v\n", index, tag, err)
- break out
- }
- fmt.Printf("%3d: t=%3d fix32 %d\n", index, tag, u)
-
- case WireFixed64:
- u, err = p.DecodeFixed64()
- if err != nil {
- fmt.Printf("%3d: t=%3d fix64 err %v\n", index, tag, err)
- break out
- }
- fmt.Printf("%3d: t=%3d fix64 %d\n", index, tag, u)
-
- case WireVarint:
- u, err = p.DecodeVarint()
- if err != nil {
- fmt.Printf("%3d: t=%3d varint err %v\n", index, tag, err)
- break out
- }
- fmt.Printf("%3d: t=%3d varint %d\n", index, tag, u)
-
- case WireStartGroup:
- fmt.Printf("%3d: t=%3d start\n", index, tag)
- depth++
-
- case WireEndGroup:
- depth--
- fmt.Printf("%3d: t=%3d end\n", index, tag)
- }
- }
-
- if depth != 0 {
- fmt.Printf("%3d: start-end not balanced %d\n", p.index, depth)
- }
- fmt.Printf("\n")
-
- p.buf = obuf
- p.index = index
-}
-
-// SetDefaults sets unset protocol buffer fields to their default values.
-// It only modifies fields that are both unset and have defined defaults.
-// It recursively sets default values in any non-nil sub-messages.
-func SetDefaults(pb Message) {
- setDefaults(reflect.ValueOf(pb), true, false)
-}
-
-// v is a pointer to a struct.
-func setDefaults(v reflect.Value, recur, zeros bool) {
- v = v.Elem()
-
- defaultMu.RLock()
- dm, ok := defaults[v.Type()]
- defaultMu.RUnlock()
- if !ok {
- dm = buildDefaultMessage(v.Type())
- defaultMu.Lock()
- defaults[v.Type()] = dm
- defaultMu.Unlock()
- }
-
- for _, sf := range dm.scalars {
- f := v.Field(sf.index)
- if !f.IsNil() {
- // field already set
- continue
- }
- dv := sf.value
- if dv == nil && !zeros {
- // no explicit default, and don't want to set zeros
- continue
- }
- fptr := f.Addr().Interface() // **T
- // TODO: Consider batching the allocations we do here.
- switch sf.kind {
- case reflect.Bool:
- b := new(bool)
- if dv != nil {
- *b = dv.(bool)
- }
- *(fptr.(**bool)) = b
- case reflect.Float32:
- f := new(float32)
- if dv != nil {
- *f = dv.(float32)
- }
- *(fptr.(**float32)) = f
- case reflect.Float64:
- f := new(float64)
- if dv != nil {
- *f = dv.(float64)
- }
- *(fptr.(**float64)) = f
- case reflect.Int32:
- // might be an enum
- if ft := f.Type(); ft != int32PtrType {
- // enum
- f.Set(reflect.New(ft.Elem()))
- if dv != nil {
- f.Elem().SetInt(int64(dv.(int32)))
- }
- } else {
- // int32 field
- i := new(int32)
- if dv != nil {
- *i = dv.(int32)
- }
- *(fptr.(**int32)) = i
- }
- case reflect.Int64:
- i := new(int64)
- if dv != nil {
- *i = dv.(int64)
- }
- *(fptr.(**int64)) = i
- case reflect.String:
- s := new(string)
- if dv != nil {
- *s = dv.(string)
- }
- *(fptr.(**string)) = s
- case reflect.Uint8:
- // exceptional case: []byte
- var b []byte
- if dv != nil {
- db := dv.([]byte)
- b = make([]byte, len(db))
- copy(b, db)
- } else {
- b = []byte{}
- }
- *(fptr.(*[]byte)) = b
- case reflect.Uint32:
- u := new(uint32)
- if dv != nil {
- *u = dv.(uint32)
- }
- *(fptr.(**uint32)) = u
- case reflect.Uint64:
- u := new(uint64)
- if dv != nil {
- *u = dv.(uint64)
- }
- *(fptr.(**uint64)) = u
- default:
- log.Printf("proto: can't set default for field %v (sf.kind=%v)", f, sf.kind)
- }
- }
-
- for _, ni := range dm.nested {
- f := v.Field(ni)
- // f is *T or []*T or map[T]*T
- switch f.Kind() {
- case reflect.Ptr:
- if f.IsNil() {
- continue
- }
- setDefaults(f, recur, zeros)
-
- case reflect.Slice:
- for i := 0; i < f.Len(); i++ {
- e := f.Index(i)
- if e.IsNil() {
- continue
- }
- setDefaults(e, recur, zeros)
- }
-
- case reflect.Map:
- for _, k := range f.MapKeys() {
- e := f.MapIndex(k)
- if e.IsNil() {
- continue
- }
- setDefaults(e, recur, zeros)
- }
- }
- }
-}
-
-var (
- // defaults maps a protocol buffer struct type to a slice of the fields,
- // with its scalar fields set to their proto-declared non-zero default values.
- defaultMu sync.RWMutex
- defaults = make(map[reflect.Type]defaultMessage)
-
- int32PtrType = reflect.TypeOf((*int32)(nil))
-)
-
-// defaultMessage represents information about the default values of a message.
-type defaultMessage struct {
- scalars []scalarField
- nested []int // struct field index of nested messages
-}
-
-type scalarField struct {
- index int // struct field index
- kind reflect.Kind // element type (the T in *T or []T)
- value interface{} // the proto-declared default value, or nil
-}
-
-// t is a struct type.
-func buildDefaultMessage(t reflect.Type) (dm defaultMessage) {
- sprop := GetProperties(t)
- for _, prop := range sprop.Prop {
- fi, ok := sprop.decoderTags.get(prop.Tag)
- if !ok {
- // XXX_unrecognized
- continue
- }
- ft := t.Field(fi).Type
-
- sf, nested, err := fieldDefault(ft, prop)
- switch {
- case err != nil:
- log.Print(err)
- case nested:
- dm.nested = append(dm.nested, fi)
- case sf != nil:
- sf.index = fi
- dm.scalars = append(dm.scalars, *sf)
- }
- }
-
- return dm
-}
-
-// fieldDefault returns the scalarField for field type ft.
-// sf will be nil if the field can not have a default.
-// nestedMessage will be true if this is a nested message.
-// Note that sf.index is not set on return.
-func fieldDefault(ft reflect.Type, prop *Properties) (sf *scalarField, nestedMessage bool, err error) {
- var canHaveDefault bool
- switch ft.Kind() {
- case reflect.Ptr:
- if ft.Elem().Kind() == reflect.Struct {
- nestedMessage = true
- } else {
- canHaveDefault = true // proto2 scalar field
- }
-
- case reflect.Slice:
- switch ft.Elem().Kind() {
- case reflect.Ptr:
- nestedMessage = true // repeated message
- case reflect.Uint8:
- canHaveDefault = true // bytes field
- }
-
- case reflect.Map:
- if ft.Elem().Kind() == reflect.Ptr {
- nestedMessage = true // map with message values
- }
- }
-
- if !canHaveDefault {
- if nestedMessage {
- return nil, true, nil
- }
- return nil, false, nil
- }
-
- // We now know that ft is a pointer or slice.
- sf = &scalarField{kind: ft.Elem().Kind()}
-
- // scalar fields without defaults
- if !prop.HasDefault {
- return sf, false, nil
- }
-
- // a scalar field: either *T or []byte
- switch ft.Elem().Kind() {
- case reflect.Bool:
- x, err := strconv.ParseBool(prop.Default)
- if err != nil {
- return nil, false, fmt.Errorf("proto: bad default bool %q: %v", prop.Default, err)
- }
- sf.value = x
- case reflect.Float32:
- x, err := strconv.ParseFloat(prop.Default, 32)
- if err != nil {
- return nil, false, fmt.Errorf("proto: bad default float32 %q: %v", prop.Default, err)
- }
- sf.value = float32(x)
- case reflect.Float64:
- x, err := strconv.ParseFloat(prop.Default, 64)
- if err != nil {
- return nil, false, fmt.Errorf("proto: bad default float64 %q: %v", prop.Default, err)
- }
- sf.value = x
- case reflect.Int32:
- x, err := strconv.ParseInt(prop.Default, 10, 32)
- if err != nil {
- return nil, false, fmt.Errorf("proto: bad default int32 %q: %v", prop.Default, err)
- }
- sf.value = int32(x)
- case reflect.Int64:
- x, err := strconv.ParseInt(prop.Default, 10, 64)
- if err != nil {
- return nil, false, fmt.Errorf("proto: bad default int64 %q: %v", prop.Default, err)
- }
- sf.value = x
- case reflect.String:
- sf.value = prop.Default
- case reflect.Uint8:
- // []byte (not *uint8)
- sf.value = []byte(prop.Default)
- case reflect.Uint32:
- x, err := strconv.ParseUint(prop.Default, 10, 32)
- if err != nil {
- return nil, false, fmt.Errorf("proto: bad default uint32 %q: %v", prop.Default, err)
- }
- sf.value = uint32(x)
- case reflect.Uint64:
- x, err := strconv.ParseUint(prop.Default, 10, 64)
- if err != nil {
- return nil, false, fmt.Errorf("proto: bad default uint64 %q: %v", prop.Default, err)
- }
- sf.value = x
- default:
- return nil, false, fmt.Errorf("proto: unhandled def kind %v", ft.Elem().Kind())
- }
-
- return sf, false, nil
-}
-
-// mapKeys returns a sort.Interface to be used for sorting the map keys.
-// Map fields may have key types of non-float scalars, strings and enums.
-func mapKeys(vs []reflect.Value) sort.Interface {
- s := mapKeySorter{vs: vs}
-
- // Type specialization per https://developers.google.com/protocol-buffers/docs/proto#maps.
- if len(vs) == 0 {
- return s
- }
- switch vs[0].Kind() {
- case reflect.Int32, reflect.Int64:
- s.less = func(a, b reflect.Value) bool { return a.Int() < b.Int() }
- case reflect.Uint32, reflect.Uint64:
- s.less = func(a, b reflect.Value) bool { return a.Uint() < b.Uint() }
- case reflect.Bool:
- s.less = func(a, b reflect.Value) bool { return !a.Bool() && b.Bool() } // false < true
- case reflect.String:
- s.less = func(a, b reflect.Value) bool { return a.String() < b.String() }
- default:
- panic(fmt.Sprintf("unsupported map key type: %v", vs[0].Kind()))
- }
-
- return s
-}
-
-type mapKeySorter struct {
- vs []reflect.Value
- less func(a, b reflect.Value) bool
-}
-
-func (s mapKeySorter) Len() int { return len(s.vs) }
-func (s mapKeySorter) Swap(i, j int) { s.vs[i], s.vs[j] = s.vs[j], s.vs[i] }
-func (s mapKeySorter) Less(i, j int) bool {
- return s.less(s.vs[i], s.vs[j])
-}
-
-// isProto3Zero reports whether v is a zero proto3 value.
-func isProto3Zero(v reflect.Value) bool {
- switch v.Kind() {
- case reflect.Bool:
- return !v.Bool()
- case reflect.Int32, reflect.Int64:
- return v.Int() == 0
- case reflect.Uint32, reflect.Uint64:
- return v.Uint() == 0
- case reflect.Float32, reflect.Float64:
- return v.Float() == 0
- case reflect.String:
- return v.String() == ""
- }
- return false
-}
-
-const (
- // ProtoPackageIsVersion3 is referenced from generated protocol buffer files
- // to assert that that code is compatible with this version of the proto package.
- ProtoPackageIsVersion3 = true
-
- // ProtoPackageIsVersion2 is referenced from generated protocol buffer files
- // to assert that that code is compatible with this version of the proto package.
- ProtoPackageIsVersion2 = true
-
- // ProtoPackageIsVersion1 is referenced from generated protocol buffer files
- // to assert that that code is compatible with this version of the proto package.
- ProtoPackageIsVersion1 = true
-)
-
-// InternalMessageInfo is a type used internally by generated .pb.go files.
-// This type is not intended to be used by non-generated code.
-// This type is not subject to any compatibility guarantee.
-type InternalMessageInfo struct {
- marshal *marshalInfo
- unmarshal *unmarshalInfo
- merge *mergeInfo
- discard *discardInfo
-}
diff --git a/vendor/github.com/golang/protobuf/proto/message_set.go b/vendor/github.com/golang/protobuf/proto/message_set.go
deleted file mode 100644
index f48a756761..0000000000
--- a/vendor/github.com/golang/protobuf/proto/message_set.go
+++ /dev/null
@@ -1,181 +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 (
- "errors"
-)
-
-// errNoMessageTypeID occurs when a protocol buffer does not have a message type ID.
-// A message type ID is required for storing a protocol buffer in a message set.
-var errNoMessageTypeID = errors.New("proto does not have a message type ID")
-
-// The first two types (_MessageSet_Item and messageSet)
-// model what the protocol compiler produces for the following protocol message:
-// message MessageSet {
-// repeated group Item = 1 {
-// required int32 type_id = 2;
-// required string message = 3;
-// };
-// }
-// That is the MessageSet wire format. We can't use a proto to generate these
-// because that would introduce a circular dependency between it and this package.
-
-type _MessageSet_Item struct {
- TypeId *int32 `protobuf:"varint,2,req,name=type_id"`
- Message []byte `protobuf:"bytes,3,req,name=message"`
-}
-
-type messageSet struct {
- Item []*_MessageSet_Item `protobuf:"group,1,rep"`
- XXX_unrecognized []byte
- // TODO: caching?
-}
-
-// Make sure messageSet is a Message.
-var _ Message = (*messageSet)(nil)
-
-// messageTypeIder is an interface satisfied by a protocol buffer type
-// that may be stored in a MessageSet.
-type messageTypeIder interface {
- MessageTypeId() int32
-}
-
-func (ms *messageSet) find(pb Message) *_MessageSet_Item {
- mti, ok := pb.(messageTypeIder)
- if !ok {
- return nil
- }
- id := mti.MessageTypeId()
- for _, item := range ms.Item {
- if *item.TypeId == id {
- return item
- }
- }
- return nil
-}
-
-func (ms *messageSet) Has(pb Message) bool {
- return ms.find(pb) != nil
-}
-
-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:]
-}
-
-// unmarshalMessageSet decodes the extension map encoded in buf in the message set wire format.
-// It is called by Unmarshal methods on protocol buffer messages with the message_set_wire_format option.
-func unmarshalMessageSet(buf []byte, exts interface{}) error {
- var m map[int32]Extension
- switch exts := exts.(type) {
- case *XXX_InternalExtensions:
- m = exts.extensionsWrite()
- case map[int32]Extension:
- m = exts
- default:
- return errors.New("proto: not an extension map")
- }
-
- ms := new(messageSet)
- if err := Unmarshal(buf, ms); err != nil {
- return err
- }
- for _, item := range ms.Item {
- id := *item.TypeId
- msg := item.Message
-
- // Restore wire type and field number varint, plus length varint.
- // Be careful to preserve duplicate items.
- b := EncodeVarint(uint64(id)<<3 | WireBytes)
- if ext, ok := m[id]; ok {
- // Existing data; rip off the tag and length varint
- // so we join the new data correctly.
- // We can assume that ext.enc is set because we are unmarshaling.
- o := ext.enc[len(b):] // skip wire type and field number
- _, n := DecodeVarint(o) // calculate length of length varint
- o = o[n:] // skip length varint
- msg = append(o, msg...) // join old data and new data
- }
- b = append(b, EncodeVarint(uint64(len(msg)))...)
- b = append(b, msg...)
-
- m[id] = Extension{enc: b}
- }
- return nil
-}
diff --git a/vendor/github.com/golang/protobuf/proto/pointer_reflect.go b/vendor/github.com/golang/protobuf/proto/pointer_reflect.go
deleted file mode 100644
index 94fa9194a8..0000000000
--- a/vendor/github.com/golang/protobuf/proto/pointer_reflect.go
+++ /dev/null
@@ -1,360 +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 purego appengine js
-
-// This file contains an implementation of proto field accesses using package reflect.
-// It is slower than the code in pointer_unsafe.go but it avoids package unsafe and can
-// be used on App Engine.
-
-package proto
-
-import (
- "reflect"
- "sync"
-)
-
-const unsafeAllowed = false
-
-// A field identifies a field in a struct, accessible from a pointer.
-// 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)
-
-// zeroField is a noop when calling pointer.offset.
-var zeroField = field([]int{})
-
-// IsValid reports whether the field identifier is valid.
-func (f field) IsValid() bool { return f != nil }
-
-// The pointer type is for the table-driven decoder.
-// The implementation here uses a reflect.Value of pointer type to
-// create a generic pointer. In pointer_unsafe.go we use unsafe
-// instead of reflect to implement the same (but faster) interface.
-type pointer struct {
- v reflect.Value
-}
-
-// toPointer converts an interface of pointer type to a pointer
-// that points to the same target.
-func toPointer(i *Message) pointer {
- return pointer{v: reflect.ValueOf(*i)}
-}
-
-// toAddrPointer converts an interface to a pointer that points to
-// the interface data.
-func toAddrPointer(i *interface{}, isptr, deref bool) pointer {
- v := reflect.ValueOf(*i)
- u := reflect.New(v.Type())
- u.Elem().Set(v)
- if deref {
- u = u.Elem()
- }
- return pointer{v: u}
-}
-
-// valToPointer converts v to a pointer. v must be of pointer type.
-func valToPointer(v reflect.Value) pointer {
- return pointer{v: v}
-}
-
-// offset converts from a pointer to a structure to a pointer to
-// one of its fields.
-func (p pointer) offset(f field) pointer {
- return pointer{v: p.v.Elem().FieldByIndex(f).Addr()}
-}
-
-func (p pointer) isNil() bool {
- return p.v.IsNil()
-}
-
-// grow updates the slice s in place to make it one element longer.
-// s must be addressable.
-// Returns the (addressable) new element.
-func grow(s reflect.Value) reflect.Value {
- n, m := s.Len(), s.Cap()
- if n < m {
- s.SetLen(n + 1)
- } else {
- s.Set(reflect.Append(s, reflect.Zero(s.Type().Elem())))
- }
- return s.Index(n)
-}
-
-func (p pointer) toInt64() *int64 {
- return p.v.Interface().(*int64)
-}
-func (p pointer) toInt64Ptr() **int64 {
- return p.v.Interface().(**int64)
-}
-func (p pointer) toInt64Slice() *[]int64 {
- return p.v.Interface().(*[]int64)
-}
-
-var int32ptr = reflect.TypeOf((*int32)(nil))
-
-func (p pointer) toInt32() *int32 {
- return p.v.Convert(int32ptr).Interface().(*int32)
-}
-
-// The toInt32Ptr/Slice methods don't work because of enums.
-// Instead, we must use set/get methods for the int32ptr/slice case.
-/*
- func (p pointer) toInt32Ptr() **int32 {
- return p.v.Interface().(**int32)
-}
- func (p pointer) toInt32Slice() *[]int32 {
- return p.v.Interface().(*[]int32)
-}
-*/
-func (p pointer) getInt32Ptr() *int32 {
- if p.v.Type().Elem().Elem() == reflect.TypeOf(int32(0)) {
- // raw int32 type
- return p.v.Elem().Interface().(*int32)
- }
- // an enum
- return p.v.Elem().Convert(int32PtrType).Interface().(*int32)
-}
-func (p pointer) setInt32Ptr(v int32) {
- // Allocate value in a *int32. Possibly convert that to a *enum.
- // Then assign it to a **int32 or **enum.
- // Note: we can convert *int32 to *enum, but we can't convert
- // **int32 to **enum!
- p.v.Elem().Set(reflect.ValueOf(&v).Convert(p.v.Type().Elem()))
-}
-
-// getInt32Slice copies []int32 from p as a new slice.
-// This behavior differs from the implementation in pointer_unsafe.go.
-func (p pointer) getInt32Slice() []int32 {
- if p.v.Type().Elem().Elem() == reflect.TypeOf(int32(0)) {
- // raw int32 type
- return p.v.Elem().Interface().([]int32)
- }
- // an enum
- // Allocate a []int32, then assign []enum's values into it.
- // Note: we can't convert []enum to []int32.
- slice := p.v.Elem()
- s := make([]int32, slice.Len())
- for i := 0; i < slice.Len(); i++ {
- s[i] = int32(slice.Index(i).Int())
- }
- return s
-}
-
-// setInt32Slice copies []int32 into p as a new slice.
-// This behavior differs from the implementation in pointer_unsafe.go.
-func (p pointer) setInt32Slice(v []int32) {
- if p.v.Type().Elem().Elem() == reflect.TypeOf(int32(0)) {
- // raw int32 type
- p.v.Elem().Set(reflect.ValueOf(v))
- return
- }
- // an enum
- // Allocate a []enum, then assign []int32's values into it.
- // Note: we can't convert []enum to []int32.
- slice := reflect.MakeSlice(p.v.Type().Elem(), len(v), cap(v))
- for i, x := range v {
- slice.Index(i).SetInt(int64(x))
- }
- p.v.Elem().Set(slice)
-}
-func (p pointer) appendInt32Slice(v int32) {
- grow(p.v.Elem()).SetInt(int64(v))
-}
-
-func (p pointer) toUint64() *uint64 {
- return p.v.Interface().(*uint64)
-}
-func (p pointer) toUint64Ptr() **uint64 {
- return p.v.Interface().(**uint64)
-}
-func (p pointer) toUint64Slice() *[]uint64 {
- return p.v.Interface().(*[]uint64)
-}
-func (p pointer) toUint32() *uint32 {
- return p.v.Interface().(*uint32)
-}
-func (p pointer) toUint32Ptr() **uint32 {
- return p.v.Interface().(**uint32)
-}
-func (p pointer) toUint32Slice() *[]uint32 {
- return p.v.Interface().(*[]uint32)
-}
-func (p pointer) toBool() *bool {
- return p.v.Interface().(*bool)
-}
-func (p pointer) toBoolPtr() **bool {
- return p.v.Interface().(**bool)
-}
-func (p pointer) toBoolSlice() *[]bool {
- return p.v.Interface().(*[]bool)
-}
-func (p pointer) toFloat64() *float64 {
- return p.v.Interface().(*float64)
-}
-func (p pointer) toFloat64Ptr() **float64 {
- return p.v.Interface().(**float64)
-}
-func (p pointer) toFloat64Slice() *[]float64 {
- return p.v.Interface().(*[]float64)
-}
-func (p pointer) toFloat32() *float32 {
- return p.v.Interface().(*float32)
-}
-func (p pointer) toFloat32Ptr() **float32 {
- return p.v.Interface().(**float32)
-}
-func (p pointer) toFloat32Slice() *[]float32 {
- return p.v.Interface().(*[]float32)
-}
-func (p pointer) toString() *string {
- return p.v.Interface().(*string)
-}
-func (p pointer) toStringPtr() **string {
- return p.v.Interface().(**string)
-}
-func (p pointer) toStringSlice() *[]string {
- return p.v.Interface().(*[]string)
-}
-func (p pointer) toBytes() *[]byte {
- return p.v.Interface().(*[]byte)
-}
-func (p pointer) toBytesSlice() *[][]byte {
- return p.v.Interface().(*[][]byte)
-}
-func (p pointer) toExtensions() *XXX_InternalExtensions {
- return p.v.Interface().(*XXX_InternalExtensions)
-}
-func (p pointer) toOldExtensions() *map[int32]Extension {
- return p.v.Interface().(*map[int32]Extension)
-}
-func (p pointer) getPointer() pointer {
- return pointer{v: p.v.Elem()}
-}
-func (p pointer) setPointer(q pointer) {
- p.v.Elem().Set(q.v)
-}
-func (p pointer) appendPointer(q pointer) {
- grow(p.v.Elem()).Set(q.v)
-}
-
-// getPointerSlice copies []*T from p as a new []pointer.
-// This behavior differs from the implementation in pointer_unsafe.go.
-func (p pointer) getPointerSlice() []pointer {
- if p.v.IsNil() {
- return nil
- }
- n := p.v.Elem().Len()
- s := make([]pointer, n)
- for i := 0; i < n; i++ {
- s[i] = pointer{v: p.v.Elem().Index(i)}
- }
- return s
-}
-
-// setPointerSlice copies []pointer into p as a new []*T.
-// This behavior differs from the implementation in pointer_unsafe.go.
-func (p pointer) setPointerSlice(v []pointer) {
- if v == nil {
- p.v.Elem().Set(reflect.New(p.v.Elem().Type()).Elem())
- return
- }
- s := reflect.MakeSlice(p.v.Elem().Type(), 0, len(v))
- for _, p := range v {
- s = reflect.Append(s, p.v)
- }
- p.v.Elem().Set(s)
-}
-
-// getInterfacePointer returns a pointer that points to the
-// interface data of the interface pointed by p.
-func (p pointer) getInterfacePointer() pointer {
- if p.v.Elem().IsNil() {
- return pointer{v: p.v.Elem()}
- }
- return pointer{v: p.v.Elem().Elem().Elem().Field(0).Addr()} // *interface -> interface -> *struct -> struct
-}
-
-func (p pointer) asPointerTo(t reflect.Type) reflect.Value {
- // TODO: check that p.v.Type().Elem() == t?
- return p.v
-}
-
-func atomicLoadUnmarshalInfo(p **unmarshalInfo) *unmarshalInfo {
- atomicLock.Lock()
- defer atomicLock.Unlock()
- return *p
-}
-func atomicStoreUnmarshalInfo(p **unmarshalInfo, v *unmarshalInfo) {
- atomicLock.Lock()
- defer atomicLock.Unlock()
- *p = v
-}
-func atomicLoadMarshalInfo(p **marshalInfo) *marshalInfo {
- atomicLock.Lock()
- defer atomicLock.Unlock()
- return *p
-}
-func atomicStoreMarshalInfo(p **marshalInfo, v *marshalInfo) {
- atomicLock.Lock()
- defer atomicLock.Unlock()
- *p = v
-}
-func atomicLoadMergeInfo(p **mergeInfo) *mergeInfo {
- atomicLock.Lock()
- defer atomicLock.Unlock()
- return *p
-}
-func atomicStoreMergeInfo(p **mergeInfo, v *mergeInfo) {
- atomicLock.Lock()
- defer atomicLock.Unlock()
- *p = v
-}
-func atomicLoadDiscardInfo(p **discardInfo) *discardInfo {
- atomicLock.Lock()
- defer atomicLock.Unlock()
- return *p
-}
-func atomicStoreDiscardInfo(p **discardInfo, v *discardInfo) {
- atomicLock.Lock()
- defer atomicLock.Unlock()
- *p = v
-}
-
-var atomicLock sync.Mutex
diff --git a/vendor/github.com/golang/protobuf/proto/pointer_unsafe.go b/vendor/github.com/golang/protobuf/proto/pointer_unsafe.go
deleted file mode 100644
index dbfffe071b..0000000000
--- a/vendor/github.com/golang/protobuf/proto/pointer_unsafe.go
+++ /dev/null
@@ -1,313 +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 !purego,!appengine,!js
-
-// This file contains the implementation of the proto field accesses using package unsafe.
-
-package proto
-
-import (
- "reflect"
- "sync/atomic"
- "unsafe"
-)
-
-const unsafeAllowed = true
-
-// A field identifies a field in a struct, accessible from a pointer.
-// 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)
-
-// zeroField is a noop when calling pointer.offset.
-const zeroField = field(0)
-
-// IsValid reports whether the field identifier is valid.
-func (f field) IsValid() bool {
- return f != invalidField
-}
-
-// The pointer type below is for the new table-driven encoder/decoder.
-// The implementation here uses unsafe.Pointer to create a generic pointer.
-// In pointer_reflect.go we use reflect instead of unsafe to implement
-// the same (but slower) interface.
-type pointer struct {
- p unsafe.Pointer
-}
-
-// size of pointer
-var ptrSize = unsafe.Sizeof(uintptr(0))
-
-// toPointer converts an interface of pointer type to a pointer
-// that points to the same target.
-func toPointer(i *Message) pointer {
- // Super-tricky - read pointer out of data word of interface value.
- // Saves ~25ns over the equivalent:
- // return valToPointer(reflect.ValueOf(*i))
- return pointer{p: (*[2]unsafe.Pointer)(unsafe.Pointer(i))[1]}
-}
-
-// toAddrPointer converts an interface to a pointer that points to
-// the interface data.
-func toAddrPointer(i *interface{}, isptr, deref bool) (p pointer) {
- // Super-tricky - read or get the address of data word of interface value.
- if isptr {
- // The interface is of pointer type, thus it is a direct interface.
- // The data word is the pointer data itself. We take its address.
- p = pointer{p: unsafe.Pointer(uintptr(unsafe.Pointer(i)) + ptrSize)}
- } else {
- // The interface is not of pointer type. The data word is the pointer
- // to the data.
- p = pointer{p: (*[2]unsafe.Pointer)(unsafe.Pointer(i))[1]}
- }
- if deref {
- p.p = *(*unsafe.Pointer)(p.p)
- }
- return p
-}
-
-// valToPointer converts v to a pointer. v must be of pointer type.
-func valToPointer(v reflect.Value) pointer {
- return pointer{p: unsafe.Pointer(v.Pointer())}
-}
-
-// offset converts from a pointer to a structure to a pointer to
-// one of its fields.
-func (p pointer) offset(f field) pointer {
- // For safety, we should panic if !f.IsValid, however calling panic causes
- // this to no longer be inlineable, which is a serious performance cost.
- /*
- if !f.IsValid() {
- panic("invalid field")
- }
- */
- return pointer{p: unsafe.Pointer(uintptr(p.p) + uintptr(f))}
-}
-
-func (p pointer) isNil() bool {
- return p.p == nil
-}
-
-func (p pointer) toInt64() *int64 {
- return (*int64)(p.p)
-}
-func (p pointer) toInt64Ptr() **int64 {
- return (**int64)(p.p)
-}
-func (p pointer) toInt64Slice() *[]int64 {
- return (*[]int64)(p.p)
-}
-func (p pointer) toInt32() *int32 {
- return (*int32)(p.p)
-}
-
-// See pointer_reflect.go for why toInt32Ptr/Slice doesn't exist.
-/*
- func (p pointer) toInt32Ptr() **int32 {
- return (**int32)(p.p)
- }
- func (p pointer) toInt32Slice() *[]int32 {
- return (*[]int32)(p.p)
- }
-*/
-func (p pointer) getInt32Ptr() *int32 {
- return *(**int32)(p.p)
-}
-func (p pointer) setInt32Ptr(v int32) {
- *(**int32)(p.p) = &v
-}
-
-// getInt32Slice loads a []int32 from p.
-// The value returned is aliased with the original slice.
-// This behavior differs from the implementation in pointer_reflect.go.
-func (p pointer) getInt32Slice() []int32 {
- return *(*[]int32)(p.p)
-}
-
-// setInt32Slice stores a []int32 to p.
-// The value set is aliased with the input slice.
-// This behavior differs from the implementation in pointer_reflect.go.
-func (p pointer) setInt32Slice(v []int32) {
- *(*[]int32)(p.p) = v
-}
-
-// TODO: Can we get rid of appendInt32Slice and use setInt32Slice instead?
-func (p pointer) appendInt32Slice(v int32) {
- s := (*[]int32)(p.p)
- *s = append(*s, v)
-}
-
-func (p pointer) toUint64() *uint64 {
- return (*uint64)(p.p)
-}
-func (p pointer) toUint64Ptr() **uint64 {
- return (**uint64)(p.p)
-}
-func (p pointer) toUint64Slice() *[]uint64 {
- return (*[]uint64)(p.p)
-}
-func (p pointer) toUint32() *uint32 {
- return (*uint32)(p.p)
-}
-func (p pointer) toUint32Ptr() **uint32 {
- return (**uint32)(p.p)
-}
-func (p pointer) toUint32Slice() *[]uint32 {
- return (*[]uint32)(p.p)
-}
-func (p pointer) toBool() *bool {
- return (*bool)(p.p)
-}
-func (p pointer) toBoolPtr() **bool {
- return (**bool)(p.p)
-}
-func (p pointer) toBoolSlice() *[]bool {
- return (*[]bool)(p.p)
-}
-func (p pointer) toFloat64() *float64 {
- return (*float64)(p.p)
-}
-func (p pointer) toFloat64Ptr() **float64 {
- return (**float64)(p.p)
-}
-func (p pointer) toFloat64Slice() *[]float64 {
- return (*[]float64)(p.p)
-}
-func (p pointer) toFloat32() *float32 {
- return (*float32)(p.p)
-}
-func (p pointer) toFloat32Ptr() **float32 {
- return (**float32)(p.p)
-}
-func (p pointer) toFloat32Slice() *[]float32 {
- return (*[]float32)(p.p)
-}
-func (p pointer) toString() *string {
- return (*string)(p.p)
-}
-func (p pointer) toStringPtr() **string {
- return (**string)(p.p)
-}
-func (p pointer) toStringSlice() *[]string {
- return (*[]string)(p.p)
-}
-func (p pointer) toBytes() *[]byte {
- return (*[]byte)(p.p)
-}
-func (p pointer) toBytesSlice() *[][]byte {
- return (*[][]byte)(p.p)
-}
-func (p pointer) toExtensions() *XXX_InternalExtensions {
- return (*XXX_InternalExtensions)(p.p)
-}
-func (p pointer) toOldExtensions() *map[int32]Extension {
- return (*map[int32]Extension)(p.p)
-}
-
-// getPointerSlice loads []*T from p as a []pointer.
-// The value returned is aliased with the original slice.
-// This behavior differs from the implementation in pointer_reflect.go.
-func (p pointer) getPointerSlice() []pointer {
- // Super-tricky - p should point to a []*T where T is a
- // message type. We load it as []pointer.
- return *(*[]pointer)(p.p)
-}
-
-// setPointerSlice stores []pointer into p as a []*T.
-// The value set is aliased with the input slice.
-// This behavior differs from the implementation in pointer_reflect.go.
-func (p pointer) setPointerSlice(v []pointer) {
- // Super-tricky - p should point to a []*T where T is a
- // message type. We store it as []pointer.
- *(*[]pointer)(p.p) = v
-}
-
-// getPointer loads the pointer at p and returns it.
-func (p pointer) getPointer() pointer {
- return pointer{p: *(*unsafe.Pointer)(p.p)}
-}
-
-// setPointer stores the pointer q at p.
-func (p pointer) setPointer(q pointer) {
- *(*unsafe.Pointer)(p.p) = q.p
-}
-
-// append q to the slice pointed to by p.
-func (p pointer) appendPointer(q pointer) {
- s := (*[]unsafe.Pointer)(p.p)
- *s = append(*s, q.p)
-}
-
-// getInterfacePointer returns a pointer that points to the
-// interface data of the interface pointed by p.
-func (p pointer) getInterfacePointer() pointer {
- // Super-tricky - read pointer out of data word of interface value.
- return pointer{p: (*(*[2]unsafe.Pointer)(p.p))[1]}
-}
-
-// asPointerTo returns a reflect.Value that is a pointer to an
-// object of type t stored at p.
-func (p pointer) asPointerTo(t reflect.Type) reflect.Value {
- return reflect.NewAt(t, p.p)
-}
-
-func atomicLoadUnmarshalInfo(p **unmarshalInfo) *unmarshalInfo {
- return (*unmarshalInfo)(atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(p))))
-}
-func atomicStoreUnmarshalInfo(p **unmarshalInfo, v *unmarshalInfo) {
- atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(p)), unsafe.Pointer(v))
-}
-func atomicLoadMarshalInfo(p **marshalInfo) *marshalInfo {
- return (*marshalInfo)(atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(p))))
-}
-func atomicStoreMarshalInfo(p **marshalInfo, v *marshalInfo) {
- atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(p)), unsafe.Pointer(v))
-}
-func atomicLoadMergeInfo(p **mergeInfo) *mergeInfo {
- return (*mergeInfo)(atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(p))))
-}
-func atomicStoreMergeInfo(p **mergeInfo, v *mergeInfo) {
- atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(p)), unsafe.Pointer(v))
-}
-func atomicLoadDiscardInfo(p **discardInfo) *discardInfo {
- return (*discardInfo)(atomic.LoadPointer((*unsafe.Pointer)(unsafe.Pointer(p))))
-}
-func atomicStoreDiscardInfo(p **discardInfo, v *discardInfo) {
- atomic.StorePointer((*unsafe.Pointer)(unsafe.Pointer(p)), unsafe.Pointer(v))
-}
diff --git a/vendor/github.com/golang/protobuf/proto/properties.go b/vendor/github.com/golang/protobuf/proto/properties.go
deleted file mode 100644
index a4b8c0cd3a..0000000000
--- a/vendor/github.com/golang/protobuf/proto/properties.go
+++ /dev/null
@@ -1,544 +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"
- "log"
- "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
-)
-
-// 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
-
- // OneofTypes contains information about the oneof fields in this message.
- // It is keyed by the original name of a field.
- OneofTypes map[string]*OneofProperties
-}
-
-// OneofProperties represents information about a specific field in a oneof.
-type OneofProperties struct {
- Type reflect.Type // pointer to generated struct type for this oneof field
- Field int // struct field number of the containing oneof in the message
- Prop *Properties
-}
-
-// Implement the sorting interface so we can sort the fields in tag order, as recommended by the spec.
-// See encode.go, (*Buffer).enc_struct.
-
-func (sp *StructProperties) Len() int { return len(sp.order) }
-func (sp *StructProperties) Less(i, j int) bool {
- return sp.Prop[sp.order[i]].Tag < sp.Prop[sp.order[j]].Tag
-}
-func (sp *StructProperties) Swap(i, j int) { sp.order[i], sp.order[j] = sp.order[j], sp.order[i] }
-
-// Properties represents the protocol-specific behavior of a single struct field.
-type Properties struct {
- Name string // name of the field, for error messages
- OrigName string // original name before protocol compiler (always set)
- JSONName string // name to use for JSON; determined by protoc
- Wire string
- WireType int
- Tag int
- Required bool
- Optional bool
- Repeated bool
- Packed bool // relevant for repeated primitives only
- Enum string // set for enum types only
- proto3 bool // whether this is known to be a proto3 field
- oneof bool // whether this is a oneof field
-
- Default string // default value
- HasDefault bool // whether an explicit default was provided
-
- stype reflect.Type // set for struct types only
- sprop *StructProperties // set for struct types only
-
- mtype reflect.Type // set for map types only
- MapKeyProp *Properties // set for map types only
- MapValProp *Properties // set for map types only
-}
-
-// String formats the properties in the protobuf struct field tag style.
-func (p *Properties) String() string {
- s := p.Wire
- s += ","
- s += strconv.Itoa(p.Tag)
- if p.Required {
- s += ",req"
- }
- if p.Optional {
- s += ",opt"
- }
- if p.Repeated {
- s += ",rep"
- }
- if p.Packed {
- s += ",packed"
- }
- s += ",name=" + p.OrigName
- if p.JSONName != p.OrigName {
- s += ",json=" + p.JSONName
- }
- if p.proto3 {
- s += ",proto3"
- }
- if p.oneof {
- s += ",oneof"
- }
- if len(p.Enum) > 0 {
- s += ",enum=" + p.Enum
- }
- if p.HasDefault {
- s += ",def=" + p.Default
- }
- return s
-}
-
-// Parse populates p by parsing a string in the protobuf struct field tag style.
-func (p *Properties) Parse(s string) {
- // "bytes,49,opt,name=foo,def=hello!"
- fields := strings.Split(s, ",") // breaks def=, but handled below.
- if len(fields) < 2 {
- log.Printf("proto: tag has too few fields: %q", s)
- return
- }
-
- p.Wire = fields[0]
- switch p.Wire {
- case "varint":
- p.WireType = WireVarint
- case "fixed32":
- p.WireType = WireFixed32
- case "fixed64":
- p.WireType = WireFixed64
- case "zigzag32":
- p.WireType = WireVarint
- case "zigzag64":
- p.WireType = WireVarint
- case "bytes", "group":
- p.WireType = WireBytes
- // no numeric converter for non-numeric types
- default:
- log.Printf("proto: tag has unknown wire type: %q", s)
- return
- }
-
- var err error
- p.Tag, err = strconv.Atoi(fields[1])
- if err != nil {
- return
- }
-
-outer:
- for i := 2; i < len(fields); i++ {
- f := fields[i]
- switch {
- case f == "req":
- p.Required = true
- case f == "opt":
- p.Optional = true
- case f == "rep":
- p.Repeated = true
- case f == "packed":
- p.Packed = true
- case strings.HasPrefix(f, "name="):
- p.OrigName = f[5:]
- case strings.HasPrefix(f, "json="):
- p.JSONName = f[5:]
- case strings.HasPrefix(f, "enum="):
- p.Enum = f[5:]
- case f == "proto3":
- p.proto3 = true
- case f == "oneof":
- p.oneof = true
- case strings.HasPrefix(f, "def="):
- p.HasDefault = true
- p.Default = f[4:] // rest of string
- if i+1 < len(fields) {
- // Commas aren't escaped, and def is always last.
- p.Default += "," + strings.Join(fields[i+1:], ",")
- break outer
- }
- }
- }
-}
-
-var protoMessageType = reflect.TypeOf((*Message)(nil)).Elem()
-
-// setFieldProps initializes the field properties for submessages and maps.
-func (p *Properties) setFieldProps(typ reflect.Type, f *reflect.StructField, lockGetProp bool) {
- switch t1 := typ; t1.Kind() {
- case reflect.Ptr:
- if t1.Elem().Kind() == reflect.Struct {
- p.stype = t1.Elem()
- }
-
- case reflect.Slice:
- if t2 := t1.Elem(); t2.Kind() == reflect.Ptr && t2.Elem().Kind() == reflect.Struct {
- p.stype = t2.Elem()
- }
-
- case reflect.Map:
- p.mtype = t1
- p.MapKeyProp = &Properties{}
- p.MapKeyProp.init(reflect.PtrTo(p.mtype.Key()), "Key", f.Tag.Get("protobuf_key"), nil, lockGetProp)
- p.MapValProp = &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.MapValProp.init(vtype, "Value", f.Tag.Get("protobuf_val"), nil, lockGetProp)
- }
-
- if p.stype != nil {
- if lockGetProp {
- p.sprop = GetProperties(p.stype)
- } else {
- p.sprop = getPropertiesLocked(p.stype)
- }
- }
-}
-
-var (
- marshalerType = reflect.TypeOf((*Marshaler)(nil)).Elem()
-)
-
-// 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 tag == "" {
- return
- }
- p.Parse(tag)
- p.setFieldProps(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 {
- return sprop
- }
-
- propertiesMu.Lock()
- sprop = getPropertiesLocked(t)
- propertiesMu.Unlock()
- return sprop
-}
-
-type (
- oneofFuncsIface interface {
- XXX_OneofFuncs() (func(Message, *Buffer) error, func(Message, int, int, *Buffer) (bool, error), func(Message) int, []interface{})
- }
- oneofWrappersIface interface {
- XXX_OneofWrappers() []interface{}
- }
-)
-
-// getPropertiesLocked requires that propertiesMu is held.
-func getPropertiesLocked(t reflect.Type) *StructProperties {
- if prop, ok := propertiesMap[t]; ok {
- return prop
- }
-
- prop := new(StructProperties)
- // in case of recursive protos, fill this in now.
- propertiesMap[t] = prop
-
- // build properties
- 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)
-
- oneof := f.Tag.Get("protobuf_oneof") // special case
- if oneof != "" {
- // Oneof fields don't use the traditional protobuf tag.
- p.OrigName = oneof
- }
- prop.Prop[i] = p
- prop.order[i] = i
- if debug {
- print(i, " ", f.Name, " ", t.String(), " ")
- if p.Tag > 0 {
- print(p.String())
- }
- print("\n")
- }
- }
-
- // Re-order prop.order.
- sort.Sort(prop)
-
- var oots []interface{}
- switch m := reflect.Zero(reflect.PtrTo(t)).Interface().(type) {
- case oneofFuncsIface:
- _, _, _, oots = m.XXX_OneofFuncs()
- case oneofWrappersIface:
- oots = m.XXX_OneofWrappers()
- }
- if len(oots) > 0 {
- // Interpret oneof metadata.
- prop.OneofTypes = make(map[string]*OneofProperties)
- for _, oot := range oots {
- oop := &OneofProperties{
- Type: reflect.ValueOf(oot).Type(), // *T
- Prop: new(Properties),
- }
- sft := oop.Type.Elem().Field(0)
- oop.Prop.Name = sft.Name
- oop.Prop.Parse(sft.Tag.Get("protobuf"))
- // There will be exactly one interface field that
- // this new value is assignable to.
- for i := 0; i < t.NumField(); i++ {
- f := t.Field(i)
- if f.Type.Kind() != reflect.Interface {
- continue
- }
- if !oop.Type.AssignableTo(f.Type) {
- continue
- }
- oop.Field = i
- break
- }
- prop.OneofTypes[oop.Prop.OrigName] = oop
- }
- }
-
- // build required counts
- // build tags
- reqCount := 0
- prop.decoderOrigNames = make(map[string]int)
- for i, p := range prop.Prop {
- if strings.HasPrefix(p.Name, "XXX_") {
- // Internal fields should not appear in tags/origNames maps.
- // They are handled specially when encoding and decoding.
- continue
- }
- if p.Required {
- reqCount++
- }
- prop.decoderTags.put(p.Tag, i)
- prop.decoderOrigNames[p.OrigName] = i
- }
- prop.reqCount = reqCount
-
- return prop
-}
-
-// A global registry of enum types.
-// The generated code will register the generated maps by calling RegisterEnum.
-
-var enumValueMaps = make(map[string]map[string]int32)
-
-// RegisterEnum is called from the generated code to install the enum descriptor
-// maps into the global table to aid parsing text format protocol buffers.
-func RegisterEnum(typeName string, unusedNameMap map[int32]string, valueMap map[string]int32) {
- if _, ok := enumValueMaps[typeName]; ok {
- panic("proto: duplicate enum registered: " + typeName)
- }
- enumValueMaps[typeName] = valueMap
-}
-
-// EnumValueMap returns the mapping from names to integers of the
-// enum type enumType, or a nil if not found.
-func EnumValueMap(enumType string) map[string]int32 {
- return enumValueMaps[enumType]
-}
-
-// A registry of all linked message types.
-// The string is a fully-qualified proto name ("pkg.Message").
-var (
- protoTypedNils = make(map[string]Message) // a map from proto names to typed nil pointers
- protoMapTypes = make(map[string]reflect.Type) // a map from proto names to map types
- revProtoTypes = make(map[reflect.Type]string)
-)
-
-// RegisterType is called from generated code and maps from the fully qualified
-// proto name to the type (pointer to struct) of the protocol buffer.
-func RegisterType(x Message, name string) {
- if _, ok := protoTypedNils[name]; ok {
- // TODO: Some day, make this a panic.
- log.Printf("proto: duplicate proto type registered: %s", name)
- return
- }
- t := reflect.TypeOf(x)
- if v := reflect.ValueOf(x); v.Kind() == reflect.Ptr && v.Pointer() == 0 {
- // Generated code always calls RegisterType with nil x.
- // This check is just for extra safety.
- protoTypedNils[name] = x
- } else {
- protoTypedNils[name] = reflect.Zero(t).Interface().(Message)
- }
- revProtoTypes[t] = name
-}
-
-// RegisterMapType is called from generated code and maps from the fully qualified
-// proto name to the native map type of the proto map definition.
-func RegisterMapType(x interface{}, name string) {
- if reflect.TypeOf(x).Kind() != reflect.Map {
- panic(fmt.Sprintf("RegisterMapType(%T, %q); want map", x, name))
- }
- if _, ok := protoMapTypes[name]; ok {
- log.Printf("proto: duplicate proto type registered: %s", name)
- return
- }
- t := reflect.TypeOf(x)
- protoMapTypes[name] = t
- revProtoTypes[t] = name
-}
-
-// MessageName returns the fully-qualified proto name for the given message type.
-func MessageName(x Message) string {
- type xname interface {
- XXX_MessageName() string
- }
- if m, ok := x.(xname); ok {
- return m.XXX_MessageName()
- }
- return revProtoTypes[reflect.TypeOf(x)]
-}
-
-// MessageType returns the message type (pointer to struct) for a named message.
-// The type is not guaranteed to implement proto.Message if the name refers to a
-// map entry.
-func MessageType(name string) reflect.Type {
- if t, ok := protoTypedNils[name]; ok {
- return reflect.TypeOf(t)
- }
- return protoMapTypes[name]
-}
-
-// A registry of all linked proto files.
-var (
- protoFiles = make(map[string][]byte) // file name => fileDescriptor
-)
-
-// RegisterFile is called from generated code and maps from the
-// full file name of a .proto file to its compressed FileDescriptorProto.
-func RegisterFile(filename string, fileDescriptor []byte) {
- protoFiles[filename] = fileDescriptor
-}
-
-// FileDescriptor returns the compressed FileDescriptorProto for a .proto file.
-func FileDescriptor(filename string) []byte { return protoFiles[filename] }
diff --git a/vendor/github.com/golang/protobuf/proto/table_marshal.go b/vendor/github.com/golang/protobuf/proto/table_marshal.go
deleted file mode 100644
index 5cb11fa955..0000000000
--- a/vendor/github.com/golang/protobuf/proto/table_marshal.go
+++ /dev/null
@@ -1,2776 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2016 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 (
- "errors"
- "fmt"
- "math"
- "reflect"
- "sort"
- "strconv"
- "strings"
- "sync"
- "sync/atomic"
- "unicode/utf8"
-)
-
-// a sizer takes a pointer to a field and the size of its tag, computes the size of
-// the encoded data.
-type sizer func(pointer, int) int
-
-// a marshaler takes a byte slice, a pointer to a field, and its tag (in wire format),
-// marshals the field to the end of the slice, returns the slice and error (if any).
-type marshaler func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error)
-
-// marshalInfo is the information used for marshaling a message.
-type marshalInfo struct {
- typ reflect.Type
- fields []*marshalFieldInfo
- unrecognized field // offset of XXX_unrecognized
- extensions field // offset of XXX_InternalExtensions
- v1extensions field // offset of XXX_extensions
- sizecache field // offset of XXX_sizecache
- initialized int32 // 0 -- only typ is set, 1 -- fully initialized
- messageset bool // uses message set wire format
- hasmarshaler bool // has custom marshaler
- sync.RWMutex // protect extElems map, also for initialization
- extElems map[int32]*marshalElemInfo // info of extension elements
-}
-
-// marshalFieldInfo is the information used for marshaling a field of a message.
-type marshalFieldInfo struct {
- field field
- wiretag uint64 // tag in wire format
- tagsize int // size of tag in wire format
- sizer sizer
- marshaler marshaler
- isPointer bool
- required bool // field is required
- name string // name of the field, for error reporting
- oneofElems map[reflect.Type]*marshalElemInfo // info of oneof elements
-}
-
-// marshalElemInfo is the information used for marshaling an extension or oneof element.
-type marshalElemInfo struct {
- wiretag uint64 // tag in wire format
- tagsize int // size of tag in wire format
- sizer sizer
- marshaler marshaler
- isptr bool // elem is pointer typed, thus interface of this type is a direct interface (extension only)
- deref bool // dereference the pointer before operating on it; implies isptr
-}
-
-var (
- marshalInfoMap = map[reflect.Type]*marshalInfo{}
- marshalInfoLock sync.Mutex
-)
-
-// getMarshalInfo returns the information to marshal a given type of message.
-// The info it returns may not necessarily initialized.
-// t is the type of the message (NOT the pointer to it).
-func getMarshalInfo(t reflect.Type) *marshalInfo {
- marshalInfoLock.Lock()
- u, ok := marshalInfoMap[t]
- if !ok {
- u = &marshalInfo{typ: t}
- marshalInfoMap[t] = u
- }
- marshalInfoLock.Unlock()
- return u
-}
-
-// Size is the entry point from generated code,
-// and should be ONLY called by generated code.
-// It computes the size of encoded data of msg.
-// a is a pointer to a place to store cached marshal info.
-func (a *InternalMessageInfo) Size(msg Message) int {
- u := getMessageMarshalInfo(msg, a)
- ptr := toPointer(&msg)
- if ptr.isNil() {
- // We get here if msg is a typed nil ((*SomeMessage)(nil)),
- // so it satisfies the interface, and msg == nil wouldn't
- // catch it. We don't want crash in this case.
- return 0
- }
- return u.size(ptr)
-}
-
-// Marshal is the entry point from generated code,
-// and should be ONLY called by generated code.
-// It marshals msg to the end of b.
-// a is a pointer to a place to store cached marshal info.
-func (a *InternalMessageInfo) Marshal(b []byte, msg Message, deterministic bool) ([]byte, error) {
- u := getMessageMarshalInfo(msg, a)
- ptr := toPointer(&msg)
- if ptr.isNil() {
- // We get here if msg is a typed nil ((*SomeMessage)(nil)),
- // so it satisfies the interface, and msg == nil wouldn't
- // catch it. We don't want crash in this case.
- return b, ErrNil
- }
- return u.marshal(b, ptr, deterministic)
-}
-
-func getMessageMarshalInfo(msg interface{}, a *InternalMessageInfo) *marshalInfo {
- // u := a.marshal, but atomically.
- // We use an atomic here to ensure memory consistency.
- u := atomicLoadMarshalInfo(&a.marshal)
- if u == nil {
- // Get marshal information from type of message.
- t := reflect.ValueOf(msg).Type()
- if t.Kind() != reflect.Ptr {
- panic(fmt.Sprintf("cannot handle non-pointer message type %v", t))
- }
- u = getMarshalInfo(t.Elem())
- // Store it in the cache for later users.
- // a.marshal = u, but atomically.
- atomicStoreMarshalInfo(&a.marshal, u)
- }
- return u
-}
-
-// size is the main function to compute the size of the encoded data of a message.
-// ptr is the pointer to the message.
-func (u *marshalInfo) size(ptr pointer) int {
- if atomic.LoadInt32(&u.initialized) == 0 {
- u.computeMarshalInfo()
- }
-
- // If the message can marshal itself, let it do it, for compatibility.
- // NOTE: This is not efficient.
- if u.hasmarshaler {
- m := ptr.asPointerTo(u.typ).Interface().(Marshaler)
- b, _ := m.Marshal()
- return len(b)
- }
-
- n := 0
- for _, f := range u.fields {
- if f.isPointer && ptr.offset(f.field).getPointer().isNil() {
- // nil pointer always marshals to nothing
- continue
- }
- n += f.sizer(ptr.offset(f.field), f.tagsize)
- }
- if u.extensions.IsValid() {
- e := ptr.offset(u.extensions).toExtensions()
- if u.messageset {
- n += u.sizeMessageSet(e)
- } else {
- n += u.sizeExtensions(e)
- }
- }
- if u.v1extensions.IsValid() {
- m := *ptr.offset(u.v1extensions).toOldExtensions()
- n += u.sizeV1Extensions(m)
- }
- if u.unrecognized.IsValid() {
- s := *ptr.offset(u.unrecognized).toBytes()
- n += len(s)
- }
- // cache the result for use in marshal
- if u.sizecache.IsValid() {
- atomic.StoreInt32(ptr.offset(u.sizecache).toInt32(), int32(n))
- }
- return n
-}
-
-// cachedsize gets the size from cache. If there is no cache (i.e. message is not generated),
-// fall back to compute the size.
-func (u *marshalInfo) cachedsize(ptr pointer) int {
- if u.sizecache.IsValid() {
- return int(atomic.LoadInt32(ptr.offset(u.sizecache).toInt32()))
- }
- return u.size(ptr)
-}
-
-// marshal is the main function to marshal a message. It takes a byte slice and appends
-// the encoded data to the end of the slice, returns the slice and error (if any).
-// ptr is the pointer to the message.
-// If deterministic is true, map is marshaled in deterministic order.
-func (u *marshalInfo) marshal(b []byte, ptr pointer, deterministic bool) ([]byte, error) {
- if atomic.LoadInt32(&u.initialized) == 0 {
- u.computeMarshalInfo()
- }
-
- // If the message can marshal itself, let it do it, for compatibility.
- // NOTE: This is not efficient.
- if u.hasmarshaler {
- m := ptr.asPointerTo(u.typ).Interface().(Marshaler)
- b1, err := m.Marshal()
- b = append(b, b1...)
- return b, err
- }
-
- var err, errLater error
- // The old marshaler encodes extensions at beginning.
- if u.extensions.IsValid() {
- e := ptr.offset(u.extensions).toExtensions()
- if u.messageset {
- b, err = u.appendMessageSet(b, e, deterministic)
- } else {
- b, err = u.appendExtensions(b, e, deterministic)
- }
- if err != nil {
- return b, err
- }
- }
- if u.v1extensions.IsValid() {
- m := *ptr.offset(u.v1extensions).toOldExtensions()
- b, err = u.appendV1Extensions(b, m, deterministic)
- if err != nil {
- return b, err
- }
- }
- for _, f := range u.fields {
- if f.required {
- if ptr.offset(f.field).getPointer().isNil() {
- // Required field is not set.
- // We record the error but keep going, to give a complete marshaling.
- if errLater == nil {
- errLater = &RequiredNotSetError{f.name}
- }
- continue
- }
- }
- if f.isPointer && ptr.offset(f.field).getPointer().isNil() {
- // nil pointer always marshals to nothing
- continue
- }
- b, err = f.marshaler(b, ptr.offset(f.field), f.wiretag, deterministic)
- if err != nil {
- if err1, ok := err.(*RequiredNotSetError); ok {
- // Required field in submessage is not set.
- // We record the error but keep going, to give a complete marshaling.
- if errLater == nil {
- errLater = &RequiredNotSetError{f.name + "." + err1.field}
- }
- continue
- }
- if err == errRepeatedHasNil {
- err = errors.New("proto: repeated field " + f.name + " has nil element")
- }
- if err == errInvalidUTF8 {
- if errLater == nil {
- fullName := revProtoTypes[reflect.PtrTo(u.typ)] + "." + f.name
- errLater = &invalidUTF8Error{fullName}
- }
- continue
- }
- return b, err
- }
- }
- if u.unrecognized.IsValid() {
- s := *ptr.offset(u.unrecognized).toBytes()
- b = append(b, s...)
- }
- return b, errLater
-}
-
-// computeMarshalInfo initializes the marshal info.
-func (u *marshalInfo) computeMarshalInfo() {
- u.Lock()
- defer u.Unlock()
- if u.initialized != 0 { // non-atomic read is ok as it is protected by the lock
- return
- }
-
- t := u.typ
- u.unrecognized = invalidField
- u.extensions = invalidField
- u.v1extensions = invalidField
- u.sizecache = invalidField
-
- // If the message can marshal itself, let it do it, for compatibility.
- // NOTE: This is not efficient.
- if reflect.PtrTo(t).Implements(marshalerType) {
- u.hasmarshaler = true
- atomic.StoreInt32(&u.initialized, 1)
- return
- }
-
- // get oneof implementers
- var oneofImplementers []interface{}
- switch m := reflect.Zero(reflect.PtrTo(t)).Interface().(type) {
- case oneofFuncsIface:
- _, _, _, oneofImplementers = m.XXX_OneofFuncs()
- case oneofWrappersIface:
- oneofImplementers = m.XXX_OneofWrappers()
- }
-
- n := t.NumField()
-
- // deal with XXX fields first
- for i := 0; i < t.NumField(); i++ {
- f := t.Field(i)
- if !strings.HasPrefix(f.Name, "XXX_") {
- continue
- }
- switch f.Name {
- case "XXX_sizecache":
- u.sizecache = toField(&f)
- case "XXX_unrecognized":
- u.unrecognized = toField(&f)
- case "XXX_InternalExtensions":
- u.extensions = toField(&f)
- u.messageset = f.Tag.Get("protobuf_messageset") == "1"
- case "XXX_extensions":
- u.v1extensions = toField(&f)
- case "XXX_NoUnkeyedLiteral":
- // nothing to do
- default:
- panic("unknown XXX field: " + f.Name)
- }
- n--
- }
-
- // normal fields
- fields := make([]marshalFieldInfo, n) // batch allocation
- u.fields = make([]*marshalFieldInfo, 0, n)
- for i, j := 0, 0; i < t.NumField(); i++ {
- f := t.Field(i)
-
- if strings.HasPrefix(f.Name, "XXX_") {
- continue
- }
- field := &fields[j]
- j++
- field.name = f.Name
- u.fields = append(u.fields, field)
- if f.Tag.Get("protobuf_oneof") != "" {
- field.computeOneofFieldInfo(&f, oneofImplementers)
- continue
- }
- if f.Tag.Get("protobuf") == "" {
- // field has no tag (not in generated message), ignore it
- u.fields = u.fields[:len(u.fields)-1]
- j--
- continue
- }
- field.computeMarshalFieldInfo(&f)
- }
-
- // fields are marshaled in tag order on the wire.
- sort.Sort(byTag(u.fields))
-
- atomic.StoreInt32(&u.initialized, 1)
-}
-
-// helper for sorting fields by tag
-type byTag []*marshalFieldInfo
-
-func (a byTag) Len() int { return len(a) }
-func (a byTag) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
-func (a byTag) Less(i, j int) bool { return a[i].wiretag < a[j].wiretag }
-
-// getExtElemInfo returns the information to marshal an extension element.
-// The info it returns is initialized.
-func (u *marshalInfo) getExtElemInfo(desc *ExtensionDesc) *marshalElemInfo {
- // get from cache first
- u.RLock()
- e, ok := u.extElems[desc.Field]
- u.RUnlock()
- if ok {
- return e
- }
-
- t := reflect.TypeOf(desc.ExtensionType) // pointer or slice to basic type or struct
- tags := strings.Split(desc.Tag, ",")
- tag, err := strconv.Atoi(tags[1])
- if err != nil {
- panic("tag is not an integer")
- }
- wt := wiretype(tags[0])
- if t.Kind() == reflect.Ptr && t.Elem().Kind() != reflect.Struct {
- t = t.Elem()
- }
- sizer, marshaler := typeMarshaler(t, tags, false, false)
- var deref bool
- if t.Kind() == reflect.Slice && t.Elem().Kind() != reflect.Uint8 {
- t = reflect.PtrTo(t)
- deref = true
- }
- e = &marshalElemInfo{
- wiretag: uint64(tag)<<3 | wt,
- tagsize: SizeVarint(uint64(tag) << 3),
- sizer: sizer,
- marshaler: marshaler,
- isptr: t.Kind() == reflect.Ptr,
- deref: deref,
- }
-
- // update cache
- u.Lock()
- if u.extElems == nil {
- u.extElems = make(map[int32]*marshalElemInfo)
- }
- u.extElems[desc.Field] = e
- u.Unlock()
- return e
-}
-
-// computeMarshalFieldInfo fills up the information to marshal a field.
-func (fi *marshalFieldInfo) computeMarshalFieldInfo(f *reflect.StructField) {
- // parse protobuf tag of the field.
- // tag has format of "bytes,49,opt,name=foo,def=hello!"
- tags := strings.Split(f.Tag.Get("protobuf"), ",")
- if tags[0] == "" {
- return
- }
- tag, err := strconv.Atoi(tags[1])
- if err != nil {
- panic("tag is not an integer")
- }
- wt := wiretype(tags[0])
- if tags[2] == "req" {
- fi.required = true
- }
- fi.setTag(f, tag, wt)
- fi.setMarshaler(f, tags)
-}
-
-func (fi *marshalFieldInfo) computeOneofFieldInfo(f *reflect.StructField, oneofImplementers []interface{}) {
- fi.field = toField(f)
- fi.wiretag = math.MaxInt32 // Use a large tag number, make oneofs sorted at the end. This tag will not appear on the wire.
- fi.isPointer = true
- fi.sizer, fi.marshaler = makeOneOfMarshaler(fi, f)
- fi.oneofElems = make(map[reflect.Type]*marshalElemInfo)
-
- ityp := f.Type // interface type
- for _, o := range oneofImplementers {
- t := reflect.TypeOf(o)
- if !t.Implements(ityp) {
- continue
- }
- sf := t.Elem().Field(0) // oneof implementer is a struct with a single field
- tags := strings.Split(sf.Tag.Get("protobuf"), ",")
- tag, err := strconv.Atoi(tags[1])
- if err != nil {
- panic("tag is not an integer")
- }
- wt := wiretype(tags[0])
- sizer, marshaler := typeMarshaler(sf.Type, tags, false, true) // oneof should not omit any zero value
- fi.oneofElems[t.Elem()] = &marshalElemInfo{
- wiretag: uint64(tag)<<3 | wt,
- tagsize: SizeVarint(uint64(tag) << 3),
- sizer: sizer,
- marshaler: marshaler,
- }
- }
-}
-
-// wiretype returns the wire encoding of the type.
-func wiretype(encoding string) uint64 {
- switch encoding {
- case "fixed32":
- return WireFixed32
- case "fixed64":
- return WireFixed64
- case "varint", "zigzag32", "zigzag64":
- return WireVarint
- case "bytes":
- return WireBytes
- case "group":
- return WireStartGroup
- }
- panic("unknown wire type " + encoding)
-}
-
-// setTag fills up the tag (in wire format) and its size in the info of a field.
-func (fi *marshalFieldInfo) setTag(f *reflect.StructField, tag int, wt uint64) {
- fi.field = toField(f)
- fi.wiretag = uint64(tag)<<3 | wt
- fi.tagsize = SizeVarint(uint64(tag) << 3)
-}
-
-// setMarshaler fills up the sizer and marshaler in the info of a field.
-func (fi *marshalFieldInfo) setMarshaler(f *reflect.StructField, tags []string) {
- switch f.Type.Kind() {
- case reflect.Map:
- // map field
- fi.isPointer = true
- fi.sizer, fi.marshaler = makeMapMarshaler(f)
- return
- case reflect.Ptr, reflect.Slice:
- fi.isPointer = true
- }
- fi.sizer, fi.marshaler = typeMarshaler(f.Type, tags, true, false)
-}
-
-// typeMarshaler returns the sizer and marshaler of a given field.
-// t is the type of the field.
-// tags is the generated "protobuf" tag of the field.
-// If nozero is true, zero value is not marshaled to the wire.
-// If oneof is true, it is a oneof field.
-func typeMarshaler(t reflect.Type, tags []string, nozero, oneof bool) (sizer, marshaler) {
- encoding := tags[0]
-
- pointer := false
- slice := false
- if t.Kind() == reflect.Slice && t.Elem().Kind() != reflect.Uint8 {
- slice = true
- t = t.Elem()
- }
- if t.Kind() == reflect.Ptr {
- pointer = true
- t = t.Elem()
- }
-
- packed := false
- proto3 := false
- validateUTF8 := true
- for i := 2; i < len(tags); i++ {
- if tags[i] == "packed" {
- packed = true
- }
- if tags[i] == "proto3" {
- proto3 = true
- }
- }
- validateUTF8 = validateUTF8 && proto3
-
- switch t.Kind() {
- case reflect.Bool:
- if pointer {
- return sizeBoolPtr, appendBoolPtr
- }
- if slice {
- if packed {
- return sizeBoolPackedSlice, appendBoolPackedSlice
- }
- return sizeBoolSlice, appendBoolSlice
- }
- if nozero {
- return sizeBoolValueNoZero, appendBoolValueNoZero
- }
- return sizeBoolValue, appendBoolValue
- case reflect.Uint32:
- switch encoding {
- case "fixed32":
- if pointer {
- return sizeFixed32Ptr, appendFixed32Ptr
- }
- if slice {
- if packed {
- return sizeFixed32PackedSlice, appendFixed32PackedSlice
- }
- return sizeFixed32Slice, appendFixed32Slice
- }
- if nozero {
- return sizeFixed32ValueNoZero, appendFixed32ValueNoZero
- }
- return sizeFixed32Value, appendFixed32Value
- case "varint":
- if pointer {
- return sizeVarint32Ptr, appendVarint32Ptr
- }
- if slice {
- if packed {
- return sizeVarint32PackedSlice, appendVarint32PackedSlice
- }
- return sizeVarint32Slice, appendVarint32Slice
- }
- if nozero {
- return sizeVarint32ValueNoZero, appendVarint32ValueNoZero
- }
- return sizeVarint32Value, appendVarint32Value
- }
- case reflect.Int32:
- switch encoding {
- case "fixed32":
- if pointer {
- return sizeFixedS32Ptr, appendFixedS32Ptr
- }
- if slice {
- if packed {
- return sizeFixedS32PackedSlice, appendFixedS32PackedSlice
- }
- return sizeFixedS32Slice, appendFixedS32Slice
- }
- if nozero {
- return sizeFixedS32ValueNoZero, appendFixedS32ValueNoZero
- }
- return sizeFixedS32Value, appendFixedS32Value
- case "varint":
- if pointer {
- return sizeVarintS32Ptr, appendVarintS32Ptr
- }
- if slice {
- if packed {
- return sizeVarintS32PackedSlice, appendVarintS32PackedSlice
- }
- return sizeVarintS32Slice, appendVarintS32Slice
- }
- if nozero {
- return sizeVarintS32ValueNoZero, appendVarintS32ValueNoZero
- }
- return sizeVarintS32Value, appendVarintS32Value
- case "zigzag32":
- if pointer {
- return sizeZigzag32Ptr, appendZigzag32Ptr
- }
- if slice {
- if packed {
- return sizeZigzag32PackedSlice, appendZigzag32PackedSlice
- }
- return sizeZigzag32Slice, appendZigzag32Slice
- }
- if nozero {
- return sizeZigzag32ValueNoZero, appendZigzag32ValueNoZero
- }
- return sizeZigzag32Value, appendZigzag32Value
- }
- case reflect.Uint64:
- switch encoding {
- case "fixed64":
- if pointer {
- return sizeFixed64Ptr, appendFixed64Ptr
- }
- if slice {
- if packed {
- return sizeFixed64PackedSlice, appendFixed64PackedSlice
- }
- return sizeFixed64Slice, appendFixed64Slice
- }
- if nozero {
- return sizeFixed64ValueNoZero, appendFixed64ValueNoZero
- }
- return sizeFixed64Value, appendFixed64Value
- case "varint":
- if pointer {
- return sizeVarint64Ptr, appendVarint64Ptr
- }
- if slice {
- if packed {
- return sizeVarint64PackedSlice, appendVarint64PackedSlice
- }
- return sizeVarint64Slice, appendVarint64Slice
- }
- if nozero {
- return sizeVarint64ValueNoZero, appendVarint64ValueNoZero
- }
- return sizeVarint64Value, appendVarint64Value
- }
- case reflect.Int64:
- switch encoding {
- case "fixed64":
- if pointer {
- return sizeFixedS64Ptr, appendFixedS64Ptr
- }
- if slice {
- if packed {
- return sizeFixedS64PackedSlice, appendFixedS64PackedSlice
- }
- return sizeFixedS64Slice, appendFixedS64Slice
- }
- if nozero {
- return sizeFixedS64ValueNoZero, appendFixedS64ValueNoZero
- }
- return sizeFixedS64Value, appendFixedS64Value
- case "varint":
- if pointer {
- return sizeVarintS64Ptr, appendVarintS64Ptr
- }
- if slice {
- if packed {
- return sizeVarintS64PackedSlice, appendVarintS64PackedSlice
- }
- return sizeVarintS64Slice, appendVarintS64Slice
- }
- if nozero {
- return sizeVarintS64ValueNoZero, appendVarintS64ValueNoZero
- }
- return sizeVarintS64Value, appendVarintS64Value
- case "zigzag64":
- if pointer {
- return sizeZigzag64Ptr, appendZigzag64Ptr
- }
- if slice {
- if packed {
- return sizeZigzag64PackedSlice, appendZigzag64PackedSlice
- }
- return sizeZigzag64Slice, appendZigzag64Slice
- }
- if nozero {
- return sizeZigzag64ValueNoZero, appendZigzag64ValueNoZero
- }
- return sizeZigzag64Value, appendZigzag64Value
- }
- case reflect.Float32:
- if pointer {
- return sizeFloat32Ptr, appendFloat32Ptr
- }
- if slice {
- if packed {
- return sizeFloat32PackedSlice, appendFloat32PackedSlice
- }
- return sizeFloat32Slice, appendFloat32Slice
- }
- if nozero {
- return sizeFloat32ValueNoZero, appendFloat32ValueNoZero
- }
- return sizeFloat32Value, appendFloat32Value
- case reflect.Float64:
- if pointer {
- return sizeFloat64Ptr, appendFloat64Ptr
- }
- if slice {
- if packed {
- return sizeFloat64PackedSlice, appendFloat64PackedSlice
- }
- return sizeFloat64Slice, appendFloat64Slice
- }
- if nozero {
- return sizeFloat64ValueNoZero, appendFloat64ValueNoZero
- }
- return sizeFloat64Value, appendFloat64Value
- case reflect.String:
- if validateUTF8 {
- if pointer {
- return sizeStringPtr, appendUTF8StringPtr
- }
- if slice {
- return sizeStringSlice, appendUTF8StringSlice
- }
- if nozero {
- return sizeStringValueNoZero, appendUTF8StringValueNoZero
- }
- return sizeStringValue, appendUTF8StringValue
- }
- if pointer {
- return sizeStringPtr, appendStringPtr
- }
- if slice {
- return sizeStringSlice, appendStringSlice
- }
- if nozero {
- return sizeStringValueNoZero, appendStringValueNoZero
- }
- return sizeStringValue, appendStringValue
- case reflect.Slice:
- if slice {
- return sizeBytesSlice, appendBytesSlice
- }
- if oneof {
- // Oneof bytes field may also have "proto3" tag.
- // We want to marshal it as a oneof field. Do this
- // check before the proto3 check.
- return sizeBytesOneof, appendBytesOneof
- }
- if proto3 {
- return sizeBytes3, appendBytes3
- }
- return sizeBytes, appendBytes
- case reflect.Struct:
- switch encoding {
- case "group":
- if slice {
- return makeGroupSliceMarshaler(getMarshalInfo(t))
- }
- return makeGroupMarshaler(getMarshalInfo(t))
- case "bytes":
- if slice {
- return makeMessageSliceMarshaler(getMarshalInfo(t))
- }
- return makeMessageMarshaler(getMarshalInfo(t))
- }
- }
- panic(fmt.Sprintf("unknown or mismatched type: type: %v, wire type: %v", t, encoding))
-}
-
-// Below are functions to size/marshal a specific type of a field.
-// They are stored in the field's info, and called by function pointers.
-// They have type sizer or marshaler.
-
-func sizeFixed32Value(_ pointer, tagsize int) int {
- return 4 + tagsize
-}
-func sizeFixed32ValueNoZero(ptr pointer, tagsize int) int {
- v := *ptr.toUint32()
- if v == 0 {
- return 0
- }
- return 4 + tagsize
-}
-func sizeFixed32Ptr(ptr pointer, tagsize int) int {
- p := *ptr.toUint32Ptr()
- if p == nil {
- return 0
- }
- return 4 + tagsize
-}
-func sizeFixed32Slice(ptr pointer, tagsize int) int {
- s := *ptr.toUint32Slice()
- return (4 + tagsize) * len(s)
-}
-func sizeFixed32PackedSlice(ptr pointer, tagsize int) int {
- s := *ptr.toUint32Slice()
- if len(s) == 0 {
- return 0
- }
- return 4*len(s) + SizeVarint(uint64(4*len(s))) + tagsize
-}
-func sizeFixedS32Value(_ pointer, tagsize int) int {
- return 4 + tagsize
-}
-func sizeFixedS32ValueNoZero(ptr pointer, tagsize int) int {
- v := *ptr.toInt32()
- if v == 0 {
- return 0
- }
- return 4 + tagsize
-}
-func sizeFixedS32Ptr(ptr pointer, tagsize int) int {
- p := ptr.getInt32Ptr()
- if p == nil {
- return 0
- }
- return 4 + tagsize
-}
-func sizeFixedS32Slice(ptr pointer, tagsize int) int {
- s := ptr.getInt32Slice()
- return (4 + tagsize) * len(s)
-}
-func sizeFixedS32PackedSlice(ptr pointer, tagsize int) int {
- s := ptr.getInt32Slice()
- if len(s) == 0 {
- return 0
- }
- return 4*len(s) + SizeVarint(uint64(4*len(s))) + tagsize
-}
-func sizeFloat32Value(_ pointer, tagsize int) int {
- return 4 + tagsize
-}
-func sizeFloat32ValueNoZero(ptr pointer, tagsize int) int {
- v := math.Float32bits(*ptr.toFloat32())
- if v == 0 {
- return 0
- }
- return 4 + tagsize
-}
-func sizeFloat32Ptr(ptr pointer, tagsize int) int {
- p := *ptr.toFloat32Ptr()
- if p == nil {
- return 0
- }
- return 4 + tagsize
-}
-func sizeFloat32Slice(ptr pointer, tagsize int) int {
- s := *ptr.toFloat32Slice()
- return (4 + tagsize) * len(s)
-}
-func sizeFloat32PackedSlice(ptr pointer, tagsize int) int {
- s := *ptr.toFloat32Slice()
- if len(s) == 0 {
- return 0
- }
- return 4*len(s) + SizeVarint(uint64(4*len(s))) + tagsize
-}
-func sizeFixed64Value(_ pointer, tagsize int) int {
- return 8 + tagsize
-}
-func sizeFixed64ValueNoZero(ptr pointer, tagsize int) int {
- v := *ptr.toUint64()
- if v == 0 {
- return 0
- }
- return 8 + tagsize
-}
-func sizeFixed64Ptr(ptr pointer, tagsize int) int {
- p := *ptr.toUint64Ptr()
- if p == nil {
- return 0
- }
- return 8 + tagsize
-}
-func sizeFixed64Slice(ptr pointer, tagsize int) int {
- s := *ptr.toUint64Slice()
- return (8 + tagsize) * len(s)
-}
-func sizeFixed64PackedSlice(ptr pointer, tagsize int) int {
- s := *ptr.toUint64Slice()
- if len(s) == 0 {
- return 0
- }
- return 8*len(s) + SizeVarint(uint64(8*len(s))) + tagsize
-}
-func sizeFixedS64Value(_ pointer, tagsize int) int {
- return 8 + tagsize
-}
-func sizeFixedS64ValueNoZero(ptr pointer, tagsize int) int {
- v := *ptr.toInt64()
- if v == 0 {
- return 0
- }
- return 8 + tagsize
-}
-func sizeFixedS64Ptr(ptr pointer, tagsize int) int {
- p := *ptr.toInt64Ptr()
- if p == nil {
- return 0
- }
- return 8 + tagsize
-}
-func sizeFixedS64Slice(ptr pointer, tagsize int) int {
- s := *ptr.toInt64Slice()
- return (8 + tagsize) * len(s)
-}
-func sizeFixedS64PackedSlice(ptr pointer, tagsize int) int {
- s := *ptr.toInt64Slice()
- if len(s) == 0 {
- return 0
- }
- return 8*len(s) + SizeVarint(uint64(8*len(s))) + tagsize
-}
-func sizeFloat64Value(_ pointer, tagsize int) int {
- return 8 + tagsize
-}
-func sizeFloat64ValueNoZero(ptr pointer, tagsize int) int {
- v := math.Float64bits(*ptr.toFloat64())
- if v == 0 {
- return 0
- }
- return 8 + tagsize
-}
-func sizeFloat64Ptr(ptr pointer, tagsize int) int {
- p := *ptr.toFloat64Ptr()
- if p == nil {
- return 0
- }
- return 8 + tagsize
-}
-func sizeFloat64Slice(ptr pointer, tagsize int) int {
- s := *ptr.toFloat64Slice()
- return (8 + tagsize) * len(s)
-}
-func sizeFloat64PackedSlice(ptr pointer, tagsize int) int {
- s := *ptr.toFloat64Slice()
- if len(s) == 0 {
- return 0
- }
- return 8*len(s) + SizeVarint(uint64(8*len(s))) + tagsize
-}
-func sizeVarint32Value(ptr pointer, tagsize int) int {
- v := *ptr.toUint32()
- return SizeVarint(uint64(v)) + tagsize
-}
-func sizeVarint32ValueNoZero(ptr pointer, tagsize int) int {
- v := *ptr.toUint32()
- if v == 0 {
- return 0
- }
- return SizeVarint(uint64(v)) + tagsize
-}
-func sizeVarint32Ptr(ptr pointer, tagsize int) int {
- p := *ptr.toUint32Ptr()
- if p == nil {
- return 0
- }
- return SizeVarint(uint64(*p)) + tagsize
-}
-func sizeVarint32Slice(ptr pointer, tagsize int) int {
- s := *ptr.toUint32Slice()
- n := 0
- for _, v := range s {
- n += SizeVarint(uint64(v)) + tagsize
- }
- return n
-}
-func sizeVarint32PackedSlice(ptr pointer, tagsize int) int {
- s := *ptr.toUint32Slice()
- if len(s) == 0 {
- return 0
- }
- n := 0
- for _, v := range s {
- n += SizeVarint(uint64(v))
- }
- return n + SizeVarint(uint64(n)) + tagsize
-}
-func sizeVarintS32Value(ptr pointer, tagsize int) int {
- v := *ptr.toInt32()
- return SizeVarint(uint64(v)) + tagsize
-}
-func sizeVarintS32ValueNoZero(ptr pointer, tagsize int) int {
- v := *ptr.toInt32()
- if v == 0 {
- return 0
- }
- return SizeVarint(uint64(v)) + tagsize
-}
-func sizeVarintS32Ptr(ptr pointer, tagsize int) int {
- p := ptr.getInt32Ptr()
- if p == nil {
- return 0
- }
- return SizeVarint(uint64(*p)) + tagsize
-}
-func sizeVarintS32Slice(ptr pointer, tagsize int) int {
- s := ptr.getInt32Slice()
- n := 0
- for _, v := range s {
- n += SizeVarint(uint64(v)) + tagsize
- }
- return n
-}
-func sizeVarintS32PackedSlice(ptr pointer, tagsize int) int {
- s := ptr.getInt32Slice()
- if len(s) == 0 {
- return 0
- }
- n := 0
- for _, v := range s {
- n += SizeVarint(uint64(v))
- }
- return n + SizeVarint(uint64(n)) + tagsize
-}
-func sizeVarint64Value(ptr pointer, tagsize int) int {
- v := *ptr.toUint64()
- return SizeVarint(v) + tagsize
-}
-func sizeVarint64ValueNoZero(ptr pointer, tagsize int) int {
- v := *ptr.toUint64()
- if v == 0 {
- return 0
- }
- return SizeVarint(v) + tagsize
-}
-func sizeVarint64Ptr(ptr pointer, tagsize int) int {
- p := *ptr.toUint64Ptr()
- if p == nil {
- return 0
- }
- return SizeVarint(*p) + tagsize
-}
-func sizeVarint64Slice(ptr pointer, tagsize int) int {
- s := *ptr.toUint64Slice()
- n := 0
- for _, v := range s {
- n += SizeVarint(v) + tagsize
- }
- return n
-}
-func sizeVarint64PackedSlice(ptr pointer, tagsize int) int {
- s := *ptr.toUint64Slice()
- if len(s) == 0 {
- return 0
- }
- n := 0
- for _, v := range s {
- n += SizeVarint(v)
- }
- return n + SizeVarint(uint64(n)) + tagsize
-}
-func sizeVarintS64Value(ptr pointer, tagsize int) int {
- v := *ptr.toInt64()
- return SizeVarint(uint64(v)) + tagsize
-}
-func sizeVarintS64ValueNoZero(ptr pointer, tagsize int) int {
- v := *ptr.toInt64()
- if v == 0 {
- return 0
- }
- return SizeVarint(uint64(v)) + tagsize
-}
-func sizeVarintS64Ptr(ptr pointer, tagsize int) int {
- p := *ptr.toInt64Ptr()
- if p == nil {
- return 0
- }
- return SizeVarint(uint64(*p)) + tagsize
-}
-func sizeVarintS64Slice(ptr pointer, tagsize int) int {
- s := *ptr.toInt64Slice()
- n := 0
- for _, v := range s {
- n += SizeVarint(uint64(v)) + tagsize
- }
- return n
-}
-func sizeVarintS64PackedSlice(ptr pointer, tagsize int) int {
- s := *ptr.toInt64Slice()
- if len(s) == 0 {
- return 0
- }
- n := 0
- for _, v := range s {
- n += SizeVarint(uint64(v))
- }
- return n + SizeVarint(uint64(n)) + tagsize
-}
-func sizeZigzag32Value(ptr pointer, tagsize int) int {
- v := *ptr.toInt32()
- return SizeVarint(uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) + tagsize
-}
-func sizeZigzag32ValueNoZero(ptr pointer, tagsize int) int {
- v := *ptr.toInt32()
- if v == 0 {
- return 0
- }
- return SizeVarint(uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) + tagsize
-}
-func sizeZigzag32Ptr(ptr pointer, tagsize int) int {
- p := ptr.getInt32Ptr()
- if p == nil {
- return 0
- }
- v := *p
- return SizeVarint(uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) + tagsize
-}
-func sizeZigzag32Slice(ptr pointer, tagsize int) int {
- s := ptr.getInt32Slice()
- n := 0
- for _, v := range s {
- n += SizeVarint(uint64((uint32(v)<<1)^uint32((int32(v)>>31)))) + tagsize
- }
- return n
-}
-func sizeZigzag32PackedSlice(ptr pointer, tagsize int) int {
- s := ptr.getInt32Slice()
- if len(s) == 0 {
- return 0
- }
- n := 0
- for _, v := range s {
- n += SizeVarint(uint64((uint32(v) << 1) ^ uint32((int32(v) >> 31))))
- }
- return n + SizeVarint(uint64(n)) + tagsize
-}
-func sizeZigzag64Value(ptr pointer, tagsize int) int {
- v := *ptr.toInt64()
- return SizeVarint(uint64(v<<1)^uint64((int64(v)>>63))) + tagsize
-}
-func sizeZigzag64ValueNoZero(ptr pointer, tagsize int) int {
- v := *ptr.toInt64()
- if v == 0 {
- return 0
- }
- return SizeVarint(uint64(v<<1)^uint64((int64(v)>>63))) + tagsize
-}
-func sizeZigzag64Ptr(ptr pointer, tagsize int) int {
- p := *ptr.toInt64Ptr()
- if p == nil {
- return 0
- }
- v := *p
- return SizeVarint(uint64(v<<1)^uint64((int64(v)>>63))) + tagsize
-}
-func sizeZigzag64Slice(ptr pointer, tagsize int) int {
- s := *ptr.toInt64Slice()
- n := 0
- for _, v := range s {
- n += SizeVarint(uint64(v<<1)^uint64((int64(v)>>63))) + tagsize
- }
- return n
-}
-func sizeZigzag64PackedSlice(ptr pointer, tagsize int) int {
- s := *ptr.toInt64Slice()
- if len(s) == 0 {
- return 0
- }
- n := 0
- for _, v := range s {
- n += SizeVarint(uint64(v<<1) ^ uint64((int64(v) >> 63)))
- }
- return n + SizeVarint(uint64(n)) + tagsize
-}
-func sizeBoolValue(_ pointer, tagsize int) int {
- return 1 + tagsize
-}
-func sizeBoolValueNoZero(ptr pointer, tagsize int) int {
- v := *ptr.toBool()
- if !v {
- return 0
- }
- return 1 + tagsize
-}
-func sizeBoolPtr(ptr pointer, tagsize int) int {
- p := *ptr.toBoolPtr()
- if p == nil {
- return 0
- }
- return 1 + tagsize
-}
-func sizeBoolSlice(ptr pointer, tagsize int) int {
- s := *ptr.toBoolSlice()
- return (1 + tagsize) * len(s)
-}
-func sizeBoolPackedSlice(ptr pointer, tagsize int) int {
- s := *ptr.toBoolSlice()
- if len(s) == 0 {
- return 0
- }
- return len(s) + SizeVarint(uint64(len(s))) + tagsize
-}
-func sizeStringValue(ptr pointer, tagsize int) int {
- v := *ptr.toString()
- return len(v) + SizeVarint(uint64(len(v))) + tagsize
-}
-func sizeStringValueNoZero(ptr pointer, tagsize int) int {
- v := *ptr.toString()
- if v == "" {
- return 0
- }
- return len(v) + SizeVarint(uint64(len(v))) + tagsize
-}
-func sizeStringPtr(ptr pointer, tagsize int) int {
- p := *ptr.toStringPtr()
- if p == nil {
- return 0
- }
- v := *p
- return len(v) + SizeVarint(uint64(len(v))) + tagsize
-}
-func sizeStringSlice(ptr pointer, tagsize int) int {
- s := *ptr.toStringSlice()
- n := 0
- for _, v := range s {
- n += len(v) + SizeVarint(uint64(len(v))) + tagsize
- }
- return n
-}
-func sizeBytes(ptr pointer, tagsize int) int {
- v := *ptr.toBytes()
- if v == nil {
- return 0
- }
- return len(v) + SizeVarint(uint64(len(v))) + tagsize
-}
-func sizeBytes3(ptr pointer, tagsize int) int {
- v := *ptr.toBytes()
- if len(v) == 0 {
- return 0
- }
- return len(v) + SizeVarint(uint64(len(v))) + tagsize
-}
-func sizeBytesOneof(ptr pointer, tagsize int) int {
- v := *ptr.toBytes()
- return len(v) + SizeVarint(uint64(len(v))) + tagsize
-}
-func sizeBytesSlice(ptr pointer, tagsize int) int {
- s := *ptr.toBytesSlice()
- n := 0
- for _, v := range s {
- n += len(v) + SizeVarint(uint64(len(v))) + tagsize
- }
- return n
-}
-
-// appendFixed32 appends an encoded fixed32 to b.
-func appendFixed32(b []byte, v uint32) []byte {
- b = append(b,
- byte(v),
- byte(v>>8),
- byte(v>>16),
- byte(v>>24))
- return b
-}
-
-// appendFixed64 appends an encoded fixed64 to b.
-func appendFixed64(b []byte, v uint64) []byte {
- b = append(b,
- byte(v),
- byte(v>>8),
- byte(v>>16),
- byte(v>>24),
- byte(v>>32),
- byte(v>>40),
- byte(v>>48),
- byte(v>>56))
- return b
-}
-
-// appendVarint appends an encoded varint to b.
-func appendVarint(b []byte, v uint64) []byte {
- // TODO: make 1-byte (maybe 2-byte) case inline-able, once we
- // have non-leaf inliner.
- switch {
- case v < 1<<7:
- b = append(b, byte(v))
- case v < 1<<14:
- b = append(b,
- byte(v&0x7f|0x80),
- byte(v>>7))
- case v < 1<<21:
- b = append(b,
- byte(v&0x7f|0x80),
- byte((v>>7)&0x7f|0x80),
- byte(v>>14))
- case v < 1<<28:
- b = append(b,
- byte(v&0x7f|0x80),
- byte((v>>7)&0x7f|0x80),
- byte((v>>14)&0x7f|0x80),
- byte(v>>21))
- case v < 1<<35:
- b = append(b,
- byte(v&0x7f|0x80),
- byte((v>>7)&0x7f|0x80),
- byte((v>>14)&0x7f|0x80),
- byte((v>>21)&0x7f|0x80),
- byte(v>>28))
- case v < 1<<42:
- b = append(b,
- byte(v&0x7f|0x80),
- byte((v>>7)&0x7f|0x80),
- byte((v>>14)&0x7f|0x80),
- byte((v>>21)&0x7f|0x80),
- byte((v>>28)&0x7f|0x80),
- byte(v>>35))
- case v < 1<<49:
- b = append(b,
- byte(v&0x7f|0x80),
- byte((v>>7)&0x7f|0x80),
- byte((v>>14)&0x7f|0x80),
- byte((v>>21)&0x7f|0x80),
- byte((v>>28)&0x7f|0x80),
- byte((v>>35)&0x7f|0x80),
- byte(v>>42))
- case v < 1<<56:
- b = append(b,
- byte(v&0x7f|0x80),
- byte((v>>7)&0x7f|0x80),
- byte((v>>14)&0x7f|0x80),
- byte((v>>21)&0x7f|0x80),
- byte((v>>28)&0x7f|0x80),
- byte((v>>35)&0x7f|0x80),
- byte((v>>42)&0x7f|0x80),
- byte(v>>49))
- case v < 1<<63:
- b = append(b,
- byte(v&0x7f|0x80),
- byte((v>>7)&0x7f|0x80),
- byte((v>>14)&0x7f|0x80),
- byte((v>>21)&0x7f|0x80),
- byte((v>>28)&0x7f|0x80),
- byte((v>>35)&0x7f|0x80),
- byte((v>>42)&0x7f|0x80),
- byte((v>>49)&0x7f|0x80),
- byte(v>>56))
- default:
- b = append(b,
- byte(v&0x7f|0x80),
- byte((v>>7)&0x7f|0x80),
- byte((v>>14)&0x7f|0x80),
- byte((v>>21)&0x7f|0x80),
- byte((v>>28)&0x7f|0x80),
- byte((v>>35)&0x7f|0x80),
- byte((v>>42)&0x7f|0x80),
- byte((v>>49)&0x7f|0x80),
- byte((v>>56)&0x7f|0x80),
- 1)
- }
- return b
-}
-
-func appendFixed32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := *ptr.toUint32()
- b = appendVarint(b, wiretag)
- b = appendFixed32(b, v)
- return b, nil
-}
-func appendFixed32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := *ptr.toUint32()
- if v == 0 {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- b = appendFixed32(b, v)
- return b, nil
-}
-func appendFixed32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- p := *ptr.toUint32Ptr()
- if p == nil {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- b = appendFixed32(b, *p)
- return b, nil
-}
-func appendFixed32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- s := *ptr.toUint32Slice()
- for _, v := range s {
- b = appendVarint(b, wiretag)
- b = appendFixed32(b, v)
- }
- return b, nil
-}
-func appendFixed32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- s := *ptr.toUint32Slice()
- if len(s) == 0 {
- return b, nil
- }
- b = appendVarint(b, wiretag&^7|WireBytes)
- b = appendVarint(b, uint64(4*len(s)))
- for _, v := range s {
- b = appendFixed32(b, v)
- }
- return b, nil
-}
-func appendFixedS32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := *ptr.toInt32()
- b = appendVarint(b, wiretag)
- b = appendFixed32(b, uint32(v))
- return b, nil
-}
-func appendFixedS32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := *ptr.toInt32()
- if v == 0 {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- b = appendFixed32(b, uint32(v))
- return b, nil
-}
-func appendFixedS32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- p := ptr.getInt32Ptr()
- if p == nil {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- b = appendFixed32(b, uint32(*p))
- return b, nil
-}
-func appendFixedS32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- s := ptr.getInt32Slice()
- for _, v := range s {
- b = appendVarint(b, wiretag)
- b = appendFixed32(b, uint32(v))
- }
- return b, nil
-}
-func appendFixedS32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- s := ptr.getInt32Slice()
- if len(s) == 0 {
- return b, nil
- }
- b = appendVarint(b, wiretag&^7|WireBytes)
- b = appendVarint(b, uint64(4*len(s)))
- for _, v := range s {
- b = appendFixed32(b, uint32(v))
- }
- return b, nil
-}
-func appendFloat32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := math.Float32bits(*ptr.toFloat32())
- b = appendVarint(b, wiretag)
- b = appendFixed32(b, v)
- return b, nil
-}
-func appendFloat32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := math.Float32bits(*ptr.toFloat32())
- if v == 0 {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- b = appendFixed32(b, v)
- return b, nil
-}
-func appendFloat32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- p := *ptr.toFloat32Ptr()
- if p == nil {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- b = appendFixed32(b, math.Float32bits(*p))
- return b, nil
-}
-func appendFloat32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- s := *ptr.toFloat32Slice()
- for _, v := range s {
- b = appendVarint(b, wiretag)
- b = appendFixed32(b, math.Float32bits(v))
- }
- return b, nil
-}
-func appendFloat32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- s := *ptr.toFloat32Slice()
- if len(s) == 0 {
- return b, nil
- }
- b = appendVarint(b, wiretag&^7|WireBytes)
- b = appendVarint(b, uint64(4*len(s)))
- for _, v := range s {
- b = appendFixed32(b, math.Float32bits(v))
- }
- return b, nil
-}
-func appendFixed64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := *ptr.toUint64()
- b = appendVarint(b, wiretag)
- b = appendFixed64(b, v)
- return b, nil
-}
-func appendFixed64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := *ptr.toUint64()
- if v == 0 {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- b = appendFixed64(b, v)
- return b, nil
-}
-func appendFixed64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- p := *ptr.toUint64Ptr()
- if p == nil {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- b = appendFixed64(b, *p)
- return b, nil
-}
-func appendFixed64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- s := *ptr.toUint64Slice()
- for _, v := range s {
- b = appendVarint(b, wiretag)
- b = appendFixed64(b, v)
- }
- return b, nil
-}
-func appendFixed64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- s := *ptr.toUint64Slice()
- if len(s) == 0 {
- return b, nil
- }
- b = appendVarint(b, wiretag&^7|WireBytes)
- b = appendVarint(b, uint64(8*len(s)))
- for _, v := range s {
- b = appendFixed64(b, v)
- }
- return b, nil
-}
-func appendFixedS64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := *ptr.toInt64()
- b = appendVarint(b, wiretag)
- b = appendFixed64(b, uint64(v))
- return b, nil
-}
-func appendFixedS64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := *ptr.toInt64()
- if v == 0 {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- b = appendFixed64(b, uint64(v))
- return b, nil
-}
-func appendFixedS64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- p := *ptr.toInt64Ptr()
- if p == nil {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- b = appendFixed64(b, uint64(*p))
- return b, nil
-}
-func appendFixedS64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- s := *ptr.toInt64Slice()
- for _, v := range s {
- b = appendVarint(b, wiretag)
- b = appendFixed64(b, uint64(v))
- }
- return b, nil
-}
-func appendFixedS64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- s := *ptr.toInt64Slice()
- if len(s) == 0 {
- return b, nil
- }
- b = appendVarint(b, wiretag&^7|WireBytes)
- b = appendVarint(b, uint64(8*len(s)))
- for _, v := range s {
- b = appendFixed64(b, uint64(v))
- }
- return b, nil
-}
-func appendFloat64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := math.Float64bits(*ptr.toFloat64())
- b = appendVarint(b, wiretag)
- b = appendFixed64(b, v)
- return b, nil
-}
-func appendFloat64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := math.Float64bits(*ptr.toFloat64())
- if v == 0 {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- b = appendFixed64(b, v)
- return b, nil
-}
-func appendFloat64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- p := *ptr.toFloat64Ptr()
- if p == nil {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- b = appendFixed64(b, math.Float64bits(*p))
- return b, nil
-}
-func appendFloat64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- s := *ptr.toFloat64Slice()
- for _, v := range s {
- b = appendVarint(b, wiretag)
- b = appendFixed64(b, math.Float64bits(v))
- }
- return b, nil
-}
-func appendFloat64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- s := *ptr.toFloat64Slice()
- if len(s) == 0 {
- return b, nil
- }
- b = appendVarint(b, wiretag&^7|WireBytes)
- b = appendVarint(b, uint64(8*len(s)))
- for _, v := range s {
- b = appendFixed64(b, math.Float64bits(v))
- }
- return b, nil
-}
-func appendVarint32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := *ptr.toUint32()
- b = appendVarint(b, wiretag)
- b = appendVarint(b, uint64(v))
- return b, nil
-}
-func appendVarint32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := *ptr.toUint32()
- if v == 0 {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- b = appendVarint(b, uint64(v))
- return b, nil
-}
-func appendVarint32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- p := *ptr.toUint32Ptr()
- if p == nil {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- b = appendVarint(b, uint64(*p))
- return b, nil
-}
-func appendVarint32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- s := *ptr.toUint32Slice()
- for _, v := range s {
- b = appendVarint(b, wiretag)
- b = appendVarint(b, uint64(v))
- }
- return b, nil
-}
-func appendVarint32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- s := *ptr.toUint32Slice()
- if len(s) == 0 {
- return b, nil
- }
- b = appendVarint(b, wiretag&^7|WireBytes)
- // compute size
- n := 0
- for _, v := range s {
- n += SizeVarint(uint64(v))
- }
- b = appendVarint(b, uint64(n))
- for _, v := range s {
- b = appendVarint(b, uint64(v))
- }
- return b, nil
-}
-func appendVarintS32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := *ptr.toInt32()
- b = appendVarint(b, wiretag)
- b = appendVarint(b, uint64(v))
- return b, nil
-}
-func appendVarintS32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := *ptr.toInt32()
- if v == 0 {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- b = appendVarint(b, uint64(v))
- return b, nil
-}
-func appendVarintS32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- p := ptr.getInt32Ptr()
- if p == nil {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- b = appendVarint(b, uint64(*p))
- return b, nil
-}
-func appendVarintS32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- s := ptr.getInt32Slice()
- for _, v := range s {
- b = appendVarint(b, wiretag)
- b = appendVarint(b, uint64(v))
- }
- return b, nil
-}
-func appendVarintS32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- s := ptr.getInt32Slice()
- if len(s) == 0 {
- return b, nil
- }
- b = appendVarint(b, wiretag&^7|WireBytes)
- // compute size
- n := 0
- for _, v := range s {
- n += SizeVarint(uint64(v))
- }
- b = appendVarint(b, uint64(n))
- for _, v := range s {
- b = appendVarint(b, uint64(v))
- }
- return b, nil
-}
-func appendVarint64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := *ptr.toUint64()
- b = appendVarint(b, wiretag)
- b = appendVarint(b, v)
- return b, nil
-}
-func appendVarint64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := *ptr.toUint64()
- if v == 0 {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- b = appendVarint(b, v)
- return b, nil
-}
-func appendVarint64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- p := *ptr.toUint64Ptr()
- if p == nil {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- b = appendVarint(b, *p)
- return b, nil
-}
-func appendVarint64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- s := *ptr.toUint64Slice()
- for _, v := range s {
- b = appendVarint(b, wiretag)
- b = appendVarint(b, v)
- }
- return b, nil
-}
-func appendVarint64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- s := *ptr.toUint64Slice()
- if len(s) == 0 {
- return b, nil
- }
- b = appendVarint(b, wiretag&^7|WireBytes)
- // compute size
- n := 0
- for _, v := range s {
- n += SizeVarint(v)
- }
- b = appendVarint(b, uint64(n))
- for _, v := range s {
- b = appendVarint(b, v)
- }
- return b, nil
-}
-func appendVarintS64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := *ptr.toInt64()
- b = appendVarint(b, wiretag)
- b = appendVarint(b, uint64(v))
- return b, nil
-}
-func appendVarintS64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := *ptr.toInt64()
- if v == 0 {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- b = appendVarint(b, uint64(v))
- return b, nil
-}
-func appendVarintS64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- p := *ptr.toInt64Ptr()
- if p == nil {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- b = appendVarint(b, uint64(*p))
- return b, nil
-}
-func appendVarintS64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- s := *ptr.toInt64Slice()
- for _, v := range s {
- b = appendVarint(b, wiretag)
- b = appendVarint(b, uint64(v))
- }
- return b, nil
-}
-func appendVarintS64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- s := *ptr.toInt64Slice()
- if len(s) == 0 {
- return b, nil
- }
- b = appendVarint(b, wiretag&^7|WireBytes)
- // compute size
- n := 0
- for _, v := range s {
- n += SizeVarint(uint64(v))
- }
- b = appendVarint(b, uint64(n))
- for _, v := range s {
- b = appendVarint(b, uint64(v))
- }
- return b, nil
-}
-func appendZigzag32Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := *ptr.toInt32()
- b = appendVarint(b, wiretag)
- b = appendVarint(b, uint64((uint32(v)<<1)^uint32((int32(v)>>31))))
- return b, nil
-}
-func appendZigzag32ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := *ptr.toInt32()
- if v == 0 {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- b = appendVarint(b, uint64((uint32(v)<<1)^uint32((int32(v)>>31))))
- return b, nil
-}
-func appendZigzag32Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- p := ptr.getInt32Ptr()
- if p == nil {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- v := *p
- b = appendVarint(b, uint64((uint32(v)<<1)^uint32((int32(v)>>31))))
- return b, nil
-}
-func appendZigzag32Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- s := ptr.getInt32Slice()
- for _, v := range s {
- b = appendVarint(b, wiretag)
- b = appendVarint(b, uint64((uint32(v)<<1)^uint32((int32(v)>>31))))
- }
- return b, nil
-}
-func appendZigzag32PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- s := ptr.getInt32Slice()
- if len(s) == 0 {
- return b, nil
- }
- b = appendVarint(b, wiretag&^7|WireBytes)
- // compute size
- n := 0
- for _, v := range s {
- n += SizeVarint(uint64((uint32(v) << 1) ^ uint32((int32(v) >> 31))))
- }
- b = appendVarint(b, uint64(n))
- for _, v := range s {
- b = appendVarint(b, uint64((uint32(v)<<1)^uint32((int32(v)>>31))))
- }
- return b, nil
-}
-func appendZigzag64Value(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := *ptr.toInt64()
- b = appendVarint(b, wiretag)
- b = appendVarint(b, uint64(v<<1)^uint64((int64(v)>>63)))
- return b, nil
-}
-func appendZigzag64ValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := *ptr.toInt64()
- if v == 0 {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- b = appendVarint(b, uint64(v<<1)^uint64((int64(v)>>63)))
- return b, nil
-}
-func appendZigzag64Ptr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- p := *ptr.toInt64Ptr()
- if p == nil {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- v := *p
- b = appendVarint(b, uint64(v<<1)^uint64((int64(v)>>63)))
- return b, nil
-}
-func appendZigzag64Slice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- s := *ptr.toInt64Slice()
- for _, v := range s {
- b = appendVarint(b, wiretag)
- b = appendVarint(b, uint64(v<<1)^uint64((int64(v)>>63)))
- }
- return b, nil
-}
-func appendZigzag64PackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- s := *ptr.toInt64Slice()
- if len(s) == 0 {
- return b, nil
- }
- b = appendVarint(b, wiretag&^7|WireBytes)
- // compute size
- n := 0
- for _, v := range s {
- n += SizeVarint(uint64(v<<1) ^ uint64((int64(v) >> 63)))
- }
- b = appendVarint(b, uint64(n))
- for _, v := range s {
- b = appendVarint(b, uint64(v<<1)^uint64((int64(v)>>63)))
- }
- return b, nil
-}
-func appendBoolValue(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := *ptr.toBool()
- b = appendVarint(b, wiretag)
- if v {
- b = append(b, 1)
- } else {
- b = append(b, 0)
- }
- return b, nil
-}
-func appendBoolValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := *ptr.toBool()
- if !v {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- b = append(b, 1)
- return b, nil
-}
-
-func appendBoolPtr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- p := *ptr.toBoolPtr()
- if p == nil {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- if *p {
- b = append(b, 1)
- } else {
- b = append(b, 0)
- }
- return b, nil
-}
-func appendBoolSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- s := *ptr.toBoolSlice()
- for _, v := range s {
- b = appendVarint(b, wiretag)
- if v {
- b = append(b, 1)
- } else {
- b = append(b, 0)
- }
- }
- return b, nil
-}
-func appendBoolPackedSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- s := *ptr.toBoolSlice()
- if len(s) == 0 {
- return b, nil
- }
- b = appendVarint(b, wiretag&^7|WireBytes)
- b = appendVarint(b, uint64(len(s)))
- for _, v := range s {
- if v {
- b = append(b, 1)
- } else {
- b = append(b, 0)
- }
- }
- return b, nil
-}
-func appendStringValue(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := *ptr.toString()
- b = appendVarint(b, wiretag)
- b = appendVarint(b, uint64(len(v)))
- b = append(b, v...)
- return b, nil
-}
-func appendStringValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := *ptr.toString()
- if v == "" {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- b = appendVarint(b, uint64(len(v)))
- b = append(b, v...)
- return b, nil
-}
-func appendStringPtr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- p := *ptr.toStringPtr()
- if p == nil {
- return b, nil
- }
- v := *p
- b = appendVarint(b, wiretag)
- b = appendVarint(b, uint64(len(v)))
- b = append(b, v...)
- return b, nil
-}
-func appendStringSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- s := *ptr.toStringSlice()
- for _, v := range s {
- b = appendVarint(b, wiretag)
- b = appendVarint(b, uint64(len(v)))
- b = append(b, v...)
- }
- return b, nil
-}
-func appendUTF8StringValue(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- var invalidUTF8 bool
- v := *ptr.toString()
- if !utf8.ValidString(v) {
- invalidUTF8 = true
- }
- b = appendVarint(b, wiretag)
- b = appendVarint(b, uint64(len(v)))
- b = append(b, v...)
- if invalidUTF8 {
- return b, errInvalidUTF8
- }
- return b, nil
-}
-func appendUTF8StringValueNoZero(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- var invalidUTF8 bool
- v := *ptr.toString()
- if v == "" {
- return b, nil
- }
- if !utf8.ValidString(v) {
- invalidUTF8 = true
- }
- b = appendVarint(b, wiretag)
- b = appendVarint(b, uint64(len(v)))
- b = append(b, v...)
- if invalidUTF8 {
- return b, errInvalidUTF8
- }
- return b, nil
-}
-func appendUTF8StringPtr(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- var invalidUTF8 bool
- p := *ptr.toStringPtr()
- if p == nil {
- return b, nil
- }
- v := *p
- if !utf8.ValidString(v) {
- invalidUTF8 = true
- }
- b = appendVarint(b, wiretag)
- b = appendVarint(b, uint64(len(v)))
- b = append(b, v...)
- if invalidUTF8 {
- return b, errInvalidUTF8
- }
- return b, nil
-}
-func appendUTF8StringSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- var invalidUTF8 bool
- s := *ptr.toStringSlice()
- for _, v := range s {
- if !utf8.ValidString(v) {
- invalidUTF8 = true
- }
- b = appendVarint(b, wiretag)
- b = appendVarint(b, uint64(len(v)))
- b = append(b, v...)
- }
- if invalidUTF8 {
- return b, errInvalidUTF8
- }
- return b, nil
-}
-func appendBytes(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := *ptr.toBytes()
- if v == nil {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- b = appendVarint(b, uint64(len(v)))
- b = append(b, v...)
- return b, nil
-}
-func appendBytes3(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := *ptr.toBytes()
- if len(v) == 0 {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- b = appendVarint(b, uint64(len(v)))
- b = append(b, v...)
- return b, nil
-}
-func appendBytesOneof(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- v := *ptr.toBytes()
- b = appendVarint(b, wiretag)
- b = appendVarint(b, uint64(len(v)))
- b = append(b, v...)
- return b, nil
-}
-func appendBytesSlice(b []byte, ptr pointer, wiretag uint64, _ bool) ([]byte, error) {
- s := *ptr.toBytesSlice()
- for _, v := range s {
- b = appendVarint(b, wiretag)
- b = appendVarint(b, uint64(len(v)))
- b = append(b, v...)
- }
- return b, nil
-}
-
-// makeGroupMarshaler returns the sizer and marshaler for a group.
-// u is the marshal info of the underlying message.
-func makeGroupMarshaler(u *marshalInfo) (sizer, marshaler) {
- return func(ptr pointer, tagsize int) int {
- p := ptr.getPointer()
- if p.isNil() {
- return 0
- }
- return u.size(p) + 2*tagsize
- },
- func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) {
- p := ptr.getPointer()
- if p.isNil() {
- return b, nil
- }
- var err error
- b = appendVarint(b, wiretag) // start group
- b, err = u.marshal(b, p, deterministic)
- b = appendVarint(b, wiretag+(WireEndGroup-WireStartGroup)) // end group
- return b, err
- }
-}
-
-// makeGroupSliceMarshaler returns the sizer and marshaler for a group slice.
-// u is the marshal info of the underlying message.
-func makeGroupSliceMarshaler(u *marshalInfo) (sizer, marshaler) {
- return func(ptr pointer, tagsize int) int {
- s := ptr.getPointerSlice()
- n := 0
- for _, v := range s {
- if v.isNil() {
- continue
- }
- n += u.size(v) + 2*tagsize
- }
- return n
- },
- func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) {
- s := ptr.getPointerSlice()
- var err error
- var nerr nonFatal
- for _, v := range s {
- if v.isNil() {
- return b, errRepeatedHasNil
- }
- b = appendVarint(b, wiretag) // start group
- b, err = u.marshal(b, v, deterministic)
- b = appendVarint(b, wiretag+(WireEndGroup-WireStartGroup)) // end group
- if !nerr.Merge(err) {
- if err == ErrNil {
- err = errRepeatedHasNil
- }
- return b, err
- }
- }
- return b, nerr.E
- }
-}
-
-// makeMessageMarshaler returns the sizer and marshaler for a message field.
-// u is the marshal info of the message.
-func makeMessageMarshaler(u *marshalInfo) (sizer, marshaler) {
- return func(ptr pointer, tagsize int) int {
- p := ptr.getPointer()
- if p.isNil() {
- return 0
- }
- siz := u.size(p)
- return siz + SizeVarint(uint64(siz)) + tagsize
- },
- func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) {
- p := ptr.getPointer()
- if p.isNil() {
- return b, nil
- }
- b = appendVarint(b, wiretag)
- siz := u.cachedsize(p)
- b = appendVarint(b, uint64(siz))
- return u.marshal(b, p, deterministic)
- }
-}
-
-// makeMessageSliceMarshaler returns the sizer and marshaler for a message slice.
-// u is the marshal info of the message.
-func makeMessageSliceMarshaler(u *marshalInfo) (sizer, marshaler) {
- return func(ptr pointer, tagsize int) int {
- s := ptr.getPointerSlice()
- n := 0
- for _, v := range s {
- if v.isNil() {
- continue
- }
- siz := u.size(v)
- n += siz + SizeVarint(uint64(siz)) + tagsize
- }
- return n
- },
- func(b []byte, ptr pointer, wiretag uint64, deterministic bool) ([]byte, error) {
- s := ptr.getPointerSlice()
- var err error
- var nerr nonFatal
- for _, v := range s {
- if v.isNil() {
- return b, errRepeatedHasNil
- }
- b = appendVarint(b, wiretag)
- siz := u.cachedsize(v)
- b = appendVarint(b, uint64(siz))
- b, err = u.marshal(b, v, deterministic)
-
- if !nerr.Merge(err) {
- if err == ErrNil {
- err = errRepeatedHasNil
- }
- return b, err
- }
- }
- return b, nerr.E
- }
-}
-
-// makeMapMarshaler returns the sizer and marshaler for a map field.
-// f is the pointer to the reflect data structure of the field.
-func makeMapMarshaler(f *reflect.StructField) (sizer, marshaler) {
- // figure out key and value type
- t := f.Type
- keyType := t.Key()
- valType := t.Elem()
- keyTags := strings.Split(f.Tag.Get("protobuf_key"), ",")
- valTags := strings.Split(f.Tag.Get("protobuf_val"), ",")
- keySizer, keyMarshaler := typeMarshaler(keyType, keyTags, false, false) // don't omit zero value in map
- valSizer, valMarshaler := typeMarshaler(valType, valTags, false, false) // don't omit zero value in map
- keyWireTag := 1<<3 | wiretype(keyTags[0])
- valWireTag := 2<<3 | wiretype(valTags[0])
-
- // We create an interface to get the addresses of the map key and value.
- // If value is pointer-typed, the interface is a direct interface, the
- // idata itself is the value. Otherwise, the idata is the pointer to the
- // value.
- // Key cannot be pointer-typed.
- valIsPtr := valType.Kind() == reflect.Ptr
-
- // If value is a message with nested maps, calling
- // valSizer in marshal may be quadratic. We should use
- // cached version in marshal (but not in size).
- // If value is not message type, we don't have size cache,
- // but it cannot be nested either. Just use valSizer.
- valCachedSizer := valSizer
- if valIsPtr && valType.Elem().Kind() == reflect.Struct {
- u := getMarshalInfo(valType.Elem())
- valCachedSizer = func(ptr pointer, tagsize int) int {
- // Same as message sizer, but use cache.
- p := ptr.getPointer()
- if p.isNil() {
- return 0
- }
- siz := u.cachedsize(p)
- return siz + SizeVarint(uint64(siz)) + tagsize
- }
- }
- return func(ptr pointer, tagsize int) int {
- m := ptr.asPointerTo(t).Elem() // the map
- n := 0
- for _, k := range m.MapKeys() {
- ki := k.Interface()
- vi := m.MapIndex(k).Interface()
- kaddr := toAddrPointer(&ki, false, false) // pointer to key
- vaddr := toAddrPointer(&vi, valIsPtr, false) // pointer to value
- siz := keySizer(kaddr, 1) + valSizer(vaddr, 1) // tag of key = 1 (size=1), tag of val = 2 (size=1)
- n += siz + SizeVarint(uint64(siz)) + tagsize
- }
- return n
- },
- func(b []byte, ptr pointer, tag uint64, deterministic bool) ([]byte, error) {
- m := ptr.asPointerTo(t).Elem() // the map
- var err error
- keys := m.MapKeys()
- if len(keys) > 1 && deterministic {
- sort.Sort(mapKeys(keys))
- }
-
- var nerr nonFatal
- for _, k := range keys {
- ki := k.Interface()
- vi := m.MapIndex(k).Interface()
- kaddr := toAddrPointer(&ki, false, false) // pointer to key
- vaddr := toAddrPointer(&vi, valIsPtr, false) // pointer to value
- b = appendVarint(b, tag)
- siz := keySizer(kaddr, 1) + valCachedSizer(vaddr, 1) // tag of key = 1 (size=1), tag of val = 2 (size=1)
- b = appendVarint(b, uint64(siz))
- b, err = keyMarshaler(b, kaddr, keyWireTag, deterministic)
- if !nerr.Merge(err) {
- return b, err
- }
- b, err = valMarshaler(b, vaddr, valWireTag, deterministic)
- if err != ErrNil && !nerr.Merge(err) { // allow nil value in map
- return b, err
- }
- }
- return b, nerr.E
- }
-}
-
-// makeOneOfMarshaler returns the sizer and marshaler for a oneof field.
-// fi is the marshal info of the field.
-// f is the pointer to the reflect data structure of the field.
-func makeOneOfMarshaler(fi *marshalFieldInfo, f *reflect.StructField) (sizer, marshaler) {
- // Oneof field is an interface. We need to get the actual data type on the fly.
- t := f.Type
- return func(ptr pointer, _ int) int {
- p := ptr.getInterfacePointer()
- if p.isNil() {
- return 0
- }
- v := ptr.asPointerTo(t).Elem().Elem().Elem() // *interface -> interface -> *struct -> struct
- telem := v.Type()
- e := fi.oneofElems[telem]
- return e.sizer(p, e.tagsize)
- },
- func(b []byte, ptr pointer, _ uint64, deterministic bool) ([]byte, error) {
- p := ptr.getInterfacePointer()
- if p.isNil() {
- return b, nil
- }
- v := ptr.asPointerTo(t).Elem().Elem().Elem() // *interface -> interface -> *struct -> struct
- telem := v.Type()
- if telem.Field(0).Type.Kind() == reflect.Ptr && p.getPointer().isNil() {
- return b, errOneofHasNil
- }
- e := fi.oneofElems[telem]
- return e.marshaler(b, p, e.wiretag, deterministic)
- }
-}
-
-// sizeExtensions computes the size of encoded data for a XXX_InternalExtensions field.
-func (u *marshalInfo) sizeExtensions(ext *XXX_InternalExtensions) int {
- m, mu := ext.extensionsRead()
- if m == nil {
- return 0
- }
- mu.Lock()
-
- n := 0
- 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.
- ei := u.getExtElemInfo(e.desc)
- v := e.value
- p := toAddrPointer(&v, ei.isptr, ei.deref)
- n += ei.sizer(p, ei.tagsize)
- }
- mu.Unlock()
- return n
-}
-
-// appendExtensions marshals a XXX_InternalExtensions field to the end of byte slice b.
-func (u *marshalInfo) appendExtensions(b []byte, ext *XXX_InternalExtensions, deterministic bool) ([]byte, error) {
- m, mu := ext.extensionsRead()
- if m == nil {
- return b, nil
- }
- mu.Lock()
- defer mu.Unlock()
-
- var err error
- var nerr nonFatal
-
- // Fast-path for common cases: zero or one extensions.
- // Don't bother sorting the keys.
- if len(m) <= 1 {
- for _, e := range m {
- if e.value == nil || e.desc == nil {
- // Extension is only in its encoded form.
- b = append(b, 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.
-
- ei := u.getExtElemInfo(e.desc)
- v := e.value
- p := toAddrPointer(&v, ei.isptr, ei.deref)
- b, err = ei.marshaler(b, p, ei.wiretag, deterministic)
- if !nerr.Merge(err) {
- return b, err
- }
- }
- return b, nerr.E
- }
-
- // Sort the keys to provide a deterministic encoding.
- // Not sure this is required, but the old code does it.
- keys := make([]int, 0, len(m))
- for k := range m {
- keys = append(keys, int(k))
- }
- sort.Ints(keys)
-
- for _, k := range keys {
- e := m[int32(k)]
- if e.value == nil || e.desc == nil {
- // Extension is only in its encoded form.
- b = append(b, 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.
-
- ei := u.getExtElemInfo(e.desc)
- v := e.value
- p := toAddrPointer(&v, ei.isptr, ei.deref)
- b, err = ei.marshaler(b, p, ei.wiretag, deterministic)
- if !nerr.Merge(err) {
- return b, err
- }
- }
- return b, nerr.E
-}
-
-// message set format is:
-// message MessageSet {
-// repeated group Item = 1 {
-// required int32 type_id = 2;
-// required string message = 3;
-// };
-// }
-
-// sizeMessageSet computes the size of encoded data for a XXX_InternalExtensions field
-// in message set format (above).
-func (u *marshalInfo) sizeMessageSet(ext *XXX_InternalExtensions) int {
- m, mu := ext.extensionsRead()
- if m == nil {
- return 0
- }
- mu.Lock()
-
- n := 0
- for id, e := range m {
- n += 2 // start group, end group. tag = 1 (size=1)
- n += SizeVarint(uint64(id)) + 1 // type_id, tag = 2 (size=1)
-
- if e.value == nil || e.desc == nil {
- // Extension is only in its encoded form.
- msgWithLen := skipVarint(e.enc) // skip old tag, but leave the length varint
- siz := len(msgWithLen)
- n += siz + 1 // message, tag = 3 (size=1)
- 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.
-
- ei := u.getExtElemInfo(e.desc)
- v := e.value
- p := toAddrPointer(&v, ei.isptr, ei.deref)
- n += ei.sizer(p, 1) // message, tag = 3 (size=1)
- }
- mu.Unlock()
- return n
-}
-
-// appendMessageSet marshals a XXX_InternalExtensions field in message set format (above)
-// to the end of byte slice b.
-func (u *marshalInfo) appendMessageSet(b []byte, ext *XXX_InternalExtensions, deterministic bool) ([]byte, error) {
- m, mu := ext.extensionsRead()
- if m == nil {
- return b, nil
- }
- mu.Lock()
- defer mu.Unlock()
-
- var err error
- var nerr nonFatal
-
- // Fast-path for common cases: zero or one extensions.
- // Don't bother sorting the keys.
- if len(m) <= 1 {
- for id, e := range m {
- b = append(b, 1<<3|WireStartGroup)
- b = append(b, 2<<3|WireVarint)
- b = appendVarint(b, uint64(id))
-
- if e.value == nil || e.desc == nil {
- // Extension is only in its encoded form.
- msgWithLen := skipVarint(e.enc) // skip old tag, but leave the length varint
- b = append(b, 3<<3|WireBytes)
- b = append(b, msgWithLen...)
- b = append(b, 1<<3|WireEndGroup)
- 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.
-
- ei := u.getExtElemInfo(e.desc)
- v := e.value
- p := toAddrPointer(&v, ei.isptr, ei.deref)
- b, err = ei.marshaler(b, p, 3<<3|WireBytes, deterministic)
- if !nerr.Merge(err) {
- return b, err
- }
- b = append(b, 1<<3|WireEndGroup)
- }
- return b, nerr.E
- }
-
- // Sort the keys to provide a deterministic encoding.
- keys := make([]int, 0, len(m))
- for k := range m {
- keys = append(keys, int(k))
- }
- sort.Ints(keys)
-
- for _, id := range keys {
- e := m[int32(id)]
- b = append(b, 1<<3|WireStartGroup)
- b = append(b, 2<<3|WireVarint)
- b = appendVarint(b, uint64(id))
-
- if e.value == nil || e.desc == nil {
- // Extension is only in its encoded form.
- msgWithLen := skipVarint(e.enc) // skip old tag, but leave the length varint
- b = append(b, 3<<3|WireBytes)
- b = append(b, msgWithLen...)
- b = append(b, 1<<3|WireEndGroup)
- 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.
-
- ei := u.getExtElemInfo(e.desc)
- v := e.value
- p := toAddrPointer(&v, ei.isptr, ei.deref)
- b, err = ei.marshaler(b, p, 3<<3|WireBytes, deterministic)
- b = append(b, 1<<3|WireEndGroup)
- if !nerr.Merge(err) {
- return b, err
- }
- }
- return b, nerr.E
-}
-
-// sizeV1Extensions computes the size of encoded data for a V1-API extension field.
-func (u *marshalInfo) sizeV1Extensions(m map[int32]Extension) int {
- if m == nil {
- return 0
- }
-
- n := 0
- 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.
-
- ei := u.getExtElemInfo(e.desc)
- v := e.value
- p := toAddrPointer(&v, ei.isptr, ei.deref)
- n += ei.sizer(p, ei.tagsize)
- }
- return n
-}
-
-// appendV1Extensions marshals a V1-API extension field to the end of byte slice b.
-func (u *marshalInfo) appendV1Extensions(b []byte, m map[int32]Extension, deterministic bool) ([]byte, error) {
- if m == nil {
- return b, nil
- }
-
- // Sort the keys to provide a deterministic encoding.
- keys := make([]int, 0, len(m))
- for k := range m {
- keys = append(keys, int(k))
- }
- sort.Ints(keys)
-
- var err error
- var nerr nonFatal
- for _, k := range keys {
- e := m[int32(k)]
- if e.value == nil || e.desc == nil {
- // Extension is only in its encoded form.
- b = append(b, 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.
-
- ei := u.getExtElemInfo(e.desc)
- v := e.value
- p := toAddrPointer(&v, ei.isptr, ei.deref)
- b, err = ei.marshaler(b, p, ei.wiretag, deterministic)
- if !nerr.Merge(err) {
- return b, err
- }
- }
- return b, nerr.E
-}
-
-// newMarshaler is the interface representing objects that can marshal themselves.
-//
-// This exists to support protoc-gen-go generated messages.
-// The proto package will stop type-asserting to this interface in the future.
-//
-// DO NOT DEPEND ON THIS.
-type newMarshaler interface {
- XXX_Size() int
- XXX_Marshal(b []byte, deterministic bool) ([]byte, error)
-}
-
-// Size returns the encoded size of a protocol buffer message.
-// This is the main entry point.
-func Size(pb Message) int {
- if m, ok := pb.(newMarshaler); ok {
- return m.XXX_Size()
- }
- if m, ok := pb.(Marshaler); ok {
- // If the message can marshal itself, let it do it, for compatibility.
- // NOTE: This is not efficient.
- b, _ := m.Marshal()
- return len(b)
- }
- // in case somehow we didn't generate the wrapper
- if pb == nil {
- return 0
- }
- var info InternalMessageInfo
- return info.Size(pb)
-}
-
-// Marshal takes a protocol buffer message
-// and encodes it into the wire format, returning the data.
-// This is the main entry point.
-func Marshal(pb Message) ([]byte, error) {
- if m, ok := pb.(newMarshaler); ok {
- siz := m.XXX_Size()
- b := make([]byte, 0, siz)
- return m.XXX_Marshal(b, false)
- }
- if m, ok := pb.(Marshaler); ok {
- // If the message can marshal itself, let it do it, for compatibility.
- // NOTE: This is not efficient.
- return m.Marshal()
- }
- // in case somehow we didn't generate the wrapper
- if pb == nil {
- return nil, ErrNil
- }
- var info InternalMessageInfo
- siz := info.Size(pb)
- b := make([]byte, 0, siz)
- return info.Marshal(b, pb, false)
-}
-
-// Marshal takes a protocol buffer message
-// and encodes it into the wire format, writing the result to the
-// Buffer.
-// This is an alternative entry point. It is not necessary to use
-// a Buffer for most applications.
-func (p *Buffer) Marshal(pb Message) error {
- var err error
- if m, ok := pb.(newMarshaler); ok {
- siz := m.XXX_Size()
- p.grow(siz) // make sure buf has enough capacity
- p.buf, err = m.XXX_Marshal(p.buf, p.deterministic)
- return err
- }
- if m, ok := pb.(Marshaler); ok {
- // If the message can marshal itself, let it do it, for compatibility.
- // NOTE: This is not efficient.
- b, err := m.Marshal()
- p.buf = append(p.buf, b...)
- return err
- }
- // in case somehow we didn't generate the wrapper
- if pb == nil {
- return ErrNil
- }
- var info InternalMessageInfo
- siz := info.Size(pb)
- p.grow(siz) // make sure buf has enough capacity
- p.buf, err = info.Marshal(p.buf, pb, p.deterministic)
- return err
-}
-
-// grow grows the buffer's capacity, if necessary, to guarantee space for
-// another n bytes. After grow(n), at least n bytes can be written to the
-// buffer without another allocation.
-func (p *Buffer) grow(n int) {
- need := len(p.buf) + n
- if need <= cap(p.buf) {
- return
- }
- newCap := len(p.buf) * 2
- if newCap < need {
- newCap = need
- }
- p.buf = append(make([]byte, 0, newCap), p.buf...)
-}
diff --git a/vendor/github.com/golang/protobuf/proto/table_merge.go b/vendor/github.com/golang/protobuf/proto/table_merge.go
deleted file mode 100644
index 5525def6a5..0000000000
--- a/vendor/github.com/golang/protobuf/proto/table_merge.go
+++ /dev/null
@@ -1,654 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2016 The Go Authors. All rights reserved.
-// https://github.com/golang/protobuf
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-//
-// * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-// * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-// * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-package proto
-
-import (
- "fmt"
- "reflect"
- "strings"
- "sync"
- "sync/atomic"
-)
-
-// Merge merges the src message into dst.
-// This assumes that dst and src of the same type and are non-nil.
-func (a *InternalMessageInfo) Merge(dst, src Message) {
- mi := atomicLoadMergeInfo(&a.merge)
- if mi == nil {
- mi = getMergeInfo(reflect.TypeOf(dst).Elem())
- atomicStoreMergeInfo(&a.merge, mi)
- }
- mi.merge(toPointer(&dst), toPointer(&src))
-}
-
-type mergeInfo struct {
- typ reflect.Type
-
- initialized int32 // 0: only typ is valid, 1: everything is valid
- lock sync.Mutex
-
- fields []mergeFieldInfo
- unrecognized field // Offset of XXX_unrecognized
-}
-
-type mergeFieldInfo struct {
- field field // Offset of field, guaranteed to be valid
-
- // isPointer reports whether the value in the field is a pointer.
- // This is true for the following situations:
- // * Pointer to struct
- // * Pointer to basic type (proto2 only)
- // * Slice (first value in slice header is a pointer)
- // * String (first value in string header is a pointer)
- isPointer bool
-
- // basicWidth reports the width of the field assuming that it is directly
- // embedded in the struct (as is the case for basic types in proto3).
- // The possible values are:
- // 0: invalid
- // 1: bool
- // 4: int32, uint32, float32
- // 8: int64, uint64, float64
- basicWidth int
-
- // Where dst and src are pointers to the types being merged.
- merge func(dst, src pointer)
-}
-
-var (
- mergeInfoMap = map[reflect.Type]*mergeInfo{}
- mergeInfoLock sync.Mutex
-)
-
-func getMergeInfo(t reflect.Type) *mergeInfo {
- mergeInfoLock.Lock()
- defer mergeInfoLock.Unlock()
- mi := mergeInfoMap[t]
- if mi == nil {
- mi = &mergeInfo{typ: t}
- mergeInfoMap[t] = mi
- }
- return mi
-}
-
-// merge merges src into dst assuming they are both of type *mi.typ.
-func (mi *mergeInfo) merge(dst, src pointer) {
- if dst.isNil() {
- panic("proto: nil destination")
- }
- if src.isNil() {
- return // Nothing to do.
- }
-
- if atomic.LoadInt32(&mi.initialized) == 0 {
- mi.computeMergeInfo()
- }
-
- for _, fi := range mi.fields {
- sfp := src.offset(fi.field)
-
- // As an optimization, we can avoid the merge function call cost
- // if we know for sure that the source will have no effect
- // by checking if it is the zero value.
- if unsafeAllowed {
- if fi.isPointer && sfp.getPointer().isNil() { // Could be slice or string
- continue
- }
- if fi.basicWidth > 0 {
- switch {
- case fi.basicWidth == 1 && !*sfp.toBool():
- continue
- case fi.basicWidth == 4 && *sfp.toUint32() == 0:
- continue
- case fi.basicWidth == 8 && *sfp.toUint64() == 0:
- continue
- }
- }
- }
-
- dfp := dst.offset(fi.field)
- fi.merge(dfp, sfp)
- }
-
- // TODO: Make this faster?
- out := dst.asPointerTo(mi.typ).Elem()
- in := src.asPointerTo(mi.typ).Elem()
- if emIn, err := extendable(in.Addr().Interface()); err == nil {
- emOut, _ := extendable(out.Addr().Interface())
- mIn, muIn := emIn.extensionsRead()
- if mIn != nil {
- mOut := emOut.extensionsWrite()
- muIn.Lock()
- mergeExtension(mOut, mIn)
- muIn.Unlock()
- }
- }
-
- if mi.unrecognized.IsValid() {
- if b := *src.offset(mi.unrecognized).toBytes(); len(b) > 0 {
- *dst.offset(mi.unrecognized).toBytes() = append([]byte(nil), b...)
- }
- }
-}
-
-func (mi *mergeInfo) computeMergeInfo() {
- mi.lock.Lock()
- defer mi.lock.Unlock()
- if mi.initialized != 0 {
- return
- }
- t := mi.typ
- n := t.NumField()
-
- props := GetProperties(t)
- for i := 0; i < n; i++ {
- f := t.Field(i)
- if strings.HasPrefix(f.Name, "XXX_") {
- continue
- }
-
- mfi := mergeFieldInfo{field: toField(&f)}
- tf := f.Type
-
- // As an optimization, we can avoid the merge function call cost
- // if we know for sure that the source will have no effect
- // by checking if it is the zero value.
- if unsafeAllowed {
- switch tf.Kind() {
- case reflect.Ptr, reflect.Slice, reflect.String:
- // As a special case, we assume slices and strings are pointers
- // since we know that the first field in the SliceSlice or
- // StringHeader is a data pointer.
- mfi.isPointer = true
- case reflect.Bool:
- mfi.basicWidth = 1
- case reflect.Int32, reflect.Uint32, reflect.Float32:
- mfi.basicWidth = 4
- case reflect.Int64, reflect.Uint64, reflect.Float64:
- mfi.basicWidth = 8
- }
- }
-
- // Unwrap tf to get at its most basic type.
- var isPointer, isSlice bool
- if tf.Kind() == reflect.Slice && tf.Elem().Kind() != reflect.Uint8 {
- isSlice = true
- tf = tf.Elem()
- }
- if tf.Kind() == reflect.Ptr {
- isPointer = true
- tf = tf.Elem()
- }
- if isPointer && isSlice && tf.Kind() != reflect.Struct {
- panic("both pointer and slice for basic type in " + tf.Name())
- }
-
- switch tf.Kind() {
- case reflect.Int32:
- switch {
- case isSlice: // E.g., []int32
- mfi.merge = func(dst, src pointer) {
- // NOTE: toInt32Slice is not defined (see pointer_reflect.go).
- /*
- sfsp := src.toInt32Slice()
- if *sfsp != nil {
- dfsp := dst.toInt32Slice()
- *dfsp = append(*dfsp, *sfsp...)
- if *dfsp == nil {
- *dfsp = []int64{}
- }
- }
- */
- sfs := src.getInt32Slice()
- if sfs != nil {
- dfs := dst.getInt32Slice()
- dfs = append(dfs, sfs...)
- if dfs == nil {
- dfs = []int32{}
- }
- dst.setInt32Slice(dfs)
- }
- }
- case isPointer: // E.g., *int32
- mfi.merge = func(dst, src pointer) {
- // NOTE: toInt32Ptr is not defined (see pointer_reflect.go).
- /*
- sfpp := src.toInt32Ptr()
- if *sfpp != nil {
- dfpp := dst.toInt32Ptr()
- if *dfpp == nil {
- *dfpp = Int32(**sfpp)
- } else {
- **dfpp = **sfpp
- }
- }
- */
- sfp := src.getInt32Ptr()
- if sfp != nil {
- dfp := dst.getInt32Ptr()
- if dfp == nil {
- dst.setInt32Ptr(*sfp)
- } else {
- *dfp = *sfp
- }
- }
- }
- default: // E.g., int32
- mfi.merge = func(dst, src pointer) {
- if v := *src.toInt32(); v != 0 {
- *dst.toInt32() = v
- }
- }
- }
- case reflect.Int64:
- switch {
- case isSlice: // E.g., []int64
- mfi.merge = func(dst, src pointer) {
- sfsp := src.toInt64Slice()
- if *sfsp != nil {
- dfsp := dst.toInt64Slice()
- *dfsp = append(*dfsp, *sfsp...)
- if *dfsp == nil {
- *dfsp = []int64{}
- }
- }
- }
- case isPointer: // E.g., *int64
- mfi.merge = func(dst, src pointer) {
- sfpp := src.toInt64Ptr()
- if *sfpp != nil {
- dfpp := dst.toInt64Ptr()
- if *dfpp == nil {
- *dfpp = Int64(**sfpp)
- } else {
- **dfpp = **sfpp
- }
- }
- }
- default: // E.g., int64
- mfi.merge = func(dst, src pointer) {
- if v := *src.toInt64(); v != 0 {
- *dst.toInt64() = v
- }
- }
- }
- case reflect.Uint32:
- switch {
- case isSlice: // E.g., []uint32
- mfi.merge = func(dst, src pointer) {
- sfsp := src.toUint32Slice()
- if *sfsp != nil {
- dfsp := dst.toUint32Slice()
- *dfsp = append(*dfsp, *sfsp...)
- if *dfsp == nil {
- *dfsp = []uint32{}
- }
- }
- }
- case isPointer: // E.g., *uint32
- mfi.merge = func(dst, src pointer) {
- sfpp := src.toUint32Ptr()
- if *sfpp != nil {
- dfpp := dst.toUint32Ptr()
- if *dfpp == nil {
- *dfpp = Uint32(**sfpp)
- } else {
- **dfpp = **sfpp
- }
- }
- }
- default: // E.g., uint32
- mfi.merge = func(dst, src pointer) {
- if v := *src.toUint32(); v != 0 {
- *dst.toUint32() = v
- }
- }
- }
- case reflect.Uint64:
- switch {
- case isSlice: // E.g., []uint64
- mfi.merge = func(dst, src pointer) {
- sfsp := src.toUint64Slice()
- if *sfsp != nil {
- dfsp := dst.toUint64Slice()
- *dfsp = append(*dfsp, *sfsp...)
- if *dfsp == nil {
- *dfsp = []uint64{}
- }
- }
- }
- case isPointer: // E.g., *uint64
- mfi.merge = func(dst, src pointer) {
- sfpp := src.toUint64Ptr()
- if *sfpp != nil {
- dfpp := dst.toUint64Ptr()
- if *dfpp == nil {
- *dfpp = Uint64(**sfpp)
- } else {
- **dfpp = **sfpp
- }
- }
- }
- default: // E.g., uint64
- mfi.merge = func(dst, src pointer) {
- if v := *src.toUint64(); v != 0 {
- *dst.toUint64() = v
- }
- }
- }
- case reflect.Float32:
- switch {
- case isSlice: // E.g., []float32
- mfi.merge = func(dst, src pointer) {
- sfsp := src.toFloat32Slice()
- if *sfsp != nil {
- dfsp := dst.toFloat32Slice()
- *dfsp = append(*dfsp, *sfsp...)
- if *dfsp == nil {
- *dfsp = []float32{}
- }
- }
- }
- case isPointer: // E.g., *float32
- mfi.merge = func(dst, src pointer) {
- sfpp := src.toFloat32Ptr()
- if *sfpp != nil {
- dfpp := dst.toFloat32Ptr()
- if *dfpp == nil {
- *dfpp = Float32(**sfpp)
- } else {
- **dfpp = **sfpp
- }
- }
- }
- default: // E.g., float32
- mfi.merge = func(dst, src pointer) {
- if v := *src.toFloat32(); v != 0 {
- *dst.toFloat32() = v
- }
- }
- }
- case reflect.Float64:
- switch {
- case isSlice: // E.g., []float64
- mfi.merge = func(dst, src pointer) {
- sfsp := src.toFloat64Slice()
- if *sfsp != nil {
- dfsp := dst.toFloat64Slice()
- *dfsp = append(*dfsp, *sfsp...)
- if *dfsp == nil {
- *dfsp = []float64{}
- }
- }
- }
- case isPointer: // E.g., *float64
- mfi.merge = func(dst, src pointer) {
- sfpp := src.toFloat64Ptr()
- if *sfpp != nil {
- dfpp := dst.toFloat64Ptr()
- if *dfpp == nil {
- *dfpp = Float64(**sfpp)
- } else {
- **dfpp = **sfpp
- }
- }
- }
- default: // E.g., float64
- mfi.merge = func(dst, src pointer) {
- if v := *src.toFloat64(); v != 0 {
- *dst.toFloat64() = v
- }
- }
- }
- case reflect.Bool:
- switch {
- case isSlice: // E.g., []bool
- mfi.merge = func(dst, src pointer) {
- sfsp := src.toBoolSlice()
- if *sfsp != nil {
- dfsp := dst.toBoolSlice()
- *dfsp = append(*dfsp, *sfsp...)
- if *dfsp == nil {
- *dfsp = []bool{}
- }
- }
- }
- case isPointer: // E.g., *bool
- mfi.merge = func(dst, src pointer) {
- sfpp := src.toBoolPtr()
- if *sfpp != nil {
- dfpp := dst.toBoolPtr()
- if *dfpp == nil {
- *dfpp = Bool(**sfpp)
- } else {
- **dfpp = **sfpp
- }
- }
- }
- default: // E.g., bool
- mfi.merge = func(dst, src pointer) {
- if v := *src.toBool(); v {
- *dst.toBool() = v
- }
- }
- }
- case reflect.String:
- switch {
- case isSlice: // E.g., []string
- mfi.merge = func(dst, src pointer) {
- sfsp := src.toStringSlice()
- if *sfsp != nil {
- dfsp := dst.toStringSlice()
- *dfsp = append(*dfsp, *sfsp...)
- if *dfsp == nil {
- *dfsp = []string{}
- }
- }
- }
- case isPointer: // E.g., *string
- mfi.merge = func(dst, src pointer) {
- sfpp := src.toStringPtr()
- if *sfpp != nil {
- dfpp := dst.toStringPtr()
- if *dfpp == nil {
- *dfpp = String(**sfpp)
- } else {
- **dfpp = **sfpp
- }
- }
- }
- default: // E.g., string
- mfi.merge = func(dst, src pointer) {
- if v := *src.toString(); v != "" {
- *dst.toString() = v
- }
- }
- }
- case reflect.Slice:
- isProto3 := props.Prop[i].proto3
- switch {
- case isPointer:
- panic("bad pointer in byte slice case in " + tf.Name())
- case tf.Elem().Kind() != reflect.Uint8:
- panic("bad element kind in byte slice case in " + tf.Name())
- case isSlice: // E.g., [][]byte
- mfi.merge = func(dst, src pointer) {
- sbsp := src.toBytesSlice()
- if *sbsp != nil {
- dbsp := dst.toBytesSlice()
- for _, sb := range *sbsp {
- if sb == nil {
- *dbsp = append(*dbsp, nil)
- } else {
- *dbsp = append(*dbsp, append([]byte{}, sb...))
- }
- }
- if *dbsp == nil {
- *dbsp = [][]byte{}
- }
- }
- }
- default: // E.g., []byte
- mfi.merge = func(dst, src pointer) {
- sbp := src.toBytes()
- if *sbp != nil {
- dbp := dst.toBytes()
- if !isProto3 || len(*sbp) > 0 {
- *dbp = append([]byte{}, *sbp...)
- }
- }
- }
- }
- case reflect.Struct:
- switch {
- case !isPointer:
- panic(fmt.Sprintf("message field %s without pointer", tf))
- case isSlice: // E.g., []*pb.T
- mi := getMergeInfo(tf)
- mfi.merge = func(dst, src pointer) {
- sps := src.getPointerSlice()
- if sps != nil {
- dps := dst.getPointerSlice()
- for _, sp := range sps {
- var dp pointer
- if !sp.isNil() {
- dp = valToPointer(reflect.New(tf))
- mi.merge(dp, sp)
- }
- dps = append(dps, dp)
- }
- if dps == nil {
- dps = []pointer{}
- }
- dst.setPointerSlice(dps)
- }
- }
- default: // E.g., *pb.T
- mi := getMergeInfo(tf)
- mfi.merge = func(dst, src pointer) {
- sp := src.getPointer()
- if !sp.isNil() {
- dp := dst.getPointer()
- if dp.isNil() {
- dp = valToPointer(reflect.New(tf))
- dst.setPointer(dp)
- }
- mi.merge(dp, sp)
- }
- }
- }
- case reflect.Map:
- switch {
- case isPointer || isSlice:
- panic("bad pointer or slice in map case in " + tf.Name())
- default: // E.g., map[K]V
- mfi.merge = func(dst, src pointer) {
- sm := src.asPointerTo(tf).Elem()
- if sm.Len() == 0 {
- return
- }
- dm := dst.asPointerTo(tf).Elem()
- if dm.IsNil() {
- dm.Set(reflect.MakeMap(tf))
- }
-
- switch tf.Elem().Kind() {
- case reflect.Ptr: // Proto struct (e.g., *T)
- for _, key := range sm.MapKeys() {
- val := sm.MapIndex(key)
- val = reflect.ValueOf(Clone(val.Interface().(Message)))
- dm.SetMapIndex(key, val)
- }
- case reflect.Slice: // E.g. Bytes type (e.g., []byte)
- for _, key := range sm.MapKeys() {
- val := sm.MapIndex(key)
- val = reflect.ValueOf(append([]byte{}, val.Bytes()...))
- dm.SetMapIndex(key, val)
- }
- default: // Basic type (e.g., string)
- for _, key := range sm.MapKeys() {
- val := sm.MapIndex(key)
- dm.SetMapIndex(key, val)
- }
- }
- }
- }
- case reflect.Interface:
- // Must be oneof field.
- switch {
- case isPointer || isSlice:
- panic("bad pointer or slice in interface case in " + tf.Name())
- default: // E.g., interface{}
- // TODO: Make this faster?
- mfi.merge = func(dst, src pointer) {
- su := src.asPointerTo(tf).Elem()
- if !su.IsNil() {
- du := dst.asPointerTo(tf).Elem()
- typ := su.Elem().Type()
- if du.IsNil() || du.Elem().Type() != typ {
- du.Set(reflect.New(typ.Elem())) // Initialize interface if empty
- }
- sv := su.Elem().Elem().Field(0)
- if sv.Kind() == reflect.Ptr && sv.IsNil() {
- return
- }
- dv := du.Elem().Elem().Field(0)
- if dv.Kind() == reflect.Ptr && dv.IsNil() {
- dv.Set(reflect.New(sv.Type().Elem())) // Initialize proto message if empty
- }
- switch sv.Type().Kind() {
- case reflect.Ptr: // Proto struct (e.g., *T)
- Merge(dv.Interface().(Message), sv.Interface().(Message))
- case reflect.Slice: // E.g. Bytes type (e.g., []byte)
- dv.Set(reflect.ValueOf(append([]byte{}, sv.Bytes()...)))
- default: // Basic type (e.g., string)
- dv.Set(sv)
- }
- }
- }
- }
- default:
- panic(fmt.Sprintf("merger not found for type:%s", tf))
- }
- mi.fields = append(mi.fields, mfi)
- }
-
- mi.unrecognized = invalidField
- if f, ok := t.FieldByName("XXX_unrecognized"); ok {
- if f.Type != reflect.TypeOf([]byte{}) {
- panic("expected XXX_unrecognized to be of type []byte")
- }
- mi.unrecognized = toField(&f)
- }
-
- atomic.StoreInt32(&mi.initialized, 1)
-}
diff --git a/vendor/github.com/golang/protobuf/proto/table_unmarshal.go b/vendor/github.com/golang/protobuf/proto/table_unmarshal.go
deleted file mode 100644
index acee2fc529..0000000000
--- a/vendor/github.com/golang/protobuf/proto/table_unmarshal.go
+++ /dev/null
@@ -1,2053 +0,0 @@
-// Go support for Protocol Buffers - Google's data interchange format
-//
-// Copyright 2016 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 (
- "errors"
- "fmt"
- "io"
- "math"
- "reflect"
- "strconv"
- "strings"
- "sync"
- "sync/atomic"
- "unicode/utf8"
-)
-
-// Unmarshal is the entry point from the generated .pb.go files.
-// This function is not intended to be used by non-generated code.
-// This function is not subject to any compatibility guarantee.
-// msg contains a pointer to a protocol buffer struct.
-// b is the data to be unmarshaled into the protocol buffer.
-// a is a pointer to a place to store cached unmarshal information.
-func (a *InternalMessageInfo) Unmarshal(msg Message, b []byte) error {
- // Load the unmarshal information for this message type.
- // The atomic load ensures memory consistency.
- u := atomicLoadUnmarshalInfo(&a.unmarshal)
- if u == nil {
- // Slow path: find unmarshal info for msg, update a with it.
- u = getUnmarshalInfo(reflect.TypeOf(msg).Elem())
- atomicStoreUnmarshalInfo(&a.unmarshal, u)
- }
- // Then do the unmarshaling.
- err := u.unmarshal(toPointer(&msg), b)
- return err
-}
-
-type unmarshalInfo struct {
- typ reflect.Type // type of the protobuf struct
-
- // 0 = only typ field is initialized
- // 1 = completely initialized
- initialized int32
- lock sync.Mutex // prevents double initialization
- dense []unmarshalFieldInfo // fields indexed by tag #
- sparse map[uint64]unmarshalFieldInfo // fields indexed by tag #
- reqFields []string // names of required fields
- reqMask uint64 // 1< 0 {
- // Read tag and wire type.
- // Special case 1 and 2 byte varints.
- var x uint64
- if b[0] < 128 {
- x = uint64(b[0])
- b = b[1:]
- } else if len(b) >= 2 && b[1] < 128 {
- x = uint64(b[0]&0x7f) + uint64(b[1])<<7
- b = b[2:]
- } else {
- var n int
- x, n = decodeVarint(b)
- if n == 0 {
- return io.ErrUnexpectedEOF
- }
- b = b[n:]
- }
- tag := x >> 3
- wire := int(x) & 7
-
- // Dispatch on the tag to one of the unmarshal* functions below.
- var f unmarshalFieldInfo
- if tag < uint64(len(u.dense)) {
- f = u.dense[tag]
- } else {
- f = u.sparse[tag]
- }
- if fn := f.unmarshal; fn != nil {
- var err error
- b, err = fn(b, m.offset(f.field), wire)
- if err == nil {
- reqMask |= f.reqMask
- continue
- }
- if r, ok := err.(*RequiredNotSetError); ok {
- // Remember this error, but keep parsing. We need to produce
- // a full parse even if a required field is missing.
- if errLater == nil {
- errLater = r
- }
- reqMask |= f.reqMask
- continue
- }
- if err != errInternalBadWireType {
- if err == errInvalidUTF8 {
- if errLater == nil {
- fullName := revProtoTypes[reflect.PtrTo(u.typ)] + "." + f.name
- errLater = &invalidUTF8Error{fullName}
- }
- continue
- }
- return err
- }
- // Fragments with bad wire type are treated as unknown fields.
- }
-
- // Unknown tag.
- if !u.unrecognized.IsValid() {
- // Don't keep unrecognized data; just skip it.
- var err error
- b, err = skipField(b, wire)
- if err != nil {
- return err
- }
- continue
- }
- // Keep unrecognized data around.
- // maybe in extensions, maybe in the unrecognized field.
- z := m.offset(u.unrecognized).toBytes()
- var emap map[int32]Extension
- var e Extension
- for _, r := range u.extensionRanges {
- if uint64(r.Start) <= tag && tag <= uint64(r.End) {
- if u.extensions.IsValid() {
- mp := m.offset(u.extensions).toExtensions()
- emap = mp.extensionsWrite()
- e = emap[int32(tag)]
- z = &e.enc
- break
- }
- if u.oldExtensions.IsValid() {
- p := m.offset(u.oldExtensions).toOldExtensions()
- emap = *p
- if emap == nil {
- emap = map[int32]Extension{}
- *p = emap
- }
- e = emap[int32(tag)]
- z = &e.enc
- break
- }
- panic("no extensions field available")
- }
- }
-
- // Use wire type to skip data.
- var err error
- b0 := b
- b, err = skipField(b, wire)
- if err != nil {
- return err
- }
- *z = encodeVarint(*z, tag<<3|uint64(wire))
- *z = append(*z, b0[:len(b0)-len(b)]...)
-
- if emap != nil {
- emap[int32(tag)] = e
- }
- }
- if reqMask != u.reqMask && errLater == nil {
- // A required field of this message is missing.
- for _, n := range u.reqFields {
- if reqMask&1 == 0 {
- errLater = &RequiredNotSetError{n}
- }
- reqMask >>= 1
- }
- }
- return errLater
-}
-
-// computeUnmarshalInfo fills in u with information for use
-// in unmarshaling protocol buffers of type u.typ.
-func (u *unmarshalInfo) computeUnmarshalInfo() {
- u.lock.Lock()
- defer u.lock.Unlock()
- if u.initialized != 0 {
- return
- }
- t := u.typ
- n := t.NumField()
-
- // Set up the "not found" value for the unrecognized byte buffer.
- // This is the default for proto3.
- u.unrecognized = invalidField
- u.extensions = invalidField
- u.oldExtensions = invalidField
-
- // List of the generated type and offset for each oneof field.
- type oneofField struct {
- ityp reflect.Type // interface type of oneof field
- field field // offset in containing message
- }
- var oneofFields []oneofField
-
- for i := 0; i < n; i++ {
- f := t.Field(i)
- if f.Name == "XXX_unrecognized" {
- // The byte slice used to hold unrecognized input is special.
- if f.Type != reflect.TypeOf(([]byte)(nil)) {
- panic("bad type for XXX_unrecognized field: " + f.Type.Name())
- }
- u.unrecognized = toField(&f)
- continue
- }
- if f.Name == "XXX_InternalExtensions" {
- // Ditto here.
- if f.Type != reflect.TypeOf(XXX_InternalExtensions{}) {
- panic("bad type for XXX_InternalExtensions field: " + f.Type.Name())
- }
- u.extensions = toField(&f)
- if f.Tag.Get("protobuf_messageset") == "1" {
- u.isMessageSet = true
- }
- continue
- }
- if f.Name == "XXX_extensions" {
- // An older form of the extensions field.
- if f.Type != reflect.TypeOf((map[int32]Extension)(nil)) {
- panic("bad type for XXX_extensions field: " + f.Type.Name())
- }
- u.oldExtensions = toField(&f)
- continue
- }
- if f.Name == "XXX_NoUnkeyedLiteral" || f.Name == "XXX_sizecache" {
- continue
- }
-
- oneof := f.Tag.Get("protobuf_oneof")
- if oneof != "" {
- oneofFields = append(oneofFields, oneofField{f.Type, toField(&f)})
- // The rest of oneof processing happens below.
- continue
- }
-
- tags := f.Tag.Get("protobuf")
- tagArray := strings.Split(tags, ",")
- if len(tagArray) < 2 {
- panic("protobuf tag not enough fields in " + t.Name() + "." + f.Name + ": " + tags)
- }
- tag, err := strconv.Atoi(tagArray[1])
- if err != nil {
- panic("protobuf tag field not an integer: " + tagArray[1])
- }
-
- name := ""
- for _, tag := range tagArray[3:] {
- if strings.HasPrefix(tag, "name=") {
- name = tag[5:]
- }
- }
-
- // Extract unmarshaling function from the field (its type and tags).
- unmarshal := fieldUnmarshaler(&f)
-
- // Required field?
- var reqMask uint64
- if tagArray[2] == "req" {
- bit := len(u.reqFields)
- u.reqFields = append(u.reqFields, name)
- reqMask = uint64(1) << uint(bit)
- // TODO: if we have more than 64 required fields, we end up
- // not verifying that all required fields are present.
- // Fix this, perhaps using a count of required fields?
- }
-
- // Store the info in the correct slot in the message.
- u.setTag(tag, toField(&f), unmarshal, reqMask, name)
- }
-
- // Find any types associated with oneof fields.
- var oneofImplementers []interface{}
- switch m := reflect.Zero(reflect.PtrTo(t)).Interface().(type) {
- case oneofFuncsIface:
- _, _, _, oneofImplementers = m.XXX_OneofFuncs()
- case oneofWrappersIface:
- oneofImplementers = m.XXX_OneofWrappers()
- }
- for _, v := range oneofImplementers {
- tptr := reflect.TypeOf(v) // *Msg_X
- typ := tptr.Elem() // Msg_X
-
- f := typ.Field(0) // oneof implementers have one field
- baseUnmarshal := fieldUnmarshaler(&f)
- tags := strings.Split(f.Tag.Get("protobuf"), ",")
- fieldNum, err := strconv.Atoi(tags[1])
- if err != nil {
- panic("protobuf tag field not an integer: " + tags[1])
- }
- var name string
- for _, tag := range tags {
- if strings.HasPrefix(tag, "name=") {
- name = strings.TrimPrefix(tag, "name=")
- break
- }
- }
-
- // Find the oneof field that this struct implements.
- // Might take O(n^2) to process all of the oneofs, but who cares.
- for _, of := range oneofFields {
- if tptr.Implements(of.ityp) {
- // We have found the corresponding interface for this struct.
- // That lets us know where this struct should be stored
- // when we encounter it during unmarshaling.
- unmarshal := makeUnmarshalOneof(typ, of.ityp, baseUnmarshal)
- u.setTag(fieldNum, of.field, unmarshal, 0, name)
- }
- }
-
- }
-
- // Get extension ranges, if any.
- fn := reflect.Zero(reflect.PtrTo(t)).MethodByName("ExtensionRangeArray")
- if fn.IsValid() {
- if !u.extensions.IsValid() && !u.oldExtensions.IsValid() {
- panic("a message with extensions, but no extensions field in " + t.Name())
- }
- u.extensionRanges = fn.Call(nil)[0].Interface().([]ExtensionRange)
- }
-
- // Explicitly disallow tag 0. This will ensure we flag an error
- // when decoding a buffer of all zeros. Without this code, we
- // would decode and skip an all-zero buffer of even length.
- // [0 0] is [tag=0/wiretype=varint varint-encoded-0].
- u.setTag(0, zeroField, func(b []byte, f pointer, w int) ([]byte, error) {
- return nil, fmt.Errorf("proto: %s: illegal tag 0 (wire type %d)", t, w)
- }, 0, "")
-
- // Set mask for required field check.
- u.reqMask = uint64(1)<= 0 && (tag < 16 || tag < 2*n) { // TODO: what are the right numbers here?
- for len(u.dense) <= tag {
- u.dense = append(u.dense, unmarshalFieldInfo{})
- }
- u.dense[tag] = i
- return
- }
- if u.sparse == nil {
- u.sparse = map[uint64]unmarshalFieldInfo{}
- }
- u.sparse[uint64(tag)] = i
-}
-
-// fieldUnmarshaler returns an unmarshaler for the given field.
-func fieldUnmarshaler(f *reflect.StructField) unmarshaler {
- if f.Type.Kind() == reflect.Map {
- return makeUnmarshalMap(f)
- }
- return typeUnmarshaler(f.Type, f.Tag.Get("protobuf"))
-}
-
-// typeUnmarshaler returns an unmarshaler for the given field type / field tag pair.
-func typeUnmarshaler(t reflect.Type, tags string) unmarshaler {
- tagArray := strings.Split(tags, ",")
- encoding := tagArray[0]
- name := "unknown"
- proto3 := false
- validateUTF8 := true
- for _, tag := range tagArray[3:] {
- if strings.HasPrefix(tag, "name=") {
- name = tag[5:]
- }
- if tag == "proto3" {
- proto3 = true
- }
- }
- validateUTF8 = validateUTF8 && proto3
-
- // Figure out packaging (pointer, slice, or both)
- slice := false
- pointer := false
- if t.Kind() == reflect.Slice && t.Elem().Kind() != reflect.Uint8 {
- slice = true
- t = t.Elem()
- }
- if t.Kind() == reflect.Ptr {
- pointer = true
- t = t.Elem()
- }
-
- // We'll never have both pointer and slice for basic types.
- if pointer && slice && t.Kind() != reflect.Struct {
- panic("both pointer and slice for basic type in " + t.Name())
- }
-
- switch t.Kind() {
- case reflect.Bool:
- if pointer {
- return unmarshalBoolPtr
- }
- if slice {
- return unmarshalBoolSlice
- }
- return unmarshalBoolValue
- case reflect.Int32:
- switch encoding {
- case "fixed32":
- if pointer {
- return unmarshalFixedS32Ptr
- }
- if slice {
- return unmarshalFixedS32Slice
- }
- return unmarshalFixedS32Value
- case "varint":
- // this could be int32 or enum
- if pointer {
- return unmarshalInt32Ptr
- }
- if slice {
- return unmarshalInt32Slice
- }
- return unmarshalInt32Value
- case "zigzag32":
- if pointer {
- return unmarshalSint32Ptr
- }
- if slice {
- return unmarshalSint32Slice
- }
- return unmarshalSint32Value
- }
- case reflect.Int64:
- switch encoding {
- case "fixed64":
- if pointer {
- return unmarshalFixedS64Ptr
- }
- if slice {
- return unmarshalFixedS64Slice
- }
- return unmarshalFixedS64Value
- case "varint":
- if pointer {
- return unmarshalInt64Ptr
- }
- if slice {
- return unmarshalInt64Slice
- }
- return unmarshalInt64Value
- case "zigzag64":
- if pointer {
- return unmarshalSint64Ptr
- }
- if slice {
- return unmarshalSint64Slice
- }
- return unmarshalSint64Value
- }
- case reflect.Uint32:
- switch encoding {
- case "fixed32":
- if pointer {
- return unmarshalFixed32Ptr
- }
- if slice {
- return unmarshalFixed32Slice
- }
- return unmarshalFixed32Value
- case "varint":
- if pointer {
- return unmarshalUint32Ptr
- }
- if slice {
- return unmarshalUint32Slice
- }
- return unmarshalUint32Value
- }
- case reflect.Uint64:
- switch encoding {
- case "fixed64":
- if pointer {
- return unmarshalFixed64Ptr
- }
- if slice {
- return unmarshalFixed64Slice
- }
- return unmarshalFixed64Value
- case "varint":
- if pointer {
- return unmarshalUint64Ptr
- }
- if slice {
- return unmarshalUint64Slice
- }
- return unmarshalUint64Value
- }
- case reflect.Float32:
- if pointer {
- return unmarshalFloat32Ptr
- }
- if slice {
- return unmarshalFloat32Slice
- }
- return unmarshalFloat32Value
- case reflect.Float64:
- if pointer {
- return unmarshalFloat64Ptr
- }
- if slice {
- return unmarshalFloat64Slice
- }
- return unmarshalFloat64Value
- case reflect.Map:
- panic("map type in typeUnmarshaler in " + t.Name())
- case reflect.Slice:
- if pointer {
- panic("bad pointer in slice case in " + t.Name())
- }
- if slice {
- return unmarshalBytesSlice
- }
- return unmarshalBytesValue
- case reflect.String:
- if validateUTF8 {
- if pointer {
- return unmarshalUTF8StringPtr
- }
- if slice {
- return unmarshalUTF8StringSlice
- }
- return unmarshalUTF8StringValue
- }
- if pointer {
- return unmarshalStringPtr
- }
- if slice {
- return unmarshalStringSlice
- }
- return unmarshalStringValue
- case reflect.Struct:
- // message or group field
- if !pointer {
- panic(fmt.Sprintf("message/group field %s:%s without pointer", t, encoding))
- }
- switch encoding {
- case "bytes":
- if slice {
- return makeUnmarshalMessageSlicePtr(getUnmarshalInfo(t), name)
- }
- return makeUnmarshalMessagePtr(getUnmarshalInfo(t), name)
- case "group":
- if slice {
- return makeUnmarshalGroupSlicePtr(getUnmarshalInfo(t), name)
- }
- return makeUnmarshalGroupPtr(getUnmarshalInfo(t), name)
- }
- }
- panic(fmt.Sprintf("unmarshaler not found type:%s encoding:%s", t, encoding))
-}
-
-// Below are all the unmarshalers for individual fields of various types.
-
-func unmarshalInt64Value(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireVarint {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- v := int64(x)
- *f.toInt64() = v
- return b, nil
-}
-
-func unmarshalInt64Ptr(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireVarint {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- v := int64(x)
- *f.toInt64Ptr() = &v
- return b, nil
-}
-
-func unmarshalInt64Slice(b []byte, f pointer, w int) ([]byte, error) {
- if w == WireBytes { // packed
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- if x > uint64(len(b)) {
- return nil, io.ErrUnexpectedEOF
- }
- res := b[x:]
- b = b[:x]
- for len(b) > 0 {
- x, n = decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- v := int64(x)
- s := f.toInt64Slice()
- *s = append(*s, v)
- }
- return res, nil
- }
- if w != WireVarint {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- v := int64(x)
- s := f.toInt64Slice()
- *s = append(*s, v)
- return b, nil
-}
-
-func unmarshalSint64Value(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireVarint {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- v := int64(x>>1) ^ int64(x)<<63>>63
- *f.toInt64() = v
- return b, nil
-}
-
-func unmarshalSint64Ptr(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireVarint {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- v := int64(x>>1) ^ int64(x)<<63>>63
- *f.toInt64Ptr() = &v
- return b, nil
-}
-
-func unmarshalSint64Slice(b []byte, f pointer, w int) ([]byte, error) {
- if w == WireBytes { // packed
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- if x > uint64(len(b)) {
- return nil, io.ErrUnexpectedEOF
- }
- res := b[x:]
- b = b[:x]
- for len(b) > 0 {
- x, n = decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- v := int64(x>>1) ^ int64(x)<<63>>63
- s := f.toInt64Slice()
- *s = append(*s, v)
- }
- return res, nil
- }
- if w != WireVarint {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- v := int64(x>>1) ^ int64(x)<<63>>63
- s := f.toInt64Slice()
- *s = append(*s, v)
- return b, nil
-}
-
-func unmarshalUint64Value(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireVarint {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- v := uint64(x)
- *f.toUint64() = v
- return b, nil
-}
-
-func unmarshalUint64Ptr(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireVarint {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- v := uint64(x)
- *f.toUint64Ptr() = &v
- return b, nil
-}
-
-func unmarshalUint64Slice(b []byte, f pointer, w int) ([]byte, error) {
- if w == WireBytes { // packed
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- if x > uint64(len(b)) {
- return nil, io.ErrUnexpectedEOF
- }
- res := b[x:]
- b = b[:x]
- for len(b) > 0 {
- x, n = decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- v := uint64(x)
- s := f.toUint64Slice()
- *s = append(*s, v)
- }
- return res, nil
- }
- if w != WireVarint {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- v := uint64(x)
- s := f.toUint64Slice()
- *s = append(*s, v)
- return b, nil
-}
-
-func unmarshalInt32Value(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireVarint {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- v := int32(x)
- *f.toInt32() = v
- return b, nil
-}
-
-func unmarshalInt32Ptr(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireVarint {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- v := int32(x)
- f.setInt32Ptr(v)
- return b, nil
-}
-
-func unmarshalInt32Slice(b []byte, f pointer, w int) ([]byte, error) {
- if w == WireBytes { // packed
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- if x > uint64(len(b)) {
- return nil, io.ErrUnexpectedEOF
- }
- res := b[x:]
- b = b[:x]
- for len(b) > 0 {
- x, n = decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- v := int32(x)
- f.appendInt32Slice(v)
- }
- return res, nil
- }
- if w != WireVarint {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- v := int32(x)
- f.appendInt32Slice(v)
- return b, nil
-}
-
-func unmarshalSint32Value(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireVarint {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- v := int32(x>>1) ^ int32(x)<<31>>31
- *f.toInt32() = v
- return b, nil
-}
-
-func unmarshalSint32Ptr(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireVarint {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- v := int32(x>>1) ^ int32(x)<<31>>31
- f.setInt32Ptr(v)
- return b, nil
-}
-
-func unmarshalSint32Slice(b []byte, f pointer, w int) ([]byte, error) {
- if w == WireBytes { // packed
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- if x > uint64(len(b)) {
- return nil, io.ErrUnexpectedEOF
- }
- res := b[x:]
- b = b[:x]
- for len(b) > 0 {
- x, n = decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- v := int32(x>>1) ^ int32(x)<<31>>31
- f.appendInt32Slice(v)
- }
- return res, nil
- }
- if w != WireVarint {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- v := int32(x>>1) ^ int32(x)<<31>>31
- f.appendInt32Slice(v)
- return b, nil
-}
-
-func unmarshalUint32Value(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireVarint {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- v := uint32(x)
- *f.toUint32() = v
- return b, nil
-}
-
-func unmarshalUint32Ptr(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireVarint {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- v := uint32(x)
- *f.toUint32Ptr() = &v
- return b, nil
-}
-
-func unmarshalUint32Slice(b []byte, f pointer, w int) ([]byte, error) {
- if w == WireBytes { // packed
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- if x > uint64(len(b)) {
- return nil, io.ErrUnexpectedEOF
- }
- res := b[x:]
- b = b[:x]
- for len(b) > 0 {
- x, n = decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- v := uint32(x)
- s := f.toUint32Slice()
- *s = append(*s, v)
- }
- return res, nil
- }
- if w != WireVarint {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- v := uint32(x)
- s := f.toUint32Slice()
- *s = append(*s, v)
- return b, nil
-}
-
-func unmarshalFixed64Value(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireFixed64 {
- return b, errInternalBadWireType
- }
- if len(b) < 8 {
- return nil, io.ErrUnexpectedEOF
- }
- v := uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56
- *f.toUint64() = v
- return b[8:], nil
-}
-
-func unmarshalFixed64Ptr(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireFixed64 {
- return b, errInternalBadWireType
- }
- if len(b) < 8 {
- return nil, io.ErrUnexpectedEOF
- }
- v := uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56
- *f.toUint64Ptr() = &v
- return b[8:], nil
-}
-
-func unmarshalFixed64Slice(b []byte, f pointer, w int) ([]byte, error) {
- if w == WireBytes { // packed
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- if x > uint64(len(b)) {
- return nil, io.ErrUnexpectedEOF
- }
- res := b[x:]
- b = b[:x]
- for len(b) > 0 {
- if len(b) < 8 {
- return nil, io.ErrUnexpectedEOF
- }
- v := uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56
- s := f.toUint64Slice()
- *s = append(*s, v)
- b = b[8:]
- }
- return res, nil
- }
- if w != WireFixed64 {
- return b, errInternalBadWireType
- }
- if len(b) < 8 {
- return nil, io.ErrUnexpectedEOF
- }
- v := uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56
- s := f.toUint64Slice()
- *s = append(*s, v)
- return b[8:], nil
-}
-
-func unmarshalFixedS64Value(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireFixed64 {
- return b, errInternalBadWireType
- }
- if len(b) < 8 {
- return nil, io.ErrUnexpectedEOF
- }
- v := int64(b[0]) | int64(b[1])<<8 | int64(b[2])<<16 | int64(b[3])<<24 | int64(b[4])<<32 | int64(b[5])<<40 | int64(b[6])<<48 | int64(b[7])<<56
- *f.toInt64() = v
- return b[8:], nil
-}
-
-func unmarshalFixedS64Ptr(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireFixed64 {
- return b, errInternalBadWireType
- }
- if len(b) < 8 {
- return nil, io.ErrUnexpectedEOF
- }
- v := int64(b[0]) | int64(b[1])<<8 | int64(b[2])<<16 | int64(b[3])<<24 | int64(b[4])<<32 | int64(b[5])<<40 | int64(b[6])<<48 | int64(b[7])<<56
- *f.toInt64Ptr() = &v
- return b[8:], nil
-}
-
-func unmarshalFixedS64Slice(b []byte, f pointer, w int) ([]byte, error) {
- if w == WireBytes { // packed
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- if x > uint64(len(b)) {
- return nil, io.ErrUnexpectedEOF
- }
- res := b[x:]
- b = b[:x]
- for len(b) > 0 {
- if len(b) < 8 {
- return nil, io.ErrUnexpectedEOF
- }
- v := int64(b[0]) | int64(b[1])<<8 | int64(b[2])<<16 | int64(b[3])<<24 | int64(b[4])<<32 | int64(b[5])<<40 | int64(b[6])<<48 | int64(b[7])<<56
- s := f.toInt64Slice()
- *s = append(*s, v)
- b = b[8:]
- }
- return res, nil
- }
- if w != WireFixed64 {
- return b, errInternalBadWireType
- }
- if len(b) < 8 {
- return nil, io.ErrUnexpectedEOF
- }
- v := int64(b[0]) | int64(b[1])<<8 | int64(b[2])<<16 | int64(b[3])<<24 | int64(b[4])<<32 | int64(b[5])<<40 | int64(b[6])<<48 | int64(b[7])<<56
- s := f.toInt64Slice()
- *s = append(*s, v)
- return b[8:], nil
-}
-
-func unmarshalFixed32Value(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireFixed32 {
- return b, errInternalBadWireType
- }
- if len(b) < 4 {
- return nil, io.ErrUnexpectedEOF
- }
- v := uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24
- *f.toUint32() = v
- return b[4:], nil
-}
-
-func unmarshalFixed32Ptr(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireFixed32 {
- return b, errInternalBadWireType
- }
- if len(b) < 4 {
- return nil, io.ErrUnexpectedEOF
- }
- v := uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24
- *f.toUint32Ptr() = &v
- return b[4:], nil
-}
-
-func unmarshalFixed32Slice(b []byte, f pointer, w int) ([]byte, error) {
- if w == WireBytes { // packed
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- if x > uint64(len(b)) {
- return nil, io.ErrUnexpectedEOF
- }
- res := b[x:]
- b = b[:x]
- for len(b) > 0 {
- if len(b) < 4 {
- return nil, io.ErrUnexpectedEOF
- }
- v := uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24
- s := f.toUint32Slice()
- *s = append(*s, v)
- b = b[4:]
- }
- return res, nil
- }
- if w != WireFixed32 {
- return b, errInternalBadWireType
- }
- if len(b) < 4 {
- return nil, io.ErrUnexpectedEOF
- }
- v := uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24
- s := f.toUint32Slice()
- *s = append(*s, v)
- return b[4:], nil
-}
-
-func unmarshalFixedS32Value(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireFixed32 {
- return b, errInternalBadWireType
- }
- if len(b) < 4 {
- return nil, io.ErrUnexpectedEOF
- }
- v := int32(b[0]) | int32(b[1])<<8 | int32(b[2])<<16 | int32(b[3])<<24
- *f.toInt32() = v
- return b[4:], nil
-}
-
-func unmarshalFixedS32Ptr(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireFixed32 {
- return b, errInternalBadWireType
- }
- if len(b) < 4 {
- return nil, io.ErrUnexpectedEOF
- }
- v := int32(b[0]) | int32(b[1])<<8 | int32(b[2])<<16 | int32(b[3])<<24
- f.setInt32Ptr(v)
- return b[4:], nil
-}
-
-func unmarshalFixedS32Slice(b []byte, f pointer, w int) ([]byte, error) {
- if w == WireBytes { // packed
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- if x > uint64(len(b)) {
- return nil, io.ErrUnexpectedEOF
- }
- res := b[x:]
- b = b[:x]
- for len(b) > 0 {
- if len(b) < 4 {
- return nil, io.ErrUnexpectedEOF
- }
- v := int32(b[0]) | int32(b[1])<<8 | int32(b[2])<<16 | int32(b[3])<<24
- f.appendInt32Slice(v)
- b = b[4:]
- }
- return res, nil
- }
- if w != WireFixed32 {
- return b, errInternalBadWireType
- }
- if len(b) < 4 {
- return nil, io.ErrUnexpectedEOF
- }
- v := int32(b[0]) | int32(b[1])<<8 | int32(b[2])<<16 | int32(b[3])<<24
- f.appendInt32Slice(v)
- return b[4:], nil
-}
-
-func unmarshalBoolValue(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireVarint {
- return b, errInternalBadWireType
- }
- // Note: any length varint is allowed, even though any sane
- // encoder will use one byte.
- // See https://github.com/golang/protobuf/issues/76
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- // TODO: check if x>1? Tests seem to indicate no.
- v := x != 0
- *f.toBool() = v
- return b[n:], nil
-}
-
-func unmarshalBoolPtr(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireVarint {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- v := x != 0
- *f.toBoolPtr() = &v
- return b[n:], nil
-}
-
-func unmarshalBoolSlice(b []byte, f pointer, w int) ([]byte, error) {
- if w == WireBytes { // packed
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- if x > uint64(len(b)) {
- return nil, io.ErrUnexpectedEOF
- }
- res := b[x:]
- b = b[:x]
- for len(b) > 0 {
- x, n = decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- v := x != 0
- s := f.toBoolSlice()
- *s = append(*s, v)
- b = b[n:]
- }
- return res, nil
- }
- if w != WireVarint {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- v := x != 0
- s := f.toBoolSlice()
- *s = append(*s, v)
- return b[n:], nil
-}
-
-func unmarshalFloat64Value(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireFixed64 {
- return b, errInternalBadWireType
- }
- if len(b) < 8 {
- return nil, io.ErrUnexpectedEOF
- }
- v := math.Float64frombits(uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56)
- *f.toFloat64() = v
- return b[8:], nil
-}
-
-func unmarshalFloat64Ptr(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireFixed64 {
- return b, errInternalBadWireType
- }
- if len(b) < 8 {
- return nil, io.ErrUnexpectedEOF
- }
- v := math.Float64frombits(uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56)
- *f.toFloat64Ptr() = &v
- return b[8:], nil
-}
-
-func unmarshalFloat64Slice(b []byte, f pointer, w int) ([]byte, error) {
- if w == WireBytes { // packed
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- if x > uint64(len(b)) {
- return nil, io.ErrUnexpectedEOF
- }
- res := b[x:]
- b = b[:x]
- for len(b) > 0 {
- if len(b) < 8 {
- return nil, io.ErrUnexpectedEOF
- }
- v := math.Float64frombits(uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56)
- s := f.toFloat64Slice()
- *s = append(*s, v)
- b = b[8:]
- }
- return res, nil
- }
- if w != WireFixed64 {
- return b, errInternalBadWireType
- }
- if len(b) < 8 {
- return nil, io.ErrUnexpectedEOF
- }
- v := math.Float64frombits(uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56)
- s := f.toFloat64Slice()
- *s = append(*s, v)
- return b[8:], nil
-}
-
-func unmarshalFloat32Value(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireFixed32 {
- return b, errInternalBadWireType
- }
- if len(b) < 4 {
- return nil, io.ErrUnexpectedEOF
- }
- v := math.Float32frombits(uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24)
- *f.toFloat32() = v
- return b[4:], nil
-}
-
-func unmarshalFloat32Ptr(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireFixed32 {
- return b, errInternalBadWireType
- }
- if len(b) < 4 {
- return nil, io.ErrUnexpectedEOF
- }
- v := math.Float32frombits(uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24)
- *f.toFloat32Ptr() = &v
- return b[4:], nil
-}
-
-func unmarshalFloat32Slice(b []byte, f pointer, w int) ([]byte, error) {
- if w == WireBytes { // packed
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- if x > uint64(len(b)) {
- return nil, io.ErrUnexpectedEOF
- }
- res := b[x:]
- b = b[:x]
- for len(b) > 0 {
- if len(b) < 4 {
- return nil, io.ErrUnexpectedEOF
- }
- v := math.Float32frombits(uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24)
- s := f.toFloat32Slice()
- *s = append(*s, v)
- b = b[4:]
- }
- return res, nil
- }
- if w != WireFixed32 {
- return b, errInternalBadWireType
- }
- if len(b) < 4 {
- return nil, io.ErrUnexpectedEOF
- }
- v := math.Float32frombits(uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24)
- s := f.toFloat32Slice()
- *s = append(*s, v)
- return b[4:], nil
-}
-
-func unmarshalStringValue(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireBytes {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- if x > uint64(len(b)) {
- return nil, io.ErrUnexpectedEOF
- }
- v := string(b[:x])
- *f.toString() = v
- return b[x:], nil
-}
-
-func unmarshalStringPtr(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireBytes {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- if x > uint64(len(b)) {
- return nil, io.ErrUnexpectedEOF
- }
- v := string(b[:x])
- *f.toStringPtr() = &v
- return b[x:], nil
-}
-
-func unmarshalStringSlice(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireBytes {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- if x > uint64(len(b)) {
- return nil, io.ErrUnexpectedEOF
- }
- v := string(b[:x])
- s := f.toStringSlice()
- *s = append(*s, v)
- return b[x:], nil
-}
-
-func unmarshalUTF8StringValue(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireBytes {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- if x > uint64(len(b)) {
- return nil, io.ErrUnexpectedEOF
- }
- v := string(b[:x])
- *f.toString() = v
- if !utf8.ValidString(v) {
- return b[x:], errInvalidUTF8
- }
- return b[x:], nil
-}
-
-func unmarshalUTF8StringPtr(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireBytes {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- if x > uint64(len(b)) {
- return nil, io.ErrUnexpectedEOF
- }
- v := string(b[:x])
- *f.toStringPtr() = &v
- if !utf8.ValidString(v) {
- return b[x:], errInvalidUTF8
- }
- return b[x:], nil
-}
-
-func unmarshalUTF8StringSlice(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireBytes {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- if x > uint64(len(b)) {
- return nil, io.ErrUnexpectedEOF
- }
- v := string(b[:x])
- s := f.toStringSlice()
- *s = append(*s, v)
- if !utf8.ValidString(v) {
- return b[x:], errInvalidUTF8
- }
- return b[x:], nil
-}
-
-var emptyBuf [0]byte
-
-func unmarshalBytesValue(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireBytes {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- if x > uint64(len(b)) {
- return nil, io.ErrUnexpectedEOF
- }
- // The use of append here is a trick which avoids the zeroing
- // that would be required if we used a make/copy pair.
- // We append to emptyBuf instead of nil because we want
- // a non-nil result even when the length is 0.
- v := append(emptyBuf[:], b[:x]...)
- *f.toBytes() = v
- return b[x:], nil
-}
-
-func unmarshalBytesSlice(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireBytes {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- if x > uint64(len(b)) {
- return nil, io.ErrUnexpectedEOF
- }
- v := append(emptyBuf[:], b[:x]...)
- s := f.toBytesSlice()
- *s = append(*s, v)
- return b[x:], nil
-}
-
-func makeUnmarshalMessagePtr(sub *unmarshalInfo, name string) unmarshaler {
- return func(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireBytes {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- if x > uint64(len(b)) {
- return nil, io.ErrUnexpectedEOF
- }
- // First read the message field to see if something is there.
- // The semantics of multiple submessages are weird. Instead of
- // the last one winning (as it is for all other fields), multiple
- // submessages are merged.
- v := f.getPointer()
- if v.isNil() {
- v = valToPointer(reflect.New(sub.typ))
- f.setPointer(v)
- }
- err := sub.unmarshal(v, b[:x])
- if err != nil {
- if r, ok := err.(*RequiredNotSetError); ok {
- r.field = name + "." + r.field
- } else {
- return nil, err
- }
- }
- return b[x:], err
- }
-}
-
-func makeUnmarshalMessageSlicePtr(sub *unmarshalInfo, name string) unmarshaler {
- return func(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireBytes {
- return b, errInternalBadWireType
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- if x > uint64(len(b)) {
- return nil, io.ErrUnexpectedEOF
- }
- v := valToPointer(reflect.New(sub.typ))
- err := sub.unmarshal(v, b[:x])
- if err != nil {
- if r, ok := err.(*RequiredNotSetError); ok {
- r.field = name + "." + r.field
- } else {
- return nil, err
- }
- }
- f.appendPointer(v)
- return b[x:], err
- }
-}
-
-func makeUnmarshalGroupPtr(sub *unmarshalInfo, name string) unmarshaler {
- return func(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireStartGroup {
- return b, errInternalBadWireType
- }
- x, y := findEndGroup(b)
- if x < 0 {
- return nil, io.ErrUnexpectedEOF
- }
- v := f.getPointer()
- if v.isNil() {
- v = valToPointer(reflect.New(sub.typ))
- f.setPointer(v)
- }
- err := sub.unmarshal(v, b[:x])
- if err != nil {
- if r, ok := err.(*RequiredNotSetError); ok {
- r.field = name + "." + r.field
- } else {
- return nil, err
- }
- }
- return b[y:], err
- }
-}
-
-func makeUnmarshalGroupSlicePtr(sub *unmarshalInfo, name string) unmarshaler {
- return func(b []byte, f pointer, w int) ([]byte, error) {
- if w != WireStartGroup {
- return b, errInternalBadWireType
- }
- x, y := findEndGroup(b)
- if x < 0 {
- return nil, io.ErrUnexpectedEOF
- }
- v := valToPointer(reflect.New(sub.typ))
- err := sub.unmarshal(v, b[:x])
- if err != nil {
- if r, ok := err.(*RequiredNotSetError); ok {
- r.field = name + "." + r.field
- } else {
- return nil, err
- }
- }
- f.appendPointer(v)
- return b[y:], err
- }
-}
-
-func makeUnmarshalMap(f *reflect.StructField) unmarshaler {
- t := f.Type
- kt := t.Key()
- vt := t.Elem()
- unmarshalKey := typeUnmarshaler(kt, f.Tag.Get("protobuf_key"))
- unmarshalVal := typeUnmarshaler(vt, f.Tag.Get("protobuf_val"))
- return func(b []byte, f pointer, w int) ([]byte, error) {
- // The map entry is a submessage. Figure out how big it is.
- if w != WireBytes {
- return nil, fmt.Errorf("proto: bad wiretype for map field: got %d want %d", w, WireBytes)
- }
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- b = b[n:]
- if x > uint64(len(b)) {
- return nil, io.ErrUnexpectedEOF
- }
- r := b[x:] // unused data to return
- b = b[:x] // data for map entry
-
- // Note: we could use #keys * #values ~= 200 functions
- // to do map decoding without reflection. Probably not worth it.
- // Maps will be somewhat slow. Oh well.
-
- // Read key and value from data.
- var nerr nonFatal
- k := reflect.New(kt)
- v := reflect.New(vt)
- for len(b) > 0 {
- x, n := decodeVarint(b)
- if n == 0 {
- return nil, io.ErrUnexpectedEOF
- }
- wire := int(x) & 7
- b = b[n:]
-
- var err error
- switch x >> 3 {
- case 1:
- b, err = unmarshalKey(b, valToPointer(k), wire)
- case 2:
- b, err = unmarshalVal(b, valToPointer(v), wire)
- default:
- err = errInternalBadWireType // skip unknown tag
- }
-
- if nerr.Merge(err) {
- continue
- }
- if err != errInternalBadWireType {
- return nil, err
- }
-
- // Skip past unknown fields.
- b, err = skipField(b, wire)
- if err != nil {
- return nil, err
- }
- }
-
- // Get map, allocate if needed.
- m := f.asPointerTo(t).Elem() // an addressable map[K]T
- if m.IsNil() {
- m.Set(reflect.MakeMap(t))
- }
-
- // Insert into map.
- m.SetMapIndex(k.Elem(), v.Elem())
-
- return r, nerr.E
- }
-}
-
-// makeUnmarshalOneof makes an unmarshaler for oneof fields.
-// for:
-// message Msg {
-// oneof F {
-// int64 X = 1;
-// float64 Y = 2;
-// }
-// }
-// typ is the type of the concrete entry for a oneof case (e.g. Msg_X).
-// ityp is the interface type of the oneof field (e.g. isMsg_F).
-// unmarshal is the unmarshaler for the base type of the oneof case (e.g. int64).
-// Note that this function will be called once for each case in the oneof.
-func makeUnmarshalOneof(typ, ityp reflect.Type, unmarshal unmarshaler) unmarshaler {
- sf := typ.Field(0)
- field0 := toField(&sf)
- return func(b []byte, f pointer, w int) ([]byte, error) {
- // Allocate holder for value.
- v := reflect.New(typ)
-
- // Unmarshal data into holder.
- // We unmarshal into the first field of the holder object.
- var err error
- var nerr nonFatal
- b, err = unmarshal(b, valToPointer(v).offset(field0), w)
- if !nerr.Merge(err) {
- return nil, err
- }
-
- // Write pointer to holder into target field.
- f.asPointerTo(ityp).Elem().Set(v)
-
- return b, nerr.E
- }
-}
-
-// Error used by decode internally.
-var errInternalBadWireType = errors.New("proto: internal error: bad wiretype")
-
-// skipField skips past a field of type wire and returns the remaining bytes.
-func skipField(b []byte, wire int) ([]byte, error) {
- switch wire {
- case WireVarint:
- _, k := decodeVarint(b)
- if k == 0 {
- return b, io.ErrUnexpectedEOF
- }
- b = b[k:]
- case WireFixed32:
- if len(b) < 4 {
- return b, io.ErrUnexpectedEOF
- }
- b = b[4:]
- case WireFixed64:
- if len(b) < 8 {
- return b, io.ErrUnexpectedEOF
- }
- b = b[8:]
- case WireBytes:
- m, k := decodeVarint(b)
- if k == 0 || uint64(len(b)-k) < m {
- return b, io.ErrUnexpectedEOF
- }
- b = b[uint64(k)+m:]
- case WireStartGroup:
- _, i := findEndGroup(b)
- if i == -1 {
- return b, io.ErrUnexpectedEOF
- }
- b = b[i:]
- default:
- return b, fmt.Errorf("proto: can't skip unknown wire type %d", wire)
- }
- return b, nil
-}
-
-// findEndGroup finds the index of the next EndGroup tag.
-// Groups may be nested, so the "next" EndGroup tag is the first
-// unpaired EndGroup.
-// findEndGroup returns the indexes of the start and end of the EndGroup tag.
-// Returns (-1,-1) if it can't find one.
-func findEndGroup(b []byte) (int, int) {
- depth := 1
- i := 0
- for {
- x, n := decodeVarint(b[i:])
- if n == 0 {
- return -1, -1
- }
- j := i
- i += n
- switch x & 7 {
- case WireVarint:
- _, k := decodeVarint(b[i:])
- if k == 0 {
- return -1, -1
- }
- i += k
- case WireFixed32:
- if len(b)-4 < i {
- return -1, -1
- }
- i += 4
- case WireFixed64:
- if len(b)-8 < i {
- return -1, -1
- }
- i += 8
- case WireBytes:
- m, k := decodeVarint(b[i:])
- if k == 0 {
- return -1, -1
- }
- i += k
- if uint64(len(b)-i) < m {
- return -1, -1
- }
- i += int(m)
- case WireStartGroup:
- depth++
- case WireEndGroup:
- depth--
- if depth == 0 {
- return j, i
- }
- default:
- return -1, -1
- }
- }
-}
-
-// encodeVarint appends a varint-encoded integer to b and returns the result.
-func encodeVarint(b []byte, x uint64) []byte {
- for x >= 1<<7 {
- b = append(b, byte(x&0x7f|0x80))
- x >>= 7
- }
- return append(b, byte(x))
-}
-
-// decodeVarint reads a varint-encoded integer from b.
-// Returns the decoded integer and the number of bytes read.
-// If there is an error, it returns 0,0.
-func decodeVarint(b []byte) (uint64, int) {
- var x, y uint64
- if len(b) == 0 {
- goto bad
- }
- x = uint64(b[0])
- if x < 0x80 {
- return x, 1
- }
- x -= 0x80
-
- if len(b) <= 1 {
- goto bad
- }
- y = uint64(b[1])
- x += y << 7
- if y < 0x80 {
- return x, 2
- }
- x -= 0x80 << 7
-
- if len(b) <= 2 {
- goto bad
- }
- y = uint64(b[2])
- x += y << 14
- if y < 0x80 {
- return x, 3
- }
- x -= 0x80 << 14
-
- if len(b) <= 3 {
- goto bad
- }
- y = uint64(b[3])
- x += y << 21
- if y < 0x80 {
- return x, 4
- }
- x -= 0x80 << 21
-
- if len(b) <= 4 {
- goto bad
- }
- y = uint64(b[4])
- x += y << 28
- if y < 0x80 {
- return x, 5
- }
- x -= 0x80 << 28
-
- if len(b) <= 5 {
- goto bad
- }
- y = uint64(b[5])
- x += y << 35
- if y < 0x80 {
- return x, 6
- }
- x -= 0x80 << 35
-
- if len(b) <= 6 {
- goto bad
- }
- y = uint64(b[6])
- x += y << 42
- if y < 0x80 {
- return x, 7
- }
- x -= 0x80 << 42
-
- if len(b) <= 7 {
- goto bad
- }
- y = uint64(b[7])
- x += y << 49
- if y < 0x80 {
- return x, 8
- }
- x -= 0x80 << 49
-
- if len(b) <= 8 {
- goto bad
- }
- y = uint64(b[8])
- x += y << 56
- if y < 0x80 {
- return x, 9
- }
- x -= 0x80 << 56
-
- if len(b) <= 9 {
- goto bad
- }
- y = uint64(b[9])
- x += y << 63
- if y < 2 {
- return x, 10
- }
-
-bad:
- return 0, 0
-}
diff --git a/vendor/github.com/golang/protobuf/proto/text.go b/vendor/github.com/golang/protobuf/proto/text.go
deleted file mode 100644
index 1aaee725b4..0000000000
--- a/vendor/github.com/golang/protobuf/proto/text.go
+++ /dev/null
@@ -1,843 +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"
- "errors"
- "fmt"
- "io"
- "log"
- "math"
- "reflect"
- "sort"
- "strings"
-)
-
-var (
- newline = []byte("\n")
- spaces = []byte(" ")
- endBraceNewline = []byte("}\n")
- backslashN = []byte{'\\', 'n'}
- backslashR = []byte{'\\', 'r'}
- backslashT = []byte{'\\', 't'}
- backslashDQ = []byte{'\\', '"'}
- backslashBS = []byte{'\\', '\\'}
- posInf = []byte("inf")
- negInf = []byte("-inf")
- nan = []byte("nan")
-)
-
-type writer interface {
- io.Writer
- WriteByte(byte) error
-}
-
-// textWriter is an io.Writer that tracks its indentation level.
-type textWriter struct {
- ind int
- complete bool // if the current position is a complete line
- compact bool // whether to write out as a one-liner
- w writer
-}
-
-func (w *textWriter) WriteString(s string) (n int, err error) {
- if !strings.Contains(s, "\n") {
- if !w.compact && w.complete {
- w.writeIndent()
- }
- w.complete = false
- return io.WriteString(w.w, s)
- }
- // WriteString is typically called without newlines, so this
- // codepath and its copy are rare. We copy to avoid
- // duplicating all of Write's logic here.
- return w.Write([]byte(s))
-}
-
-func (w *textWriter) Write(p []byte) (n int, err error) {
- newlines := bytes.Count(p, newline)
- if newlines == 0 {
- if !w.compact && w.complete {
- w.writeIndent()
- }
- n, err = w.w.Write(p)
- w.complete = false
- return n, err
- }
-
- frags := bytes.SplitN(p, newline, newlines+1)
- if w.compact {
- for i, frag := range frags {
- if i > 0 {
- if err := w.w.WriteByte(' '); err != nil {
- return n, err
- }
- n++
- }
- nn, err := w.w.Write(frag)
- n += nn
- if err != nil {
- return n, err
- }
- }
- return n, nil
- }
-
- for i, frag := range frags {
- if w.complete {
- w.writeIndent()
- }
- nn, err := w.w.Write(frag)
- n += nn
- if err != nil {
- return n, err
- }
- if i+1 < len(frags) {
- if err := w.w.WriteByte('\n'); err != nil {
- return n, err
- }
- n++
- }
- }
- w.complete = len(frags[len(frags)-1]) == 0
- return n, nil
-}
-
-func (w *textWriter) WriteByte(c byte) error {
- if w.compact && c == '\n' {
- c = ' '
- }
- if !w.compact && w.complete {
- w.writeIndent()
- }
- err := w.w.WriteByte(c)
- w.complete = c == '\n'
- return err
-}
-
-func (w *textWriter) indent() { w.ind++ }
-
-func (w *textWriter) unindent() {
- if w.ind == 0 {
- log.Print("proto: textWriter unindented too far")
- return
- }
- w.ind--
-}
-
-func writeName(w *textWriter, props *Properties) error {
- if _, err := w.WriteString(props.OrigName); err != nil {
- return err
- }
- if props.Wire != "group" {
- return w.WriteByte(':')
- }
- return nil
-}
-
-func requiresQuotes(u string) bool {
- // When type URL contains any characters except [0-9A-Za-z./\-]*, it must be quoted.
- for _, ch := range u {
- switch {
- case ch == '.' || ch == '/' || ch == '_':
- continue
- case '0' <= ch && ch <= '9':
- continue
- case 'A' <= ch && ch <= 'Z':
- continue
- case 'a' <= ch && ch <= 'z':
- continue
- default:
- return true
- }
- }
- return false
-}
-
-// isAny reports whether sv is a google.protobuf.Any message
-func isAny(sv reflect.Value) bool {
- type wkt interface {
- XXX_WellKnownType() string
- }
- t, ok := sv.Addr().Interface().(wkt)
- return ok && t.XXX_WellKnownType() == "Any"
-}
-
-// writeProto3Any writes an expanded google.protobuf.Any message.
-//
-// It returns (false, nil) if sv value can't be unmarshaled (e.g. because
-// required messages are not linked in).
-//
-// It returns (true, error) when sv was written in expanded format or an error
-// was encountered.
-func (tm *TextMarshaler) writeProto3Any(w *textWriter, sv reflect.Value) (bool, error) {
- turl := sv.FieldByName("TypeUrl")
- val := sv.FieldByName("Value")
- if !turl.IsValid() || !val.IsValid() {
- return true, errors.New("proto: invalid google.protobuf.Any message")
- }
-
- b, ok := val.Interface().([]byte)
- if !ok {
- return true, errors.New("proto: invalid google.protobuf.Any message")
- }
-
- parts := strings.Split(turl.String(), "/")
- mt := MessageType(parts[len(parts)-1])
- if mt == nil {
- return false, nil
- }
- m := reflect.New(mt.Elem())
- if err := Unmarshal(b, m.Interface().(Message)); err != nil {
- return false, nil
- }
- w.Write([]byte("["))
- u := turl.String()
- if requiresQuotes(u) {
- writeString(w, u)
- } else {
- w.Write([]byte(u))
- }
- if w.compact {
- w.Write([]byte("]:<"))
- } else {
- w.Write([]byte("]: <\n"))
- w.ind++
- }
- if err := tm.writeStruct(w, m.Elem()); err != nil {
- return true, err
- }
- if w.compact {
- w.Write([]byte("> "))
- } else {
- w.ind--
- w.Write([]byte(">\n"))
- }
- return true, nil
-}
-
-func (tm *TextMarshaler) writeStruct(w *textWriter, sv reflect.Value) error {
- if tm.ExpandAny && isAny(sv) {
- if canExpand, err := tm.writeProto3Any(w, sv); canExpand {
- return err
- }
- }
- st := sv.Type()
- sprops := GetProperties(st)
- for i := 0; i < sv.NumField(); i++ {
- fv := sv.Field(i)
- props := sprops.Prop[i]
- name := st.Field(i).Name
-
- if name == "XXX_NoUnkeyedLiteral" {
- continue
- }
-
- 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 := tm.writeAny(w, v, props); err != nil {
- return err
- }
- if err := w.WriteByte('\n'); err != nil {
- return err
- }
- }
- continue
- }
- if fv.Kind() == reflect.Map {
- // Map fields are rendered as a repeated struct with key/value fields.
- keys := fv.MapKeys()
- sort.Sort(mapKeys(keys))
- for _, key := range keys {
- val := fv.MapIndex(key)
- if err := writeName(w, props); err != nil {
- return err
- }
- if !w.compact {
- if err := w.WriteByte(' '); err != nil {
- return err
- }
- }
- // open struct
- if err := w.WriteByte('<'); err != nil {
- return err
- }
- if !w.compact {
- if err := w.WriteByte('\n'); err != nil {
- return err
- }
- }
- w.indent()
- // key
- if _, err := w.WriteString("key:"); err != nil {
- return err
- }
- if !w.compact {
- if err := w.WriteByte(' '); err != nil {
- return err
- }
- }
- if err := tm.writeAny(w, key, props.MapKeyProp); err != nil {
- return err
- }
- if err := w.WriteByte('\n'); err != nil {
- return err
- }
- // nil values aren't legal, but we can avoid panicking because of them.
- if val.Kind() != reflect.Ptr || !val.IsNil() {
- // value
- if _, err := w.WriteString("value:"); err != nil {
- return err
- }
- if !w.compact {
- if err := w.WriteByte(' '); err != nil {
- return err
- }
- }
- if err := tm.writeAny(w, val, props.MapValProp); err != nil {
- return err
- }
- if err := w.WriteByte('\n'); err != nil {
- return err
- }
- }
- // close struct
- w.unindent()
- if err := w.WriteByte('>'); err != nil {
- return err
- }
- if err := w.WriteByte('\n'); err != nil {
- return err
- }
- }
- continue
- }
- if props.proto3 && fv.Kind() == reflect.Slice && fv.Len() == 0 {
- // empty bytes field
- continue
- }
- if fv.Kind() != reflect.Ptr && fv.Kind() != reflect.Slice {
- // proto3 non-repeated scalar field; skip if zero value
- if isProto3Zero(fv) {
- continue
- }
- }
-
- if fv.Kind() == reflect.Interface {
- // Check if it is a oneof.
- if st.Field(i).Tag.Get("protobuf_oneof") != "" {
- // fv is nil, or holds a pointer to generated struct.
- // That generated struct has exactly one field,
- // which has a protobuf struct tag.
- if fv.IsNil() {
- continue
- }
- inner := fv.Elem().Elem() // interface -> *T -> T
- tag := inner.Type().Field(0).Tag.Get("protobuf")
- props = new(Properties) // Overwrite the outer props var, but not its pointee.
- props.Parse(tag)
- // Write the value in the oneof, not the oneof itself.
- fv = inner.Field(0)
-
- // Special case to cope with malformed messages gracefully:
- // If the value in the oneof is a nil pointer, don't panic
- // in writeAny.
- if fv.Kind() == reflect.Ptr && fv.IsNil() {
- // Use errors.New so writeAny won't render quotes.
- msg := errors.New("/* nil */")
- fv = reflect.ValueOf(&msg).Elem()
- }
- }
- }
-
- if err := writeName(w, props); err != nil {
- return err
- }
- if !w.compact {
- if err := w.WriteByte(' '); err != nil {
- return err
- }
- }
-
- // Enums have a String method, so writeAny will work fine.
- if err := tm.writeAny(w, fv, props); err != nil {
- return err
- }
-
- if err := w.WriteByte('\n'); err != nil {
- return err
- }
- }
-
- // Extensions (the XXX_extensions field).
- pv := sv.Addr()
- if _, err := extendable(pv.Interface()); err == nil {
- if err := tm.writeExtensions(w, pv); err != nil {
- return err
- }
- }
-
- return nil
-}
-
-// writeAny writes an arbitrary field.
-func (tm *TextMarshaler) writeAny(w *textWriter, v reflect.Value, props *Properties) error {
- v = reflect.Indirect(v)
-
- // Floats have special cases.
- if v.Kind() == reflect.Float32 || v.Kind() == reflect.Float64 {
- x := v.Float()
- var b []byte
- switch {
- case math.IsInf(x, 1):
- b = posInf
- case math.IsInf(x, -1):
- b = negInf
- case math.IsNaN(x):
- b = nan
- }
- if b != nil {
- _, err := w.Write(b)
- return err
- }
- // Other values are handled below.
- }
-
- // We don't attempt to serialise every possible value type; only those
- // that can occur in protocol buffers.
- switch v.Kind() {
- case reflect.Slice:
- // Should only be a []byte; repeated fields are handled in writeStruct.
- if err := writeString(w, string(v.Bytes())); err != nil {
- return err
- }
- case reflect.String:
- if err := writeString(w, v.String()); err != nil {
- return err
- }
- case reflect.Struct:
- // Required/optional group/message.
- var bra, ket byte = '<', '>'
- if props != nil && props.Wire == "group" {
- bra, ket = '{', '}'
- }
- if err := w.WriteByte(bra); err != nil {
- return err
- }
- if !w.compact {
- if err := w.WriteByte('\n'); err != nil {
- return err
- }
- }
- w.indent()
- if v.CanAddr() {
- // Calling v.Interface on a struct causes the reflect package to
- // copy the entire struct. This is racy with the new Marshaler
- // since we atomically update the XXX_sizecache.
- //
- // Thus, we retrieve a pointer to the struct if possible to avoid
- // a race since v.Interface on the pointer doesn't copy the struct.
- //
- // If v is not addressable, then we are not worried about a race
- // since it implies that the binary Marshaler cannot possibly be
- // mutating this value.
- v = v.Addr()
- }
- if etm, ok := v.Interface().(encoding.TextMarshaler); ok {
- text, err := etm.MarshalText()
- if err != nil {
- return err
- }
- if _, err = w.Write(text); err != nil {
- return err
- }
- } else {
- if v.Kind() == reflect.Ptr {
- v = v.Elem()
- }
- if err := tm.writeStruct(w, v); err != nil {
- return err
- }
- }
- w.unindent()
- if err := w.WriteByte(ket); err != nil {
- return err
- }
- default:
- _, err := fmt.Fprint(w, v.Interface())
- return err
- }
- return nil
-}
-
-// equivalent to C's isprint.
-func isprint(c byte) bool {
- return c >= 0x20 && c < 0x7f
-}
-
-// writeString writes a string in the protocol buffer text format.
-// It is similar to strconv.Quote except we don't use Go escape sequences,
-// we treat the string as a byte sequence, and we use octal escapes.
-// These differences are to maintain interoperability with the other
-// languages' implementations of the text format.
-func writeString(w *textWriter, s string) error {
- // use WriteByte here to get any needed indent
- if err := w.WriteByte('"'); err != nil {
- return err
- }
- // Loop over the bytes, not the runes.
- for i := 0; i < len(s); i++ {
- var err error
- // Divergence from C++: we don't escape apostrophes.
- // There's no need to escape them, and the C++ parser
- // copes with a naked apostrophe.
- switch c := s[i]; c {
- case '\n':
- _, err = w.w.Write(backslashN)
- case '\r':
- _, err = w.w.Write(backslashR)
- case '\t':
- _, err = w.w.Write(backslashT)
- case '"':
- _, err = w.w.Write(backslashDQ)
- case '\\':
- _, err = w.w.Write(backslashBS)
- default:
- if isprint(c) {
- err = w.w.WriteByte(c)
- } else {
- _, err = fmt.Fprintf(w.w, "\\%03o", c)
- }
- }
- if err != nil {
- return err
- }
- }
- return w.WriteByte('"')
-}
-
-func writeUnknownStruct(w *textWriter, data []byte) (err error) {
- if !w.compact {
- if _, err := fmt.Fprintf(w, "/* %d unknown bytes */\n", len(data)); err != nil {
- return err
- }
- }
- b := NewBuffer(data)
- for b.index < len(b.buf) {
- x, err := b.DecodeVarint()
- if err != nil {
- _, err := fmt.Fprintf(w, "/* %v */\n", err)
- return err
- }
- wire, tag := x&7, x>>3
- if wire == WireEndGroup {
- w.unindent()
- if _, err := w.Write(endBraceNewline); err != nil {
- return err
- }
- continue
- }
- if _, err := fmt.Fprint(w, tag); err != nil {
- return err
- }
- if wire != WireStartGroup {
- if err := w.WriteByte(':'); err != nil {
- return err
- }
- }
- if !w.compact || wire == WireStartGroup {
- if err := w.WriteByte(' '); err != nil {
- return err
- }
- }
- switch wire {
- case WireBytes:
- buf, e := b.DecodeRawBytes(false)
- if e == nil {
- _, err = fmt.Fprintf(w, "%q", buf)
- } else {
- _, err = fmt.Fprintf(w, "/* %v */", e)
- }
- case WireFixed32:
- x, err = b.DecodeFixed32()
- err = writeUnknownInt(w, x, err)
- case WireFixed64:
- x, err = b.DecodeFixed64()
- err = writeUnknownInt(w, x, err)
- case WireStartGroup:
- err = w.WriteByte('{')
- w.indent()
- case WireVarint:
- x, err = b.DecodeVarint()
- err = writeUnknownInt(w, x, err)
- default:
- _, err = fmt.Fprintf(w, "/* unknown wire type %d */", wire)
- }
- if err != nil {
- return err
- }
- if err = w.WriteByte('\n'); err != nil {
- return err
- }
- }
- return nil
-}
-
-func writeUnknownInt(w *textWriter, x uint64, err error) error {
- if err == nil {
- _, err = fmt.Fprint(w, x)
- } else {
- _, err = fmt.Fprintf(w, "/* %v */", err)
- }
- return err
-}
-
-type int32Slice []int32
-
-func (s int32Slice) Len() int { return len(s) }
-func (s int32Slice) Less(i, j int) bool { return s[i] < s[j] }
-func (s int32Slice) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
-
-// writeExtensions writes all the extensions in pv.
-// pv is assumed to be a pointer to a protocol message struct that is extendable.
-func (tm *TextMarshaler) writeExtensions(w *textWriter, pv reflect.Value) error {
- emap := extensionMaps[pv.Type().Elem()]
- ep, _ := extendable(pv.Interface())
-
- // Order the extensions by ID.
- // This isn't strictly necessary, but it will give us
- // canonical output, which will also make testing easier.
- m, mu := ep.extensionsRead()
- if m == nil {
- return nil
- }
- mu.Lock()
- ids := make([]int32, 0, len(m))
- for id := range m {
- ids = append(ids, id)
- }
- sort.Sort(int32Slice(ids))
- mu.Unlock()
-
- for _, extNum := range ids {
- ext := m[extNum]
- var desc *ExtensionDesc
- if emap != nil {
- desc = emap[extNum]
- }
- if desc == nil {
- // Unknown extension.
- if err := writeUnknownStruct(w, ext.enc); err != nil {
- return err
- }
- continue
- }
-
- pb, err := GetExtension(ep, desc)
- if err != nil {
- return fmt.Errorf("failed getting extension: %v", err)
- }
-
- // Repeated extensions will appear as a slice.
- if !desc.repeated() {
- if err := tm.writeExtension(w, desc.Name, pb); err != nil {
- return err
- }
- } else {
- v := reflect.ValueOf(pb)
- for i := 0; i < v.Len(); i++ {
- if err := tm.writeExtension(w, desc.Name, v.Index(i).Interface()); err != nil {
- return err
- }
- }
- }
- }
- return nil
-}
-
-func (tm *TextMarshaler) writeExtension(w *textWriter, name string, pb interface{}) error {
- if _, err := fmt.Fprintf(w, "[%s]:", name); err != nil {
- return err
- }
- if !w.compact {
- if err := w.WriteByte(' '); err != nil {
- return err
- }
- }
- if err := tm.writeAny(w, reflect.ValueOf(pb), nil); err != nil {
- return err
- }
- if err := w.WriteByte('\n'); err != nil {
- return err
- }
- return nil
-}
-
-func (w *textWriter) writeIndent() {
- if !w.complete {
- return
- }
- remain := w.ind * 2
- for remain > 0 {
- n := remain
- if n > len(spaces) {
- n = len(spaces)
- }
- w.w.Write(spaces[:n])
- remain -= n
- }
- w.complete = false
-}
-
-// TextMarshaler is a configurable text format marshaler.
-type TextMarshaler struct {
- Compact bool // use compact text format (one line).
- ExpandAny bool // expand google.protobuf.Any messages of known types
-}
-
-// Marshal writes a given protocol buffer in text format.
-// The only errors returned are from w.
-func (tm *TextMarshaler) Marshal(w io.Writer, pb Message) error {
- val := reflect.ValueOf(pb)
- if pb == nil || val.IsNil() {
- w.Write([]byte(""))
- return nil
- }
- var bw *bufio.Writer
- ww, ok := w.(writer)
- if !ok {
- bw = bufio.NewWriter(w)
- ww = bw
- }
- aw := &textWriter{
- w: ww,
- complete: true,
- compact: tm.Compact,
- }
-
- if etm, ok := pb.(encoding.TextMarshaler); ok {
- text, err := etm.MarshalText()
- if err != nil {
- return err
- }
- if _, err = aw.Write(text); err != nil {
- return err
- }
- if bw != nil {
- return bw.Flush()
- }
- return nil
- }
- // Dereference the received pointer so we don't have outer < and >.
- v := reflect.Indirect(val)
- if err := tm.writeStruct(aw, v); err != nil {
- return err
- }
- if bw != nil {
- return bw.Flush()
- }
- return nil
-}
-
-// Text is the same as Marshal, but returns the string directly.
-func (tm *TextMarshaler) Text(pb Message) string {
- var buf bytes.Buffer
- tm.Marshal(&buf, pb)
- return buf.String()
-}
-
-var (
- defaultTextMarshaler = TextMarshaler{}
- compactTextMarshaler = TextMarshaler{Compact: true}
-)
-
-// TODO: consider removing some of the Marshal functions below.
-
-// MarshalText writes a given protocol buffer in text format.
-// The only errors returned are from w.
-func MarshalText(w io.Writer, pb Message) error { return defaultTextMarshaler.Marshal(w, pb) }
-
-// MarshalTextString is the same as MarshalText, but returns the string directly.
-func MarshalTextString(pb Message) string { return defaultTextMarshaler.Text(pb) }
-
-// CompactText writes a given protocol buffer in compact text format (one line).
-func CompactText(w io.Writer, pb Message) error { return compactTextMarshaler.Marshal(w, pb) }
-
-// CompactTextString is the same as CompactText, but returns the string directly.
-func CompactTextString(pb Message) string { return compactTextMarshaler.Text(pb) }
diff --git a/vendor/github.com/golang/protobuf/proto/text_parser.go b/vendor/github.com/golang/protobuf/proto/text_parser.go
deleted file mode 100644
index bb55a3af27..0000000000
--- a/vendor/github.com/golang/protobuf/proto/text_parser.go
+++ /dev/null
@@ -1,880 +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"
-)
-
-// Error string emitted when deserializing Any and fields are already set
-const anyRepeatedlyUnpacked = "Any message unpacked multiple times, or %q already set"
-
-type ParseError struct {
- Message string
- Line int // 1-based line number
- Offset int // 0-based byte offset from start of input
-}
-
-func (p *ParseError) Error() string {
- if p.Line == 1 {
- // show offset only for first line
- return fmt.Sprintf("line 1.%d: %v", p.Offset, p.Message)
- }
- return fmt.Sprintf("line %d: %v", p.Line, p.Message)
-}
-
-type token struct {
- value string
- err *ParseError
- line int // line number
- offset int // byte number from start of input, not start of line
- unquoted string // the unquoted version of value, if it was a quoted string
-}
-
-func (t *token) String() string {
- if t.err == nil {
- return fmt.Sprintf("%q (line=%d, offset=%d)", t.value, t.line, t.offset)
- }
- return fmt.Sprintf("parse error: %v", t.err)
-}
-
-type textParser struct {
- s string // remaining input
- done bool // whether the parsing is finished (success or error)
- backed bool // whether back() was called
- offset, line int
- cur token
-}
-
-func newTextParser(s string) *textParser {
- p := new(textParser)
- p.s = s
- p.line = 1
- p.cur.line = 1
- return p
-}
-
-func (p *textParser) errorf(format string, a ...interface{}) *ParseError {
- pe := &ParseError{fmt.Sprintf(format, a...), p.cur.line, p.cur.offset}
- p.cur.err = pe
- p.done = true
- return pe
-}
-
-// Numbers and identifiers are matched by [-+._A-Za-z0-9]
-func isIdentOrNumberChar(c byte) bool {
- switch {
- case 'A' <= c && c <= 'Z', 'a' <= c && c <= 'z':
- return true
- case '0' <= c && c <= '9':
- return true
- }
- switch c {
- case '-', '+', '.', '_':
- return true
- }
- return false
-}
-
-func isWhitespace(c byte) bool {
- switch c {
- case ' ', '\t', '\n', '\r':
- return true
- }
- return false
-}
-
-func isQuote(c byte) bool {
- switch c {
- case '"', '\'':
- return true
- }
- return false
-}
-
-func (p *textParser) skipWhitespace() {
- i := 0
- for i < len(p.s) && (isWhitespace(p.s[i]) || p.s[i] == '#') {
- if p.s[i] == '#' {
- // comment; skip to end of line or input
- for i < len(p.s) && p.s[i] != '\n' {
- i++
- }
- if i == len(p.s) {
- break
- }
- }
- if p.s[i] == '\n' {
- p.line++
- }
- i++
- }
- p.offset += i
- p.s = p.s[i:len(p.s)]
- if len(p.s) == 0 {
- p.done = true
- }
-}
-
-func (p *textParser) advance() {
- // Skip whitespace
- p.skipWhitespace()
- if p.done {
- return
- }
-
- // Start of non-whitespace
- p.cur.err = nil
- p.cur.offset, p.cur.line = p.offset, p.line
- p.cur.unquoted = ""
- switch p.s[0] {
- case '<', '>', '{', '}', ':', '[', ']', ';', ',', '/':
- // Single symbol
- p.cur.value, p.s = p.s[0:1], p.s[1:len(p.s)]
- case '"', '\'':
- // Quoted string
- i := 1
- for i < len(p.s) && p.s[i] != p.s[0] && p.s[i] != '\n' {
- if p.s[i] == '\\' && i+1 < len(p.s) {
- // skip escaped char
- i++
- }
- i++
- }
- if i >= len(p.s) || p.s[i] != p.s[0] {
- p.errorf("unmatched quote")
- return
- }
- unq, err := unquoteC(p.s[1:i], rune(p.s[0]))
- if err != nil {
- p.errorf("invalid quoted string %s: %v", p.s[0:i+1], err)
- return
- }
- p.cur.value, p.s = p.s[0:i+1], p.s[i+1:len(p.s)]
- p.cur.unquoted = unq
- default:
- i := 0
- for i < len(p.s) && isIdentOrNumberChar(p.s[i]) {
- i++
- }
- if i == 0 {
- p.errorf("unexpected byte %#x", p.s[0])
- return
- }
- p.cur.value, p.s = p.s[0:i], p.s[i:len(p.s)]
- }
- p.offset += len(p.cur.value)
-}
-
-var (
- errBadUTF8 = errors.New("proto: bad UTF-8")
-)
-
-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':
- if len(s) < 2 {
- return "", "", fmt.Errorf(`\%c requires 2 following digits`, r)
- }
- ss := string(r) + s[:2]
- s = s[2:]
- i, err := strconv.ParseUint(ss, 8, 8)
- if err != nil {
- return "", "", fmt.Errorf(`\%s contains non-octal digits`, ss)
- }
- return string([]byte{byte(i)}), s, nil
- case 'x', 'X', 'u', 'U':
- var n int
- switch r {
- case 'x', 'X':
- n = 2
- case 'u':
- n = 4
- case 'U':
- n = 8
- }
- if len(s) < n {
- return "", "", fmt.Errorf(`\%c requires %d following digits`, r, n)
- }
- ss := s[:n]
- s = s[n:]
- i, err := strconv.ParseUint(ss, 16, 64)
- if err != nil {
- return "", "", fmt.Errorf(`\%c%s contains non-hexadecimal digits`, r, ss)
- }
- if r == 'x' || r == 'X' {
- return string([]byte{byte(i)}), s, nil
- }
- if i > utf8.MaxRune {
- return "", "", fmt.Errorf(`\%c%s is not a valid Unicode code point`, r, ss)
- }
- return string(i), s, nil
- }
- return "", "", fmt.Errorf(`unknown escape \%c`, r)
-}
-
-// Back off the parser by one token. Can only be done between calls to next().
-// It makes the next advance() a no-op.
-func (p *textParser) back() { p.backed = true }
-
-// Advances the parser and returns the new current token.
-func (p *textParser) next() *token {
- if p.backed || p.done {
- p.backed = false
- return &p.cur
- }
- p.advance()
- if p.done {
- p.cur.value = ""
- } else if len(p.cur.value) > 0 && isQuote(p.cur.value[0]) {
- // Look for multiple quoted strings separated by whitespace,
- // and concatenate them.
- cat := p.cur
- for {
- p.skipWhitespace()
- if p.done || !isQuote(p.s[0]) {
- break
- }
- p.advance()
- if p.cur.err != nil {
- return &p.cur
- }
- cat.value += " " + p.cur.value
- cat.unquoted += p.cur.unquoted
- }
- p.done = false // parser may have seen EOF, but we want to return cat
- p.cur = cat
- }
- return &p.cur
-}
-
-func (p *textParser) consumeToken(s string) error {
- tok := p.next()
- if tok.err != nil {
- return tok.err
- }
- if tok.value != s {
- p.back()
- return p.errorf("expected %q, found %q", s, tok.value)
- }
- return nil
-}
-
-// Return a RequiredNotSetError indicating which required field was not set.
-func (p *textParser) missingRequiredFieldError(sv reflect.Value) *RequiredNotSetError {
- st := sv.Type()
- sprops := GetProperties(st)
- for i := 0; i < st.NumField(); i++ {
- if !isNil(sv.Field(i)) {
- continue
- }
-
- props := sprops.Prop[i]
- if props.Required {
- return &RequiredNotSetError{fmt.Sprintf("%v.%v", st, props.OrigName)}
- }
- }
- return &RequiredNotSetError{fmt.Sprintf("%v.", st)} // should not happen
-}
-
-// Returns the index in the struct for the named field, as well as the parsed tag properties.
-func structFieldByName(sprops *StructProperties, name string) (int, *Properties, bool) {
- i, ok := sprops.decoderOrigNames[name]
- if ok {
- return i, sprops.Prop[i], true
- }
- return -1, nil, false
-}
-
-// Consume a ':' from the input stream (if the next token is a colon),
-// returning an error if a colon is needed but not present.
-func (p *textParser) checkForColon(props *Properties, typ reflect.Type) *ParseError {
- tok := p.next()
- if tok.err != nil {
- return tok.err
- }
- if tok.value != ":" {
- // Colon is optional when the field is a group or message.
- needColon := true
- switch props.Wire {
- case "group":
- needColon = false
- case "bytes":
- // A "bytes" field is either a message, a string, or a repeated field;
- // those three become *T, *string and []T respectively, so we can check for
- // this field being a pointer to a non-string.
- if typ.Kind() == reflect.Ptr {
- // *T or *string
- if typ.Elem().Kind() == reflect.String {
- break
- }
- } else if typ.Kind() == reflect.Slice {
- // []T or []*T
- if typ.Elem().Kind() != reflect.Ptr {
- break
- }
- } else if typ.Kind() == reflect.String {
- // The proto3 exception is for a string field,
- // which requires a colon.
- break
- }
- needColon = false
- }
- if needColon {
- return p.errorf("expected ':', found %q", tok.value)
- }
- p.back()
- }
- return nil
-}
-
-func (p *textParser) readStruct(sv reflect.Value, terminator string) error {
- st := sv.Type()
- sprops := GetProperties(st)
- reqCount := sprops.reqCount
- var reqFieldErr error
- fieldSet := make(map[string]bool)
- // A struct is a sequence of "name: value", terminated by one of
- // '>' or '}', or the end of the input. A name may also be
- // "[extension]" or "[type/url]".
- //
- // The whole struct can also be an expanded Any message, like:
- // [type/url] < ... struct contents ... >
- for {
- tok := p.next()
- if tok.err != nil {
- return tok.err
- }
- if tok.value == terminator {
- break
- }
- if tok.value == "[" {
- // Looks like an extension or an Any.
- //
- // TODO: Check whether we need to handle
- // namespace rooted names (e.g. ".something.Foo").
- extName, err := p.consumeExtName()
- if err != nil {
- return err
- }
-
- if s := strings.LastIndex(extName, "/"); s >= 0 {
- // If it contains a slash, it's an Any type URL.
- messageName := extName[s+1:]
- mt := MessageType(messageName)
- if mt == nil {
- return p.errorf("unrecognized message %q in google.protobuf.Any", messageName)
- }
- tok = p.next()
- if tok.err != nil {
- return tok.err
- }
- // consume an optional colon
- if tok.value == ":" {
- tok = p.next()
- if tok.err != nil {
- return tok.err
- }
- }
- var terminator string
- switch tok.value {
- case "<":
- terminator = ">"
- case "{":
- terminator = "}"
- default:
- return p.errorf("expected '{' or '<', found %q", tok.value)
- }
- v := reflect.New(mt.Elem())
- if pe := p.readStruct(v.Elem(), terminator); pe != nil {
- return pe
- }
- b, err := Marshal(v.Interface().(Message))
- if err != nil {
- return p.errorf("failed to marshal message of type %q: %v", messageName, err)
- }
- if fieldSet["type_url"] {
- return p.errorf(anyRepeatedlyUnpacked, "type_url")
- }
- if fieldSet["value"] {
- return p.errorf(anyRepeatedlyUnpacked, "value")
- }
- sv.FieldByName("TypeUrl").SetString(extName)
- sv.FieldByName("Value").SetBytes(b)
- fieldSet["type_url"] = true
- fieldSet["value"] = true
- continue
- }
-
- var desc *ExtensionDesc
- // This could be faster, but it's functional.
- // TODO: Do something smarter than a linear scan.
- for _, d := range RegisteredExtensions(reflect.New(st).Interface().(Message)) {
- if d.Name == extName {
- desc = d
- break
- }
- }
- if desc == nil {
- return p.errorf("unrecognized extension %q", extName)
- }
-
- props := &Properties{}
- props.Parse(desc.Tag)
-
- typ := reflect.TypeOf(desc.ExtensionType)
- if err := p.checkForColon(props, typ); err != nil {
- return err
- }
-
- rep := desc.repeated()
-
- // Read the extension structure, and set it in
- // the value we're constructing.
- var ext reflect.Value
- if !rep {
- ext = reflect.New(typ).Elem()
- } else {
- ext = reflect.New(typ.Elem()).Elem()
- }
- if err := p.readAny(ext, props); err != nil {
- if _, ok := err.(*RequiredNotSetError); !ok {
- return err
- }
- reqFieldErr = err
- }
- ep := sv.Addr().Interface().(Message)
- if !rep {
- SetExtension(ep, desc, ext.Interface())
- } else {
- old, err := GetExtension(ep, desc)
- var sl reflect.Value
- if err == nil {
- sl = reflect.ValueOf(old) // existing slice
- } else {
- sl = reflect.MakeSlice(typ, 0, 1)
- }
- sl = reflect.Append(sl, ext)
- SetExtension(ep, desc, sl.Interface())
- }
- if err := p.consumeOptionalSeparator(); err != nil {
- return err
- }
- continue
- }
-
- // This is a normal, non-extension field.
- name := tok.value
- var dst reflect.Value
- fi, props, ok := structFieldByName(sprops, name)
- if ok {
- dst = sv.Field(fi)
- } else if oop, ok := sprops.OneofTypes[name]; ok {
- // It is a oneof.
- props = oop.Prop
- nv := reflect.New(oop.Type.Elem())
- dst = nv.Elem().Field(0)
- field := sv.Field(oop.Field)
- if !field.IsNil() {
- return p.errorf("field '%s' would overwrite already parsed oneof '%s'", name, sv.Type().Field(oop.Field).Name)
- }
- field.Set(nv)
- }
- if !dst.IsValid() {
- return p.errorf("unknown field name %q in %v", name, st)
- }
-
- if dst.Kind() == reflect.Map {
- // Consume any colon.
- if err := p.checkForColon(props, dst.Type()); err != nil {
- return err
- }
-
- // Construct the map if it doesn't already exist.
- if dst.IsNil() {
- dst.Set(reflect.MakeMap(dst.Type()))
- }
- key := reflect.New(dst.Type().Key()).Elem()
- val := reflect.New(dst.Type().Elem()).Elem()
-
- // The map entry should be this sequence of tokens:
- // < key : KEY value : VALUE >
- // However, implementations may omit key or value, and technically
- // we should support them in any order. See b/28924776 for a time
- // this went wrong.
-
- tok := p.next()
- var terminator string
- switch tok.value {
- case "<":
- terminator = ">"
- case "{":
- terminator = "}"
- default:
- return p.errorf("expected '{' or '<', found %q", tok.value)
- }
- for {
- tok := p.next()
- if tok.err != nil {
- return tok.err
- }
- if tok.value == terminator {
- break
- }
- switch tok.value {
- case "key":
- if err := p.consumeToken(":"); err != nil {
- return err
- }
- if err := p.readAny(key, props.MapKeyProp); err != nil {
- return err
- }
- if err := p.consumeOptionalSeparator(); err != nil {
- return err
- }
- case "value":
- if err := p.checkForColon(props.MapValProp, dst.Type().Elem()); err != nil {
- return err
- }
- if err := p.readAny(val, props.MapValProp); err != nil {
- return err
- }
- if err := p.consumeOptionalSeparator(); err != nil {
- return err
- }
- default:
- p.back()
- return p.errorf(`expected "key", "value", or %q, found %q`, terminator, tok.value)
- }
- }
-
- dst.SetMapIndex(key, val)
- continue
- }
-
- // Check that it's not already set if it's not a repeated field.
- if !props.Repeated && fieldSet[name] {
- return p.errorf("non-repeated field %q was repeated", name)
- }
-
- if err := p.checkForColon(props, dst.Type()); err != nil {
- return err
- }
-
- // Parse into the field.
- fieldSet[name] = true
- if err := p.readAny(dst, props); err != nil {
- if _, ok := err.(*RequiredNotSetError); !ok {
- return err
- }
- reqFieldErr = err
- }
- if props.Required {
- reqCount--
- }
-
- if err := p.consumeOptionalSeparator(); err != nil {
- return err
- }
-
- }
-
- if reqCount > 0 {
- return p.missingRequiredFieldError(sv)
- }
- return reqFieldErr
-}
-
-// consumeExtName consumes extension name or expanded Any type URL and the
-// following ']'. It returns the name or URL consumed.
-func (p *textParser) consumeExtName() (string, error) {
- tok := p.next()
- if tok.err != nil {
- return "", tok.err
- }
-
- // If extension name or type url is quoted, it's a single token.
- if len(tok.value) > 2 && isQuote(tok.value[0]) && tok.value[len(tok.value)-1] == tok.value[0] {
- name, err := unquoteC(tok.value[1:len(tok.value)-1], rune(tok.value[0]))
- if err != nil {
- return "", err
- }
- return name, p.consumeToken("]")
- }
-
- // Consume everything up to "]"
- var parts []string
- for tok.value != "]" {
- parts = append(parts, tok.value)
- tok = p.next()
- if tok.err != nil {
- return "", p.errorf("unrecognized type_url or extension name: %s", tok.err)
- }
- if p.done && tok.value != "]" {
- return "", p.errorf("unclosed type_url or extension name")
- }
- }
- return strings.Join(parts, ""), nil
-}
-
-// consumeOptionalSeparator consumes an optional semicolon or comma.
-// It is used in readStruct to provide backward compatibility.
-func (p *textParser) consumeOptionalSeparator() error {
- tok := p.next()
- if tok.err != nil {
- return tok.err
- }
- if tok.value != ";" && tok.value != "," {
- p.back()
- }
- return nil
-}
-
-func (p *textParser) readAny(v reflect.Value, props *Properties) error {
- tok := p.next()
- if tok.err != nil {
- return tok.err
- }
- if tok.value == "" {
- return p.errorf("unexpected EOF")
- }
-
- switch fv := v; fv.Kind() {
- case reflect.Slice:
- at := v.Type()
- if at.Elem().Kind() == reflect.Uint8 {
- // Special case for []byte
- if tok.value[0] != '"' && tok.value[0] != '\'' {
- // Deliberately written out here, as the error after
- // this switch statement would write "invalid []byte: ...",
- // which is not as user-friendly.
- return p.errorf("invalid string: %v", tok.value)
- }
- bytes := []byte(tok.unquoted)
- fv.Set(reflect.ValueOf(bytes))
- return nil
- }
- // Repeated field.
- if tok.value == "[" {
- // Repeated field with list notation, like [1,2,3].
- for {
- fv.Set(reflect.Append(fv, reflect.New(at.Elem()).Elem()))
- err := p.readAny(fv.Index(fv.Len()-1), props)
- if err != nil {
- return err
- }
- tok := p.next()
- if tok.err != nil {
- return tok.err
- }
- if tok.value == "]" {
- break
- }
- if tok.value != "," {
- return p.errorf("Expected ']' or ',' found %q", tok.value)
- }
- }
- return nil
- }
- // One value of the repeated field.
- p.back()
- fv.Set(reflect.Append(fv, reflect.New(at.Elem()).Elem()))
- return p.readAny(fv.Index(fv.Len()-1), props)
- case reflect.Bool:
- // true/1/t/True or false/f/0/False.
- switch tok.value {
- case "true", "1", "t", "True":
- fv.SetBool(true)
- return nil
- case "false", "0", "f", "False":
- fv.SetBool(false)
- return nil
- }
- case reflect.Float32, reflect.Float64:
- v := tok.value
- // Ignore 'f' for compatibility with output generated by C++, but don't
- // remove 'f' when the value is "-inf" or "inf".
- if strings.HasSuffix(v, "f") && tok.value != "-inf" && tok.value != "inf" {
- v = v[:len(v)-1]
- }
- if f, err := strconv.ParseFloat(v, fv.Type().Bits()); err == nil {
- fv.SetFloat(f)
- return nil
- }
- case reflect.Int32:
- if x, err := strconv.ParseInt(tok.value, 0, 32); err == nil {
- fv.SetInt(x)
- return nil
- }
-
- if len(props.Enum) == 0 {
- break
- }
- m, ok := enumValueMaps[props.Enum]
- if !ok {
- break
- }
- x, ok := m[tok.value]
- if !ok {
- break
- }
- fv.SetInt(int64(x))
- return nil
- case reflect.Int64:
- if x, err := strconv.ParseInt(tok.value, 0, 64); err == nil {
- fv.SetInt(x)
- return nil
- }
-
- case reflect.Ptr:
- // A basic field (indirected through pointer), or a repeated message/group
- p.back()
- fv.Set(reflect.New(fv.Type().Elem()))
- return p.readAny(fv.Elem(), props)
- case reflect.String:
- if tok.value[0] == '"' || tok.value[0] == '\'' {
- fv.SetString(tok.unquoted)
- return nil
- }
- case reflect.Struct:
- var terminator string
- switch tok.value {
- case "{":
- terminator = "}"
- case "<":
- terminator = ">"
- default:
- return p.errorf("expected '{' or '<', found %q", tok.value)
- }
- // TODO: Handle nested messages which implement encoding.TextUnmarshaler.
- return p.readStruct(fv, terminator)
- case reflect.Uint32:
- if x, err := strconv.ParseUint(tok.value, 0, 32); err == nil {
- fv.SetUint(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 {
- return um.UnmarshalText([]byte(s))
- }
- pb.Reset()
- v := reflect.ValueOf(pb)
- return newTextParser(s).readStruct(v.Elem(), "")
-}
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/descriptor/descriptor.pb.go b/vendor/github.com/golang/protobuf/protoc-gen-go/descriptor/descriptor.pb.go
deleted file mode 100644
index 1ded05bbe7..0000000000
--- a/vendor/github.com/golang/protobuf/protoc-gen-go/descriptor/descriptor.pb.go
+++ /dev/null
@@ -1,2887 +0,0 @@
-// Code generated by protoc-gen-go. DO NOT EDIT.
-// source: google/protobuf/descriptor.proto
-
-package descriptor
-
-import (
- fmt "fmt"
- proto "github.com/golang/protobuf/proto"
- math "math"
-)
-
-// Reference imports to suppress errors if they are not otherwise used.
-var _ = proto.Marshal
-var _ = fmt.Errorf
-var _ = math.Inf
-
-// This is a compile-time assertion to ensure that this generated file
-// is compatible with the proto package it is being compiled against.
-// A compilation error at this line likely means your copy of the
-// proto package needs to be updated.
-const _ = proto.ProtoPackageIsVersion3 // please upgrade the proto package
-
-type FieldDescriptorProto_Type int32
-
-const (
- // 0 is reserved for errors.
- // Order is weird for historical reasons.
- FieldDescriptorProto_TYPE_DOUBLE FieldDescriptorProto_Type = 1
- FieldDescriptorProto_TYPE_FLOAT FieldDescriptorProto_Type = 2
- // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT64 if
- // negative values are likely.
- FieldDescriptorProto_TYPE_INT64 FieldDescriptorProto_Type = 3
- FieldDescriptorProto_TYPE_UINT64 FieldDescriptorProto_Type = 4
- // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT32 if
- // negative values are likely.
- FieldDescriptorProto_TYPE_INT32 FieldDescriptorProto_Type = 5
- FieldDescriptorProto_TYPE_FIXED64 FieldDescriptorProto_Type = 6
- FieldDescriptorProto_TYPE_FIXED32 FieldDescriptorProto_Type = 7
- FieldDescriptorProto_TYPE_BOOL FieldDescriptorProto_Type = 8
- FieldDescriptorProto_TYPE_STRING FieldDescriptorProto_Type = 9
- // Tag-delimited aggregate.
- // Group type is deprecated and not supported in proto3. However, Proto3
- // implementations should still be able to parse the group wire format and
- // treat group fields as unknown fields.
- FieldDescriptorProto_TYPE_GROUP FieldDescriptorProto_Type = 10
- FieldDescriptorProto_TYPE_MESSAGE FieldDescriptorProto_Type = 11
- // New in version 2.
- FieldDescriptorProto_TYPE_BYTES FieldDescriptorProto_Type = 12
- FieldDescriptorProto_TYPE_UINT32 FieldDescriptorProto_Type = 13
- FieldDescriptorProto_TYPE_ENUM FieldDescriptorProto_Type = 14
- FieldDescriptorProto_TYPE_SFIXED32 FieldDescriptorProto_Type = 15
- FieldDescriptorProto_TYPE_SFIXED64 FieldDescriptorProto_Type = 16
- FieldDescriptorProto_TYPE_SINT32 FieldDescriptorProto_Type = 17
- FieldDescriptorProto_TYPE_SINT64 FieldDescriptorProto_Type = 18
-)
-
-var FieldDescriptorProto_Type_name = map[int32]string{
- 1: "TYPE_DOUBLE",
- 2: "TYPE_FLOAT",
- 3: "TYPE_INT64",
- 4: "TYPE_UINT64",
- 5: "TYPE_INT32",
- 6: "TYPE_FIXED64",
- 7: "TYPE_FIXED32",
- 8: "TYPE_BOOL",
- 9: "TYPE_STRING",
- 10: "TYPE_GROUP",
- 11: "TYPE_MESSAGE",
- 12: "TYPE_BYTES",
- 13: "TYPE_UINT32",
- 14: "TYPE_ENUM",
- 15: "TYPE_SFIXED32",
- 16: "TYPE_SFIXED64",
- 17: "TYPE_SINT32",
- 18: "TYPE_SINT64",
-}
-
-var FieldDescriptorProto_Type_value = map[string]int32{
- "TYPE_DOUBLE": 1,
- "TYPE_FLOAT": 2,
- "TYPE_INT64": 3,
- "TYPE_UINT64": 4,
- "TYPE_INT32": 5,
- "TYPE_FIXED64": 6,
- "TYPE_FIXED32": 7,
- "TYPE_BOOL": 8,
- "TYPE_STRING": 9,
- "TYPE_GROUP": 10,
- "TYPE_MESSAGE": 11,
- "TYPE_BYTES": 12,
- "TYPE_UINT32": 13,
- "TYPE_ENUM": 14,
- "TYPE_SFIXED32": 15,
- "TYPE_SFIXED64": 16,
- "TYPE_SINT32": 17,
- "TYPE_SINT64": 18,
-}
-
-func (x FieldDescriptorProto_Type) Enum() *FieldDescriptorProto_Type {
- p := new(FieldDescriptorProto_Type)
- *p = x
- return p
-}
-
-func (x FieldDescriptorProto_Type) String() string {
- return proto.EnumName(FieldDescriptorProto_Type_name, int32(x))
-}
-
-func (x *FieldDescriptorProto_Type) UnmarshalJSON(data []byte) error {
- value, err := proto.UnmarshalJSONEnum(FieldDescriptorProto_Type_value, data, "FieldDescriptorProto_Type")
- if err != nil {
- return err
- }
- *x = FieldDescriptorProto_Type(value)
- return nil
-}
-
-func (FieldDescriptorProto_Type) EnumDescriptor() ([]byte, []int) {
- return fileDescriptor_e5baabe45344a177, []int{4, 0}
-}
-
-type FieldDescriptorProto_Label int32
-
-const (
- // 0 is reserved for errors
- FieldDescriptorProto_LABEL_OPTIONAL FieldDescriptorProto_Label = 1
- FieldDescriptorProto_LABEL_REQUIRED FieldDescriptorProto_Label = 2
- FieldDescriptorProto_LABEL_REPEATED FieldDescriptorProto_Label = 3
-)
-
-var FieldDescriptorProto_Label_name = map[int32]string{
- 1: "LABEL_OPTIONAL",
- 2: "LABEL_REQUIRED",
- 3: "LABEL_REPEATED",
-}
-
-var FieldDescriptorProto_Label_value = map[string]int32{
- "LABEL_OPTIONAL": 1,
- "LABEL_REQUIRED": 2,
- "LABEL_REPEATED": 3,
-}
-
-func (x FieldDescriptorProto_Label) Enum() *FieldDescriptorProto_Label {
- p := new(FieldDescriptorProto_Label)
- *p = x
- return p
-}
-
-func (x FieldDescriptorProto_Label) String() string {
- return proto.EnumName(FieldDescriptorProto_Label_name, int32(x))
-}
-
-func (x *FieldDescriptorProto_Label) UnmarshalJSON(data []byte) error {
- value, err := proto.UnmarshalJSONEnum(FieldDescriptorProto_Label_value, data, "FieldDescriptorProto_Label")
- if err != nil {
- return err
- }
- *x = FieldDescriptorProto_Label(value)
- return nil
-}
-
-func (FieldDescriptorProto_Label) EnumDescriptor() ([]byte, []int) {
- return fileDescriptor_e5baabe45344a177, []int{4, 1}
-}
-
-// Generated classes can be optimized for speed or code size.
-type FileOptions_OptimizeMode int32
-
-const (
- FileOptions_SPEED FileOptions_OptimizeMode = 1
- // etc.
- FileOptions_CODE_SIZE FileOptions_OptimizeMode = 2
- FileOptions_LITE_RUNTIME FileOptions_OptimizeMode = 3
-)
-
-var FileOptions_OptimizeMode_name = map[int32]string{
- 1: "SPEED",
- 2: "CODE_SIZE",
- 3: "LITE_RUNTIME",
-}
-
-var FileOptions_OptimizeMode_value = map[string]int32{
- "SPEED": 1,
- "CODE_SIZE": 2,
- "LITE_RUNTIME": 3,
-}
-
-func (x FileOptions_OptimizeMode) Enum() *FileOptions_OptimizeMode {
- p := new(FileOptions_OptimizeMode)
- *p = x
- return p
-}
-
-func (x FileOptions_OptimizeMode) String() string {
- return proto.EnumName(FileOptions_OptimizeMode_name, int32(x))
-}
-
-func (x *FileOptions_OptimizeMode) UnmarshalJSON(data []byte) error {
- value, err := proto.UnmarshalJSONEnum(FileOptions_OptimizeMode_value, data, "FileOptions_OptimizeMode")
- if err != nil {
- return err
- }
- *x = FileOptions_OptimizeMode(value)
- return nil
-}
-
-func (FileOptions_OptimizeMode) EnumDescriptor() ([]byte, []int) {
- return fileDescriptor_e5baabe45344a177, []int{10, 0}
-}
-
-type FieldOptions_CType int32
-
-const (
- // Default mode.
- FieldOptions_STRING FieldOptions_CType = 0
- FieldOptions_CORD FieldOptions_CType = 1
- FieldOptions_STRING_PIECE FieldOptions_CType = 2
-)
-
-var FieldOptions_CType_name = map[int32]string{
- 0: "STRING",
- 1: "CORD",
- 2: "STRING_PIECE",
-}
-
-var FieldOptions_CType_value = map[string]int32{
- "STRING": 0,
- "CORD": 1,
- "STRING_PIECE": 2,
-}
-
-func (x FieldOptions_CType) Enum() *FieldOptions_CType {
- p := new(FieldOptions_CType)
- *p = x
- return p
-}
-
-func (x FieldOptions_CType) String() string {
- return proto.EnumName(FieldOptions_CType_name, int32(x))
-}
-
-func (x *FieldOptions_CType) UnmarshalJSON(data []byte) error {
- value, err := proto.UnmarshalJSONEnum(FieldOptions_CType_value, data, "FieldOptions_CType")
- if err != nil {
- return err
- }
- *x = FieldOptions_CType(value)
- return nil
-}
-
-func (FieldOptions_CType) EnumDescriptor() ([]byte, []int) {
- return fileDescriptor_e5baabe45344a177, []int{12, 0}
-}
-
-type FieldOptions_JSType int32
-
-const (
- // Use the default type.
- FieldOptions_JS_NORMAL FieldOptions_JSType = 0
- // Use JavaScript strings.
- FieldOptions_JS_STRING FieldOptions_JSType = 1
- // Use JavaScript numbers.
- FieldOptions_JS_NUMBER FieldOptions_JSType = 2
-)
-
-var FieldOptions_JSType_name = map[int32]string{
- 0: "JS_NORMAL",
- 1: "JS_STRING",
- 2: "JS_NUMBER",
-}
-
-var FieldOptions_JSType_value = map[string]int32{
- "JS_NORMAL": 0,
- "JS_STRING": 1,
- "JS_NUMBER": 2,
-}
-
-func (x FieldOptions_JSType) Enum() *FieldOptions_JSType {
- p := new(FieldOptions_JSType)
- *p = x
- return p
-}
-
-func (x FieldOptions_JSType) String() string {
- return proto.EnumName(FieldOptions_JSType_name, int32(x))
-}
-
-func (x *FieldOptions_JSType) UnmarshalJSON(data []byte) error {
- value, err := proto.UnmarshalJSONEnum(FieldOptions_JSType_value, data, "FieldOptions_JSType")
- if err != nil {
- return err
- }
- *x = FieldOptions_JSType(value)
- return nil
-}
-
-func (FieldOptions_JSType) EnumDescriptor() ([]byte, []int) {
- return fileDescriptor_e5baabe45344a177, []int{12, 1}
-}
-
-// Is this method side-effect-free (or safe in HTTP parlance), or idempotent,
-// or neither? HTTP based RPC implementation may choose GET verb for safe
-// methods, and PUT verb for idempotent methods instead of the default POST.
-type MethodOptions_IdempotencyLevel int32
-
-const (
- MethodOptions_IDEMPOTENCY_UNKNOWN MethodOptions_IdempotencyLevel = 0
- MethodOptions_NO_SIDE_EFFECTS MethodOptions_IdempotencyLevel = 1
- MethodOptions_IDEMPOTENT MethodOptions_IdempotencyLevel = 2
-)
-
-var MethodOptions_IdempotencyLevel_name = map[int32]string{
- 0: "IDEMPOTENCY_UNKNOWN",
- 1: "NO_SIDE_EFFECTS",
- 2: "IDEMPOTENT",
-}
-
-var MethodOptions_IdempotencyLevel_value = map[string]int32{
- "IDEMPOTENCY_UNKNOWN": 0,
- "NO_SIDE_EFFECTS": 1,
- "IDEMPOTENT": 2,
-}
-
-func (x MethodOptions_IdempotencyLevel) Enum() *MethodOptions_IdempotencyLevel {
- p := new(MethodOptions_IdempotencyLevel)
- *p = x
- return p
-}
-
-func (x MethodOptions_IdempotencyLevel) String() string {
- return proto.EnumName(MethodOptions_IdempotencyLevel_name, int32(x))
-}
-
-func (x *MethodOptions_IdempotencyLevel) UnmarshalJSON(data []byte) error {
- value, err := proto.UnmarshalJSONEnum(MethodOptions_IdempotencyLevel_value, data, "MethodOptions_IdempotencyLevel")
- if err != nil {
- return err
- }
- *x = MethodOptions_IdempotencyLevel(value)
- return nil
-}
-
-func (MethodOptions_IdempotencyLevel) EnumDescriptor() ([]byte, []int) {
- return fileDescriptor_e5baabe45344a177, []int{17, 0}
-}
-
-// The protocol compiler can output a FileDescriptorSet containing the .proto
-// files it parses.
-type FileDescriptorSet struct {
- File []*FileDescriptorProto `protobuf:"bytes,1,rep,name=file" json:"file,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *FileDescriptorSet) Reset() { *m = FileDescriptorSet{} }
-func (m *FileDescriptorSet) String() string { return proto.CompactTextString(m) }
-func (*FileDescriptorSet) ProtoMessage() {}
-func (*FileDescriptorSet) Descriptor() ([]byte, []int) {
- return fileDescriptor_e5baabe45344a177, []int{0}
-}
-
-func (m *FileDescriptorSet) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_FileDescriptorSet.Unmarshal(m, b)
-}
-func (m *FileDescriptorSet) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_FileDescriptorSet.Marshal(b, m, deterministic)
-}
-func (m *FileDescriptorSet) XXX_Merge(src proto.Message) {
- xxx_messageInfo_FileDescriptorSet.Merge(m, src)
-}
-func (m *FileDescriptorSet) XXX_Size() int {
- return xxx_messageInfo_FileDescriptorSet.Size(m)
-}
-func (m *FileDescriptorSet) XXX_DiscardUnknown() {
- xxx_messageInfo_FileDescriptorSet.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_FileDescriptorSet proto.InternalMessageInfo
-
-func (m *FileDescriptorSet) GetFile() []*FileDescriptorProto {
- if m != nil {
- return m.File
- }
- return nil
-}
-
-// Describes a complete .proto file.
-type FileDescriptorProto struct {
- Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
- Package *string `protobuf:"bytes,2,opt,name=package" json:"package,omitempty"`
- // Names of files imported by this file.
- Dependency []string `protobuf:"bytes,3,rep,name=dependency" json:"dependency,omitempty"`
- // Indexes of the public imported files in the dependency list above.
- PublicDependency []int32 `protobuf:"varint,10,rep,name=public_dependency,json=publicDependency" json:"public_dependency,omitempty"`
- // Indexes of the weak imported files in the dependency list.
- // For Google-internal migration only. Do not use.
- WeakDependency []int32 `protobuf:"varint,11,rep,name=weak_dependency,json=weakDependency" json:"weak_dependency,omitempty"`
- // All top-level definitions in this file.
- MessageType []*DescriptorProto `protobuf:"bytes,4,rep,name=message_type,json=messageType" json:"message_type,omitempty"`
- EnumType []*EnumDescriptorProto `protobuf:"bytes,5,rep,name=enum_type,json=enumType" json:"enum_type,omitempty"`
- Service []*ServiceDescriptorProto `protobuf:"bytes,6,rep,name=service" json:"service,omitempty"`
- Extension []*FieldDescriptorProto `protobuf:"bytes,7,rep,name=extension" json:"extension,omitempty"`
- Options *FileOptions `protobuf:"bytes,8,opt,name=options" json:"options,omitempty"`
- // This field contains optional information about the original source code.
- // You may safely remove this entire field without harming runtime
- // functionality of the descriptors -- the information is needed only by
- // development tools.
- SourceCodeInfo *SourceCodeInfo `protobuf:"bytes,9,opt,name=source_code_info,json=sourceCodeInfo" json:"source_code_info,omitempty"`
- // The syntax of the proto file.
- // The supported values are "proto2" and "proto3".
- Syntax *string `protobuf:"bytes,12,opt,name=syntax" json:"syntax,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *FileDescriptorProto) Reset() { *m = FileDescriptorProto{} }
-func (m *FileDescriptorProto) String() string { return proto.CompactTextString(m) }
-func (*FileDescriptorProto) ProtoMessage() {}
-func (*FileDescriptorProto) Descriptor() ([]byte, []int) {
- return fileDescriptor_e5baabe45344a177, []int{1}
-}
-
-func (m *FileDescriptorProto) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_FileDescriptorProto.Unmarshal(m, b)
-}
-func (m *FileDescriptorProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_FileDescriptorProto.Marshal(b, m, deterministic)
-}
-func (m *FileDescriptorProto) XXX_Merge(src proto.Message) {
- xxx_messageInfo_FileDescriptorProto.Merge(m, src)
-}
-func (m *FileDescriptorProto) XXX_Size() int {
- return xxx_messageInfo_FileDescriptorProto.Size(m)
-}
-func (m *FileDescriptorProto) XXX_DiscardUnknown() {
- xxx_messageInfo_FileDescriptorProto.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_FileDescriptorProto proto.InternalMessageInfo
-
-func (m *FileDescriptorProto) GetName() string {
- if m != nil && m.Name != nil {
- return *m.Name
- }
- return ""
-}
-
-func (m *FileDescriptorProto) GetPackage() string {
- if m != nil && m.Package != nil {
- return *m.Package
- }
- return ""
-}
-
-func (m *FileDescriptorProto) GetDependency() []string {
- if m != nil {
- return m.Dependency
- }
- return nil
-}
-
-func (m *FileDescriptorProto) GetPublicDependency() []int32 {
- if m != nil {
- return m.PublicDependency
- }
- return nil
-}
-
-func (m *FileDescriptorProto) GetWeakDependency() []int32 {
- if m != nil {
- return m.WeakDependency
- }
- return nil
-}
-
-func (m *FileDescriptorProto) GetMessageType() []*DescriptorProto {
- if m != nil {
- return m.MessageType
- }
- return nil
-}
-
-func (m *FileDescriptorProto) GetEnumType() []*EnumDescriptorProto {
- if m != nil {
- return m.EnumType
- }
- return nil
-}
-
-func (m *FileDescriptorProto) GetService() []*ServiceDescriptorProto {
- if m != nil {
- return m.Service
- }
- return nil
-}
-
-func (m *FileDescriptorProto) GetExtension() []*FieldDescriptorProto {
- if m != nil {
- return m.Extension
- }
- return nil
-}
-
-func (m *FileDescriptorProto) GetOptions() *FileOptions {
- if m != nil {
- return m.Options
- }
- return nil
-}
-
-func (m *FileDescriptorProto) GetSourceCodeInfo() *SourceCodeInfo {
- if m != nil {
- return m.SourceCodeInfo
- }
- return nil
-}
-
-func (m *FileDescriptorProto) GetSyntax() string {
- if m != nil && m.Syntax != nil {
- return *m.Syntax
- }
- return ""
-}
-
-// Describes a message type.
-type DescriptorProto struct {
- Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
- Field []*FieldDescriptorProto `protobuf:"bytes,2,rep,name=field" json:"field,omitempty"`
- Extension []*FieldDescriptorProto `protobuf:"bytes,6,rep,name=extension" json:"extension,omitempty"`
- NestedType []*DescriptorProto `protobuf:"bytes,3,rep,name=nested_type,json=nestedType" json:"nested_type,omitempty"`
- EnumType []*EnumDescriptorProto `protobuf:"bytes,4,rep,name=enum_type,json=enumType" json:"enum_type,omitempty"`
- ExtensionRange []*DescriptorProto_ExtensionRange `protobuf:"bytes,5,rep,name=extension_range,json=extensionRange" json:"extension_range,omitempty"`
- OneofDecl []*OneofDescriptorProto `protobuf:"bytes,8,rep,name=oneof_decl,json=oneofDecl" json:"oneof_decl,omitempty"`
- Options *MessageOptions `protobuf:"bytes,7,opt,name=options" json:"options,omitempty"`
- ReservedRange []*DescriptorProto_ReservedRange `protobuf:"bytes,9,rep,name=reserved_range,json=reservedRange" json:"reserved_range,omitempty"`
- // Reserved field names, which may not be used by fields in the same message.
- // A given name may only be reserved once.
- ReservedName []string `protobuf:"bytes,10,rep,name=reserved_name,json=reservedName" json:"reserved_name,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *DescriptorProto) Reset() { *m = DescriptorProto{} }
-func (m *DescriptorProto) String() string { return proto.CompactTextString(m) }
-func (*DescriptorProto) ProtoMessage() {}
-func (*DescriptorProto) Descriptor() ([]byte, []int) {
- return fileDescriptor_e5baabe45344a177, []int{2}
-}
-
-func (m *DescriptorProto) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_DescriptorProto.Unmarshal(m, b)
-}
-func (m *DescriptorProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_DescriptorProto.Marshal(b, m, deterministic)
-}
-func (m *DescriptorProto) XXX_Merge(src proto.Message) {
- xxx_messageInfo_DescriptorProto.Merge(m, src)
-}
-func (m *DescriptorProto) XXX_Size() int {
- return xxx_messageInfo_DescriptorProto.Size(m)
-}
-func (m *DescriptorProto) XXX_DiscardUnknown() {
- xxx_messageInfo_DescriptorProto.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_DescriptorProto proto.InternalMessageInfo
-
-func (m *DescriptorProto) GetName() string {
- if m != nil && m.Name != nil {
- return *m.Name
- }
- return ""
-}
-
-func (m *DescriptorProto) GetField() []*FieldDescriptorProto {
- if m != nil {
- return m.Field
- }
- return nil
-}
-
-func (m *DescriptorProto) GetExtension() []*FieldDescriptorProto {
- if m != nil {
- return m.Extension
- }
- return nil
-}
-
-func (m *DescriptorProto) GetNestedType() []*DescriptorProto {
- if m != nil {
- return m.NestedType
- }
- return nil
-}
-
-func (m *DescriptorProto) GetEnumType() []*EnumDescriptorProto {
- if m != nil {
- return m.EnumType
- }
- return nil
-}
-
-func (m *DescriptorProto) GetExtensionRange() []*DescriptorProto_ExtensionRange {
- if m != nil {
- return m.ExtensionRange
- }
- return nil
-}
-
-func (m *DescriptorProto) GetOneofDecl() []*OneofDescriptorProto {
- if m != nil {
- return m.OneofDecl
- }
- return nil
-}
-
-func (m *DescriptorProto) GetOptions() *MessageOptions {
- if m != nil {
- return m.Options
- }
- return nil
-}
-
-func (m *DescriptorProto) GetReservedRange() []*DescriptorProto_ReservedRange {
- if m != nil {
- return m.ReservedRange
- }
- return nil
-}
-
-func (m *DescriptorProto) GetReservedName() []string {
- if m != nil {
- return m.ReservedName
- }
- return nil
-}
-
-type DescriptorProto_ExtensionRange struct {
- Start *int32 `protobuf:"varint,1,opt,name=start" json:"start,omitempty"`
- End *int32 `protobuf:"varint,2,opt,name=end" json:"end,omitempty"`
- Options *ExtensionRangeOptions `protobuf:"bytes,3,opt,name=options" json:"options,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *DescriptorProto_ExtensionRange) Reset() { *m = DescriptorProto_ExtensionRange{} }
-func (m *DescriptorProto_ExtensionRange) String() string { return proto.CompactTextString(m) }
-func (*DescriptorProto_ExtensionRange) ProtoMessage() {}
-func (*DescriptorProto_ExtensionRange) Descriptor() ([]byte, []int) {
- return fileDescriptor_e5baabe45344a177, []int{2, 0}
-}
-
-func (m *DescriptorProto_ExtensionRange) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_DescriptorProto_ExtensionRange.Unmarshal(m, b)
-}
-func (m *DescriptorProto_ExtensionRange) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_DescriptorProto_ExtensionRange.Marshal(b, m, deterministic)
-}
-func (m *DescriptorProto_ExtensionRange) XXX_Merge(src proto.Message) {
- xxx_messageInfo_DescriptorProto_ExtensionRange.Merge(m, src)
-}
-func (m *DescriptorProto_ExtensionRange) XXX_Size() int {
- return xxx_messageInfo_DescriptorProto_ExtensionRange.Size(m)
-}
-func (m *DescriptorProto_ExtensionRange) XXX_DiscardUnknown() {
- xxx_messageInfo_DescriptorProto_ExtensionRange.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_DescriptorProto_ExtensionRange proto.InternalMessageInfo
-
-func (m *DescriptorProto_ExtensionRange) GetStart() int32 {
- if m != nil && m.Start != nil {
- return *m.Start
- }
- return 0
-}
-
-func (m *DescriptorProto_ExtensionRange) GetEnd() int32 {
- if m != nil && m.End != nil {
- return *m.End
- }
- return 0
-}
-
-func (m *DescriptorProto_ExtensionRange) GetOptions() *ExtensionRangeOptions {
- if m != nil {
- return m.Options
- }
- return nil
-}
-
-// Range of reserved tag numbers. Reserved tag numbers may not be used by
-// fields or extension ranges in the same message. Reserved ranges may
-// not overlap.
-type DescriptorProto_ReservedRange struct {
- Start *int32 `protobuf:"varint,1,opt,name=start" json:"start,omitempty"`
- End *int32 `protobuf:"varint,2,opt,name=end" json:"end,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *DescriptorProto_ReservedRange) Reset() { *m = DescriptorProto_ReservedRange{} }
-func (m *DescriptorProto_ReservedRange) String() string { return proto.CompactTextString(m) }
-func (*DescriptorProto_ReservedRange) ProtoMessage() {}
-func (*DescriptorProto_ReservedRange) Descriptor() ([]byte, []int) {
- return fileDescriptor_e5baabe45344a177, []int{2, 1}
-}
-
-func (m *DescriptorProto_ReservedRange) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_DescriptorProto_ReservedRange.Unmarshal(m, b)
-}
-func (m *DescriptorProto_ReservedRange) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_DescriptorProto_ReservedRange.Marshal(b, m, deterministic)
-}
-func (m *DescriptorProto_ReservedRange) XXX_Merge(src proto.Message) {
- xxx_messageInfo_DescriptorProto_ReservedRange.Merge(m, src)
-}
-func (m *DescriptorProto_ReservedRange) XXX_Size() int {
- return xxx_messageInfo_DescriptorProto_ReservedRange.Size(m)
-}
-func (m *DescriptorProto_ReservedRange) XXX_DiscardUnknown() {
- xxx_messageInfo_DescriptorProto_ReservedRange.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_DescriptorProto_ReservedRange proto.InternalMessageInfo
-
-func (m *DescriptorProto_ReservedRange) GetStart() int32 {
- if m != nil && m.Start != nil {
- return *m.Start
- }
- return 0
-}
-
-func (m *DescriptorProto_ReservedRange) GetEnd() int32 {
- if m != nil && m.End != nil {
- return *m.End
- }
- return 0
-}
-
-type ExtensionRangeOptions struct {
- // The parser stores options it doesn't recognize here. See above.
- UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- proto.XXX_InternalExtensions `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *ExtensionRangeOptions) Reset() { *m = ExtensionRangeOptions{} }
-func (m *ExtensionRangeOptions) String() string { return proto.CompactTextString(m) }
-func (*ExtensionRangeOptions) ProtoMessage() {}
-func (*ExtensionRangeOptions) Descriptor() ([]byte, []int) {
- return fileDescriptor_e5baabe45344a177, []int{3}
-}
-
-var extRange_ExtensionRangeOptions = []proto.ExtensionRange{
- {Start: 1000, End: 536870911},
-}
-
-func (*ExtensionRangeOptions) ExtensionRangeArray() []proto.ExtensionRange {
- return extRange_ExtensionRangeOptions
-}
-
-func (m *ExtensionRangeOptions) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_ExtensionRangeOptions.Unmarshal(m, b)
-}
-func (m *ExtensionRangeOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_ExtensionRangeOptions.Marshal(b, m, deterministic)
-}
-func (m *ExtensionRangeOptions) XXX_Merge(src proto.Message) {
- xxx_messageInfo_ExtensionRangeOptions.Merge(m, src)
-}
-func (m *ExtensionRangeOptions) XXX_Size() int {
- return xxx_messageInfo_ExtensionRangeOptions.Size(m)
-}
-func (m *ExtensionRangeOptions) XXX_DiscardUnknown() {
- xxx_messageInfo_ExtensionRangeOptions.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_ExtensionRangeOptions proto.InternalMessageInfo
-
-func (m *ExtensionRangeOptions) GetUninterpretedOption() []*UninterpretedOption {
- if m != nil {
- return m.UninterpretedOption
- }
- return nil
-}
-
-// Describes a field within a message.
-type FieldDescriptorProto struct {
- Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
- Number *int32 `protobuf:"varint,3,opt,name=number" json:"number,omitempty"`
- Label *FieldDescriptorProto_Label `protobuf:"varint,4,opt,name=label,enum=google.protobuf.FieldDescriptorProto_Label" json:"label,omitempty"`
- // If type_name is set, this need not be set. If both this and type_name
- // are set, this must be one of TYPE_ENUM, TYPE_MESSAGE or TYPE_GROUP.
- Type *FieldDescriptorProto_Type `protobuf:"varint,5,opt,name=type,enum=google.protobuf.FieldDescriptorProto_Type" json:"type,omitempty"`
- // For message and enum types, this is the name of the type. If the name
- // starts with a '.', it is fully-qualified. Otherwise, C++-like scoping
- // rules are used to find the type (i.e. first the nested types within this
- // message are searched, then within the parent, on up to the root
- // namespace).
- TypeName *string `protobuf:"bytes,6,opt,name=type_name,json=typeName" json:"type_name,omitempty"`
- // For extensions, this is the name of the type being extended. It is
- // resolved in the same manner as type_name.
- Extendee *string `protobuf:"bytes,2,opt,name=extendee" json:"extendee,omitempty"`
- // For numeric types, contains the original text representation of the value.
- // For booleans, "true" or "false".
- // For strings, contains the default text contents (not escaped in any way).
- // For bytes, contains the C escaped value. All bytes >= 128 are escaped.
- // TODO(kenton): Base-64 encode?
- DefaultValue *string `protobuf:"bytes,7,opt,name=default_value,json=defaultValue" json:"default_value,omitempty"`
- // If set, gives the index of a oneof in the containing type's oneof_decl
- // list. This field is a member of that oneof.
- OneofIndex *int32 `protobuf:"varint,9,opt,name=oneof_index,json=oneofIndex" json:"oneof_index,omitempty"`
- // JSON name of this field. The value is set by protocol compiler. If the
- // user has set a "json_name" option on this field, that option's value
- // will be used. Otherwise, it's deduced from the field's name by converting
- // it to camelCase.
- JsonName *string `protobuf:"bytes,10,opt,name=json_name,json=jsonName" json:"json_name,omitempty"`
- Options *FieldOptions `protobuf:"bytes,8,opt,name=options" json:"options,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *FieldDescriptorProto) Reset() { *m = FieldDescriptorProto{} }
-func (m *FieldDescriptorProto) String() string { return proto.CompactTextString(m) }
-func (*FieldDescriptorProto) ProtoMessage() {}
-func (*FieldDescriptorProto) Descriptor() ([]byte, []int) {
- return fileDescriptor_e5baabe45344a177, []int{4}
-}
-
-func (m *FieldDescriptorProto) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_FieldDescriptorProto.Unmarshal(m, b)
-}
-func (m *FieldDescriptorProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_FieldDescriptorProto.Marshal(b, m, deterministic)
-}
-func (m *FieldDescriptorProto) XXX_Merge(src proto.Message) {
- xxx_messageInfo_FieldDescriptorProto.Merge(m, src)
-}
-func (m *FieldDescriptorProto) XXX_Size() int {
- return xxx_messageInfo_FieldDescriptorProto.Size(m)
-}
-func (m *FieldDescriptorProto) XXX_DiscardUnknown() {
- xxx_messageInfo_FieldDescriptorProto.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_FieldDescriptorProto proto.InternalMessageInfo
-
-func (m *FieldDescriptorProto) GetName() string {
- if m != nil && m.Name != nil {
- return *m.Name
- }
- return ""
-}
-
-func (m *FieldDescriptorProto) GetNumber() int32 {
- if m != nil && m.Number != nil {
- return *m.Number
- }
- return 0
-}
-
-func (m *FieldDescriptorProto) GetLabel() FieldDescriptorProto_Label {
- if m != nil && m.Label != nil {
- return *m.Label
- }
- return FieldDescriptorProto_LABEL_OPTIONAL
-}
-
-func (m *FieldDescriptorProto) GetType() FieldDescriptorProto_Type {
- if m != nil && m.Type != nil {
- return *m.Type
- }
- return FieldDescriptorProto_TYPE_DOUBLE
-}
-
-func (m *FieldDescriptorProto) GetTypeName() string {
- if m != nil && m.TypeName != nil {
- return *m.TypeName
- }
- return ""
-}
-
-func (m *FieldDescriptorProto) GetExtendee() string {
- if m != nil && m.Extendee != nil {
- return *m.Extendee
- }
- return ""
-}
-
-func (m *FieldDescriptorProto) GetDefaultValue() string {
- if m != nil && m.DefaultValue != nil {
- return *m.DefaultValue
- }
- return ""
-}
-
-func (m *FieldDescriptorProto) GetOneofIndex() int32 {
- if m != nil && m.OneofIndex != nil {
- return *m.OneofIndex
- }
- return 0
-}
-
-func (m *FieldDescriptorProto) GetJsonName() string {
- if m != nil && m.JsonName != nil {
- return *m.JsonName
- }
- return ""
-}
-
-func (m *FieldDescriptorProto) GetOptions() *FieldOptions {
- if m != nil {
- return m.Options
- }
- return nil
-}
-
-// Describes a oneof.
-type OneofDescriptorProto struct {
- Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
- Options *OneofOptions `protobuf:"bytes,2,opt,name=options" json:"options,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *OneofDescriptorProto) Reset() { *m = OneofDescriptorProto{} }
-func (m *OneofDescriptorProto) String() string { return proto.CompactTextString(m) }
-func (*OneofDescriptorProto) ProtoMessage() {}
-func (*OneofDescriptorProto) Descriptor() ([]byte, []int) {
- return fileDescriptor_e5baabe45344a177, []int{5}
-}
-
-func (m *OneofDescriptorProto) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_OneofDescriptorProto.Unmarshal(m, b)
-}
-func (m *OneofDescriptorProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_OneofDescriptorProto.Marshal(b, m, deterministic)
-}
-func (m *OneofDescriptorProto) XXX_Merge(src proto.Message) {
- xxx_messageInfo_OneofDescriptorProto.Merge(m, src)
-}
-func (m *OneofDescriptorProto) XXX_Size() int {
- return xxx_messageInfo_OneofDescriptorProto.Size(m)
-}
-func (m *OneofDescriptorProto) XXX_DiscardUnknown() {
- xxx_messageInfo_OneofDescriptorProto.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_OneofDescriptorProto proto.InternalMessageInfo
-
-func (m *OneofDescriptorProto) GetName() string {
- if m != nil && m.Name != nil {
- return *m.Name
- }
- return ""
-}
-
-func (m *OneofDescriptorProto) GetOptions() *OneofOptions {
- if m != nil {
- return m.Options
- }
- return nil
-}
-
-// Describes an enum type.
-type EnumDescriptorProto struct {
- Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
- Value []*EnumValueDescriptorProto `protobuf:"bytes,2,rep,name=value" json:"value,omitempty"`
- Options *EnumOptions `protobuf:"bytes,3,opt,name=options" json:"options,omitempty"`
- // Range of reserved numeric values. Reserved numeric values may not be used
- // by enum values in the same enum declaration. Reserved ranges may not
- // overlap.
- ReservedRange []*EnumDescriptorProto_EnumReservedRange `protobuf:"bytes,4,rep,name=reserved_range,json=reservedRange" json:"reserved_range,omitempty"`
- // Reserved enum value names, which may not be reused. A given name may only
- // be reserved once.
- ReservedName []string `protobuf:"bytes,5,rep,name=reserved_name,json=reservedName" json:"reserved_name,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *EnumDescriptorProto) Reset() { *m = EnumDescriptorProto{} }
-func (m *EnumDescriptorProto) String() string { return proto.CompactTextString(m) }
-func (*EnumDescriptorProto) ProtoMessage() {}
-func (*EnumDescriptorProto) Descriptor() ([]byte, []int) {
- return fileDescriptor_e5baabe45344a177, []int{6}
-}
-
-func (m *EnumDescriptorProto) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_EnumDescriptorProto.Unmarshal(m, b)
-}
-func (m *EnumDescriptorProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_EnumDescriptorProto.Marshal(b, m, deterministic)
-}
-func (m *EnumDescriptorProto) XXX_Merge(src proto.Message) {
- xxx_messageInfo_EnumDescriptorProto.Merge(m, src)
-}
-func (m *EnumDescriptorProto) XXX_Size() int {
- return xxx_messageInfo_EnumDescriptorProto.Size(m)
-}
-func (m *EnumDescriptorProto) XXX_DiscardUnknown() {
- xxx_messageInfo_EnumDescriptorProto.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_EnumDescriptorProto proto.InternalMessageInfo
-
-func (m *EnumDescriptorProto) GetName() string {
- if m != nil && m.Name != nil {
- return *m.Name
- }
- return ""
-}
-
-func (m *EnumDescriptorProto) GetValue() []*EnumValueDescriptorProto {
- if m != nil {
- return m.Value
- }
- return nil
-}
-
-func (m *EnumDescriptorProto) GetOptions() *EnumOptions {
- if m != nil {
- return m.Options
- }
- return nil
-}
-
-func (m *EnumDescriptorProto) GetReservedRange() []*EnumDescriptorProto_EnumReservedRange {
- if m != nil {
- return m.ReservedRange
- }
- return nil
-}
-
-func (m *EnumDescriptorProto) GetReservedName() []string {
- if m != nil {
- return m.ReservedName
- }
- return nil
-}
-
-// Range of reserved numeric values. Reserved values may not be used by
-// entries in the same enum. Reserved ranges may not overlap.
-//
-// Note that this is distinct from DescriptorProto.ReservedRange in that it
-// is inclusive such that it can appropriately represent the entire int32
-// domain.
-type EnumDescriptorProto_EnumReservedRange struct {
- Start *int32 `protobuf:"varint,1,opt,name=start" json:"start,omitempty"`
- End *int32 `protobuf:"varint,2,opt,name=end" json:"end,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *EnumDescriptorProto_EnumReservedRange) Reset() { *m = EnumDescriptorProto_EnumReservedRange{} }
-func (m *EnumDescriptorProto_EnumReservedRange) String() string { return proto.CompactTextString(m) }
-func (*EnumDescriptorProto_EnumReservedRange) ProtoMessage() {}
-func (*EnumDescriptorProto_EnumReservedRange) Descriptor() ([]byte, []int) {
- return fileDescriptor_e5baabe45344a177, []int{6, 0}
-}
-
-func (m *EnumDescriptorProto_EnumReservedRange) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_EnumDescriptorProto_EnumReservedRange.Unmarshal(m, b)
-}
-func (m *EnumDescriptorProto_EnumReservedRange) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_EnumDescriptorProto_EnumReservedRange.Marshal(b, m, deterministic)
-}
-func (m *EnumDescriptorProto_EnumReservedRange) XXX_Merge(src proto.Message) {
- xxx_messageInfo_EnumDescriptorProto_EnumReservedRange.Merge(m, src)
-}
-func (m *EnumDescriptorProto_EnumReservedRange) XXX_Size() int {
- return xxx_messageInfo_EnumDescriptorProto_EnumReservedRange.Size(m)
-}
-func (m *EnumDescriptorProto_EnumReservedRange) XXX_DiscardUnknown() {
- xxx_messageInfo_EnumDescriptorProto_EnumReservedRange.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_EnumDescriptorProto_EnumReservedRange proto.InternalMessageInfo
-
-func (m *EnumDescriptorProto_EnumReservedRange) GetStart() int32 {
- if m != nil && m.Start != nil {
- return *m.Start
- }
- return 0
-}
-
-func (m *EnumDescriptorProto_EnumReservedRange) GetEnd() int32 {
- if m != nil && m.End != nil {
- return *m.End
- }
- return 0
-}
-
-// Describes a value within an enum.
-type EnumValueDescriptorProto struct {
- Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
- Number *int32 `protobuf:"varint,2,opt,name=number" json:"number,omitempty"`
- Options *EnumValueOptions `protobuf:"bytes,3,opt,name=options" json:"options,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *EnumValueDescriptorProto) Reset() { *m = EnumValueDescriptorProto{} }
-func (m *EnumValueDescriptorProto) String() string { return proto.CompactTextString(m) }
-func (*EnumValueDescriptorProto) ProtoMessage() {}
-func (*EnumValueDescriptorProto) Descriptor() ([]byte, []int) {
- return fileDescriptor_e5baabe45344a177, []int{7}
-}
-
-func (m *EnumValueDescriptorProto) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_EnumValueDescriptorProto.Unmarshal(m, b)
-}
-func (m *EnumValueDescriptorProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_EnumValueDescriptorProto.Marshal(b, m, deterministic)
-}
-func (m *EnumValueDescriptorProto) XXX_Merge(src proto.Message) {
- xxx_messageInfo_EnumValueDescriptorProto.Merge(m, src)
-}
-func (m *EnumValueDescriptorProto) XXX_Size() int {
- return xxx_messageInfo_EnumValueDescriptorProto.Size(m)
-}
-func (m *EnumValueDescriptorProto) XXX_DiscardUnknown() {
- xxx_messageInfo_EnumValueDescriptorProto.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_EnumValueDescriptorProto proto.InternalMessageInfo
-
-func (m *EnumValueDescriptorProto) GetName() string {
- if m != nil && m.Name != nil {
- return *m.Name
- }
- return ""
-}
-
-func (m *EnumValueDescriptorProto) GetNumber() int32 {
- if m != nil && m.Number != nil {
- return *m.Number
- }
- return 0
-}
-
-func (m *EnumValueDescriptorProto) GetOptions() *EnumValueOptions {
- if m != nil {
- return m.Options
- }
- return nil
-}
-
-// Describes a service.
-type ServiceDescriptorProto struct {
- Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
- Method []*MethodDescriptorProto `protobuf:"bytes,2,rep,name=method" json:"method,omitempty"`
- Options *ServiceOptions `protobuf:"bytes,3,opt,name=options" json:"options,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *ServiceDescriptorProto) Reset() { *m = ServiceDescriptorProto{} }
-func (m *ServiceDescriptorProto) String() string { return proto.CompactTextString(m) }
-func (*ServiceDescriptorProto) ProtoMessage() {}
-func (*ServiceDescriptorProto) Descriptor() ([]byte, []int) {
- return fileDescriptor_e5baabe45344a177, []int{8}
-}
-
-func (m *ServiceDescriptorProto) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_ServiceDescriptorProto.Unmarshal(m, b)
-}
-func (m *ServiceDescriptorProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_ServiceDescriptorProto.Marshal(b, m, deterministic)
-}
-func (m *ServiceDescriptorProto) XXX_Merge(src proto.Message) {
- xxx_messageInfo_ServiceDescriptorProto.Merge(m, src)
-}
-func (m *ServiceDescriptorProto) XXX_Size() int {
- return xxx_messageInfo_ServiceDescriptorProto.Size(m)
-}
-func (m *ServiceDescriptorProto) XXX_DiscardUnknown() {
- xxx_messageInfo_ServiceDescriptorProto.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_ServiceDescriptorProto proto.InternalMessageInfo
-
-func (m *ServiceDescriptorProto) GetName() string {
- if m != nil && m.Name != nil {
- return *m.Name
- }
- return ""
-}
-
-func (m *ServiceDescriptorProto) GetMethod() []*MethodDescriptorProto {
- if m != nil {
- return m.Method
- }
- return nil
-}
-
-func (m *ServiceDescriptorProto) GetOptions() *ServiceOptions {
- if m != nil {
- return m.Options
- }
- return nil
-}
-
-// Describes a method of a service.
-type MethodDescriptorProto struct {
- Name *string `protobuf:"bytes,1,opt,name=name" json:"name,omitempty"`
- // Input and output type names. These are resolved in the same way as
- // FieldDescriptorProto.type_name, but must refer to a message type.
- InputType *string `protobuf:"bytes,2,opt,name=input_type,json=inputType" json:"input_type,omitempty"`
- OutputType *string `protobuf:"bytes,3,opt,name=output_type,json=outputType" json:"output_type,omitempty"`
- Options *MethodOptions `protobuf:"bytes,4,opt,name=options" json:"options,omitempty"`
- // Identifies if client streams multiple client messages
- ClientStreaming *bool `protobuf:"varint,5,opt,name=client_streaming,json=clientStreaming,def=0" json:"client_streaming,omitempty"`
- // Identifies if server streams multiple server messages
- ServerStreaming *bool `protobuf:"varint,6,opt,name=server_streaming,json=serverStreaming,def=0" json:"server_streaming,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *MethodDescriptorProto) Reset() { *m = MethodDescriptorProto{} }
-func (m *MethodDescriptorProto) String() string { return proto.CompactTextString(m) }
-func (*MethodDescriptorProto) ProtoMessage() {}
-func (*MethodDescriptorProto) Descriptor() ([]byte, []int) {
- return fileDescriptor_e5baabe45344a177, []int{9}
-}
-
-func (m *MethodDescriptorProto) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_MethodDescriptorProto.Unmarshal(m, b)
-}
-func (m *MethodDescriptorProto) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_MethodDescriptorProto.Marshal(b, m, deterministic)
-}
-func (m *MethodDescriptorProto) XXX_Merge(src proto.Message) {
- xxx_messageInfo_MethodDescriptorProto.Merge(m, src)
-}
-func (m *MethodDescriptorProto) XXX_Size() int {
- return xxx_messageInfo_MethodDescriptorProto.Size(m)
-}
-func (m *MethodDescriptorProto) XXX_DiscardUnknown() {
- xxx_messageInfo_MethodDescriptorProto.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_MethodDescriptorProto proto.InternalMessageInfo
-
-const Default_MethodDescriptorProto_ClientStreaming bool = false
-const Default_MethodDescriptorProto_ServerStreaming bool = false
-
-func (m *MethodDescriptorProto) GetName() string {
- if m != nil && m.Name != nil {
- return *m.Name
- }
- return ""
-}
-
-func (m *MethodDescriptorProto) GetInputType() string {
- if m != nil && m.InputType != nil {
- return *m.InputType
- }
- return ""
-}
-
-func (m *MethodDescriptorProto) GetOutputType() string {
- if m != nil && m.OutputType != nil {
- return *m.OutputType
- }
- return ""
-}
-
-func (m *MethodDescriptorProto) GetOptions() *MethodOptions {
- if m != nil {
- return m.Options
- }
- return nil
-}
-
-func (m *MethodDescriptorProto) GetClientStreaming() bool {
- if m != nil && m.ClientStreaming != nil {
- return *m.ClientStreaming
- }
- return Default_MethodDescriptorProto_ClientStreaming
-}
-
-func (m *MethodDescriptorProto) GetServerStreaming() bool {
- if m != nil && m.ServerStreaming != nil {
- return *m.ServerStreaming
- }
- return Default_MethodDescriptorProto_ServerStreaming
-}
-
-type FileOptions struct {
- // Sets the Java package where classes generated from this .proto will be
- // placed. By default, the proto package is used, but this is often
- // inappropriate because proto packages do not normally start with backwards
- // domain names.
- JavaPackage *string `protobuf:"bytes,1,opt,name=java_package,json=javaPackage" json:"java_package,omitempty"`
- // If set, all the classes from the .proto file are wrapped in a single
- // outer class with the given name. This applies to both Proto1
- // (equivalent to the old "--one_java_file" option) and Proto2 (where
- // a .proto always translates to a single class, but you may want to
- // explicitly choose the class name).
- JavaOuterClassname *string `protobuf:"bytes,8,opt,name=java_outer_classname,json=javaOuterClassname" json:"java_outer_classname,omitempty"`
- // If set true, then the Java code generator will generate a separate .java
- // file for each top-level message, enum, and service defined in the .proto
- // file. Thus, these types will *not* be nested inside the outer class
- // named by java_outer_classname. However, the outer class will still be
- // generated to contain the file's getDescriptor() method as well as any
- // top-level extensions defined in the file.
- JavaMultipleFiles *bool `protobuf:"varint,10,opt,name=java_multiple_files,json=javaMultipleFiles,def=0" json:"java_multiple_files,omitempty"`
- // This option does nothing.
- JavaGenerateEqualsAndHash *bool `protobuf:"varint,20,opt,name=java_generate_equals_and_hash,json=javaGenerateEqualsAndHash" json:"java_generate_equals_and_hash,omitempty"` // Deprecated: Do not use.
- // If set true, then the Java2 code generator will generate code that
- // throws an exception whenever an attempt is made to assign a non-UTF-8
- // byte sequence to a string field.
- // Message reflection will do the same.
- // However, an extension field still accepts non-UTF-8 byte sequences.
- // This option has no effect on when used with the lite runtime.
- JavaStringCheckUtf8 *bool `protobuf:"varint,27,opt,name=java_string_check_utf8,json=javaStringCheckUtf8,def=0" json:"java_string_check_utf8,omitempty"`
- OptimizeFor *FileOptions_OptimizeMode `protobuf:"varint,9,opt,name=optimize_for,json=optimizeFor,enum=google.protobuf.FileOptions_OptimizeMode,def=1" json:"optimize_for,omitempty"`
- // Sets the Go package where structs generated from this .proto will be
- // placed. If omitted, the Go package will be derived from the following:
- // - The basename of the package import path, if provided.
- // - Otherwise, the package statement in the .proto file, if present.
- // - Otherwise, the basename of the .proto file, without extension.
- GoPackage *string `protobuf:"bytes,11,opt,name=go_package,json=goPackage" json:"go_package,omitempty"`
- // Should generic services be generated in each language? "Generic" services
- // are not specific to any particular RPC system. They are generated by the
- // main code generators in each language (without additional plugins).
- // Generic services were the only kind of service generation supported by
- // early versions of google.protobuf.
- //
- // Generic services are now considered deprecated in favor of using plugins
- // that generate code specific to your particular RPC system. Therefore,
- // these default to false. Old code which depends on generic services should
- // explicitly set them to true.
- CcGenericServices *bool `protobuf:"varint,16,opt,name=cc_generic_services,json=ccGenericServices,def=0" json:"cc_generic_services,omitempty"`
- JavaGenericServices *bool `protobuf:"varint,17,opt,name=java_generic_services,json=javaGenericServices,def=0" json:"java_generic_services,omitempty"`
- PyGenericServices *bool `protobuf:"varint,18,opt,name=py_generic_services,json=pyGenericServices,def=0" json:"py_generic_services,omitempty"`
- PhpGenericServices *bool `protobuf:"varint,42,opt,name=php_generic_services,json=phpGenericServices,def=0" json:"php_generic_services,omitempty"`
- // Is this file deprecated?
- // Depending on the target platform, this can emit Deprecated annotations
- // for everything in the file, or it will be completely ignored; in the very
- // least, this is a formalization for deprecating files.
- Deprecated *bool `protobuf:"varint,23,opt,name=deprecated,def=0" json:"deprecated,omitempty"`
- // Enables the use of arenas for the proto messages in this file. This applies
- // only to generated classes for C++.
- CcEnableArenas *bool `protobuf:"varint,31,opt,name=cc_enable_arenas,json=ccEnableArenas,def=0" json:"cc_enable_arenas,omitempty"`
- // Sets the objective c class prefix which is prepended to all objective c
- // generated classes from this .proto. There is no default.
- ObjcClassPrefix *string `protobuf:"bytes,36,opt,name=objc_class_prefix,json=objcClassPrefix" json:"objc_class_prefix,omitempty"`
- // Namespace for generated classes; defaults to the package.
- CsharpNamespace *string `protobuf:"bytes,37,opt,name=csharp_namespace,json=csharpNamespace" json:"csharp_namespace,omitempty"`
- // By default Swift generators will take the proto package and CamelCase it
- // replacing '.' with underscore and use that to prefix the types/symbols
- // defined. When this options is provided, they will use this value instead
- // to prefix the types/symbols defined.
- SwiftPrefix *string `protobuf:"bytes,39,opt,name=swift_prefix,json=swiftPrefix" json:"swift_prefix,omitempty"`
- // Sets the php class prefix which is prepended to all php generated classes
- // from this .proto. Default is empty.
- PhpClassPrefix *string `protobuf:"bytes,40,opt,name=php_class_prefix,json=phpClassPrefix" json:"php_class_prefix,omitempty"`
- // Use this option to change the namespace of php generated classes. Default
- // is empty. When this option is empty, the package name will be used for
- // determining the namespace.
- PhpNamespace *string `protobuf:"bytes,41,opt,name=php_namespace,json=phpNamespace" json:"php_namespace,omitempty"`
- // Use this option to change the namespace of php generated metadata classes.
- // Default is empty. When this option is empty, the proto file name will be used
- // for determining the namespace.
- PhpMetadataNamespace *string `protobuf:"bytes,44,opt,name=php_metadata_namespace,json=phpMetadataNamespace" json:"php_metadata_namespace,omitempty"`
- // Use this option to change the package of ruby generated classes. Default
- // is empty. When this option is not set, the package name will be used for
- // determining the ruby package.
- RubyPackage *string `protobuf:"bytes,45,opt,name=ruby_package,json=rubyPackage" json:"ruby_package,omitempty"`
- // The parser stores options it doesn't recognize here.
- // See the documentation for the "Options" section above.
- UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- proto.XXX_InternalExtensions `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *FileOptions) Reset() { *m = FileOptions{} }
-func (m *FileOptions) String() string { return proto.CompactTextString(m) }
-func (*FileOptions) ProtoMessage() {}
-func (*FileOptions) Descriptor() ([]byte, []int) {
- return fileDescriptor_e5baabe45344a177, []int{10}
-}
-
-var extRange_FileOptions = []proto.ExtensionRange{
- {Start: 1000, End: 536870911},
-}
-
-func (*FileOptions) ExtensionRangeArray() []proto.ExtensionRange {
- return extRange_FileOptions
-}
-
-func (m *FileOptions) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_FileOptions.Unmarshal(m, b)
-}
-func (m *FileOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_FileOptions.Marshal(b, m, deterministic)
-}
-func (m *FileOptions) XXX_Merge(src proto.Message) {
- xxx_messageInfo_FileOptions.Merge(m, src)
-}
-func (m *FileOptions) XXX_Size() int {
- return xxx_messageInfo_FileOptions.Size(m)
-}
-func (m *FileOptions) XXX_DiscardUnknown() {
- xxx_messageInfo_FileOptions.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_FileOptions proto.InternalMessageInfo
-
-const Default_FileOptions_JavaMultipleFiles bool = false
-const Default_FileOptions_JavaStringCheckUtf8 bool = false
-const Default_FileOptions_OptimizeFor FileOptions_OptimizeMode = FileOptions_SPEED
-const Default_FileOptions_CcGenericServices bool = false
-const Default_FileOptions_JavaGenericServices bool = false
-const Default_FileOptions_PyGenericServices bool = false
-const Default_FileOptions_PhpGenericServices bool = false
-const Default_FileOptions_Deprecated bool = false
-const Default_FileOptions_CcEnableArenas bool = false
-
-func (m *FileOptions) GetJavaPackage() string {
- if m != nil && m.JavaPackage != nil {
- return *m.JavaPackage
- }
- return ""
-}
-
-func (m *FileOptions) GetJavaOuterClassname() string {
- if m != nil && m.JavaOuterClassname != nil {
- return *m.JavaOuterClassname
- }
- return ""
-}
-
-func (m *FileOptions) GetJavaMultipleFiles() bool {
- if m != nil && m.JavaMultipleFiles != nil {
- return *m.JavaMultipleFiles
- }
- return Default_FileOptions_JavaMultipleFiles
-}
-
-// Deprecated: Do not use.
-func (m *FileOptions) GetJavaGenerateEqualsAndHash() bool {
- if m != nil && m.JavaGenerateEqualsAndHash != nil {
- return *m.JavaGenerateEqualsAndHash
- }
- return false
-}
-
-func (m *FileOptions) GetJavaStringCheckUtf8() bool {
- if m != nil && m.JavaStringCheckUtf8 != nil {
- return *m.JavaStringCheckUtf8
- }
- return Default_FileOptions_JavaStringCheckUtf8
-}
-
-func (m *FileOptions) GetOptimizeFor() FileOptions_OptimizeMode {
- if m != nil && m.OptimizeFor != nil {
- return *m.OptimizeFor
- }
- return Default_FileOptions_OptimizeFor
-}
-
-func (m *FileOptions) GetGoPackage() string {
- if m != nil && m.GoPackage != nil {
- return *m.GoPackage
- }
- return ""
-}
-
-func (m *FileOptions) GetCcGenericServices() bool {
- if m != nil && m.CcGenericServices != nil {
- return *m.CcGenericServices
- }
- return Default_FileOptions_CcGenericServices
-}
-
-func (m *FileOptions) GetJavaGenericServices() bool {
- if m != nil && m.JavaGenericServices != nil {
- return *m.JavaGenericServices
- }
- return Default_FileOptions_JavaGenericServices
-}
-
-func (m *FileOptions) GetPyGenericServices() bool {
- if m != nil && m.PyGenericServices != nil {
- return *m.PyGenericServices
- }
- return Default_FileOptions_PyGenericServices
-}
-
-func (m *FileOptions) GetPhpGenericServices() bool {
- if m != nil && m.PhpGenericServices != nil {
- return *m.PhpGenericServices
- }
- return Default_FileOptions_PhpGenericServices
-}
-
-func (m *FileOptions) GetDeprecated() bool {
- if m != nil && m.Deprecated != nil {
- return *m.Deprecated
- }
- return Default_FileOptions_Deprecated
-}
-
-func (m *FileOptions) GetCcEnableArenas() bool {
- if m != nil && m.CcEnableArenas != nil {
- return *m.CcEnableArenas
- }
- return Default_FileOptions_CcEnableArenas
-}
-
-func (m *FileOptions) GetObjcClassPrefix() string {
- if m != nil && m.ObjcClassPrefix != nil {
- return *m.ObjcClassPrefix
- }
- return ""
-}
-
-func (m *FileOptions) GetCsharpNamespace() string {
- if m != nil && m.CsharpNamespace != nil {
- return *m.CsharpNamespace
- }
- return ""
-}
-
-func (m *FileOptions) GetSwiftPrefix() string {
- if m != nil && m.SwiftPrefix != nil {
- return *m.SwiftPrefix
- }
- return ""
-}
-
-func (m *FileOptions) GetPhpClassPrefix() string {
- if m != nil && m.PhpClassPrefix != nil {
- return *m.PhpClassPrefix
- }
- return ""
-}
-
-func (m *FileOptions) GetPhpNamespace() string {
- if m != nil && m.PhpNamespace != nil {
- return *m.PhpNamespace
- }
- return ""
-}
-
-func (m *FileOptions) GetPhpMetadataNamespace() string {
- if m != nil && m.PhpMetadataNamespace != nil {
- return *m.PhpMetadataNamespace
- }
- return ""
-}
-
-func (m *FileOptions) GetRubyPackage() string {
- if m != nil && m.RubyPackage != nil {
- return *m.RubyPackage
- }
- return ""
-}
-
-func (m *FileOptions) GetUninterpretedOption() []*UninterpretedOption {
- if m != nil {
- return m.UninterpretedOption
- }
- return nil
-}
-
-type MessageOptions struct {
- // Set true to use the old proto1 MessageSet wire format for extensions.
- // This is provided for backwards-compatibility with the MessageSet wire
- // format. You should not use this for any other reason: It's less
- // efficient, has fewer features, and is more complicated.
- //
- // The message must be defined exactly as follows:
- // message Foo {
- // option message_set_wire_format = true;
- // extensions 4 to max;
- // }
- // Note that the message cannot have any defined fields; MessageSets only
- // have extensions.
- //
- // All extensions of your type must be singular messages; e.g. they cannot
- // be int32s, enums, or repeated messages.
- //
- // Because this is an option, the above two restrictions are not enforced by
- // the protocol compiler.
- MessageSetWireFormat *bool `protobuf:"varint,1,opt,name=message_set_wire_format,json=messageSetWireFormat,def=0" json:"message_set_wire_format,omitempty"`
- // Disables the generation of the standard "descriptor()" accessor, which can
- // conflict with a field of the same name. This is meant to make migration
- // from proto1 easier; new code should avoid fields named "descriptor".
- NoStandardDescriptorAccessor *bool `protobuf:"varint,2,opt,name=no_standard_descriptor_accessor,json=noStandardDescriptorAccessor,def=0" json:"no_standard_descriptor_accessor,omitempty"`
- // Is this message deprecated?
- // Depending on the target platform, this can emit Deprecated annotations
- // for the message, or it will be completely ignored; in the very least,
- // this is a formalization for deprecating messages.
- Deprecated *bool `protobuf:"varint,3,opt,name=deprecated,def=0" json:"deprecated,omitempty"`
- // Whether the message is an automatically generated map entry type for the
- // maps field.
- //
- // For maps fields:
- // map map_field = 1;
- // The parsed descriptor looks like:
- // message MapFieldEntry {
- // option map_entry = true;
- // optional KeyType key = 1;
- // optional ValueType value = 2;
- // }
- // repeated MapFieldEntry map_field = 1;
- //
- // Implementations may choose not to generate the map_entry=true message, but
- // use a native map in the target language to hold the keys and values.
- // The reflection APIs in such implementions still need to work as
- // if the field is a repeated message field.
- //
- // NOTE: Do not set the option in .proto files. Always use the maps syntax
- // instead. The option should only be implicitly set by the proto compiler
- // parser.
- MapEntry *bool `protobuf:"varint,7,opt,name=map_entry,json=mapEntry" json:"map_entry,omitempty"`
- // The parser stores options it doesn't recognize here. See above.
- UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- proto.XXX_InternalExtensions `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *MessageOptions) Reset() { *m = MessageOptions{} }
-func (m *MessageOptions) String() string { return proto.CompactTextString(m) }
-func (*MessageOptions) ProtoMessage() {}
-func (*MessageOptions) Descriptor() ([]byte, []int) {
- return fileDescriptor_e5baabe45344a177, []int{11}
-}
-
-var extRange_MessageOptions = []proto.ExtensionRange{
- {Start: 1000, End: 536870911},
-}
-
-func (*MessageOptions) ExtensionRangeArray() []proto.ExtensionRange {
- return extRange_MessageOptions
-}
-
-func (m *MessageOptions) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_MessageOptions.Unmarshal(m, b)
-}
-func (m *MessageOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_MessageOptions.Marshal(b, m, deterministic)
-}
-func (m *MessageOptions) XXX_Merge(src proto.Message) {
- xxx_messageInfo_MessageOptions.Merge(m, src)
-}
-func (m *MessageOptions) XXX_Size() int {
- return xxx_messageInfo_MessageOptions.Size(m)
-}
-func (m *MessageOptions) XXX_DiscardUnknown() {
- xxx_messageInfo_MessageOptions.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_MessageOptions proto.InternalMessageInfo
-
-const Default_MessageOptions_MessageSetWireFormat bool = false
-const Default_MessageOptions_NoStandardDescriptorAccessor bool = false
-const Default_MessageOptions_Deprecated bool = false
-
-func (m *MessageOptions) GetMessageSetWireFormat() bool {
- if m != nil && m.MessageSetWireFormat != nil {
- return *m.MessageSetWireFormat
- }
- return Default_MessageOptions_MessageSetWireFormat
-}
-
-func (m *MessageOptions) GetNoStandardDescriptorAccessor() bool {
- if m != nil && m.NoStandardDescriptorAccessor != nil {
- return *m.NoStandardDescriptorAccessor
- }
- return Default_MessageOptions_NoStandardDescriptorAccessor
-}
-
-func (m *MessageOptions) GetDeprecated() bool {
- if m != nil && m.Deprecated != nil {
- return *m.Deprecated
- }
- return Default_MessageOptions_Deprecated
-}
-
-func (m *MessageOptions) GetMapEntry() bool {
- if m != nil && m.MapEntry != nil {
- return *m.MapEntry
- }
- return false
-}
-
-func (m *MessageOptions) GetUninterpretedOption() []*UninterpretedOption {
- if m != nil {
- return m.UninterpretedOption
- }
- return nil
-}
-
-type FieldOptions struct {
- // The ctype option instructs the C++ code generator to use a different
- // representation of the field than it normally would. See the specific
- // options below. This option is not yet implemented in the open source
- // release -- sorry, we'll try to include it in a future version!
- Ctype *FieldOptions_CType `protobuf:"varint,1,opt,name=ctype,enum=google.protobuf.FieldOptions_CType,def=0" json:"ctype,omitempty"`
- // The packed option can be enabled for repeated primitive fields to enable
- // a more efficient representation on the wire. Rather than repeatedly
- // writing the tag and type for each element, the entire array is encoded as
- // a single length-delimited blob. In proto3, only explicit setting it to
- // false will avoid using packed encoding.
- Packed *bool `protobuf:"varint,2,opt,name=packed" json:"packed,omitempty"`
- // The jstype option determines the JavaScript type used for values of the
- // field. The option is permitted only for 64 bit integral and fixed types
- // (int64, uint64, sint64, fixed64, sfixed64). A field with jstype JS_STRING
- // is represented as JavaScript string, which avoids loss of precision that
- // can happen when a large value is converted to a floating point JavaScript.
- // Specifying JS_NUMBER for the jstype causes the generated JavaScript code to
- // use the JavaScript "number" type. The behavior of the default option
- // JS_NORMAL is implementation dependent.
- //
- // This option is an enum to permit additional types to be added, e.g.
- // goog.math.Integer.
- Jstype *FieldOptions_JSType `protobuf:"varint,6,opt,name=jstype,enum=google.protobuf.FieldOptions_JSType,def=0" json:"jstype,omitempty"`
- // Should this field be parsed lazily? Lazy applies only to message-type
- // fields. It means that when the outer message is initially parsed, the
- // inner message's contents will not be parsed but instead stored in encoded
- // form. The inner message will actually be parsed when it is first accessed.
- //
- // This is only a hint. Implementations are free to choose whether to use
- // eager or lazy parsing regardless of the value of this option. However,
- // setting this option true suggests that the protocol author believes that
- // using lazy parsing on this field is worth the additional bookkeeping
- // overhead typically needed to implement it.
- //
- // This option does not affect the public interface of any generated code;
- // all method signatures remain the same. Furthermore, thread-safety of the
- // interface is not affected by this option; const methods remain safe to
- // call from multiple threads concurrently, while non-const methods continue
- // to require exclusive access.
- //
- //
- // Note that implementations may choose not to check required fields within
- // a lazy sub-message. That is, calling IsInitialized() on the outer message
- // may return true even if the inner message has missing required fields.
- // This is necessary because otherwise the inner message would have to be
- // parsed in order to perform the check, defeating the purpose of lazy
- // parsing. An implementation which chooses not to check required fields
- // must be consistent about it. That is, for any particular sub-message, the
- // implementation must either *always* check its required fields, or *never*
- // check its required fields, regardless of whether or not the message has
- // been parsed.
- Lazy *bool `protobuf:"varint,5,opt,name=lazy,def=0" json:"lazy,omitempty"`
- // Is this field deprecated?
- // Depending on the target platform, this can emit Deprecated annotations
- // for accessors, or it will be completely ignored; in the very least, this
- // is a formalization for deprecating fields.
- Deprecated *bool `protobuf:"varint,3,opt,name=deprecated,def=0" json:"deprecated,omitempty"`
- // For Google-internal migration only. Do not use.
- Weak *bool `protobuf:"varint,10,opt,name=weak,def=0" json:"weak,omitempty"`
- // The parser stores options it doesn't recognize here. See above.
- UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- proto.XXX_InternalExtensions `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *FieldOptions) Reset() { *m = FieldOptions{} }
-func (m *FieldOptions) String() string { return proto.CompactTextString(m) }
-func (*FieldOptions) ProtoMessage() {}
-func (*FieldOptions) Descriptor() ([]byte, []int) {
- return fileDescriptor_e5baabe45344a177, []int{12}
-}
-
-var extRange_FieldOptions = []proto.ExtensionRange{
- {Start: 1000, End: 536870911},
-}
-
-func (*FieldOptions) ExtensionRangeArray() []proto.ExtensionRange {
- return extRange_FieldOptions
-}
-
-func (m *FieldOptions) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_FieldOptions.Unmarshal(m, b)
-}
-func (m *FieldOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_FieldOptions.Marshal(b, m, deterministic)
-}
-func (m *FieldOptions) XXX_Merge(src proto.Message) {
- xxx_messageInfo_FieldOptions.Merge(m, src)
-}
-func (m *FieldOptions) XXX_Size() int {
- return xxx_messageInfo_FieldOptions.Size(m)
-}
-func (m *FieldOptions) XXX_DiscardUnknown() {
- xxx_messageInfo_FieldOptions.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_FieldOptions proto.InternalMessageInfo
-
-const Default_FieldOptions_Ctype FieldOptions_CType = FieldOptions_STRING
-const Default_FieldOptions_Jstype FieldOptions_JSType = FieldOptions_JS_NORMAL
-const Default_FieldOptions_Lazy bool = false
-const Default_FieldOptions_Deprecated bool = false
-const Default_FieldOptions_Weak bool = false
-
-func (m *FieldOptions) GetCtype() FieldOptions_CType {
- if m != nil && m.Ctype != nil {
- return *m.Ctype
- }
- return Default_FieldOptions_Ctype
-}
-
-func (m *FieldOptions) GetPacked() bool {
- if m != nil && m.Packed != nil {
- return *m.Packed
- }
- return false
-}
-
-func (m *FieldOptions) GetJstype() FieldOptions_JSType {
- if m != nil && m.Jstype != nil {
- return *m.Jstype
- }
- return Default_FieldOptions_Jstype
-}
-
-func (m *FieldOptions) GetLazy() bool {
- if m != nil && m.Lazy != nil {
- return *m.Lazy
- }
- return Default_FieldOptions_Lazy
-}
-
-func (m *FieldOptions) GetDeprecated() bool {
- if m != nil && m.Deprecated != nil {
- return *m.Deprecated
- }
- return Default_FieldOptions_Deprecated
-}
-
-func (m *FieldOptions) GetWeak() bool {
- if m != nil && m.Weak != nil {
- return *m.Weak
- }
- return Default_FieldOptions_Weak
-}
-
-func (m *FieldOptions) GetUninterpretedOption() []*UninterpretedOption {
- if m != nil {
- return m.UninterpretedOption
- }
- return nil
-}
-
-type OneofOptions struct {
- // The parser stores options it doesn't recognize here. See above.
- UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- proto.XXX_InternalExtensions `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *OneofOptions) Reset() { *m = OneofOptions{} }
-func (m *OneofOptions) String() string { return proto.CompactTextString(m) }
-func (*OneofOptions) ProtoMessage() {}
-func (*OneofOptions) Descriptor() ([]byte, []int) {
- return fileDescriptor_e5baabe45344a177, []int{13}
-}
-
-var extRange_OneofOptions = []proto.ExtensionRange{
- {Start: 1000, End: 536870911},
-}
-
-func (*OneofOptions) ExtensionRangeArray() []proto.ExtensionRange {
- return extRange_OneofOptions
-}
-
-func (m *OneofOptions) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_OneofOptions.Unmarshal(m, b)
-}
-func (m *OneofOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_OneofOptions.Marshal(b, m, deterministic)
-}
-func (m *OneofOptions) XXX_Merge(src proto.Message) {
- xxx_messageInfo_OneofOptions.Merge(m, src)
-}
-func (m *OneofOptions) XXX_Size() int {
- return xxx_messageInfo_OneofOptions.Size(m)
-}
-func (m *OneofOptions) XXX_DiscardUnknown() {
- xxx_messageInfo_OneofOptions.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_OneofOptions proto.InternalMessageInfo
-
-func (m *OneofOptions) GetUninterpretedOption() []*UninterpretedOption {
- if m != nil {
- return m.UninterpretedOption
- }
- return nil
-}
-
-type EnumOptions struct {
- // Set this option to true to allow mapping different tag names to the same
- // value.
- AllowAlias *bool `protobuf:"varint,2,opt,name=allow_alias,json=allowAlias" json:"allow_alias,omitempty"`
- // Is this enum deprecated?
- // Depending on the target platform, this can emit Deprecated annotations
- // for the enum, or it will be completely ignored; in the very least, this
- // is a formalization for deprecating enums.
- Deprecated *bool `protobuf:"varint,3,opt,name=deprecated,def=0" json:"deprecated,omitempty"`
- // The parser stores options it doesn't recognize here. See above.
- UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- proto.XXX_InternalExtensions `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *EnumOptions) Reset() { *m = EnumOptions{} }
-func (m *EnumOptions) String() string { return proto.CompactTextString(m) }
-func (*EnumOptions) ProtoMessage() {}
-func (*EnumOptions) Descriptor() ([]byte, []int) {
- return fileDescriptor_e5baabe45344a177, []int{14}
-}
-
-var extRange_EnumOptions = []proto.ExtensionRange{
- {Start: 1000, End: 536870911},
-}
-
-func (*EnumOptions) ExtensionRangeArray() []proto.ExtensionRange {
- return extRange_EnumOptions
-}
-
-func (m *EnumOptions) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_EnumOptions.Unmarshal(m, b)
-}
-func (m *EnumOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_EnumOptions.Marshal(b, m, deterministic)
-}
-func (m *EnumOptions) XXX_Merge(src proto.Message) {
- xxx_messageInfo_EnumOptions.Merge(m, src)
-}
-func (m *EnumOptions) XXX_Size() int {
- return xxx_messageInfo_EnumOptions.Size(m)
-}
-func (m *EnumOptions) XXX_DiscardUnknown() {
- xxx_messageInfo_EnumOptions.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_EnumOptions proto.InternalMessageInfo
-
-const Default_EnumOptions_Deprecated bool = false
-
-func (m *EnumOptions) GetAllowAlias() bool {
- if m != nil && m.AllowAlias != nil {
- return *m.AllowAlias
- }
- return false
-}
-
-func (m *EnumOptions) GetDeprecated() bool {
- if m != nil && m.Deprecated != nil {
- return *m.Deprecated
- }
- return Default_EnumOptions_Deprecated
-}
-
-func (m *EnumOptions) GetUninterpretedOption() []*UninterpretedOption {
- if m != nil {
- return m.UninterpretedOption
- }
- return nil
-}
-
-type EnumValueOptions struct {
- // Is this enum value deprecated?
- // Depending on the target platform, this can emit Deprecated annotations
- // for the enum value, or it will be completely ignored; in the very least,
- // this is a formalization for deprecating enum values.
- Deprecated *bool `protobuf:"varint,1,opt,name=deprecated,def=0" json:"deprecated,omitempty"`
- // The parser stores options it doesn't recognize here. See above.
- UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- proto.XXX_InternalExtensions `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *EnumValueOptions) Reset() { *m = EnumValueOptions{} }
-func (m *EnumValueOptions) String() string { return proto.CompactTextString(m) }
-func (*EnumValueOptions) ProtoMessage() {}
-func (*EnumValueOptions) Descriptor() ([]byte, []int) {
- return fileDescriptor_e5baabe45344a177, []int{15}
-}
-
-var extRange_EnumValueOptions = []proto.ExtensionRange{
- {Start: 1000, End: 536870911},
-}
-
-func (*EnumValueOptions) ExtensionRangeArray() []proto.ExtensionRange {
- return extRange_EnumValueOptions
-}
-
-func (m *EnumValueOptions) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_EnumValueOptions.Unmarshal(m, b)
-}
-func (m *EnumValueOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_EnumValueOptions.Marshal(b, m, deterministic)
-}
-func (m *EnumValueOptions) XXX_Merge(src proto.Message) {
- xxx_messageInfo_EnumValueOptions.Merge(m, src)
-}
-func (m *EnumValueOptions) XXX_Size() int {
- return xxx_messageInfo_EnumValueOptions.Size(m)
-}
-func (m *EnumValueOptions) XXX_DiscardUnknown() {
- xxx_messageInfo_EnumValueOptions.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_EnumValueOptions proto.InternalMessageInfo
-
-const Default_EnumValueOptions_Deprecated bool = false
-
-func (m *EnumValueOptions) GetDeprecated() bool {
- if m != nil && m.Deprecated != nil {
- return *m.Deprecated
- }
- return Default_EnumValueOptions_Deprecated
-}
-
-func (m *EnumValueOptions) GetUninterpretedOption() []*UninterpretedOption {
- if m != nil {
- return m.UninterpretedOption
- }
- return nil
-}
-
-type ServiceOptions struct {
- // Is this service deprecated?
- // Depending on the target platform, this can emit Deprecated annotations
- // for the service, or it will be completely ignored; in the very least,
- // this is a formalization for deprecating services.
- Deprecated *bool `protobuf:"varint,33,opt,name=deprecated,def=0" json:"deprecated,omitempty"`
- // The parser stores options it doesn't recognize here. See above.
- UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- proto.XXX_InternalExtensions `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *ServiceOptions) Reset() { *m = ServiceOptions{} }
-func (m *ServiceOptions) String() string { return proto.CompactTextString(m) }
-func (*ServiceOptions) ProtoMessage() {}
-func (*ServiceOptions) Descriptor() ([]byte, []int) {
- return fileDescriptor_e5baabe45344a177, []int{16}
-}
-
-var extRange_ServiceOptions = []proto.ExtensionRange{
- {Start: 1000, End: 536870911},
-}
-
-func (*ServiceOptions) ExtensionRangeArray() []proto.ExtensionRange {
- return extRange_ServiceOptions
-}
-
-func (m *ServiceOptions) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_ServiceOptions.Unmarshal(m, b)
-}
-func (m *ServiceOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_ServiceOptions.Marshal(b, m, deterministic)
-}
-func (m *ServiceOptions) XXX_Merge(src proto.Message) {
- xxx_messageInfo_ServiceOptions.Merge(m, src)
-}
-func (m *ServiceOptions) XXX_Size() int {
- return xxx_messageInfo_ServiceOptions.Size(m)
-}
-func (m *ServiceOptions) XXX_DiscardUnknown() {
- xxx_messageInfo_ServiceOptions.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_ServiceOptions proto.InternalMessageInfo
-
-const Default_ServiceOptions_Deprecated bool = false
-
-func (m *ServiceOptions) GetDeprecated() bool {
- if m != nil && m.Deprecated != nil {
- return *m.Deprecated
- }
- return Default_ServiceOptions_Deprecated
-}
-
-func (m *ServiceOptions) GetUninterpretedOption() []*UninterpretedOption {
- if m != nil {
- return m.UninterpretedOption
- }
- return nil
-}
-
-type MethodOptions struct {
- // Is this method deprecated?
- // Depending on the target platform, this can emit Deprecated annotations
- // for the method, or it will be completely ignored; in the very least,
- // this is a formalization for deprecating methods.
- Deprecated *bool `protobuf:"varint,33,opt,name=deprecated,def=0" json:"deprecated,omitempty"`
- IdempotencyLevel *MethodOptions_IdempotencyLevel `protobuf:"varint,34,opt,name=idempotency_level,json=idempotencyLevel,enum=google.protobuf.MethodOptions_IdempotencyLevel,def=0" json:"idempotency_level,omitempty"`
- // The parser stores options it doesn't recognize here. See above.
- UninterpretedOption []*UninterpretedOption `protobuf:"bytes,999,rep,name=uninterpreted_option,json=uninterpretedOption" json:"uninterpreted_option,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- proto.XXX_InternalExtensions `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *MethodOptions) Reset() { *m = MethodOptions{} }
-func (m *MethodOptions) String() string { return proto.CompactTextString(m) }
-func (*MethodOptions) ProtoMessage() {}
-func (*MethodOptions) Descriptor() ([]byte, []int) {
- return fileDescriptor_e5baabe45344a177, []int{17}
-}
-
-var extRange_MethodOptions = []proto.ExtensionRange{
- {Start: 1000, End: 536870911},
-}
-
-func (*MethodOptions) ExtensionRangeArray() []proto.ExtensionRange {
- return extRange_MethodOptions
-}
-
-func (m *MethodOptions) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_MethodOptions.Unmarshal(m, b)
-}
-func (m *MethodOptions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_MethodOptions.Marshal(b, m, deterministic)
-}
-func (m *MethodOptions) XXX_Merge(src proto.Message) {
- xxx_messageInfo_MethodOptions.Merge(m, src)
-}
-func (m *MethodOptions) XXX_Size() int {
- return xxx_messageInfo_MethodOptions.Size(m)
-}
-func (m *MethodOptions) XXX_DiscardUnknown() {
- xxx_messageInfo_MethodOptions.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_MethodOptions proto.InternalMessageInfo
-
-const Default_MethodOptions_Deprecated bool = false
-const Default_MethodOptions_IdempotencyLevel MethodOptions_IdempotencyLevel = MethodOptions_IDEMPOTENCY_UNKNOWN
-
-func (m *MethodOptions) GetDeprecated() bool {
- if m != nil && m.Deprecated != nil {
- return *m.Deprecated
- }
- return Default_MethodOptions_Deprecated
-}
-
-func (m *MethodOptions) GetIdempotencyLevel() MethodOptions_IdempotencyLevel {
- if m != nil && m.IdempotencyLevel != nil {
- return *m.IdempotencyLevel
- }
- return Default_MethodOptions_IdempotencyLevel
-}
-
-func (m *MethodOptions) GetUninterpretedOption() []*UninterpretedOption {
- if m != nil {
- return m.UninterpretedOption
- }
- return nil
-}
-
-// A message representing a option the parser does not recognize. This only
-// appears in options protos created by the compiler::Parser class.
-// DescriptorPool resolves these when building Descriptor objects. Therefore,
-// options protos in descriptor objects (e.g. returned by Descriptor::options(),
-// or produced by Descriptor::CopyTo()) will never have UninterpretedOptions
-// in them.
-type UninterpretedOption struct {
- Name []*UninterpretedOption_NamePart `protobuf:"bytes,2,rep,name=name" json:"name,omitempty"`
- // The value of the uninterpreted option, in whatever type the tokenizer
- // identified it as during parsing. Exactly one of these should be set.
- IdentifierValue *string `protobuf:"bytes,3,opt,name=identifier_value,json=identifierValue" json:"identifier_value,omitempty"`
- PositiveIntValue *uint64 `protobuf:"varint,4,opt,name=positive_int_value,json=positiveIntValue" json:"positive_int_value,omitempty"`
- NegativeIntValue *int64 `protobuf:"varint,5,opt,name=negative_int_value,json=negativeIntValue" json:"negative_int_value,omitempty"`
- DoubleValue *float64 `protobuf:"fixed64,6,opt,name=double_value,json=doubleValue" json:"double_value,omitempty"`
- StringValue []byte `protobuf:"bytes,7,opt,name=string_value,json=stringValue" json:"string_value,omitempty"`
- AggregateValue *string `protobuf:"bytes,8,opt,name=aggregate_value,json=aggregateValue" json:"aggregate_value,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *UninterpretedOption) Reset() { *m = UninterpretedOption{} }
-func (m *UninterpretedOption) String() string { return proto.CompactTextString(m) }
-func (*UninterpretedOption) ProtoMessage() {}
-func (*UninterpretedOption) Descriptor() ([]byte, []int) {
- return fileDescriptor_e5baabe45344a177, []int{18}
-}
-
-func (m *UninterpretedOption) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_UninterpretedOption.Unmarshal(m, b)
-}
-func (m *UninterpretedOption) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_UninterpretedOption.Marshal(b, m, deterministic)
-}
-func (m *UninterpretedOption) XXX_Merge(src proto.Message) {
- xxx_messageInfo_UninterpretedOption.Merge(m, src)
-}
-func (m *UninterpretedOption) XXX_Size() int {
- return xxx_messageInfo_UninterpretedOption.Size(m)
-}
-func (m *UninterpretedOption) XXX_DiscardUnknown() {
- xxx_messageInfo_UninterpretedOption.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_UninterpretedOption proto.InternalMessageInfo
-
-func (m *UninterpretedOption) GetName() []*UninterpretedOption_NamePart {
- if m != nil {
- return m.Name
- }
- return nil
-}
-
-func (m *UninterpretedOption) GetIdentifierValue() string {
- if m != nil && m.IdentifierValue != nil {
- return *m.IdentifierValue
- }
- return ""
-}
-
-func (m *UninterpretedOption) GetPositiveIntValue() uint64 {
- if m != nil && m.PositiveIntValue != nil {
- return *m.PositiveIntValue
- }
- return 0
-}
-
-func (m *UninterpretedOption) GetNegativeIntValue() int64 {
- if m != nil && m.NegativeIntValue != nil {
- return *m.NegativeIntValue
- }
- return 0
-}
-
-func (m *UninterpretedOption) GetDoubleValue() float64 {
- if m != nil && m.DoubleValue != nil {
- return *m.DoubleValue
- }
- return 0
-}
-
-func (m *UninterpretedOption) GetStringValue() []byte {
- if m != nil {
- return m.StringValue
- }
- return nil
-}
-
-func (m *UninterpretedOption) GetAggregateValue() string {
- if m != nil && m.AggregateValue != nil {
- return *m.AggregateValue
- }
- return ""
-}
-
-// The name of the uninterpreted option. Each string represents a segment in
-// a dot-separated name. is_extension is true iff a segment represents an
-// extension (denoted with parentheses in options specs in .proto files).
-// E.g.,{ ["foo", false], ["bar.baz", true], ["qux", false] } represents
-// "foo.(bar.baz).qux".
-type UninterpretedOption_NamePart struct {
- NamePart *string `protobuf:"bytes,1,req,name=name_part,json=namePart" json:"name_part,omitempty"`
- IsExtension *bool `protobuf:"varint,2,req,name=is_extension,json=isExtension" json:"is_extension,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *UninterpretedOption_NamePart) Reset() { *m = UninterpretedOption_NamePart{} }
-func (m *UninterpretedOption_NamePart) String() string { return proto.CompactTextString(m) }
-func (*UninterpretedOption_NamePart) ProtoMessage() {}
-func (*UninterpretedOption_NamePart) Descriptor() ([]byte, []int) {
- return fileDescriptor_e5baabe45344a177, []int{18, 0}
-}
-
-func (m *UninterpretedOption_NamePart) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_UninterpretedOption_NamePart.Unmarshal(m, b)
-}
-func (m *UninterpretedOption_NamePart) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_UninterpretedOption_NamePart.Marshal(b, m, deterministic)
-}
-func (m *UninterpretedOption_NamePart) XXX_Merge(src proto.Message) {
- xxx_messageInfo_UninterpretedOption_NamePart.Merge(m, src)
-}
-func (m *UninterpretedOption_NamePart) XXX_Size() int {
- return xxx_messageInfo_UninterpretedOption_NamePart.Size(m)
-}
-func (m *UninterpretedOption_NamePart) XXX_DiscardUnknown() {
- xxx_messageInfo_UninterpretedOption_NamePart.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_UninterpretedOption_NamePart proto.InternalMessageInfo
-
-func (m *UninterpretedOption_NamePart) GetNamePart() string {
- if m != nil && m.NamePart != nil {
- return *m.NamePart
- }
- return ""
-}
-
-func (m *UninterpretedOption_NamePart) GetIsExtension() bool {
- if m != nil && m.IsExtension != nil {
- return *m.IsExtension
- }
- return false
-}
-
-// Encapsulates information about the original source file from which a
-// FileDescriptorProto was generated.
-type SourceCodeInfo struct {
- // A Location identifies a piece of source code in a .proto file which
- // corresponds to a particular definition. This information is intended
- // to be useful to IDEs, code indexers, documentation generators, and similar
- // tools.
- //
- // For example, say we have a file like:
- // message Foo {
- // optional string foo = 1;
- // }
- // Let's look at just the field definition:
- // optional string foo = 1;
- // ^ ^^ ^^ ^ ^^^
- // a bc de f ghi
- // We have the following locations:
- // span path represents
- // [a,i) [ 4, 0, 2, 0 ] The whole field definition.
- // [a,b) [ 4, 0, 2, 0, 4 ] The label (optional).
- // [c,d) [ 4, 0, 2, 0, 5 ] The type (string).
- // [e,f) [ 4, 0, 2, 0, 1 ] The name (foo).
- // [g,h) [ 4, 0, 2, 0, 3 ] The number (1).
- //
- // Notes:
- // - A location may refer to a repeated field itself (i.e. not to any
- // particular index within it). This is used whenever a set of elements are
- // logically enclosed in a single code segment. For example, an entire
- // extend block (possibly containing multiple extension definitions) will
- // have an outer location whose path refers to the "extensions" repeated
- // field without an index.
- // - Multiple locations may have the same path. This happens when a single
- // logical declaration is spread out across multiple places. The most
- // obvious example is the "extend" block again -- there may be multiple
- // extend blocks in the same scope, each of which will have the same path.
- // - A location's span is not always a subset of its parent's span. For
- // example, the "extendee" of an extension declaration appears at the
- // beginning of the "extend" block and is shared by all extensions within
- // the block.
- // - Just because a location's span is a subset of some other location's span
- // does not mean that it is a descendent. For example, a "group" defines
- // both a type and a field in a single declaration. Thus, the locations
- // corresponding to the type and field and their components will overlap.
- // - Code which tries to interpret locations should probably be designed to
- // ignore those that it doesn't understand, as more types of locations could
- // be recorded in the future.
- Location []*SourceCodeInfo_Location `protobuf:"bytes,1,rep,name=location" json:"location,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *SourceCodeInfo) Reset() { *m = SourceCodeInfo{} }
-func (m *SourceCodeInfo) String() string { return proto.CompactTextString(m) }
-func (*SourceCodeInfo) ProtoMessage() {}
-func (*SourceCodeInfo) Descriptor() ([]byte, []int) {
- return fileDescriptor_e5baabe45344a177, []int{19}
-}
-
-func (m *SourceCodeInfo) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_SourceCodeInfo.Unmarshal(m, b)
-}
-func (m *SourceCodeInfo) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_SourceCodeInfo.Marshal(b, m, deterministic)
-}
-func (m *SourceCodeInfo) XXX_Merge(src proto.Message) {
- xxx_messageInfo_SourceCodeInfo.Merge(m, src)
-}
-func (m *SourceCodeInfo) XXX_Size() int {
- return xxx_messageInfo_SourceCodeInfo.Size(m)
-}
-func (m *SourceCodeInfo) XXX_DiscardUnknown() {
- xxx_messageInfo_SourceCodeInfo.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_SourceCodeInfo proto.InternalMessageInfo
-
-func (m *SourceCodeInfo) GetLocation() []*SourceCodeInfo_Location {
- if m != nil {
- return m.Location
- }
- return nil
-}
-
-type SourceCodeInfo_Location struct {
- // Identifies which part of the FileDescriptorProto was defined at this
- // location.
- //
- // Each element is a field number or an index. They form a path from
- // the root FileDescriptorProto to the place where the definition. For
- // example, this path:
- // [ 4, 3, 2, 7, 1 ]
- // refers to:
- // file.message_type(3) // 4, 3
- // .field(7) // 2, 7
- // .name() // 1
- // This is because FileDescriptorProto.message_type has field number 4:
- // repeated DescriptorProto message_type = 4;
- // and DescriptorProto.field has field number 2:
- // repeated FieldDescriptorProto field = 2;
- // and FieldDescriptorProto.name has field number 1:
- // optional string name = 1;
- //
- // Thus, the above path gives the location of a field name. If we removed
- // the last element:
- // [ 4, 3, 2, 7 ]
- // this path refers to the whole field declaration (from the beginning
- // of the label to the terminating semicolon).
- Path []int32 `protobuf:"varint,1,rep,packed,name=path" json:"path,omitempty"`
- // Always has exactly three or four elements: start line, start column,
- // end line (optional, otherwise assumed same as start line), end column.
- // These are packed into a single field for efficiency. Note that line
- // and column numbers are zero-based -- typically you will want to add
- // 1 to each before displaying to a user.
- Span []int32 `protobuf:"varint,2,rep,packed,name=span" json:"span,omitempty"`
- // If this SourceCodeInfo represents a complete declaration, these are any
- // comments appearing before and after the declaration which appear to be
- // attached to the declaration.
- //
- // A series of line comments appearing on consecutive lines, with no other
- // tokens appearing on those lines, will be treated as a single comment.
- //
- // leading_detached_comments will keep paragraphs of comments that appear
- // before (but not connected to) the current element. Each paragraph,
- // separated by empty lines, will be one comment element in the repeated
- // field.
- //
- // Only the comment content is provided; comment markers (e.g. //) are
- // stripped out. For block comments, leading whitespace and an asterisk
- // will be stripped from the beginning of each line other than the first.
- // Newlines are included in the output.
- //
- // Examples:
- //
- // optional int32 foo = 1; // Comment attached to foo.
- // // Comment attached to bar.
- // optional int32 bar = 2;
- //
- // optional string baz = 3;
- // // Comment attached to baz.
- // // Another line attached to baz.
- //
- // // Comment attached to qux.
- // //
- // // Another line attached to qux.
- // optional double qux = 4;
- //
- // // Detached comment for corge. This is not leading or trailing comments
- // // to qux or corge because there are blank lines separating it from
- // // both.
- //
- // // Detached comment for corge paragraph 2.
- //
- // optional string corge = 5;
- // /* Block comment attached
- // * to corge. Leading asterisks
- // * will be removed. */
- // /* Block comment attached to
- // * grault. */
- // optional int32 grault = 6;
- //
- // // ignored detached comments.
- LeadingComments *string `protobuf:"bytes,3,opt,name=leading_comments,json=leadingComments" json:"leading_comments,omitempty"`
- TrailingComments *string `protobuf:"bytes,4,opt,name=trailing_comments,json=trailingComments" json:"trailing_comments,omitempty"`
- LeadingDetachedComments []string `protobuf:"bytes,6,rep,name=leading_detached_comments,json=leadingDetachedComments" json:"leading_detached_comments,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *SourceCodeInfo_Location) Reset() { *m = SourceCodeInfo_Location{} }
-func (m *SourceCodeInfo_Location) String() string { return proto.CompactTextString(m) }
-func (*SourceCodeInfo_Location) ProtoMessage() {}
-func (*SourceCodeInfo_Location) Descriptor() ([]byte, []int) {
- return fileDescriptor_e5baabe45344a177, []int{19, 0}
-}
-
-func (m *SourceCodeInfo_Location) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_SourceCodeInfo_Location.Unmarshal(m, b)
-}
-func (m *SourceCodeInfo_Location) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_SourceCodeInfo_Location.Marshal(b, m, deterministic)
-}
-func (m *SourceCodeInfo_Location) XXX_Merge(src proto.Message) {
- xxx_messageInfo_SourceCodeInfo_Location.Merge(m, src)
-}
-func (m *SourceCodeInfo_Location) XXX_Size() int {
- return xxx_messageInfo_SourceCodeInfo_Location.Size(m)
-}
-func (m *SourceCodeInfo_Location) XXX_DiscardUnknown() {
- xxx_messageInfo_SourceCodeInfo_Location.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_SourceCodeInfo_Location proto.InternalMessageInfo
-
-func (m *SourceCodeInfo_Location) GetPath() []int32 {
- if m != nil {
- return m.Path
- }
- return nil
-}
-
-func (m *SourceCodeInfo_Location) GetSpan() []int32 {
- if m != nil {
- return m.Span
- }
- return nil
-}
-
-func (m *SourceCodeInfo_Location) GetLeadingComments() string {
- if m != nil && m.LeadingComments != nil {
- return *m.LeadingComments
- }
- return ""
-}
-
-func (m *SourceCodeInfo_Location) GetTrailingComments() string {
- if m != nil && m.TrailingComments != nil {
- return *m.TrailingComments
- }
- return ""
-}
-
-func (m *SourceCodeInfo_Location) GetLeadingDetachedComments() []string {
- if m != nil {
- return m.LeadingDetachedComments
- }
- return nil
-}
-
-// Describes the relationship between generated code and its original source
-// file. A GeneratedCodeInfo message is associated with only one generated
-// source file, but may contain references to different source .proto files.
-type GeneratedCodeInfo struct {
- // An Annotation connects some span of text in generated code to an element
- // of its generating .proto file.
- Annotation []*GeneratedCodeInfo_Annotation `protobuf:"bytes,1,rep,name=annotation" json:"annotation,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *GeneratedCodeInfo) Reset() { *m = GeneratedCodeInfo{} }
-func (m *GeneratedCodeInfo) String() string { return proto.CompactTextString(m) }
-func (*GeneratedCodeInfo) ProtoMessage() {}
-func (*GeneratedCodeInfo) Descriptor() ([]byte, []int) {
- return fileDescriptor_e5baabe45344a177, []int{20}
-}
-
-func (m *GeneratedCodeInfo) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_GeneratedCodeInfo.Unmarshal(m, b)
-}
-func (m *GeneratedCodeInfo) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_GeneratedCodeInfo.Marshal(b, m, deterministic)
-}
-func (m *GeneratedCodeInfo) XXX_Merge(src proto.Message) {
- xxx_messageInfo_GeneratedCodeInfo.Merge(m, src)
-}
-func (m *GeneratedCodeInfo) XXX_Size() int {
- return xxx_messageInfo_GeneratedCodeInfo.Size(m)
-}
-func (m *GeneratedCodeInfo) XXX_DiscardUnknown() {
- xxx_messageInfo_GeneratedCodeInfo.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_GeneratedCodeInfo proto.InternalMessageInfo
-
-func (m *GeneratedCodeInfo) GetAnnotation() []*GeneratedCodeInfo_Annotation {
- if m != nil {
- return m.Annotation
- }
- return nil
-}
-
-type GeneratedCodeInfo_Annotation struct {
- // Identifies the element in the original source .proto file. This field
- // is formatted the same as SourceCodeInfo.Location.path.
- Path []int32 `protobuf:"varint,1,rep,packed,name=path" json:"path,omitempty"`
- // Identifies the filesystem path to the original source .proto.
- SourceFile *string `protobuf:"bytes,2,opt,name=source_file,json=sourceFile" json:"source_file,omitempty"`
- // Identifies the starting offset in bytes in the generated code
- // that relates to the identified object.
- Begin *int32 `protobuf:"varint,3,opt,name=begin" json:"begin,omitempty"`
- // Identifies the ending offset in bytes in the generated code that
- // relates to the identified offset. The end offset should be one past
- // the last relevant byte (so the length of the text = end - begin).
- End *int32 `protobuf:"varint,4,opt,name=end" json:"end,omitempty"`
- XXX_NoUnkeyedLiteral struct{} `json:"-"`
- XXX_unrecognized []byte `json:"-"`
- XXX_sizecache int32 `json:"-"`
-}
-
-func (m *GeneratedCodeInfo_Annotation) Reset() { *m = GeneratedCodeInfo_Annotation{} }
-func (m *GeneratedCodeInfo_Annotation) String() string { return proto.CompactTextString(m) }
-func (*GeneratedCodeInfo_Annotation) ProtoMessage() {}
-func (*GeneratedCodeInfo_Annotation) Descriptor() ([]byte, []int) {
- return fileDescriptor_e5baabe45344a177, []int{20, 0}
-}
-
-func (m *GeneratedCodeInfo_Annotation) XXX_Unmarshal(b []byte) error {
- return xxx_messageInfo_GeneratedCodeInfo_Annotation.Unmarshal(m, b)
-}
-func (m *GeneratedCodeInfo_Annotation) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
- return xxx_messageInfo_GeneratedCodeInfo_Annotation.Marshal(b, m, deterministic)
-}
-func (m *GeneratedCodeInfo_Annotation) XXX_Merge(src proto.Message) {
- xxx_messageInfo_GeneratedCodeInfo_Annotation.Merge(m, src)
-}
-func (m *GeneratedCodeInfo_Annotation) XXX_Size() int {
- return xxx_messageInfo_GeneratedCodeInfo_Annotation.Size(m)
-}
-func (m *GeneratedCodeInfo_Annotation) XXX_DiscardUnknown() {
- xxx_messageInfo_GeneratedCodeInfo_Annotation.DiscardUnknown(m)
-}
-
-var xxx_messageInfo_GeneratedCodeInfo_Annotation proto.InternalMessageInfo
-
-func (m *GeneratedCodeInfo_Annotation) GetPath() []int32 {
- if m != nil {
- return m.Path
- }
- return nil
-}
-
-func (m *GeneratedCodeInfo_Annotation) GetSourceFile() string {
- if m != nil && m.SourceFile != nil {
- return *m.SourceFile
- }
- return ""
-}
-
-func (m *GeneratedCodeInfo_Annotation) GetBegin() int32 {
- if m != nil && m.Begin != nil {
- return *m.Begin
- }
- return 0
-}
-
-func (m *GeneratedCodeInfo_Annotation) GetEnd() int32 {
- if m != nil && m.End != nil {
- return *m.End
- }
- return 0
-}
-
-func init() {
- proto.RegisterEnum("google.protobuf.FieldDescriptorProto_Type", FieldDescriptorProto_Type_name, FieldDescriptorProto_Type_value)
- proto.RegisterEnum("google.protobuf.FieldDescriptorProto_Label", FieldDescriptorProto_Label_name, FieldDescriptorProto_Label_value)
- proto.RegisterEnum("google.protobuf.FileOptions_OptimizeMode", FileOptions_OptimizeMode_name, FileOptions_OptimizeMode_value)
- proto.RegisterEnum("google.protobuf.FieldOptions_CType", FieldOptions_CType_name, FieldOptions_CType_value)
- proto.RegisterEnum("google.protobuf.FieldOptions_JSType", FieldOptions_JSType_name, FieldOptions_JSType_value)
- proto.RegisterEnum("google.protobuf.MethodOptions_IdempotencyLevel", MethodOptions_IdempotencyLevel_name, MethodOptions_IdempotencyLevel_value)
- proto.RegisterType((*FileDescriptorSet)(nil), "google.protobuf.FileDescriptorSet")
- proto.RegisterType((*FileDescriptorProto)(nil), "google.protobuf.FileDescriptorProto")
- proto.RegisterType((*DescriptorProto)(nil), "google.protobuf.DescriptorProto")
- proto.RegisterType((*DescriptorProto_ExtensionRange)(nil), "google.protobuf.DescriptorProto.ExtensionRange")
- proto.RegisterType((*DescriptorProto_ReservedRange)(nil), "google.protobuf.DescriptorProto.ReservedRange")
- proto.RegisterType((*ExtensionRangeOptions)(nil), "google.protobuf.ExtensionRangeOptions")
- proto.RegisterType((*FieldDescriptorProto)(nil), "google.protobuf.FieldDescriptorProto")
- proto.RegisterType((*OneofDescriptorProto)(nil), "google.protobuf.OneofDescriptorProto")
- proto.RegisterType((*EnumDescriptorProto)(nil), "google.protobuf.EnumDescriptorProto")
- proto.RegisterType((*EnumDescriptorProto_EnumReservedRange)(nil), "google.protobuf.EnumDescriptorProto.EnumReservedRange")
- proto.RegisterType((*EnumValueDescriptorProto)(nil), "google.protobuf.EnumValueDescriptorProto")
- proto.RegisterType((*ServiceDescriptorProto)(nil), "google.protobuf.ServiceDescriptorProto")
- proto.RegisterType((*MethodDescriptorProto)(nil), "google.protobuf.MethodDescriptorProto")
- proto.RegisterType((*FileOptions)(nil), "google.protobuf.FileOptions")
- proto.RegisterType((*MessageOptions)(nil), "google.protobuf.MessageOptions")
- proto.RegisterType((*FieldOptions)(nil), "google.protobuf.FieldOptions")
- proto.RegisterType((*OneofOptions)(nil), "google.protobuf.OneofOptions")
- proto.RegisterType((*EnumOptions)(nil), "google.protobuf.EnumOptions")
- proto.RegisterType((*EnumValueOptions)(nil), "google.protobuf.EnumValueOptions")
- proto.RegisterType((*ServiceOptions)(nil), "google.protobuf.ServiceOptions")
- proto.RegisterType((*MethodOptions)(nil), "google.protobuf.MethodOptions")
- proto.RegisterType((*UninterpretedOption)(nil), "google.protobuf.UninterpretedOption")
- proto.RegisterType((*UninterpretedOption_NamePart)(nil), "google.protobuf.UninterpretedOption.NamePart")
- proto.RegisterType((*SourceCodeInfo)(nil), "google.protobuf.SourceCodeInfo")
- proto.RegisterType((*SourceCodeInfo_Location)(nil), "google.protobuf.SourceCodeInfo.Location")
- proto.RegisterType((*GeneratedCodeInfo)(nil), "google.protobuf.GeneratedCodeInfo")
- proto.RegisterType((*GeneratedCodeInfo_Annotation)(nil), "google.protobuf.GeneratedCodeInfo.Annotation")
-}
-
-func init() { proto.RegisterFile("google/protobuf/descriptor.proto", fileDescriptor_e5baabe45344a177) }
-
-var fileDescriptor_e5baabe45344a177 = []byte{
- // 2589 bytes of a gzipped FileDescriptorProto
- 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xc4, 0x59, 0xdd, 0x8e, 0xdb, 0xc6,
- 0x15, 0x0e, 0xf5, 0xb7, 0xd2, 0x91, 0x56, 0x3b, 0x3b, 0xbb, 0xb1, 0xe9, 0xcd, 0x8f, 0xd7, 0xca,
- 0x8f, 0xd7, 0x4e, 0xac, 0x0d, 0x1c, 0xdb, 0x71, 0xd6, 0x45, 0x5a, 0xad, 0x44, 0x6f, 0xe4, 0xee,
- 0x4a, 0x2a, 0xa5, 0x6d, 0x7e, 0x80, 0x82, 0x98, 0x25, 0x47, 0x12, 0x6d, 0x8a, 0x64, 0x48, 0xca,
- 0xf6, 0x06, 0xbd, 0x30, 0xd0, 0xab, 0x5e, 0x15, 0xe8, 0x55, 0x51, 0x14, 0xbd, 0xe8, 0x4d, 0x80,
- 0x3e, 0x40, 0x81, 0xde, 0xf5, 0x09, 0x0a, 0xe4, 0x0d, 0x8a, 0xb6, 0x40, 0xfb, 0x08, 0xbd, 0x2c,
- 0x66, 0x86, 0xa4, 0x48, 0x49, 0x1b, 0x6f, 0x02, 0xc4, 0xb9, 0x92, 0xe6, 0x3b, 0xdf, 0x39, 0x73,
- 0xe6, 0xcc, 0x99, 0x99, 0x33, 0x43, 0xd8, 0x1e, 0x39, 0xce, 0xc8, 0xa2, 0xbb, 0xae, 0xe7, 0x04,
- 0xce, 0xc9, 0x74, 0xb8, 0x6b, 0x50, 0x5f, 0xf7, 0x4c, 0x37, 0x70, 0xbc, 0x3a, 0xc7, 0xf0, 0x9a,
- 0x60, 0xd4, 0x23, 0x46, 0xed, 0x08, 0xd6, 0xef, 0x9b, 0x16, 0x6d, 0xc5, 0xc4, 0x3e, 0x0d, 0xf0,
- 0x5d, 0xc8, 0x0d, 0x4d, 0x8b, 0xca, 0xd2, 0x76, 0x76, 0xa7, 0x7c, 0xf3, 0xcd, 0xfa, 0x9c, 0x52,
- 0x3d, 0xad, 0xd1, 0x63, 0xb0, 0xca, 0x35, 0x6a, 0xff, 0xce, 0xc1, 0xc6, 0x12, 0x29, 0xc6, 0x90,
- 0xb3, 0xc9, 0x84, 0x59, 0x94, 0x76, 0x4a, 0x2a, 0xff, 0x8f, 0x65, 0x58, 0x71, 0x89, 0xfe, 0x88,
- 0x8c, 0xa8, 0x9c, 0xe1, 0x70, 0xd4, 0xc4, 0xaf, 0x03, 0x18, 0xd4, 0xa5, 0xb6, 0x41, 0x6d, 0xfd,
- 0x54, 0xce, 0x6e, 0x67, 0x77, 0x4a, 0x6a, 0x02, 0xc1, 0xef, 0xc0, 0xba, 0x3b, 0x3d, 0xb1, 0x4c,
- 0x5d, 0x4b, 0xd0, 0x60, 0x3b, 0xbb, 0x93, 0x57, 0x91, 0x10, 0xb4, 0x66, 0xe4, 0xab, 0xb0, 0xf6,
- 0x84, 0x92, 0x47, 0x49, 0x6a, 0x99, 0x53, 0xab, 0x0c, 0x4e, 0x10, 0x9b, 0x50, 0x99, 0x50, 0xdf,
- 0x27, 0x23, 0xaa, 0x05, 0xa7, 0x2e, 0x95, 0x73, 0x7c, 0xf4, 0xdb, 0x0b, 0xa3, 0x9f, 0x1f, 0x79,
- 0x39, 0xd4, 0x1a, 0x9c, 0xba, 0x14, 0x37, 0xa0, 0x44, 0xed, 0xe9, 0x44, 0x58, 0xc8, 0x9f, 0x11,
- 0x3f, 0xc5, 0x9e, 0x4e, 0xe6, 0xad, 0x14, 0x99, 0x5a, 0x68, 0x62, 0xc5, 0xa7, 0xde, 0x63, 0x53,
- 0xa7, 0x72, 0x81, 0x1b, 0xb8, 0xba, 0x60, 0xa0, 0x2f, 0xe4, 0xf3, 0x36, 0x22, 0x3d, 0xdc, 0x84,
- 0x12, 0x7d, 0x1a, 0x50, 0xdb, 0x37, 0x1d, 0x5b, 0x5e, 0xe1, 0x46, 0xde, 0x5a, 0x32, 0x8b, 0xd4,
- 0x32, 0xe6, 0x4d, 0xcc, 0xf4, 0xf0, 0x1d, 0x58, 0x71, 0xdc, 0xc0, 0x74, 0x6c, 0x5f, 0x2e, 0x6e,
- 0x4b, 0x3b, 0xe5, 0x9b, 0xaf, 0x2e, 0x4d, 0x84, 0xae, 0xe0, 0xa8, 0x11, 0x19, 0xb7, 0x01, 0xf9,
- 0xce, 0xd4, 0xd3, 0xa9, 0xa6, 0x3b, 0x06, 0xd5, 0x4c, 0x7b, 0xe8, 0xc8, 0x25, 0x6e, 0xe0, 0xf2,
- 0xe2, 0x40, 0x38, 0xb1, 0xe9, 0x18, 0xb4, 0x6d, 0x0f, 0x1d, 0xb5, 0xea, 0xa7, 0xda, 0xf8, 0x02,
- 0x14, 0xfc, 0x53, 0x3b, 0x20, 0x4f, 0xe5, 0x0a, 0xcf, 0x90, 0xb0, 0x55, 0xfb, 0x6b, 0x01, 0xd6,
- 0xce, 0x93, 0x62, 0xf7, 0x20, 0x3f, 0x64, 0xa3, 0x94, 0x33, 0xdf, 0x26, 0x06, 0x42, 0x27, 0x1d,
- 0xc4, 0xc2, 0x77, 0x0c, 0x62, 0x03, 0xca, 0x36, 0xf5, 0x03, 0x6a, 0x88, 0x8c, 0xc8, 0x9e, 0x33,
- 0xa7, 0x40, 0x28, 0x2d, 0xa6, 0x54, 0xee, 0x3b, 0xa5, 0xd4, 0xa7, 0xb0, 0x16, 0xbb, 0xa4, 0x79,
- 0xc4, 0x1e, 0x45, 0xb9, 0xb9, 0xfb, 0x3c, 0x4f, 0xea, 0x4a, 0xa4, 0xa7, 0x32, 0x35, 0xb5, 0x4a,
- 0x53, 0x6d, 0xdc, 0x02, 0x70, 0x6c, 0xea, 0x0c, 0x35, 0x83, 0xea, 0x96, 0x5c, 0x3c, 0x23, 0x4a,
- 0x5d, 0x46, 0x59, 0x88, 0x92, 0x23, 0x50, 0xdd, 0xc2, 0x1f, 0xce, 0x52, 0x6d, 0xe5, 0x8c, 0x4c,
- 0x39, 0x12, 0x8b, 0x6c, 0x21, 0xdb, 0x8e, 0xa1, 0xea, 0x51, 0x96, 0xf7, 0xd4, 0x08, 0x47, 0x56,
- 0xe2, 0x4e, 0xd4, 0x9f, 0x3b, 0x32, 0x35, 0x54, 0x13, 0x03, 0x5b, 0xf5, 0x92, 0x4d, 0xfc, 0x06,
- 0xc4, 0x80, 0xc6, 0xd3, 0x0a, 0xf8, 0x2e, 0x54, 0x89, 0xc0, 0x0e, 0x99, 0xd0, 0xad, 0x2f, 0xa1,
- 0x9a, 0x0e, 0x0f, 0xde, 0x84, 0xbc, 0x1f, 0x10, 0x2f, 0xe0, 0x59, 0x98, 0x57, 0x45, 0x03, 0x23,
- 0xc8, 0x52, 0xdb, 0xe0, 0xbb, 0x5c, 0x5e, 0x65, 0x7f, 0xf1, 0x4f, 0x66, 0x03, 0xce, 0xf2, 0x01,
- 0xbf, 0xbd, 0x38, 0xa3, 0x29, 0xcb, 0xf3, 0xe3, 0xde, 0xfa, 0x00, 0x56, 0x53, 0x03, 0x38, 0x6f,
- 0xd7, 0xb5, 0x5f, 0xc2, 0xcb, 0x4b, 0x4d, 0xe3, 0x4f, 0x61, 0x73, 0x6a, 0x9b, 0x76, 0x40, 0x3d,
- 0xd7, 0xa3, 0x2c, 0x63, 0x45, 0x57, 0xf2, 0x7f, 0x56, 0xce, 0xc8, 0xb9, 0xe3, 0x24, 0x5b, 0x58,
- 0x51, 0x37, 0xa6, 0x8b, 0xe0, 0xf5, 0x52, 0xf1, 0xbf, 0x2b, 0xe8, 0xd9, 0xb3, 0x67, 0xcf, 0x32,
- 0xb5, 0xdf, 0x15, 0x60, 0x73, 0xd9, 0x9a, 0x59, 0xba, 0x7c, 0x2f, 0x40, 0xc1, 0x9e, 0x4e, 0x4e,
- 0xa8, 0xc7, 0x83, 0x94, 0x57, 0xc3, 0x16, 0x6e, 0x40, 0xde, 0x22, 0x27, 0xd4, 0x92, 0x73, 0xdb,
- 0xd2, 0x4e, 0xf5, 0xe6, 0x3b, 0xe7, 0x5a, 0x95, 0xf5, 0x43, 0xa6, 0xa2, 0x0a, 0x4d, 0xfc, 0x11,
- 0xe4, 0xc2, 0x2d, 0x9a, 0x59, 0xb8, 0x7e, 0x3e, 0x0b, 0x6c, 0x2d, 0xa9, 0x5c, 0x0f, 0xbf, 0x02,
- 0x25, 0xf6, 0x2b, 0x72, 0xa3, 0xc0, 0x7d, 0x2e, 0x32, 0x80, 0xe5, 0x05, 0xde, 0x82, 0x22, 0x5f,
- 0x26, 0x06, 0x8d, 0x8e, 0xb6, 0xb8, 0xcd, 0x12, 0xcb, 0xa0, 0x43, 0x32, 0xb5, 0x02, 0xed, 0x31,
- 0xb1, 0xa6, 0x94, 0x27, 0x7c, 0x49, 0xad, 0x84, 0xe0, 0xcf, 0x19, 0x86, 0x2f, 0x43, 0x59, 0xac,
- 0x2a, 0xd3, 0x36, 0xe8, 0x53, 0xbe, 0x7b, 0xe6, 0x55, 0xb1, 0xd0, 0xda, 0x0c, 0x61, 0xdd, 0x3f,
- 0xf4, 0x1d, 0x3b, 0x4a, 0x4d, 0xde, 0x05, 0x03, 0x78, 0xf7, 0x1f, 0xcc, 0x6f, 0xdc, 0xaf, 0x2d,
- 0x1f, 0xde, 0x7c, 0x4e, 0xd5, 0xfe, 0x92, 0x81, 0x1c, 0xdf, 0x2f, 0xd6, 0xa0, 0x3c, 0xf8, 0xac,
- 0xa7, 0x68, 0xad, 0xee, 0xf1, 0xfe, 0xa1, 0x82, 0x24, 0x5c, 0x05, 0xe0, 0xc0, 0xfd, 0xc3, 0x6e,
- 0x63, 0x80, 0x32, 0x71, 0xbb, 0xdd, 0x19, 0xdc, 0xb9, 0x85, 0xb2, 0xb1, 0xc2, 0xb1, 0x00, 0x72,
- 0x49, 0xc2, 0xfb, 0x37, 0x51, 0x1e, 0x23, 0xa8, 0x08, 0x03, 0xed, 0x4f, 0x95, 0xd6, 0x9d, 0x5b,
- 0xa8, 0x90, 0x46, 0xde, 0xbf, 0x89, 0x56, 0xf0, 0x2a, 0x94, 0x38, 0xb2, 0xdf, 0xed, 0x1e, 0xa2,
- 0x62, 0x6c, 0xb3, 0x3f, 0x50, 0xdb, 0x9d, 0x03, 0x54, 0x8a, 0x6d, 0x1e, 0xa8, 0xdd, 0xe3, 0x1e,
- 0x82, 0xd8, 0xc2, 0x91, 0xd2, 0xef, 0x37, 0x0e, 0x14, 0x54, 0x8e, 0x19, 0xfb, 0x9f, 0x0d, 0x94,
- 0x3e, 0xaa, 0xa4, 0xdc, 0x7a, 0xff, 0x26, 0x5a, 0x8d, 0xbb, 0x50, 0x3a, 0xc7, 0x47, 0xa8, 0x8a,
- 0xd7, 0x61, 0x55, 0x74, 0x11, 0x39, 0xb1, 0x36, 0x07, 0xdd, 0xb9, 0x85, 0xd0, 0xcc, 0x11, 0x61,
- 0x65, 0x3d, 0x05, 0xdc, 0xb9, 0x85, 0x70, 0xad, 0x09, 0x79, 0x9e, 0x5d, 0x18, 0x43, 0xf5, 0xb0,
- 0xb1, 0xaf, 0x1c, 0x6a, 0xdd, 0xde, 0xa0, 0xdd, 0xed, 0x34, 0x0e, 0x91, 0x34, 0xc3, 0x54, 0xe5,
- 0x67, 0xc7, 0x6d, 0x55, 0x69, 0xa1, 0x4c, 0x12, 0xeb, 0x29, 0x8d, 0x81, 0xd2, 0x42, 0xd9, 0x9a,
- 0x0e, 0x9b, 0xcb, 0xf6, 0xc9, 0xa5, 0x2b, 0x23, 0x31, 0xc5, 0x99, 0x33, 0xa6, 0x98, 0xdb, 0x5a,
- 0x98, 0xe2, 0x7f, 0x65, 0x60, 0x63, 0xc9, 0x59, 0xb1, 0xb4, 0x93, 0x1f, 0x43, 0x5e, 0xa4, 0xa8,
- 0x38, 0x3d, 0xaf, 0x2d, 0x3d, 0x74, 0x78, 0xc2, 0x2e, 0x9c, 0xa0, 0x5c, 0x2f, 0x59, 0x41, 0x64,
- 0xcf, 0xa8, 0x20, 0x98, 0x89, 0x85, 0x3d, 0xfd, 0x17, 0x0b, 0x7b, 0xba, 0x38, 0xf6, 0xee, 0x9c,
- 0xe7, 0xd8, 0xe3, 0xd8, 0xb7, 0xdb, 0xdb, 0xf3, 0x4b, 0xf6, 0xf6, 0x7b, 0xb0, 0xbe, 0x60, 0xe8,
- 0xdc, 0x7b, 0xec, 0xaf, 0x24, 0x90, 0xcf, 0x0a, 0xce, 0x73, 0x76, 0xba, 0x4c, 0x6a, 0xa7, 0xbb,
- 0x37, 0x1f, 0xc1, 0x2b, 0x67, 0x4f, 0xc2, 0xc2, 0x5c, 0x7f, 0x25, 0xc1, 0x85, 0xe5, 0x95, 0xe2,
- 0x52, 0x1f, 0x3e, 0x82, 0xc2, 0x84, 0x06, 0x63, 0x27, 0xaa, 0x96, 0xde, 0x5e, 0x72, 0x06, 0x33,
- 0xf1, 0xfc, 0x64, 0x87, 0x5a, 0xc9, 0x43, 0x3c, 0x7b, 0x56, 0xb9, 0x27, 0xbc, 0x59, 0xf0, 0xf4,
- 0xd7, 0x19, 0x78, 0x79, 0xa9, 0xf1, 0xa5, 0x8e, 0xbe, 0x06, 0x60, 0xda, 0xee, 0x34, 0x10, 0x15,
- 0x91, 0xd8, 0x60, 0x4b, 0x1c, 0xe1, 0x9b, 0x17, 0xdb, 0x3c, 0xa7, 0x41, 0x2c, 0xcf, 0x72, 0x39,
- 0x08, 0x88, 0x13, 0xee, 0xce, 0x1c, 0xcd, 0x71, 0x47, 0x5f, 0x3f, 0x63, 0xa4, 0x0b, 0x89, 0xf9,
- 0x1e, 0x20, 0xdd, 0x32, 0xa9, 0x1d, 0x68, 0x7e, 0xe0, 0x51, 0x32, 0x31, 0xed, 0x11, 0x3f, 0x41,
- 0x8a, 0x7b, 0xf9, 0x21, 0xb1, 0x7c, 0xaa, 0xae, 0x09, 0x71, 0x3f, 0x92, 0x32, 0x0d, 0x9e, 0x40,
- 0x5e, 0x42, 0xa3, 0x90, 0xd2, 0x10, 0xe2, 0x58, 0xa3, 0xf6, 0xdb, 0x12, 0x94, 0x13, 0x75, 0x35,
- 0xbe, 0x02, 0x95, 0x87, 0xe4, 0x31, 0xd1, 0xa2, 0xbb, 0x92, 0x88, 0x44, 0x99, 0x61, 0xbd, 0xf0,
- 0xbe, 0xf4, 0x1e, 0x6c, 0x72, 0x8a, 0x33, 0x0d, 0xa8, 0xa7, 0xe9, 0x16, 0xf1, 0x7d, 0x1e, 0xb4,
- 0x22, 0xa7, 0x62, 0x26, 0xeb, 0x32, 0x51, 0x33, 0x92, 0xe0, 0xdb, 0xb0, 0xc1, 0x35, 0x26, 0x53,
- 0x2b, 0x30, 0x5d, 0x8b, 0x6a, 0xec, 0xf6, 0xe6, 0xf3, 0x93, 0x24, 0xf6, 0x6c, 0x9d, 0x31, 0x8e,
- 0x42, 0x02, 0xf3, 0xc8, 0xc7, 0x2d, 0x78, 0x8d, 0xab, 0x8d, 0xa8, 0x4d, 0x3d, 0x12, 0x50, 0x8d,
- 0x7e, 0x31, 0x25, 0x96, 0xaf, 0x11, 0xdb, 0xd0, 0xc6, 0xc4, 0x1f, 0xcb, 0x9b, 0xcc, 0xc0, 0x7e,
- 0x46, 0x96, 0xd4, 0x4b, 0x8c, 0x78, 0x10, 0xf2, 0x14, 0x4e, 0x6b, 0xd8, 0xc6, 0xc7, 0xc4, 0x1f,
- 0xe3, 0x3d, 0xb8, 0xc0, 0xad, 0xf8, 0x81, 0x67, 0xda, 0x23, 0x4d, 0x1f, 0x53, 0xfd, 0x91, 0x36,
- 0x0d, 0x86, 0x77, 0xe5, 0x57, 0x92, 0xfd, 0x73, 0x0f, 0xfb, 0x9c, 0xd3, 0x64, 0x94, 0xe3, 0x60,
- 0x78, 0x17, 0xf7, 0xa1, 0xc2, 0x26, 0x63, 0x62, 0x7e, 0x49, 0xb5, 0xa1, 0xe3, 0xf1, 0xa3, 0xb1,
- 0xba, 0x64, 0x6b, 0x4a, 0x44, 0xb0, 0xde, 0x0d, 0x15, 0x8e, 0x1c, 0x83, 0xee, 0xe5, 0xfb, 0x3d,
- 0x45, 0x69, 0xa9, 0xe5, 0xc8, 0xca, 0x7d, 0xc7, 0x63, 0x09, 0x35, 0x72, 0xe2, 0x00, 0x97, 0x45,
- 0x42, 0x8d, 0x9c, 0x28, 0xbc, 0xb7, 0x61, 0x43, 0xd7, 0xc5, 0x98, 0x4d, 0x5d, 0x0b, 0xef, 0x58,
- 0xbe, 0x8c, 0x52, 0xc1, 0xd2, 0xf5, 0x03, 0x41, 0x08, 0x73, 0xdc, 0xc7, 0x1f, 0xc2, 0xcb, 0xb3,
- 0x60, 0x25, 0x15, 0xd7, 0x17, 0x46, 0x39, 0xaf, 0x7a, 0x1b, 0x36, 0xdc, 0xd3, 0x45, 0x45, 0x9c,
- 0xea, 0xd1, 0x3d, 0x9d, 0x57, 0xfb, 0x00, 0x36, 0xdd, 0xb1, 0xbb, 0xa8, 0x77, 0x3d, 0xa9, 0x87,
- 0xdd, 0xb1, 0x3b, 0xaf, 0xf8, 0x16, 0xbf, 0x70, 0x7b, 0x54, 0x27, 0x01, 0x35, 0xe4, 0x8b, 0x49,
- 0x7a, 0x42, 0x80, 0x77, 0x01, 0xe9, 0xba, 0x46, 0x6d, 0x72, 0x62, 0x51, 0x8d, 0x78, 0xd4, 0x26,
- 0xbe, 0x7c, 0x39, 0x49, 0xae, 0xea, 0xba, 0xc2, 0xa5, 0x0d, 0x2e, 0xc4, 0xd7, 0x61, 0xdd, 0x39,
- 0x79, 0xa8, 0x8b, 0x94, 0xd4, 0x5c, 0x8f, 0x0e, 0xcd, 0xa7, 0xf2, 0x9b, 0x3c, 0xbe, 0x6b, 0x4c,
- 0xc0, 0x13, 0xb2, 0xc7, 0x61, 0x7c, 0x0d, 0x90, 0xee, 0x8f, 0x89, 0xe7, 0xf2, 0x3d, 0xd9, 0x77,
- 0x89, 0x4e, 0xe5, 0xb7, 0x04, 0x55, 0xe0, 0x9d, 0x08, 0x66, 0x4b, 0xc2, 0x7f, 0x62, 0x0e, 0x83,
- 0xc8, 0xe2, 0x55, 0xb1, 0x24, 0x38, 0x16, 0x5a, 0xdb, 0x01, 0xc4, 0x42, 0x91, 0xea, 0x78, 0x87,
- 0xd3, 0xaa, 0xee, 0xd8, 0x4d, 0xf6, 0xfb, 0x06, 0xac, 0x32, 0xe6, 0xac, 0xd3, 0x6b, 0xa2, 0x20,
- 0x73, 0xc7, 0x89, 0x1e, 0x6f, 0xc1, 0x05, 0x46, 0x9a, 0xd0, 0x80, 0x18, 0x24, 0x20, 0x09, 0xf6,
- 0xbb, 0x9c, 0xcd, 0xe2, 0x7e, 0x14, 0x0a, 0x53, 0x7e, 0x7a, 0xd3, 0x93, 0xd3, 0x38, 0xb3, 0x6e,
- 0x08, 0x3f, 0x19, 0x16, 0xe5, 0xd6, 0xf7, 0x56, 0x74, 0xd7, 0xf6, 0xa0, 0x92, 0x4c, 0x7c, 0x5c,
- 0x02, 0x91, 0xfa, 0x48, 0x62, 0x55, 0x50, 0xb3, 0xdb, 0x62, 0xf5, 0xcb, 0xe7, 0x0a, 0xca, 0xb0,
- 0x3a, 0xea, 0xb0, 0x3d, 0x50, 0x34, 0xf5, 0xb8, 0x33, 0x68, 0x1f, 0x29, 0x28, 0x9b, 0x28, 0xd8,
- 0x1f, 0xe4, 0x8a, 0x6f, 0xa3, 0xab, 0xb5, 0xaf, 0x33, 0x50, 0x4d, 0xdf, 0xc0, 0xf0, 0x8f, 0xe0,
- 0x62, 0xf4, 0x5c, 0xe2, 0xd3, 0x40, 0x7b, 0x62, 0x7a, 0x7c, 0x45, 0x4e, 0x88, 0x38, 0x1d, 0xe3,
- 0x9c, 0xd8, 0x0c, 0x59, 0x7d, 0x1a, 0x7c, 0x62, 0x7a, 0x6c, 0xbd, 0x4d, 0x48, 0x80, 0x0f, 0xe1,
- 0xb2, 0xed, 0x68, 0x7e, 0x40, 0x6c, 0x83, 0x78, 0x86, 0x36, 0x7b, 0xa8, 0xd2, 0x88, 0xae, 0x53,
- 0xdf, 0x77, 0xc4, 0x49, 0x18, 0x5b, 0x79, 0xd5, 0x76, 0xfa, 0x21, 0x79, 0x76, 0x44, 0x34, 0x42,
- 0xea, 0x5c, 0xfe, 0x66, 0xcf, 0xca, 0xdf, 0x57, 0xa0, 0x34, 0x21, 0xae, 0x46, 0xed, 0xc0, 0x3b,
- 0xe5, 0x75, 0x77, 0x51, 0x2d, 0x4e, 0x88, 0xab, 0xb0, 0xf6, 0x0b, 0xb9, 0xfe, 0x3c, 0xc8, 0x15,
- 0x8b, 0xa8, 0xf4, 0x20, 0x57, 0x2c, 0x21, 0xa8, 0xfd, 0x33, 0x0b, 0x95, 0x64, 0x1d, 0xce, 0xae,
- 0x35, 0x3a, 0x3f, 0xb2, 0x24, 0xbe, 0xa9, 0xbd, 0xf1, 0x8d, 0x55, 0x7b, 0xbd, 0xc9, 0xce, 0xb2,
- 0xbd, 0x82, 0xa8, 0x8e, 0x55, 0xa1, 0xc9, 0xea, 0x08, 0x96, 0x6c, 0x54, 0x54, 0x23, 0x45, 0x35,
- 0x6c, 0xe1, 0x03, 0x28, 0x3c, 0xf4, 0xb9, 0xed, 0x02, 0xb7, 0xfd, 0xe6, 0x37, 0xdb, 0x7e, 0xd0,
- 0xe7, 0xc6, 0x4b, 0x0f, 0xfa, 0x5a, 0xa7, 0xab, 0x1e, 0x35, 0x0e, 0xd5, 0x50, 0x1d, 0x5f, 0x82,
- 0x9c, 0x45, 0xbe, 0x3c, 0x4d, 0x9f, 0x7a, 0x1c, 0x3a, 0xef, 0x24, 0x5c, 0x82, 0xdc, 0x13, 0x4a,
- 0x1e, 0xa5, 0xcf, 0x1a, 0x0e, 0x7d, 0x8f, 0x8b, 0x61, 0x17, 0xf2, 0x3c, 0x5e, 0x18, 0x20, 0x8c,
- 0x18, 0x7a, 0x09, 0x17, 0x21, 0xd7, 0xec, 0xaa, 0x6c, 0x41, 0x20, 0xa8, 0x08, 0x54, 0xeb, 0xb5,
- 0x95, 0xa6, 0x82, 0x32, 0xb5, 0xdb, 0x50, 0x10, 0x41, 0x60, 0x8b, 0x25, 0x0e, 0x03, 0x7a, 0x29,
- 0x6c, 0x86, 0x36, 0xa4, 0x48, 0x7a, 0x7c, 0xb4, 0xaf, 0xa8, 0x28, 0x93, 0x9e, 0xea, 0x1c, 0xca,
- 0xd7, 0x7c, 0xa8, 0x24, 0x0b, 0xf1, 0x17, 0x73, 0xc9, 0xfe, 0x9b, 0x04, 0xe5, 0x44, 0x61, 0xcd,
- 0x2a, 0x22, 0x62, 0x59, 0xce, 0x13, 0x8d, 0x58, 0x26, 0xf1, 0xc3, 0xd4, 0x00, 0x0e, 0x35, 0x18,
- 0x72, 0xde, 0xa9, 0x7b, 0x41, 0x4b, 0x24, 0x8f, 0x0a, 0xb5, 0x3f, 0x4a, 0x80, 0xe6, 0x2b, 0xdb,
- 0x39, 0x37, 0xa5, 0x1f, 0xd2, 0xcd, 0xda, 0x1f, 0x24, 0xa8, 0xa6, 0xcb, 0xd9, 0x39, 0xf7, 0xae,
- 0xfc, 0xa0, 0xee, 0xfd, 0x23, 0x03, 0xab, 0xa9, 0x22, 0xf6, 0xbc, 0xde, 0x7d, 0x01, 0xeb, 0xa6,
- 0x41, 0x27, 0xae, 0x13, 0x50, 0x5b, 0x3f, 0xd5, 0x2c, 0xfa, 0x98, 0x5a, 0x72, 0x8d, 0x6f, 0x1a,
- 0xbb, 0xdf, 0x5c, 0x26, 0xd7, 0xdb, 0x33, 0xbd, 0x43, 0xa6, 0xb6, 0xb7, 0xd1, 0x6e, 0x29, 0x47,
- 0xbd, 0xee, 0x40, 0xe9, 0x34, 0x3f, 0xd3, 0x8e, 0x3b, 0x3f, 0xed, 0x74, 0x3f, 0xe9, 0xa8, 0xc8,
- 0x9c, 0xa3, 0x7d, 0x8f, 0xcb, 0xbe, 0x07, 0x68, 0xde, 0x29, 0x7c, 0x11, 0x96, 0xb9, 0x85, 0x5e,
- 0xc2, 0x1b, 0xb0, 0xd6, 0xe9, 0x6a, 0xfd, 0x76, 0x4b, 0xd1, 0x94, 0xfb, 0xf7, 0x95, 0xe6, 0xa0,
- 0x2f, 0x1e, 0x3e, 0x62, 0xf6, 0x20, 0xb5, 0xc0, 0x6b, 0xbf, 0xcf, 0xc2, 0xc6, 0x12, 0x4f, 0x70,
- 0x23, 0xbc, 0xb2, 0x88, 0x5b, 0xd4, 0x8d, 0xf3, 0x78, 0x5f, 0x67, 0x35, 0x43, 0x8f, 0x78, 0x41,
- 0x78, 0xc3, 0xb9, 0x06, 0x2c, 0x4a, 0x76, 0x60, 0x0e, 0x4d, 0xea, 0x85, 0xef, 0x44, 0xe2, 0x1e,
- 0xb3, 0x36, 0xc3, 0xc5, 0x53, 0xd1, 0xbb, 0x80, 0x5d, 0xc7, 0x37, 0x03, 0xf3, 0x31, 0xd5, 0x4c,
- 0x3b, 0x7a, 0x54, 0x62, 0xf7, 0x9a, 0x9c, 0x8a, 0x22, 0x49, 0xdb, 0x0e, 0x62, 0xb6, 0x4d, 0x47,
- 0x64, 0x8e, 0xcd, 0x36, 0xf3, 0xac, 0x8a, 0x22, 0x49, 0xcc, 0xbe, 0x02, 0x15, 0xc3, 0x99, 0xb2,
- 0x62, 0x4f, 0xf0, 0xd8, 0xd9, 0x21, 0xa9, 0x65, 0x81, 0xc5, 0x94, 0xb0, 0x8c, 0x9f, 0xbd, 0x66,
- 0x55, 0xd4, 0xb2, 0xc0, 0x04, 0xe5, 0x2a, 0xac, 0x91, 0xd1, 0xc8, 0x63, 0xc6, 0x23, 0x43, 0xe2,
- 0x62, 0x52, 0x8d, 0x61, 0x4e, 0xdc, 0x7a, 0x00, 0xc5, 0x28, 0x0e, 0xec, 0xa8, 0x66, 0x91, 0xd0,
- 0x5c, 0x71, 0xdb, 0xce, 0xec, 0x94, 0xd4, 0xa2, 0x1d, 0x09, 0xaf, 0x40, 0xc5, 0xf4, 0xb5, 0xd9,
- 0xe3, 0x7c, 0x66, 0x3b, 0xb3, 0x53, 0x54, 0xcb, 0xa6, 0x1f, 0x3f, 0x6c, 0xd6, 0xbe, 0xca, 0x40,
- 0x35, 0xfd, 0x71, 0x01, 0xb7, 0xa0, 0x68, 0x39, 0x3a, 0xe1, 0xa9, 0x25, 0xbe, 0x6c, 0xed, 0x3c,
- 0xe7, 0x7b, 0x44, 0xfd, 0x30, 0xe4, 0xab, 0xb1, 0xe6, 0xd6, 0xdf, 0x25, 0x28, 0x46, 0x30, 0xbe,
- 0x00, 0x39, 0x97, 0x04, 0x63, 0x6e, 0x2e, 0xbf, 0x9f, 0x41, 0x92, 0xca, 0xdb, 0x0c, 0xf7, 0x5d,
- 0x62, 0xf3, 0x14, 0x08, 0x71, 0xd6, 0x66, 0xf3, 0x6a, 0x51, 0x62, 0xf0, 0x5b, 0x8f, 0x33, 0x99,
- 0x50, 0x3b, 0xf0, 0xa3, 0x79, 0x0d, 0xf1, 0x66, 0x08, 0xe3, 0x77, 0x60, 0x3d, 0xf0, 0x88, 0x69,
- 0xa5, 0xb8, 0x39, 0xce, 0x45, 0x91, 0x20, 0x26, 0xef, 0xc1, 0xa5, 0xc8, 0xae, 0x41, 0x03, 0xa2,
- 0x8f, 0xa9, 0x31, 0x53, 0x2a, 0xf0, 0xd7, 0x8d, 0x8b, 0x21, 0xa1, 0x15, 0xca, 0x23, 0xdd, 0xda,
- 0xd7, 0x12, 0xac, 0x47, 0xf7, 0x34, 0x23, 0x0e, 0xd6, 0x11, 0x00, 0xb1, 0x6d, 0x27, 0x48, 0x86,
- 0x6b, 0x31, 0x95, 0x17, 0xf4, 0xea, 0x8d, 0x58, 0x49, 0x4d, 0x18, 0xd8, 0x9a, 0x00, 0xcc, 0x24,
- 0x67, 0x86, 0xed, 0x32, 0x94, 0xc3, 0x2f, 0x47, 0xfc, 0xf3, 0xa3, 0xb8, 0xd9, 0x83, 0x80, 0xd8,
- 0x85, 0x0e, 0x6f, 0x42, 0xfe, 0x84, 0x8e, 0x4c, 0x3b, 0x7c, 0x0f, 0x16, 0x8d, 0xe8, 0xfd, 0x25,
- 0x17, 0xbf, 0xbf, 0xec, 0xff, 0x46, 0x82, 0x0d, 0xdd, 0x99, 0xcc, 0xfb, 0xbb, 0x8f, 0xe6, 0x9e,
- 0x17, 0xfc, 0x8f, 0xa5, 0xcf, 0x3f, 0x1a, 0x99, 0xc1, 0x78, 0x7a, 0x52, 0xd7, 0x9d, 0xc9, 0xee,
- 0xc8, 0xb1, 0x88, 0x3d, 0x9a, 0x7d, 0x3f, 0xe5, 0x7f, 0xf4, 0x1b, 0x23, 0x6a, 0xdf, 0x18, 0x39,
- 0x89, 0xaf, 0xa9, 0xf7, 0x66, 0x7f, 0xff, 0x27, 0x49, 0x7f, 0xca, 0x64, 0x0f, 0x7a, 0xfb, 0x7f,
- 0xce, 0x6c, 0x1d, 0x88, 0xee, 0x7a, 0x51, 0x78, 0x54, 0x3a, 0xb4, 0xa8, 0xce, 0x86, 0xfc, 0xff,
- 0x00, 0x00, 0x00, 0xff, 0xff, 0x3e, 0xe8, 0xef, 0xc4, 0x9b, 0x1d, 0x00, 0x00,
-}
diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/descriptor/descriptor.proto b/vendor/github.com/golang/protobuf/protoc-gen-go/descriptor/descriptor.proto
deleted file mode 100644
index ed08fcbc54..0000000000
--- a/vendor/github.com/golang/protobuf/protoc-gen-go/descriptor/descriptor.proto
+++ /dev/null
@@ -1,883 +0,0 @@
-// Protocol Buffers - Google's data interchange format
-// Copyright 2008 Google Inc. All rights reserved.
-// https://developers.google.com/protocol-buffers/
-//
-// 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.
-
-// Author: kenton@google.com (Kenton Varda)
-// Based on original Protocol Buffers design by
-// Sanjay Ghemawat, Jeff Dean, and others.
-//
-// The messages in this file describe the definitions found in .proto files.
-// A valid .proto file can be translated directly to a FileDescriptorProto
-// without any other information (e.g. without reading its imports).
-
-
-syntax = "proto2";
-
-package google.protobuf;
-option go_package = "github.com/golang/protobuf/protoc-gen-go/descriptor;descriptor";
-option java_package = "com.google.protobuf";
-option java_outer_classname = "DescriptorProtos";
-option csharp_namespace = "Google.Protobuf.Reflection";
-option objc_class_prefix = "GPB";
-option cc_enable_arenas = true;
-
-// descriptor.proto must be optimized for speed because reflection-based
-// algorithms don't work during bootstrapping.
-option optimize_for = SPEED;
-
-// The protocol compiler can output a FileDescriptorSet containing the .proto
-// files it parses.
-message FileDescriptorSet {
- repeated FileDescriptorProto file = 1;
-}
-
-// Describes a complete .proto file.
-message FileDescriptorProto {
- optional string name = 1; // file name, relative to root of source tree
- optional string package = 2; // e.g. "foo", "foo.bar", etc.
-
- // Names of files imported by this file.
- repeated string dependency = 3;
- // Indexes of the public imported files in the dependency list above.
- repeated int32 public_dependency = 10;
- // Indexes of the weak imported files in the dependency list.
- // For Google-internal migration only. Do not use.
- repeated int32 weak_dependency = 11;
-
- // All top-level definitions in this file.
- repeated DescriptorProto message_type = 4;
- repeated EnumDescriptorProto enum_type = 5;
- repeated ServiceDescriptorProto service = 6;
- repeated FieldDescriptorProto extension = 7;
-
- optional FileOptions options = 8;
-
- // This field contains optional information about the original source code.
- // You may safely remove this entire field without harming runtime
- // functionality of the descriptors -- the information is needed only by
- // development tools.
- optional SourceCodeInfo source_code_info = 9;
-
- // The syntax of the proto file.
- // The supported values are "proto2" and "proto3".
- optional string syntax = 12;
-}
-
-// Describes a message type.
-message DescriptorProto {
- optional string name = 1;
-
- repeated FieldDescriptorProto field = 2;
- repeated FieldDescriptorProto extension = 6;
-
- repeated DescriptorProto nested_type = 3;
- repeated EnumDescriptorProto enum_type = 4;
-
- message ExtensionRange {
- optional int32 start = 1;
- optional int32 end = 2;
-
- optional ExtensionRangeOptions options = 3;
- }
- repeated ExtensionRange extension_range = 5;
-
- repeated OneofDescriptorProto oneof_decl = 8;
-
- optional MessageOptions options = 7;
-
- // Range of reserved tag numbers. Reserved tag numbers may not be used by
- // fields or extension ranges in the same message. Reserved ranges may
- // not overlap.
- message ReservedRange {
- optional int32 start = 1; // Inclusive.
- optional int32 end = 2; // Exclusive.
- }
- repeated ReservedRange reserved_range = 9;
- // Reserved field names, which may not be used by fields in the same message.
- // A given name may only be reserved once.
- repeated string reserved_name = 10;
-}
-
-message ExtensionRangeOptions {
- // The parser stores options it doesn't recognize here. See above.
- repeated UninterpretedOption uninterpreted_option = 999;
-
- // Clients can define custom options in extensions of this message. See above.
- extensions 1000 to max;
-}
-
-// Describes a field within a message.
-message FieldDescriptorProto {
- enum Type {
- // 0 is reserved for errors.
- // Order is weird for historical reasons.
- TYPE_DOUBLE = 1;
- TYPE_FLOAT = 2;
- // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT64 if
- // negative values are likely.
- TYPE_INT64 = 3;
- TYPE_UINT64 = 4;
- // Not ZigZag encoded. Negative numbers take 10 bytes. Use TYPE_SINT32 if
- // negative values are likely.
- TYPE_INT32 = 5;
- TYPE_FIXED64 = 6;
- TYPE_FIXED32 = 7;
- TYPE_BOOL = 8;
- TYPE_STRING = 9;
- // Tag-delimited aggregate.
- // Group type is deprecated and not supported in proto3. However, Proto3
- // implementations should still be able to parse the group wire format and
- // treat group fields as unknown fields.
- TYPE_GROUP = 10;
- TYPE_MESSAGE = 11; // Length-delimited aggregate.
-
- // New in version 2.
- TYPE_BYTES = 12;
- TYPE_UINT32 = 13;
- TYPE_ENUM = 14;
- TYPE_SFIXED32 = 15;
- TYPE_SFIXED64 = 16;
- TYPE_SINT32 = 17; // Uses ZigZag encoding.
- TYPE_SINT64 = 18; // Uses ZigZag encoding.
- };
-
- enum Label {
- // 0 is reserved for errors
- LABEL_OPTIONAL = 1;
- LABEL_REQUIRED = 2;
- LABEL_REPEATED = 3;
- };
-
- optional string name = 1;
- optional int32 number = 3;
- optional Label label = 4;
-
- // If type_name is set, this need not be set. If both this and type_name
- // are set, this must be one of TYPE_ENUM, TYPE_MESSAGE or TYPE_GROUP.
- optional Type type = 5;
-
- // For message and enum types, this is the name of the type. If the name
- // starts with a '.', it is fully-qualified. Otherwise, C++-like scoping
- // rules are used to find the type (i.e. first the nested types within this
- // message are searched, then within the parent, on up to the root
- // namespace).
- optional string type_name = 6;
-
- // For extensions, this is the name of the type being extended. It is
- // resolved in the same manner as type_name.
- optional string extendee = 2;
-
- // For numeric types, contains the original text representation of the value.
- // For booleans, "true" or "false".
- // For strings, contains the default text contents (not escaped in any way).
- // For bytes, contains the C escaped value. All bytes >= 128 are escaped.
- // TODO(kenton): Base-64 encode?
- optional string default_value = 7;
-
- // If set, gives the index of a oneof in the containing type's oneof_decl
- // list. This field is a member of that oneof.
- optional int32 oneof_index = 9;
-
- // JSON name of this field. The value is set by protocol compiler. If the
- // user has set a "json_name" option on this field, that option's value
- // will be used. Otherwise, it's deduced from the field's name by converting
- // it to camelCase.
- optional string json_name = 10;
-
- optional FieldOptions options = 8;
-}
-
-// Describes a oneof.
-message OneofDescriptorProto {
- optional string name = 1;
- optional OneofOptions options = 2;
-}
-
-// Describes an enum type.
-message EnumDescriptorProto {
- optional string name = 1;
-
- repeated EnumValueDescriptorProto value = 2;
-
- optional EnumOptions options = 3;
-
- // Range of reserved numeric values. Reserved values may not be used by
- // entries in the same enum. Reserved ranges may not overlap.
- //
- // Note that this is distinct from DescriptorProto.ReservedRange in that it
- // is inclusive such that it can appropriately represent the entire int32
- // domain.
- message EnumReservedRange {
- optional int32 start = 1; // Inclusive.
- optional int32 end = 2; // Inclusive.
- }
-
- // Range of reserved numeric values. Reserved numeric values may not be used
- // by enum values in the same enum declaration. Reserved ranges may not
- // overlap.
- repeated EnumReservedRange reserved_range = 4;
-
- // Reserved enum value names, which may not be reused. A given name may only
- // be reserved once.
- repeated string reserved_name = 5;
-}
-
-// Describes a value within an enum.
-message EnumValueDescriptorProto {
- optional string name = 1;
- optional int32 number = 2;
-
- optional EnumValueOptions options = 3;
-}
-
-// Describes a service.
-message ServiceDescriptorProto {
- optional string name = 1;
- repeated MethodDescriptorProto method = 2;
-
- optional ServiceOptions options = 3;
-}
-
-// Describes a method of a service.
-message MethodDescriptorProto {
- optional string name = 1;
-
- // Input and output type names. These are resolved in the same way as
- // FieldDescriptorProto.type_name, but must refer to a message type.
- optional string input_type = 2;
- optional string output_type = 3;
-
- optional MethodOptions options = 4;
-
- // Identifies if client streams multiple client messages
- optional bool client_streaming = 5 [default=false];
- // Identifies if server streams multiple server messages
- optional bool server_streaming = 6 [default=false];
-}
-
-
-// ===================================================================
-// Options
-
-// Each of the definitions above may have "options" attached. These are
-// just annotations which may cause code to be generated slightly differently
-// or may contain hints for code that manipulates protocol messages.
-//
-// Clients may define custom options as extensions of the *Options messages.
-// These extensions may not yet be known at parsing time, so the parser cannot
-// store the values in them. Instead it stores them in a field in the *Options
-// message called uninterpreted_option. This field must have the same name
-// across all *Options messages. We then use this field to populate the
-// extensions when we build a descriptor, at which point all protos have been
-// parsed and so all extensions are known.
-//
-// Extension numbers for custom options may be chosen as follows:
-// * For options which will only be used within a single application or
-// organization, or for experimental options, use field numbers 50000
-// through 99999. It is up to you to ensure that you do not use the
-// same number for multiple options.
-// * For options which will be published and used publicly by multiple
-// independent entities, e-mail protobuf-global-extension-registry@google.com
-// to reserve extension numbers. Simply provide your project name (e.g.
-// Objective-C plugin) and your project website (if available) -- there's no
-// need to explain how you intend to use them. Usually you only need one
-// extension number. You can declare multiple options with only one extension
-// number by putting them in a sub-message. See the Custom Options section of
-// the docs for examples:
-// https://developers.google.com/protocol-buffers/docs/proto#options
-// If this turns out to be popular, a web service will be set up
-// to automatically assign option numbers.
-
-
-message FileOptions {
-
- // Sets the Java package where classes generated from this .proto will be
- // placed. By default, the proto package is used, but this is often
- // inappropriate because proto packages do not normally start with backwards
- // domain names.
- optional string java_package = 1;
-
-
- // If set, all the classes from the .proto file are wrapped in a single
- // outer class with the given name. This applies to both Proto1
- // (equivalent to the old "--one_java_file" option) and Proto2 (where
- // a .proto always translates to a single class, but you may want to
- // explicitly choose the class name).
- optional string java_outer_classname = 8;
-
- // If set true, then the Java code generator will generate a separate .java
- // file for each top-level message, enum, and service defined in the .proto
- // file. Thus, these types will *not* be nested inside the outer class
- // named by java_outer_classname. However, the outer class will still be
- // generated to contain the file's getDescriptor() method as well as any
- // top-level extensions defined in the file.
- optional bool java_multiple_files = 10 [default=false];
-
- // This option does nothing.
- optional bool java_generate_equals_and_hash = 20 [deprecated=true];
-
- // If set true, then the Java2 code generator will generate code that
- // throws an exception whenever an attempt is made to assign a non-UTF-8
- // byte sequence to a string field.
- // Message reflection will do the same.
- // However, an extension field still accepts non-UTF-8 byte sequences.
- // This option has no effect on when used with the lite runtime.
- optional bool java_string_check_utf8 = 27 [default=false];
-
-
- // Generated classes can be optimized for speed or code size.
- enum OptimizeMode {
- SPEED = 1; // Generate complete code for parsing, serialization,
- // etc.
- CODE_SIZE = 2; // Use ReflectionOps to implement these methods.
- LITE_RUNTIME = 3; // Generate code using MessageLite and the lite runtime.
- }
- optional OptimizeMode optimize_for = 9 [default=SPEED];
-
- // Sets the Go package where structs generated from this .proto will be
- // placed. If omitted, the Go package will be derived from the following:
- // - The basename of the package import path, if provided.
- // - Otherwise, the package statement in the .proto file, if present.
- // - Otherwise, the basename of the .proto file, without extension.
- optional string go_package = 11;
-
-
-
- // Should generic services be generated in each language? "Generic" services
- // are not specific to any particular RPC system. They are generated by the
- // main code generators in each language (without additional plugins).
- // Generic services were the only kind of service generation supported by
- // early versions of google.protobuf.
- //
- // Generic services are now considered deprecated in favor of using plugins
- // that generate code specific to your particular RPC system. Therefore,
- // these default to false. Old code which depends on generic services should
- // explicitly set them to true.
- optional bool cc_generic_services = 16 [default=false];
- optional bool java_generic_services = 17 [default=false];
- optional bool py_generic_services = 18 [default=false];
- optional bool php_generic_services = 42 [default=false];
-
- // Is this file deprecated?
- // Depending on the target platform, this can emit Deprecated annotations
- // for everything in the file, or it will be completely ignored; in the very
- // least, this is a formalization for deprecating files.
- optional bool deprecated = 23 [default=false];
-
- // Enables the use of arenas for the proto messages in this file. This applies
- // only to generated classes for C++.
- optional bool cc_enable_arenas = 31 [default=false];
-
-
- // Sets the objective c class prefix which is prepended to all objective c
- // generated classes from this .proto. There is no default.
- optional string objc_class_prefix = 36;
-
- // Namespace for generated classes; defaults to the package.
- optional string csharp_namespace = 37;
-
- // By default Swift generators will take the proto package and CamelCase it
- // replacing '.' with underscore and use that to prefix the types/symbols
- // defined. When this options is provided, they will use this value instead
- // to prefix the types/symbols defined.
- optional string swift_prefix = 39;
-
- // Sets the php class prefix which is prepended to all php generated classes
- // from this .proto. Default is empty.
- optional string php_class_prefix = 40;
-
- // Use this option to change the namespace of php generated classes. Default
- // is empty. When this option is empty, the package name will be used for
- // determining the namespace.
- optional string php_namespace = 41;
-
-
- // Use this option to change the namespace of php generated metadata classes.
- // Default is empty. When this option is empty, the proto file name will be used
- // for determining the namespace.
- optional string php_metadata_namespace = 44;
-
- // Use this option to change the package of ruby generated classes. Default
- // is empty. When this option is not set, the package name will be used for
- // determining the ruby package.
- optional string ruby_package = 45;
-
- // The parser stores options it doesn't recognize here.
- // See the documentation for the "Options" section above.
- repeated UninterpretedOption uninterpreted_option = 999;
-
- // Clients can define custom options in extensions of this message.
- // See the documentation for the "Options" section above.
- extensions 1000 to max;
-
- reserved 38;
-}
-
-message MessageOptions {
- // Set true to use the old proto1 MessageSet wire format for extensions.
- // This is provided for backwards-compatibility with the MessageSet wire
- // format. You should not use this for any other reason: It's less
- // efficient, has fewer features, and is more complicated.
- //
- // The message must be defined exactly as follows:
- // message Foo {
- // option message_set_wire_format = true;
- // extensions 4 to max;
- // }
- // Note that the message cannot have any defined fields; MessageSets only
- // have extensions.
- //
- // All extensions of your type must be singular messages; e.g. they cannot
- // be int32s, enums, or repeated messages.
- //
- // Because this is an option, the above two restrictions are not enforced by
- // the protocol compiler.
- optional bool message_set_wire_format = 1 [default=false];
-
- // Disables the generation of the standard "descriptor()" accessor, which can
- // conflict with a field of the same name. This is meant to make migration
- // from proto1 easier; new code should avoid fields named "descriptor".
- optional bool no_standard_descriptor_accessor = 2 [default=false];
-
- // Is this message deprecated?
- // Depending on the target platform, this can emit Deprecated annotations
- // for the message, or it will be completely ignored; in the very least,
- // this is a formalization for deprecating messages.
- optional bool deprecated = 3 [default=false];
-
- // Whether the message is an automatically generated map entry type for the
- // maps field.
- //
- // For maps fields:
- // map map_field = 1;
- // The parsed descriptor looks like:
- // message MapFieldEntry {
- // option map_entry = true;
- // optional KeyType key = 1;
- // optional ValueType value = 2;
- // }
- // repeated MapFieldEntry map_field = 1;
- //
- // Implementations may choose not to generate the map_entry=true message, but
- // use a native map in the target language to hold the keys and values.
- // The reflection APIs in such implementions still need to work as
- // if the field is a repeated message field.
- //
- // NOTE: Do not set the option in .proto files. Always use the maps syntax
- // instead. The option should only be implicitly set by the proto compiler
- // parser.
- optional bool map_entry = 7;
-
- reserved 8; // javalite_serializable
- reserved 9; // javanano_as_lite
-
- // The parser stores options it doesn't recognize here. See above.
- repeated UninterpretedOption uninterpreted_option = 999;
-
- // Clients can define custom options in extensions of this message. See above.
- extensions 1000 to max;
-}
-
-message FieldOptions {
- // The ctype option instructs the C++ code generator to use a different
- // representation of the field than it normally would. See the specific
- // options below. This option is not yet implemented in the open source
- // release -- sorry, we'll try to include it in a future version!
- optional CType ctype = 1 [default = STRING];
- enum CType {
- // Default mode.
- STRING = 0;
-
- CORD = 1;
-
- STRING_PIECE = 2;
- }
- // The packed option can be enabled for repeated primitive fields to enable
- // a more efficient representation on the wire. Rather than repeatedly
- // writing the tag and type for each element, the entire array is encoded as
- // a single length-delimited blob. In proto3, only explicit setting it to
- // false will avoid using packed encoding.
- optional bool packed = 2;
-
- // The jstype option determines the JavaScript type used for values of the
- // field. The option is permitted only for 64 bit integral and fixed types
- // (int64, uint64, sint64, fixed64, sfixed64). A field with jstype JS_STRING
- // is represented as JavaScript string, which avoids loss of precision that
- // can happen when a large value is converted to a floating point JavaScript.
- // Specifying JS_NUMBER for the jstype causes the generated JavaScript code to
- // use the JavaScript "number" type. The behavior of the default option
- // JS_NORMAL is implementation dependent.
- //
- // This option is an enum to permit additional types to be added, e.g.
- // goog.math.Integer.
- optional JSType jstype = 6 [default = JS_NORMAL];
- enum JSType {
- // Use the default type.
- JS_NORMAL = 0;
-
- // Use JavaScript strings.
- JS_STRING = 1;
-
- // Use JavaScript numbers.
- JS_NUMBER = 2;
- }
-
- // Should this field be parsed lazily? Lazy applies only to message-type
- // fields. It means that when the outer message is initially parsed, the
- // inner message's contents will not be parsed but instead stored in encoded
- // form. The inner message will actually be parsed when it is first accessed.
- //
- // This is only a hint. Implementations are free to choose whether to use
- // eager or lazy parsing regardless of the value of this option. However,
- // setting this option true suggests that the protocol author believes that
- // using lazy parsing on this field is worth the additional bookkeeping
- // overhead typically needed to implement it.
- //
- // This option does not affect the public interface of any generated code;
- // all method signatures remain the same. Furthermore, thread-safety of the
- // interface is not affected by this option; const methods remain safe to
- // call from multiple threads concurrently, while non-const methods continue
- // to require exclusive access.
- //
- //
- // Note that implementations may choose not to check required fields within
- // a lazy sub-message. That is, calling IsInitialized() on the outer message
- // may return true even if the inner message has missing required fields.
- // This is necessary because otherwise the inner message would have to be
- // parsed in order to perform the check, defeating the purpose of lazy
- // parsing. An implementation which chooses not to check required fields
- // must be consistent about it. That is, for any particular sub-message, the
- // implementation must either *always* check its required fields, or *never*
- // check its required fields, regardless of whether or not the message has
- // been parsed.
- optional bool lazy = 5 [default=false];
-
- // Is this field deprecated?
- // Depending on the target platform, this can emit Deprecated annotations
- // for accessors, or it will be completely ignored; in the very least, this
- // is a formalization for deprecating fields.
- optional bool deprecated = 3 [default=false];
-
- // For Google-internal migration only. Do not use.
- optional bool weak = 10 [default=false];
-
-
- // The parser stores options it doesn't recognize here. See above.
- repeated UninterpretedOption uninterpreted_option = 999;
-
- // Clients can define custom options in extensions of this message. See above.
- extensions 1000 to max;
-
- reserved 4; // removed jtype
-}
-
-message OneofOptions {
- // The parser stores options it doesn't recognize here. See above.
- repeated UninterpretedOption uninterpreted_option = 999;
-
- // Clients can define custom options in extensions of this message. See above.
- extensions 1000 to max;
-}
-
-message EnumOptions {
-
- // Set this option to true to allow mapping different tag names to the same
- // value.
- optional bool allow_alias = 2;
-
- // Is this enum deprecated?
- // Depending on the target platform, this can emit Deprecated annotations
- // for the enum, or it will be completely ignored; in the very least, this
- // is a formalization for deprecating enums.
- optional bool deprecated = 3 [default=false];
-
- reserved 5; // javanano_as_lite
-
- // The parser stores options it doesn't recognize here. See above.
- repeated UninterpretedOption uninterpreted_option = 999;
-
- // Clients can define custom options in extensions of this message. See above.
- extensions 1000 to max;
-}
-
-message EnumValueOptions {
- // Is this enum value deprecated?
- // Depending on the target platform, this can emit Deprecated annotations
- // for the enum value, or it will be completely ignored; in the very least,
- // this is a formalization for deprecating enum values.
- optional bool deprecated = 1 [default=false];
-
- // The parser stores options it doesn't recognize here. See above.
- repeated UninterpretedOption uninterpreted_option = 999;
-
- // Clients can define custom options in extensions of this message. See above.
- extensions 1000 to max;
-}
-
-message ServiceOptions {
-
- // Note: Field numbers 1 through 32 are reserved for Google's internal RPC
- // framework. We apologize for hoarding these numbers to ourselves, but
- // we were already using them long before we decided to release Protocol
- // Buffers.
-
- // Is this service deprecated?
- // Depending on the target platform, this can emit Deprecated annotations
- // for the service, or it will be completely ignored; in the very least,
- // this is a formalization for deprecating services.
- optional bool deprecated = 33 [default=false];
-
- // The parser stores options it doesn't recognize here. See above.
- repeated UninterpretedOption uninterpreted_option = 999;
-
- // Clients can define custom options in extensions of this message. See above.
- extensions 1000 to max;
-}
-
-message MethodOptions {
-
- // Note: Field numbers 1 through 32 are reserved for Google's internal RPC
- // framework. We apologize for hoarding these numbers to ourselves, but
- // we were already using them long before we decided to release Protocol
- // Buffers.
-
- // Is this method deprecated?
- // Depending on the target platform, this can emit Deprecated annotations
- // for the method, or it will be completely ignored; in the very least,
- // this is a formalization for deprecating methods.
- optional bool deprecated = 33 [default=false];
-
- // Is this method side-effect-free (or safe in HTTP parlance), or idempotent,
- // or neither? HTTP based RPC implementation may choose GET verb for safe
- // methods, and PUT verb for idempotent methods instead of the default POST.
- enum IdempotencyLevel {
- IDEMPOTENCY_UNKNOWN = 0;
- NO_SIDE_EFFECTS = 1; // implies idempotent
- IDEMPOTENT = 2; // idempotent, but may have side effects
- }
- optional IdempotencyLevel idempotency_level =
- 34 [default=IDEMPOTENCY_UNKNOWN];
-
- // The parser stores options it doesn't recognize here. See above.
- repeated UninterpretedOption uninterpreted_option = 999;
-
- // Clients can define custom options in extensions of this message. See above.
- extensions 1000 to max;
-}
-
-
-// A message representing a option the parser does not recognize. This only
-// appears in options protos created by the compiler::Parser class.
-// DescriptorPool resolves these when building Descriptor objects. Therefore,
-// options protos in descriptor objects (e.g. returned by Descriptor::options(),
-// or produced by Descriptor::CopyTo()) will never have UninterpretedOptions
-// in them.
-message UninterpretedOption {
- // The name of the uninterpreted option. Each string represents a segment in
- // a dot-separated name. is_extension is true iff a segment represents an
- // extension (denoted with parentheses in options specs in .proto files).
- // E.g.,{ ["foo", false], ["bar.baz", true], ["qux", false] } represents
- // "foo.(bar.baz).qux".
- message NamePart {
- required string name_part = 1;
- required bool is_extension = 2;
- }
- repeated NamePart name = 2;
-
- // The value of the uninterpreted option, in whatever type the tokenizer
- // identified it as during parsing. Exactly one of these should be set.
- optional string identifier_value = 3;
- optional uint64 positive_int_value = 4;
- optional int64 negative_int_value = 5;
- optional double double_value = 6;
- optional bytes string_value = 7;
- optional string aggregate_value = 8;
-}
-
-// ===================================================================
-// Optional source code info
-
-// Encapsulates information about the original source file from which a
-// FileDescriptorProto was generated.
-message SourceCodeInfo {
- // A Location identifies a piece of source code in a .proto file which
- // corresponds to a particular definition. This information is intended
- // to be useful to IDEs, code indexers, documentation generators, and similar
- // tools.
- //
- // For example, say we have a file like:
- // message Foo {
- // optional string foo = 1;
- // }
- // Let's look at just the field definition:
- // optional string foo = 1;
- // ^ ^^ ^^ ^ ^^^
- // a bc de f ghi
- // We have the following locations:
- // span path represents
- // [a,i) [ 4, 0, 2, 0 ] The whole field definition.
- // [a,b) [ 4, 0, 2, 0, 4 ] The label (optional).
- // [c,d) [ 4, 0, 2, 0, 5 ] The type (string).
- // [e,f) [ 4, 0, 2, 0, 1 ] The name (foo).
- // [g,h) [ 4, 0, 2, 0, 3 ] The number (1).
- //
- // Notes:
- // - A location may refer to a repeated field itself (i.e. not to any
- // particular index within it). This is used whenever a set of elements are
- // logically enclosed in a single code segment. For example, an entire
- // extend block (possibly containing multiple extension definitions) will
- // have an outer location whose path refers to the "extensions" repeated
- // field without an index.
- // - Multiple locations may have the same path. This happens when a single
- // logical declaration is spread out across multiple places. The most
- // obvious example is the "extend" block again -- there may be multiple
- // extend blocks in the same scope, each of which will have the same path.
- // - A location's span is not always a subset of its parent's span. For
- // example, the "extendee" of an extension declaration appears at the
- // beginning of the "extend" block and is shared by all extensions within
- // the block.
- // - Just because a location's span is a subset of some other location's span
- // does not mean that it is a descendent. For example, a "group" defines
- // both a type and a field in a single declaration. Thus, the locations
- // corresponding to the type and field and their components will overlap.
- // - Code which tries to interpret locations should probably be designed to
- // ignore those that it doesn't understand, as more types of locations could
- // be recorded in the future.
- repeated Location location = 1;
- message Location {
- // Identifies which part of the FileDescriptorProto was defined at this
- // location.
- //
- // Each element is a field number or an index. They form a path from
- // the root FileDescriptorProto to the place where the definition. For
- // example, this path:
- // [ 4, 3, 2, 7, 1 ]
- // refers to:
- // file.message_type(3) // 4, 3
- // .field(7) // 2, 7
- // .name() // 1
- // This is because FileDescriptorProto.message_type has field number 4:
- // repeated DescriptorProto message_type = 4;
- // and DescriptorProto.field has field number 2:
- // repeated FieldDescriptorProto field = 2;
- // and FieldDescriptorProto.name has field number 1:
- // optional string name = 1;
- //
- // Thus, the above path gives the location of a field name. If we removed
- // the last element:
- // [ 4, 3, 2, 7 ]
- // this path refers to the whole field declaration (from the beginning
- // of the label to the terminating semicolon).
- repeated int32 path = 1 [packed=true];
-
- // Always has exactly three or four elements: start line, start column,
- // end line (optional, otherwise assumed same as start line), end column.
- // These are packed into a single field for efficiency. Note that line
- // and column numbers are zero-based -- typically you will want to add
- // 1 to each before displaying to a user.
- repeated int32 span = 2 [packed=true];
-
- // If this SourceCodeInfo represents a complete declaration, these are any
- // comments appearing before and after the declaration which appear to be
- // attached to the declaration.
- //
- // A series of line comments appearing on consecutive lines, with no other
- // tokens appearing on those lines, will be treated as a single comment.
- //
- // leading_detached_comments will keep paragraphs of comments that appear
- // before (but not connected to) the current element. Each paragraph,
- // separated by empty lines, will be one comment element in the repeated
- // field.
- //
- // Only the comment content is provided; comment markers (e.g. //) are
- // stripped out. For block comments, leading whitespace and an asterisk
- // will be stripped from the beginning of each line other than the first.
- // Newlines are included in the output.
- //
- // Examples:
- //
- // optional int32 foo = 1; // Comment attached to foo.
- // // Comment attached to bar.
- // optional int32 bar = 2;
- //
- // optional string baz = 3;
- // // Comment attached to baz.
- // // Another line attached to baz.
- //
- // // Comment attached to qux.
- // //
- // // Another line attached to qux.
- // optional double qux = 4;
- //
- // // Detached comment for corge. This is not leading or trailing comments
- // // to qux or corge because there are blank lines separating it from
- // // both.
- //
- // // Detached comment for corge paragraph 2.
- //
- // optional string corge = 5;
- // /* Block comment attached
- // * to corge. Leading asterisks
- // * will be removed. */
- // /* Block comment attached to
- // * grault. */
- // optional int32 grault = 6;
- //
- // // ignored detached comments.
- optional string leading_comments = 3;
- optional string trailing_comments = 4;
- repeated string leading_detached_comments = 6;
- }
-}
-
-// Describes the relationship between generated code and its original source
-// file. A GeneratedCodeInfo message is associated with only one generated
-// source file, but may contain references to different source .proto files.
-message GeneratedCodeInfo {
- // An Annotation connects some span of text in generated code to an element
- // of its generating .proto file.
- repeated Annotation annotation = 1;
- message Annotation {
- // Identifies the element in the original source .proto file. This field
- // is formatted the same as SourceCodeInfo.Location.path.
- repeated int32 path = 1 [packed=true];
-
- // Identifies the filesystem path to the original source .proto.
- optional string source_file = 2;
-
- // Identifies the starting offset in bytes in the generated code
- // that relates to the identified object.
- optional int32 begin = 3;
-
- // Identifies the ending offset in bytes in the generated code that
- // relates to the identified offset. The end offset should be one past
- // the last relevant byte (so the length of the text = end - begin).
- optional int32 end = 4;
- }
-}
diff --git a/vendor/github.com/golang/snappy/AUTHORS b/vendor/github.com/golang/snappy/AUTHORS
deleted file mode 100644
index bcfa19520a..0000000000
--- a/vendor/github.com/golang/snappy/AUTHORS
+++ /dev/null
@@ -1,15 +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>
-Rodolfo Carvalho
-Sebastien Binet
diff --git a/vendor/github.com/golang/snappy/CONTRIBUTORS b/vendor/github.com/golang/snappy/CONTRIBUTORS
deleted file mode 100644
index 931ae31606..0000000000
--- a/vendor/github.com/golang/snappy/CONTRIBUTORS
+++ /dev/null
@@ -1,37 +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
-Rodolfo Carvalho
-Russ Cox
-Sebastien Binet
diff --git a/vendor/github.com/golang/snappy/LICENSE b/vendor/github.com/golang/snappy/LICENSE
deleted file mode 100644
index 6050c10f4c..0000000000
--- a/vendor/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/vendor/github.com/golang/snappy/README b/vendor/github.com/golang/snappy/README
deleted file mode 100644
index cea12879a0..0000000000
--- a/vendor/github.com/golang/snappy/README
+++ /dev/null
@@ -1,107 +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.
-
-
-
-Benchmarks.
-
-The golang/snappy benchmarks include compressing (Z) and decompressing (U) ten
-or so files, the same set used by the C++ Snappy code (github.com/google/snappy
-and note the "google", not "golang"). On an "Intel(R) Core(TM) i7-3770 CPU @
-3.40GHz", Go's GOARCH=amd64 numbers as of 2016-05-29:
-
-"go test -test.bench=."
-
-_UFlat0-8 2.19GB/s ± 0% html
-_UFlat1-8 1.41GB/s ± 0% urls
-_UFlat2-8 23.5GB/s ± 2% jpg
-_UFlat3-8 1.91GB/s ± 0% jpg_200
-_UFlat4-8 14.0GB/s ± 1% pdf
-_UFlat5-8 1.97GB/s ± 0% html4
-_UFlat6-8 814MB/s ± 0% txt1
-_UFlat7-8 785MB/s ± 0% txt2
-_UFlat8-8 857MB/s ± 0% txt3
-_UFlat9-8 719MB/s ± 1% txt4
-_UFlat10-8 2.84GB/s ± 0% pb
-_UFlat11-8 1.05GB/s ± 0% gaviota
-
-_ZFlat0-8 1.04GB/s ± 0% html
-_ZFlat1-8 534MB/s ± 0% urls
-_ZFlat2-8 15.7GB/s ± 1% jpg
-_ZFlat3-8 740MB/s ± 3% jpg_200
-_ZFlat4-8 9.20GB/s ± 1% pdf
-_ZFlat5-8 991MB/s ± 0% html4
-_ZFlat6-8 379MB/s ± 0% txt1
-_ZFlat7-8 352MB/s ± 0% txt2
-_ZFlat8-8 396MB/s ± 1% txt3
-_ZFlat9-8 327MB/s ± 1% txt4
-_ZFlat10-8 1.33GB/s ± 1% pb
-_ZFlat11-8 605MB/s ± 1% gaviota
-
-
-
-"go test -test.bench=. -tags=noasm"
-
-_UFlat0-8 621MB/s ± 2% html
-_UFlat1-8 494MB/s ± 1% urls
-_UFlat2-8 23.2GB/s ± 1% jpg
-_UFlat3-8 1.12GB/s ± 1% jpg_200
-_UFlat4-8 4.35GB/s ± 1% pdf
-_UFlat5-8 609MB/s ± 0% html4
-_UFlat6-8 296MB/s ± 0% txt1
-_UFlat7-8 288MB/s ± 0% txt2
-_UFlat8-8 309MB/s ± 1% txt3
-_UFlat9-8 280MB/s ± 1% txt4
-_UFlat10-8 753MB/s ± 0% pb
-_UFlat11-8 400MB/s ± 0% gaviota
-
-_ZFlat0-8 409MB/s ± 1% html
-_ZFlat1-8 250MB/s ± 1% urls
-_ZFlat2-8 12.3GB/s ± 1% jpg
-_ZFlat3-8 132MB/s ± 0% jpg_200
-_ZFlat4-8 2.92GB/s ± 0% pdf
-_ZFlat5-8 405MB/s ± 1% html4
-_ZFlat6-8 179MB/s ± 1% txt1
-_ZFlat7-8 170MB/s ± 1% txt2
-_ZFlat8-8 189MB/s ± 1% txt3
-_ZFlat9-8 164MB/s ± 1% txt4
-_ZFlat10-8 479MB/s ± 1% pb
-_ZFlat11-8 270MB/s ± 1% gaviota
-
-
-
-For comparison (Go's encoded output is byte-for-byte identical to C++'s), here
-are the numbers from C++ Snappy's
-
-make CXXFLAGS="-O2 -DNDEBUG -g" clean snappy_unittest.log && cat snappy_unittest.log
-
-BM_UFlat/0 2.4GB/s html
-BM_UFlat/1 1.4GB/s urls
-BM_UFlat/2 21.8GB/s jpg
-BM_UFlat/3 1.5GB/s jpg_200
-BM_UFlat/4 13.3GB/s pdf
-BM_UFlat/5 2.1GB/s html4
-BM_UFlat/6 1.0GB/s txt1
-BM_UFlat/7 959.4MB/s txt2
-BM_UFlat/8 1.0GB/s txt3
-BM_UFlat/9 864.5MB/s txt4
-BM_UFlat/10 2.9GB/s pb
-BM_UFlat/11 1.2GB/s gaviota
-
-BM_ZFlat/0 944.3MB/s html (22.31 %)
-BM_ZFlat/1 501.6MB/s urls (47.78 %)
-BM_ZFlat/2 14.3GB/s jpg (99.95 %)
-BM_ZFlat/3 538.3MB/s jpg_200 (73.00 %)
-BM_ZFlat/4 8.3GB/s pdf (83.30 %)
-BM_ZFlat/5 903.5MB/s html4 (22.52 %)
-BM_ZFlat/6 336.0MB/s txt1 (57.88 %)
-BM_ZFlat/7 312.3MB/s txt2 (61.91 %)
-BM_ZFlat/8 353.1MB/s txt3 (54.99 %)
-BM_ZFlat/9 289.9MB/s txt4 (66.26 %)
-BM_ZFlat/10 1.2GB/s pb (19.68 %)
-BM_ZFlat/11 527.4MB/s gaviota (37.72 %)
diff --git a/vendor/github.com/golang/snappy/decode.go b/vendor/github.com/golang/snappy/decode.go
deleted file mode 100644
index 72efb0353d..0000000000
--- a/vendor/github.com/golang/snappy/decode.go
+++ /dev/null
@@ -1,237 +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")
- // ErrTooLarge reports that the uncompressed length is too large.
- ErrTooLarge = errors.New("snappy: decoded block is too large")
- // ErrUnsupported reports that the input isn't supported.
- ErrUnsupported = errors.New("snappy: unsupported input")
-
- errUnsupportedLiteralLength = errors.New("snappy: unsupported literal length")
-)
-
-// 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 || v > 0xffffffff {
- return 0, 0, ErrCorrupt
- }
-
- const wordSize = 32 << (^uint(0) >> 32 & 1)
- if wordSize == 32 && v > 0x7fffffff {
- return 0, 0, ErrTooLarge
- }
- return int(v), n, nil
-}
-
-const (
- decodeErrCodeCorrupt = 1
- decodeErrCodeUnsupportedLiteralLength = 2
-)
-
-// 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.
-//
-// The dst and src must not overlap. 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 dLen <= len(dst) {
- dst = dst[:dLen]
- } else {
- dst = make([]byte, dLen)
- }
- switch decode(dst, src[s:]) {
- case 0:
- return dst, nil
- case decodeErrCodeUnsupportedLiteralLength:
- return nil, errUnsupportedLiteralLength
- }
- return nil, ErrCorrupt
-}
-
-// 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, maxBlockSize),
- buf: make([]byte, maxEncodedLenOfMaxBlockSize+checksumSize),
- }
-}
-
-// Reader is an io.Reader that 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, allowEOF bool) (ok bool) {
- if _, r.err = io.ReadFull(r.r, p); r.err != nil {
- if r.err == io.ErrUnexpectedEOF || (r.err == io.EOF && !allowEOF) {
- 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], true) {
- 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, false) {
- 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, false) {
- 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 n > len(r.decoded) {
- r.err = ErrCorrupt
- return 0, r.err
- }
- if !r.readFull(r.decoded[:n], false) {
- 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)], false) {
- 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], false) {
- return 0, r.err
- }
- }
-}
diff --git a/vendor/github.com/golang/snappy/decode_amd64.go b/vendor/github.com/golang/snappy/decode_amd64.go
deleted file mode 100644
index fcd192b849..0000000000
--- a/vendor/github.com/golang/snappy/decode_amd64.go
+++ /dev/null
@@ -1,14 +0,0 @@
-// Copyright 2016 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.
-
-// +build !appengine
-// +build gc
-// +build !noasm
-
-package snappy
-
-// decode has the same semantics as in decode_other.go.
-//
-//go:noescape
-func decode(dst, src []byte) int
diff --git a/vendor/github.com/golang/snappy/decode_amd64.s b/vendor/github.com/golang/snappy/decode_amd64.s
deleted file mode 100644
index e6179f65e3..0000000000
--- a/vendor/github.com/golang/snappy/decode_amd64.s
+++ /dev/null
@@ -1,490 +0,0 @@
-// Copyright 2016 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 !appengine
-// +build gc
-// +build !noasm
-
-#include "textflag.h"
-
-// The asm code generally follows the pure Go code in decode_other.go, except
-// where marked with a "!!!".
-
-// func decode(dst, src []byte) int
-//
-// All local variables fit into registers. The non-zero stack size is only to
-// spill registers and push args when issuing a CALL. The register allocation:
-// - AX scratch
-// - BX scratch
-// - CX length or x
-// - DX offset
-// - SI &src[s]
-// - DI &dst[d]
-// + R8 dst_base
-// + R9 dst_len
-// + R10 dst_base + dst_len
-// + R11 src_base
-// + R12 src_len
-// + R13 src_base + src_len
-// - R14 used by doCopy
-// - R15 used by doCopy
-//
-// The registers R8-R13 (marked with a "+") are set at the start of the
-// function, and after a CALL returns, and are not otherwise modified.
-//
-// The d variable is implicitly DI - R8, and len(dst)-d is R10 - DI.
-// The s variable is implicitly SI - R11, and len(src)-s is R13 - SI.
-TEXT ·decode(SB), NOSPLIT, $48-56
- // Initialize SI, DI and R8-R13.
- MOVQ dst_base+0(FP), R8
- MOVQ dst_len+8(FP), R9
- MOVQ R8, DI
- MOVQ R8, R10
- ADDQ R9, R10
- MOVQ src_base+24(FP), R11
- MOVQ src_len+32(FP), R12
- MOVQ R11, SI
- MOVQ R11, R13
- ADDQ R12, R13
-
-loop:
- // for s < len(src)
- CMPQ SI, R13
- JEQ end
-
- // CX = uint32(src[s])
- //
- // switch src[s] & 0x03
- MOVBLZX (SI), CX
- MOVL CX, BX
- ANDL $3, BX
- CMPL BX, $1
- JAE tagCopy
-
- // ----------------------------------------
- // The code below handles literal tags.
-
- // case tagLiteral:
- // x := uint32(src[s] >> 2)
- // switch
- SHRL $2, CX
- CMPL CX, $60
- JAE tagLit60Plus
-
- // case x < 60:
- // s++
- INCQ SI
-
-doLit:
- // This is the end of the inner "switch", when we have a literal tag.
- //
- // We assume that CX == x and x fits in a uint32, where x is the variable
- // used in the pure Go decode_other.go code.
-
- // length = int(x) + 1
- //
- // Unlike the pure Go code, we don't need to check if length <= 0 because
- // CX can hold 64 bits, so the increment cannot overflow.
- INCQ CX
-
- // Prepare to check if copying length bytes will run past the end of dst or
- // src.
- //
- // AX = len(dst) - d
- // BX = len(src) - s
- MOVQ R10, AX
- SUBQ DI, AX
- MOVQ R13, BX
- SUBQ SI, BX
-
- // !!! Try a faster technique for short (16 or fewer bytes) copies.
- //
- // if length > 16 || len(dst)-d < 16 || len(src)-s < 16 {
- // goto callMemmove // Fall back on calling runtime·memmove.
- // }
- //
- // The C++ snappy code calls this TryFastAppend. It also checks len(src)-s
- // against 21 instead of 16, because it cannot assume that all of its input
- // is contiguous in memory and so it needs to leave enough source bytes to
- // read the next tag without refilling buffers, but Go's Decode assumes
- // contiguousness (the src argument is a []byte).
- CMPQ CX, $16
- JGT callMemmove
- CMPQ AX, $16
- JLT callMemmove
- CMPQ BX, $16
- JLT callMemmove
-
- // !!! Implement the copy from src to dst as a 16-byte load and store.
- // (Decode's documentation says that dst and src must not overlap.)
- //
- // This always copies 16 bytes, instead of only length bytes, but that's
- // OK. If the input is a valid Snappy encoding then subsequent iterations
- // will fix up the overrun. Otherwise, Decode returns a nil []byte (and a
- // non-nil error), so the overrun will be ignored.
- //
- // Note that on amd64, it is legal and cheap to issue unaligned 8-byte or
- // 16-byte loads and stores. This technique probably wouldn't be as
- // effective on architectures that are fussier about alignment.
- MOVOU 0(SI), X0
- MOVOU X0, 0(DI)
-
- // d += length
- // s += length
- ADDQ CX, DI
- ADDQ CX, SI
- JMP loop
-
-callMemmove:
- // if length > len(dst)-d || length > len(src)-s { etc }
- CMPQ CX, AX
- JGT errCorrupt
- CMPQ CX, BX
- JGT errCorrupt
-
- // copy(dst[d:], src[s:s+length])
- //
- // This means calling runtime·memmove(&dst[d], &src[s], length), so we push
- // DI, SI and CX as arguments. Coincidentally, we also need to spill those
- // three registers to the stack, to save local variables across the CALL.
- MOVQ DI, 0(SP)
- MOVQ SI, 8(SP)
- MOVQ CX, 16(SP)
- MOVQ DI, 24(SP)
- MOVQ SI, 32(SP)
- MOVQ CX, 40(SP)
- CALL runtime·memmove(SB)
-
- // Restore local variables: unspill registers from the stack and
- // re-calculate R8-R13.
- MOVQ 24(SP), DI
- MOVQ 32(SP), SI
- MOVQ 40(SP), CX
- MOVQ dst_base+0(FP), R8
- MOVQ dst_len+8(FP), R9
- MOVQ R8, R10
- ADDQ R9, R10
- MOVQ src_base+24(FP), R11
- MOVQ src_len+32(FP), R12
- MOVQ R11, R13
- ADDQ R12, R13
-
- // d += length
- // s += length
- ADDQ CX, DI
- ADDQ CX, SI
- JMP loop
-
-tagLit60Plus:
- // !!! This fragment does the
- //
- // s += x - 58; if uint(s) > uint(len(src)) { etc }
- //
- // checks. In the asm version, we code it once instead of once per switch case.
- ADDQ CX, SI
- SUBQ $58, SI
- MOVQ SI, BX
- SUBQ R11, BX
- CMPQ BX, R12
- JA errCorrupt
-
- // case x == 60:
- CMPL CX, $61
- JEQ tagLit61
- JA tagLit62Plus
-
- // x = uint32(src[s-1])
- MOVBLZX -1(SI), CX
- JMP doLit
-
-tagLit61:
- // case x == 61:
- // x = uint32(src[s-2]) | uint32(src[s-1])<<8
- MOVWLZX -2(SI), CX
- JMP doLit
-
-tagLit62Plus:
- CMPL CX, $62
- JA tagLit63
-
- // case x == 62:
- // x = uint32(src[s-3]) | uint32(src[s-2])<<8 | uint32(src[s-1])<<16
- MOVWLZX -3(SI), CX
- MOVBLZX -1(SI), BX
- SHLL $16, BX
- ORL BX, CX
- JMP doLit
-
-tagLit63:
- // case x == 63:
- // x = uint32(src[s-4]) | uint32(src[s-3])<<8 | uint32(src[s-2])<<16 | uint32(src[s-1])<<24
- MOVL -4(SI), CX
- JMP doLit
-
-// The code above handles literal tags.
-// ----------------------------------------
-// The code below handles copy tags.
-
-tagCopy4:
- // case tagCopy4:
- // s += 5
- ADDQ $5, SI
-
- // if uint(s) > uint(len(src)) { etc }
- MOVQ SI, BX
- SUBQ R11, BX
- CMPQ BX, R12
- JA errCorrupt
-
- // length = 1 + int(src[s-5])>>2
- SHRQ $2, CX
- INCQ CX
-
- // offset = int(uint32(src[s-4]) | uint32(src[s-3])<<8 | uint32(src[s-2])<<16 | uint32(src[s-1])<<24)
- MOVLQZX -4(SI), DX
- JMP doCopy
-
-tagCopy2:
- // case tagCopy2:
- // s += 3
- ADDQ $3, SI
-
- // if uint(s) > uint(len(src)) { etc }
- MOVQ SI, BX
- SUBQ R11, BX
- CMPQ BX, R12
- JA errCorrupt
-
- // length = 1 + int(src[s-3])>>2
- SHRQ $2, CX
- INCQ CX
-
- // offset = int(uint32(src[s-2]) | uint32(src[s-1])<<8)
- MOVWQZX -2(SI), DX
- JMP doCopy
-
-tagCopy:
- // We have a copy tag. We assume that:
- // - BX == src[s] & 0x03
- // - CX == src[s]
- CMPQ BX, $2
- JEQ tagCopy2
- JA tagCopy4
-
- // case tagCopy1:
- // s += 2
- ADDQ $2, SI
-
- // if uint(s) > uint(len(src)) { etc }
- MOVQ SI, BX
- SUBQ R11, BX
- CMPQ BX, R12
- JA errCorrupt
-
- // offset = int(uint32(src[s-2])&0xe0<<3 | uint32(src[s-1]))
- MOVQ CX, DX
- ANDQ $0xe0, DX
- SHLQ $3, DX
- MOVBQZX -1(SI), BX
- ORQ BX, DX
-
- // length = 4 + int(src[s-2])>>2&0x7
- SHRQ $2, CX
- ANDQ $7, CX
- ADDQ $4, CX
-
-doCopy:
- // This is the end of the outer "switch", when we have a copy tag.
- //
- // We assume that:
- // - CX == length && CX > 0
- // - DX == offset
-
- // if offset <= 0 { etc }
- CMPQ DX, $0
- JLE errCorrupt
-
- // if d < offset { etc }
- MOVQ DI, BX
- SUBQ R8, BX
- CMPQ BX, DX
- JLT errCorrupt
-
- // if length > len(dst)-d { etc }
- MOVQ R10, BX
- SUBQ DI, BX
- CMPQ CX, BX
- JGT errCorrupt
-
- // forwardCopy(dst[d:d+length], dst[d-offset:]); d += length
- //
- // Set:
- // - R14 = len(dst)-d
- // - R15 = &dst[d-offset]
- MOVQ R10, R14
- SUBQ DI, R14
- MOVQ DI, R15
- SUBQ DX, R15
-
- // !!! Try a faster technique for short (16 or fewer bytes) forward copies.
- //
- // First, try using two 8-byte load/stores, similar to the doLit technique
- // above. Even if dst[d:d+length] and dst[d-offset:] can overlap, this is
- // still OK if offset >= 8. Note that this has to be two 8-byte load/stores
- // and not one 16-byte load/store, and the first store has to be before the
- // second load, due to the overlap if offset is in the range [8, 16).
- //
- // if length > 16 || offset < 8 || len(dst)-d < 16 {
- // goto slowForwardCopy
- // }
- // copy 16 bytes
- // d += length
- CMPQ CX, $16
- JGT slowForwardCopy
- CMPQ DX, $8
- JLT slowForwardCopy
- CMPQ R14, $16
- JLT slowForwardCopy
- MOVQ 0(R15), AX
- MOVQ AX, 0(DI)
- MOVQ 8(R15), BX
- MOVQ BX, 8(DI)
- ADDQ CX, DI
- JMP loop
-
-slowForwardCopy:
- // !!! If the forward copy is longer than 16 bytes, or if offset < 8, we
- // can still try 8-byte load stores, provided we can overrun up to 10 extra
- // bytes. As above, the overrun will be fixed up by subsequent iterations
- // of the outermost loop.
- //
- // The C++ snappy code calls this technique IncrementalCopyFastPath. Its
- // commentary says:
- //
- // ----
- //
- // The main part of this loop is a simple copy of eight bytes at a time
- // until we've copied (at least) the requested amount of bytes. However,
- // if d and d-offset are less than eight bytes apart (indicating a
- // repeating pattern of length < 8), we first need to expand the pattern in
- // order to get the correct results. For instance, if the buffer looks like
- // this, with the eight-byte and patterns marked as
- // intervals:
- //
- // abxxxxxxxxxxxx
- // [------] d-offset
- // [------] d
- //
- // a single eight-byte copy from to will repeat the pattern
- // once, after which we can move two bytes without moving :
- //
- // ababxxxxxxxxxx
- // [------] d-offset
- // [------] d
- //
- // and repeat the exercise until the two no longer overlap.
- //
- // This allows us to do very well in the special case of one single byte
- // repeated many times, without taking a big hit for more general cases.
- //
- // The worst case of extra writing past the end of the match occurs when
- // offset == 1 and length == 1; the last copy will read from byte positions
- // [0..7] and write to [4..11], whereas it was only supposed to write to
- // position 1. Thus, ten excess bytes.
- //
- // ----
- //
- // That "10 byte overrun" worst case is confirmed by Go's
- // TestSlowForwardCopyOverrun, which also tests the fixUpSlowForwardCopy
- // and finishSlowForwardCopy algorithm.
- //
- // if length > len(dst)-d-10 {
- // goto verySlowForwardCopy
- // }
- SUBQ $10, R14
- CMPQ CX, R14
- JGT verySlowForwardCopy
-
-makeOffsetAtLeast8:
- // !!! As above, expand the pattern so that offset >= 8 and we can use
- // 8-byte load/stores.
- //
- // for offset < 8 {
- // copy 8 bytes from dst[d-offset:] to dst[d:]
- // length -= offset
- // d += offset
- // offset += offset
- // // The two previous lines together means that d-offset, and therefore
- // // R15, is unchanged.
- // }
- CMPQ DX, $8
- JGE fixUpSlowForwardCopy
- MOVQ (R15), BX
- MOVQ BX, (DI)
- SUBQ DX, CX
- ADDQ DX, DI
- ADDQ DX, DX
- JMP makeOffsetAtLeast8
-
-fixUpSlowForwardCopy:
- // !!! Add length (which might be negative now) to d (implied by DI being
- // &dst[d]) so that d ends up at the right place when we jump back to the
- // top of the loop. Before we do that, though, we save DI to AX so that, if
- // length is positive, copying the remaining length bytes will write to the
- // right place.
- MOVQ DI, AX
- ADDQ CX, DI
-
-finishSlowForwardCopy:
- // !!! Repeat 8-byte load/stores until length <= 0. Ending with a negative
- // length means that we overrun, but as above, that will be fixed up by
- // subsequent iterations of the outermost loop.
- CMPQ CX, $0
- JLE loop
- MOVQ (R15), BX
- MOVQ BX, (AX)
- ADDQ $8, R15
- ADDQ $8, AX
- SUBQ $8, CX
- JMP finishSlowForwardCopy
-
-verySlowForwardCopy:
- // verySlowForwardCopy is a simple implementation of forward copy. In C
- // parlance, this is a do/while loop instead of a while loop, since we know
- // that length > 0. In Go syntax:
- //
- // for {
- // dst[d] = dst[d - offset]
- // d++
- // length--
- // if length == 0 {
- // break
- // }
- // }
- MOVB (R15), BX
- MOVB BX, (DI)
- INCQ R15
- INCQ DI
- DECQ CX
- JNZ verySlowForwardCopy
- JMP loop
-
-// The code above handles copy tags.
-// ----------------------------------------
-
-end:
- // This is the end of the "for s < len(src)".
- //
- // if d != len(dst) { etc }
- CMPQ DI, R10
- JNE errCorrupt
-
- // return 0
- MOVQ $0, ret+48(FP)
- RET
-
-errCorrupt:
- // return decodeErrCodeCorrupt
- MOVQ $1, ret+48(FP)
- RET
diff --git a/vendor/github.com/golang/snappy/decode_other.go b/vendor/github.com/golang/snappy/decode_other.go
deleted file mode 100644
index 8c9f2049bc..0000000000
--- a/vendor/github.com/golang/snappy/decode_other.go
+++ /dev/null
@@ -1,101 +0,0 @@
-// Copyright 2016 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.
-
-// +build !amd64 appengine !gc noasm
-
-package snappy
-
-// decode writes the decoding of src to dst. It assumes that the varint-encoded
-// length of the decompressed bytes has already been read, and that len(dst)
-// equals that length.
-//
-// It returns 0 on success or a decodeErrCodeXxx error code on failure.
-func decode(dst, src []byte) int {
- var d, s, offset, length int
- for s < len(src) {
- switch src[s] & 0x03 {
- case tagLiteral:
- x := uint32(src[s] >> 2)
- switch {
- case x < 60:
- s++
- case x == 60:
- s += 2
- if uint(s) > uint(len(src)) { // The uint conversions catch overflow from the previous line.
- return decodeErrCodeCorrupt
- }
- x = uint32(src[s-1])
- case x == 61:
- s += 3
- if uint(s) > uint(len(src)) { // The uint conversions catch overflow from the previous line.
- return decodeErrCodeCorrupt
- }
- x = uint32(src[s-2]) | uint32(src[s-1])<<8
- case x == 62:
- s += 4
- if uint(s) > uint(len(src)) { // The uint conversions catch overflow from the previous line.
- return decodeErrCodeCorrupt
- }
- x = uint32(src[s-3]) | uint32(src[s-2])<<8 | uint32(src[s-1])<<16
- case x == 63:
- s += 5
- if uint(s) > uint(len(src)) { // The uint conversions catch overflow from the previous line.
- return decodeErrCodeCorrupt
- }
- x = uint32(src[s-4]) | uint32(src[s-3])<<8 | uint32(src[s-2])<<16 | uint32(src[s-1])<<24
- }
- length = int(x) + 1
- if length <= 0 {
- return decodeErrCodeUnsupportedLiteralLength
- }
- if length > len(dst)-d || length > len(src)-s {
- return decodeErrCodeCorrupt
- }
- copy(dst[d:], src[s:s+length])
- d += length
- s += length
- continue
-
- case tagCopy1:
- s += 2
- if uint(s) > uint(len(src)) { // The uint conversions catch overflow from the previous line.
- return decodeErrCodeCorrupt
- }
- length = 4 + int(src[s-2])>>2&0x7
- offset = int(uint32(src[s-2])&0xe0<<3 | uint32(src[s-1]))
-
- case tagCopy2:
- s += 3
- if uint(s) > uint(len(src)) { // The uint conversions catch overflow from the previous line.
- return decodeErrCodeCorrupt
- }
- length = 1 + int(src[s-3])>>2
- offset = int(uint32(src[s-2]) | uint32(src[s-1])<<8)
-
- case tagCopy4:
- s += 5
- if uint(s) > uint(len(src)) { // The uint conversions catch overflow from the previous line.
- return decodeErrCodeCorrupt
- }
- length = 1 + int(src[s-5])>>2
- offset = int(uint32(src[s-4]) | uint32(src[s-3])<<8 | uint32(src[s-2])<<16 | uint32(src[s-1])<<24)
- }
-
- if offset <= 0 || d < offset || length > len(dst)-d {
- return decodeErrCodeCorrupt
- }
- // Copy from an earlier sub-slice of dst to a later sub-slice. Unlike
- // the built-in copy function, this byte-by-byte copy always runs
- // forwards, even if the slices overlap. Conceptually, this is:
- //
- // d += forwardCopy(dst[d:d+length], dst[d-offset:])
- for end := d + length; d != end; d++ {
- dst[d] = dst[d-offset]
- }
- }
- if d != len(dst) {
- return decodeErrCodeCorrupt
- }
- return 0
-}
diff --git a/vendor/github.com/golang/snappy/encode.go b/vendor/github.com/golang/snappy/encode.go
deleted file mode 100644
index 8d393e904b..0000000000
--- a/vendor/github.com/golang/snappy/encode.go
+++ /dev/null
@@ -1,285 +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"
-)
-
-// 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.
-//
-// The dst and src must not overlap. It is valid to pass a nil dst.
-func Encode(dst, src []byte) []byte {
- if n := MaxEncodedLen(len(src)); n < 0 {
- panic(ErrTooLarge)
- } else if 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)))
-
- for len(src) > 0 {
- p := src
- src = nil
- if len(p) > maxBlockSize {
- p, src = p[:maxBlockSize], p[maxBlockSize:]
- }
- if len(p) < minNonLiteralBlockSize {
- d += emitLiteral(dst[d:], p)
- } else {
- d += encodeBlock(dst[d:], p)
- }
- }
- return dst[:d]
-}
-
-// inputMargin is the minimum number of extra input bytes to keep, inside
-// encodeBlock's inner loop. On some architectures, this margin lets us
-// implement a fast path for emitLiteral, where the copy of short (<= 16 byte)
-// literals can be implemented as a single load to and store from a 16-byte
-// register. That literal's actual length can be as short as 1 byte, so this
-// can copy up to 15 bytes too much, but that's OK as subsequent iterations of
-// the encoding loop will fix up the copy overrun, and this inputMargin ensures
-// that we don't overrun the dst and src buffers.
-const inputMargin = 16 - 1
-
-// minNonLiteralBlockSize is the minimum size of the input to encodeBlock that
-// could be encoded with a copy tag. This is the minimum with respect to the
-// algorithm used by encodeBlock, not a minimum enforced by the file format.
-//
-// The encoded output must start with at least a 1 byte literal, as there are
-// no previous bytes to copy. A minimal (1 byte) copy after that, generated
-// from an emitCopy call in encodeBlock's main loop, would require at least
-// another inputMargin bytes, for the reason above: we want any emitLiteral
-// calls inside encodeBlock's main loop to use the fast path if possible, which
-// requires being able to overrun by inputMargin bytes. Thus,
-// minNonLiteralBlockSize equals 1 + 1 + inputMargin.
-//
-// The C++ code doesn't use this exact threshold, but it could, as discussed at
-// https://groups.google.com/d/topic/snappy-compression/oGbhsdIJSJ8/discussion
-// The difference between Go (2+inputMargin) and C++ (inputMargin) is purely an
-// optimization. It should not affect the encoded form. This is tested by
-// TestSameEncodingAsCppShortCopies.
-const minNonLiteralBlockSize = 1 + 1 + inputMargin
-
-// MaxEncodedLen returns the maximum length of a snappy block, given its
-// uncompressed length.
-//
-// It will return a negative value if srcLen is too large to encode.
-func MaxEncodedLen(srcLen int) int {
- n := uint64(srcLen)
- if n > 0xffffffff {
- return -1
- }
- // 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:
- n = 32 + n + n/6
- if n > 0xffffffff {
- return -1
- }
- return int(n)
-}
-
-var errClosed = errors.New("snappy: Writer is closed")
-
-// NewWriter returns a new Writer that compresses to w.
-//
-// The Writer returned does not buffer writes. There is no need to Flush or
-// Close such a Writer.
-//
-// Deprecated: the Writer returned is not suitable for many small writes, only
-// for few large writes. Use NewBufferedWriter instead, which is efficient
-// regardless of the frequency and shape of the writes, and remember to Close
-// that Writer when done.
-func NewWriter(w io.Writer) *Writer {
- return &Writer{
- w: w,
- obuf: make([]byte, obufLen),
- }
-}
-
-// NewBufferedWriter returns a new Writer that compresses to w, using the
-// framing format described at
-// https://github.com/google/snappy/blob/master/framing_format.txt
-//
-// The Writer returned buffers writes. Users must call Close to guarantee all
-// data has been forwarded to the underlying io.Writer. They may also call
-// Flush zero or more times before calling Close.
-func NewBufferedWriter(w io.Writer) *Writer {
- return &Writer{
- w: w,
- ibuf: make([]byte, 0, maxBlockSize),
- obuf: make([]byte, obufLen),
- }
-}
-
-// Writer is an io.Writer that can write Snappy-compressed bytes.
-type Writer struct {
- w io.Writer
- err error
-
- // ibuf is a buffer for the incoming (uncompressed) bytes.
- //
- // Its use is optional. For backwards compatibility, Writers created by the
- // NewWriter function have ibuf == nil, do not buffer incoming bytes, and
- // therefore do not need to be Flush'ed or Close'd.
- ibuf []byte
-
- // obuf is a buffer for the outgoing (compressed) bytes.
- obuf []byte
-
- // wroteStreamHeader is whether we have written the stream header.
- wroteStreamHeader 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
- if w.ibuf != nil {
- w.ibuf = w.ibuf[:0]
- }
- w.wroteStreamHeader = false
-}
-
-// Write satisfies the io.Writer interface.
-func (w *Writer) Write(p []byte) (nRet int, errRet error) {
- if w.ibuf == nil {
- // Do not buffer incoming bytes. This does not perform or compress well
- // if the caller of Writer.Write writes many small slices. This
- // behavior is therefore deprecated, but still supported for backwards
- // compatibility with code that doesn't explicitly Flush or Close.
- return w.write(p)
- }
-
- // The remainder of this method is based on bufio.Writer.Write from the
- // standard library.
-
- for len(p) > (cap(w.ibuf)-len(w.ibuf)) && w.err == nil {
- var n int
- if len(w.ibuf) == 0 {
- // Large write, empty buffer.
- // Write directly from p to avoid copy.
- n, _ = w.write(p)
- } else {
- n = copy(w.ibuf[len(w.ibuf):cap(w.ibuf)], p)
- w.ibuf = w.ibuf[:len(w.ibuf)+n]
- w.Flush()
- }
- nRet += n
- p = p[n:]
- }
- if w.err != nil {
- return nRet, w.err
- }
- n := copy(w.ibuf[len(w.ibuf):cap(w.ibuf)], p)
- w.ibuf = w.ibuf[:len(w.ibuf)+n]
- nRet += n
- return nRet, nil
-}
-
-func (w *Writer) write(p []byte) (nRet int, errRet error) {
- if w.err != nil {
- return 0, w.err
- }
- for len(p) > 0 {
- obufStart := len(magicChunk)
- if !w.wroteStreamHeader {
- w.wroteStreamHeader = true
- copy(w.obuf, magicChunk)
- obufStart = 0
- }
-
- var uncompressed []byte
- if len(p) > maxBlockSize {
- uncompressed, p = p[:maxBlockSize], p[maxBlockSize:]
- } else {
- uncompressed, p = p, nil
- }
- checksum := crc(uncompressed)
-
- // Compress the buffer, discarding the result if the improvement
- // isn't at least 12.5%.
- compressed := Encode(w.obuf[obufHeaderLen:], uncompressed)
- chunkType := uint8(chunkTypeCompressedData)
- chunkLen := 4 + len(compressed)
- obufEnd := obufHeaderLen + len(compressed)
- if len(compressed) >= len(uncompressed)-len(uncompressed)/8 {
- chunkType = chunkTypeUncompressedData
- chunkLen = 4 + len(uncompressed)
- obufEnd = obufHeaderLen
- }
-
- // Fill in the per-chunk header that comes before the body.
- w.obuf[len(magicChunk)+0] = chunkType
- w.obuf[len(magicChunk)+1] = uint8(chunkLen >> 0)
- w.obuf[len(magicChunk)+2] = uint8(chunkLen >> 8)
- w.obuf[len(magicChunk)+3] = uint8(chunkLen >> 16)
- w.obuf[len(magicChunk)+4] = uint8(checksum >> 0)
- w.obuf[len(magicChunk)+5] = uint8(checksum >> 8)
- w.obuf[len(magicChunk)+6] = uint8(checksum >> 16)
- w.obuf[len(magicChunk)+7] = uint8(checksum >> 24)
-
- if _, err := w.w.Write(w.obuf[obufStart:obufEnd]); err != nil {
- w.err = err
- return nRet, err
- }
- if chunkType == chunkTypeUncompressedData {
- if _, err := w.w.Write(uncompressed); err != nil {
- w.err = err
- return nRet, err
- }
- }
- nRet += len(uncompressed)
- }
- return nRet, nil
-}
-
-// Flush flushes the Writer to its underlying io.Writer.
-func (w *Writer) Flush() error {
- if w.err != nil {
- return w.err
- }
- if len(w.ibuf) == 0 {
- return nil
- }
- w.write(w.ibuf)
- w.ibuf = w.ibuf[:0]
- return w.err
-}
-
-// Close calls Flush and then closes the Writer.
-func (w *Writer) Close() error {
- w.Flush()
- ret := w.err
- if w.err == nil {
- w.err = errClosed
- }
- return ret
-}
diff --git a/vendor/github.com/golang/snappy/encode_amd64.go b/vendor/github.com/golang/snappy/encode_amd64.go
deleted file mode 100644
index 150d91bc8b..0000000000
--- a/vendor/github.com/golang/snappy/encode_amd64.go
+++ /dev/null
@@ -1,29 +0,0 @@
-// Copyright 2016 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.
-
-// +build !appengine
-// +build gc
-// +build !noasm
-
-package snappy
-
-// emitLiteral has the same semantics as in encode_other.go.
-//
-//go:noescape
-func emitLiteral(dst, lit []byte) int
-
-// emitCopy has the same semantics as in encode_other.go.
-//
-//go:noescape
-func emitCopy(dst []byte, offset, length int) int
-
-// extendMatch has the same semantics as in encode_other.go.
-//
-//go:noescape
-func extendMatch(src []byte, i, j int) int
-
-// encodeBlock has the same semantics as in encode_other.go.
-//
-//go:noescape
-func encodeBlock(dst, src []byte) (d int)
diff --git a/vendor/github.com/golang/snappy/encode_amd64.s b/vendor/github.com/golang/snappy/encode_amd64.s
deleted file mode 100644
index adfd979fe2..0000000000
--- a/vendor/github.com/golang/snappy/encode_amd64.s
+++ /dev/null
@@ -1,730 +0,0 @@
-// Copyright 2016 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 !appengine
-// +build gc
-// +build !noasm
-
-#include "textflag.h"
-
-// The XXX lines assemble on Go 1.4, 1.5 and 1.7, but not 1.6, due to a
-// Go toolchain regression. See https://github.com/golang/go/issues/15426 and
-// https://github.com/golang/snappy/issues/29
-//
-// As a workaround, the package was built with a known good assembler, and
-// those instructions were disassembled by "objdump -d" to yield the
-// 4e 0f b7 7c 5c 78 movzwq 0x78(%rsp,%r11,2),%r15
-// style comments, in AT&T asm syntax. Note that rsp here is a physical
-// register, not Go/asm's SP pseudo-register (see https://golang.org/doc/asm).
-// The instructions were then encoded as "BYTE $0x.." sequences, which assemble
-// fine on Go 1.6.
-
-// The asm code generally follows the pure Go code in encode_other.go, except
-// where marked with a "!!!".
-
-// ----------------------------------------------------------------------------
-
-// func emitLiteral(dst, lit []byte) int
-//
-// All local variables fit into registers. The register allocation:
-// - AX len(lit)
-// - BX n
-// - DX return value
-// - DI &dst[i]
-// - R10 &lit[0]
-//
-// The 24 bytes of stack space is to call runtime·memmove.
-//
-// The unusual register allocation of local variables, such as R10 for the
-// source pointer, matches the allocation used at the call site in encodeBlock,
-// which makes it easier to manually inline this function.
-TEXT ·emitLiteral(SB), NOSPLIT, $24-56
- MOVQ dst_base+0(FP), DI
- MOVQ lit_base+24(FP), R10
- MOVQ lit_len+32(FP), AX
- MOVQ AX, DX
- MOVL AX, BX
- SUBL $1, BX
-
- CMPL BX, $60
- JLT oneByte
- CMPL BX, $256
- JLT twoBytes
-
-threeBytes:
- MOVB $0xf4, 0(DI)
- MOVW BX, 1(DI)
- ADDQ $3, DI
- ADDQ $3, DX
- JMP memmove
-
-twoBytes:
- MOVB $0xf0, 0(DI)
- MOVB BX, 1(DI)
- ADDQ $2, DI
- ADDQ $2, DX
- JMP memmove
-
-oneByte:
- SHLB $2, BX
- MOVB BX, 0(DI)
- ADDQ $1, DI
- ADDQ $1, DX
-
-memmove:
- MOVQ DX, ret+48(FP)
-
- // copy(dst[i:], lit)
- //
- // This means calling runtime·memmove(&dst[i], &lit[0], len(lit)), so we push
- // DI, R10 and AX as arguments.
- MOVQ DI, 0(SP)
- MOVQ R10, 8(SP)
- MOVQ AX, 16(SP)
- CALL runtime·memmove(SB)
- RET
-
-// ----------------------------------------------------------------------------
-
-// func emitCopy(dst []byte, offset, length int) int
-//
-// All local variables fit into registers. The register allocation:
-// - AX length
-// - SI &dst[0]
-// - DI &dst[i]
-// - R11 offset
-//
-// The unusual register allocation of local variables, such as R11 for the
-// offset, matches the allocation used at the call site in encodeBlock, which
-// makes it easier to manually inline this function.
-TEXT ·emitCopy(SB), NOSPLIT, $0-48
- MOVQ dst_base+0(FP), DI
- MOVQ DI, SI
- MOVQ offset+24(FP), R11
- MOVQ length+32(FP), AX
-
-loop0:
- // for length >= 68 { etc }
- CMPL AX, $68
- JLT step1
-
- // Emit a length 64 copy, encoded as 3 bytes.
- MOVB $0xfe, 0(DI)
- MOVW R11, 1(DI)
- ADDQ $3, DI
- SUBL $64, AX
- JMP loop0
-
-step1:
- // if length > 64 { etc }
- CMPL AX, $64
- JLE step2
-
- // Emit a length 60 copy, encoded as 3 bytes.
- MOVB $0xee, 0(DI)
- MOVW R11, 1(DI)
- ADDQ $3, DI
- SUBL $60, AX
-
-step2:
- // if length >= 12 || offset >= 2048 { goto step3 }
- CMPL AX, $12
- JGE step3
- CMPL R11, $2048
- JGE step3
-
- // Emit the remaining copy, encoded as 2 bytes.
- MOVB R11, 1(DI)
- SHRL $8, R11
- SHLB $5, R11
- SUBB $4, AX
- SHLB $2, AX
- ORB AX, R11
- ORB $1, R11
- MOVB R11, 0(DI)
- ADDQ $2, DI
-
- // Return the number of bytes written.
- SUBQ SI, DI
- MOVQ DI, ret+40(FP)
- RET
-
-step3:
- // Emit the remaining copy, encoded as 3 bytes.
- SUBL $1, AX
- SHLB $2, AX
- ORB $2, AX
- MOVB AX, 0(DI)
- MOVW R11, 1(DI)
- ADDQ $3, DI
-
- // Return the number of bytes written.
- SUBQ SI, DI
- MOVQ DI, ret+40(FP)
- RET
-
-// ----------------------------------------------------------------------------
-
-// func extendMatch(src []byte, i, j int) int
-//
-// All local variables fit into registers. The register allocation:
-// - DX &src[0]
-// - SI &src[j]
-// - R13 &src[len(src) - 8]
-// - R14 &src[len(src)]
-// - R15 &src[i]
-//
-// The unusual register allocation of local variables, such as R15 for a source
-// pointer, matches the allocation used at the call site in encodeBlock, which
-// makes it easier to manually inline this function.
-TEXT ·extendMatch(SB), NOSPLIT, $0-48
- MOVQ src_base+0(FP), DX
- MOVQ src_len+8(FP), R14
- MOVQ i+24(FP), R15
- MOVQ j+32(FP), SI
- ADDQ DX, R14
- ADDQ DX, R15
- ADDQ DX, SI
- MOVQ R14, R13
- SUBQ $8, R13
-
-cmp8:
- // As long as we are 8 or more bytes before the end of src, we can load and
- // compare 8 bytes at a time. If those 8 bytes are equal, repeat.
- CMPQ SI, R13
- JA cmp1
- MOVQ (R15), AX
- MOVQ (SI), BX
- CMPQ AX, BX
- JNE bsf
- ADDQ $8, R15
- ADDQ $8, SI
- JMP cmp8
-
-bsf:
- // If those 8 bytes were not equal, XOR the two 8 byte values, and return
- // the index of the first byte that differs. The BSF instruction finds the
- // least significant 1 bit, the amd64 architecture is little-endian, and
- // the shift by 3 converts a bit index to a byte index.
- XORQ AX, BX
- BSFQ BX, BX
- SHRQ $3, BX
- ADDQ BX, SI
-
- // Convert from &src[ret] to ret.
- SUBQ DX, SI
- MOVQ SI, ret+40(FP)
- RET
-
-cmp1:
- // In src's tail, compare 1 byte at a time.
- CMPQ SI, R14
- JAE extendMatchEnd
- MOVB (R15), AX
- MOVB (SI), BX
- CMPB AX, BX
- JNE extendMatchEnd
- ADDQ $1, R15
- ADDQ $1, SI
- JMP cmp1
-
-extendMatchEnd:
- // Convert from &src[ret] to ret.
- SUBQ DX, SI
- MOVQ SI, ret+40(FP)
- RET
-
-// ----------------------------------------------------------------------------
-
-// func encodeBlock(dst, src []byte) (d int)
-//
-// All local variables fit into registers, other than "var table". The register
-// allocation:
-// - AX . .
-// - BX . .
-// - CX 56 shift (note that amd64 shifts by non-immediates must use CX).
-// - DX 64 &src[0], tableSize
-// - SI 72 &src[s]
-// - DI 80 &dst[d]
-// - R9 88 sLimit
-// - R10 . &src[nextEmit]
-// - R11 96 prevHash, currHash, nextHash, offset
-// - R12 104 &src[base], skip
-// - R13 . &src[nextS], &src[len(src) - 8]
-// - R14 . len(src), bytesBetweenHashLookups, &src[len(src)], x
-// - R15 112 candidate
-//
-// The second column (56, 64, etc) is the stack offset to spill the registers
-// when calling other functions. We could pack this slightly tighter, but it's
-// simpler to have a dedicated spill map independent of the function called.
-//
-// "var table [maxTableSize]uint16" takes up 32768 bytes of stack space. An
-// extra 56 bytes, to call other functions, and an extra 64 bytes, to spill
-// local variables (registers) during calls gives 32768 + 56 + 64 = 32888.
-TEXT ·encodeBlock(SB), 0, $32888-56
- MOVQ dst_base+0(FP), DI
- MOVQ src_base+24(FP), SI
- MOVQ src_len+32(FP), R14
-
- // shift, tableSize := uint32(32-8), 1<<8
- MOVQ $24, CX
- MOVQ $256, DX
-
-calcShift:
- // for ; tableSize < maxTableSize && tableSize < len(src); tableSize *= 2 {
- // shift--
- // }
- CMPQ DX, $16384
- JGE varTable
- CMPQ DX, R14
- JGE varTable
- SUBQ $1, CX
- SHLQ $1, DX
- JMP calcShift
-
-varTable:
- // var table [maxTableSize]uint16
- //
- // In the asm code, unlike the Go code, we can zero-initialize only the
- // first tableSize elements. Each uint16 element is 2 bytes and each MOVOU
- // writes 16 bytes, so we can do only tableSize/8 writes instead of the
- // 2048 writes that would zero-initialize all of table's 32768 bytes.
- SHRQ $3, DX
- LEAQ table-32768(SP), BX
- PXOR X0, X0
-
-memclr:
- MOVOU X0, 0(BX)
- ADDQ $16, BX
- SUBQ $1, DX
- JNZ memclr
-
- // !!! DX = &src[0]
- MOVQ SI, DX
-
- // sLimit := len(src) - inputMargin
- MOVQ R14, R9
- SUBQ $15, R9
-
- // !!! Pre-emptively spill CX, DX and R9 to the stack. Their values don't
- // change for the rest of the function.
- MOVQ CX, 56(SP)
- MOVQ DX, 64(SP)
- MOVQ R9, 88(SP)
-
- // nextEmit := 0
- MOVQ DX, R10
-
- // s := 1
- ADDQ $1, SI
-
- // nextHash := hash(load32(src, s), shift)
- MOVL 0(SI), R11
- IMULL $0x1e35a7bd, R11
- SHRL CX, R11
-
-outer:
- // for { etc }
-
- // skip := 32
- MOVQ $32, R12
-
- // nextS := s
- MOVQ SI, R13
-
- // candidate := 0
- MOVQ $0, R15
-
-inner0:
- // for { etc }
-
- // s := nextS
- MOVQ R13, SI
-
- // bytesBetweenHashLookups := skip >> 5
- MOVQ R12, R14
- SHRQ $5, R14
-
- // nextS = s + bytesBetweenHashLookups
- ADDQ R14, R13
-
- // skip += bytesBetweenHashLookups
- ADDQ R14, R12
-
- // if nextS > sLimit { goto emitRemainder }
- MOVQ R13, AX
- SUBQ DX, AX
- CMPQ AX, R9
- JA emitRemainder
-
- // candidate = int(table[nextHash])
- // XXX: MOVWQZX table-32768(SP)(R11*2), R15
- // XXX: 4e 0f b7 7c 5c 78 movzwq 0x78(%rsp,%r11,2),%r15
- BYTE $0x4e
- BYTE $0x0f
- BYTE $0xb7
- BYTE $0x7c
- BYTE $0x5c
- BYTE $0x78
-
- // table[nextHash] = uint16(s)
- MOVQ SI, AX
- SUBQ DX, AX
-
- // XXX: MOVW AX, table-32768(SP)(R11*2)
- // XXX: 66 42 89 44 5c 78 mov %ax,0x78(%rsp,%r11,2)
- BYTE $0x66
- BYTE $0x42
- BYTE $0x89
- BYTE $0x44
- BYTE $0x5c
- BYTE $0x78
-
- // nextHash = hash(load32(src, nextS), shift)
- MOVL 0(R13), R11
- IMULL $0x1e35a7bd, R11
- SHRL CX, R11
-
- // if load32(src, s) != load32(src, candidate) { continue } break
- MOVL 0(SI), AX
- MOVL (DX)(R15*1), BX
- CMPL AX, BX
- JNE inner0
-
-fourByteMatch:
- // As per the encode_other.go code:
- //
- // A 4-byte match has been found. We'll later see etc.
-
- // !!! Jump to a fast path for short (<= 16 byte) literals. See the comment
- // on inputMargin in encode.go.
- MOVQ SI, AX
- SUBQ R10, AX
- CMPQ AX, $16
- JLE emitLiteralFastPath
-
- // ----------------------------------------
- // Begin inline of the emitLiteral call.
- //
- // d += emitLiteral(dst[d:], src[nextEmit:s])
-
- MOVL AX, BX
- SUBL $1, BX
-
- CMPL BX, $60
- JLT inlineEmitLiteralOneByte
- CMPL BX, $256
- JLT inlineEmitLiteralTwoBytes
-
-inlineEmitLiteralThreeBytes:
- MOVB $0xf4, 0(DI)
- MOVW BX, 1(DI)
- ADDQ $3, DI
- JMP inlineEmitLiteralMemmove
-
-inlineEmitLiteralTwoBytes:
- MOVB $0xf0, 0(DI)
- MOVB BX, 1(DI)
- ADDQ $2, DI
- JMP inlineEmitLiteralMemmove
-
-inlineEmitLiteralOneByte:
- SHLB $2, BX
- MOVB BX, 0(DI)
- ADDQ $1, DI
-
-inlineEmitLiteralMemmove:
- // Spill local variables (registers) onto the stack; call; unspill.
- //
- // copy(dst[i:], lit)
- //
- // This means calling runtime·memmove(&dst[i], &lit[0], len(lit)), so we push
- // DI, R10 and AX as arguments.
- MOVQ DI, 0(SP)
- MOVQ R10, 8(SP)
- MOVQ AX, 16(SP)
- ADDQ AX, DI // Finish the "d +=" part of "d += emitLiteral(etc)".
- MOVQ SI, 72(SP)
- MOVQ DI, 80(SP)
- MOVQ R15, 112(SP)
- CALL runtime·memmove(SB)
- MOVQ 56(SP), CX
- MOVQ 64(SP), DX
- MOVQ 72(SP), SI
- MOVQ 80(SP), DI
- MOVQ 88(SP), R9
- MOVQ 112(SP), R15
- JMP inner1
-
-inlineEmitLiteralEnd:
- // End inline of the emitLiteral call.
- // ----------------------------------------
-
-emitLiteralFastPath:
- // !!! Emit the 1-byte encoding "uint8(len(lit)-1)<<2".
- MOVB AX, BX
- SUBB $1, BX
- SHLB $2, BX
- MOVB BX, (DI)
- ADDQ $1, DI
-
- // !!! Implement the copy from lit to dst as a 16-byte load and store.
- // (Encode's documentation says that dst and src must not overlap.)
- //
- // This always copies 16 bytes, instead of only len(lit) bytes, but that's
- // OK. Subsequent iterations will fix up the overrun.
- //
- // Note that on amd64, it is legal and cheap to issue unaligned 8-byte or
- // 16-byte loads and stores. This technique probably wouldn't be as
- // effective on architectures that are fussier about alignment.
- MOVOU 0(R10), X0
- MOVOU X0, 0(DI)
- ADDQ AX, DI
-
-inner1:
- // for { etc }
-
- // base := s
- MOVQ SI, R12
-
- // !!! offset := base - candidate
- MOVQ R12, R11
- SUBQ R15, R11
- SUBQ DX, R11
-
- // ----------------------------------------
- // Begin inline of the extendMatch call.
- //
- // s = extendMatch(src, candidate+4, s+4)
-
- // !!! R14 = &src[len(src)]
- MOVQ src_len+32(FP), R14
- ADDQ DX, R14
-
- // !!! R13 = &src[len(src) - 8]
- MOVQ R14, R13
- SUBQ $8, R13
-
- // !!! R15 = &src[candidate + 4]
- ADDQ $4, R15
- ADDQ DX, R15
-
- // !!! s += 4
- ADDQ $4, SI
-
-inlineExtendMatchCmp8:
- // As long as we are 8 or more bytes before the end of src, we can load and
- // compare 8 bytes at a time. If those 8 bytes are equal, repeat.
- CMPQ SI, R13
- JA inlineExtendMatchCmp1
- MOVQ (R15), AX
- MOVQ (SI), BX
- CMPQ AX, BX
- JNE inlineExtendMatchBSF
- ADDQ $8, R15
- ADDQ $8, SI
- JMP inlineExtendMatchCmp8
-
-inlineExtendMatchBSF:
- // If those 8 bytes were not equal, XOR the two 8 byte values, and return
- // the index of the first byte that differs. The BSF instruction finds the
- // least significant 1 bit, the amd64 architecture is little-endian, and
- // the shift by 3 converts a bit index to a byte index.
- XORQ AX, BX
- BSFQ BX, BX
- SHRQ $3, BX
- ADDQ BX, SI
- JMP inlineExtendMatchEnd
-
-inlineExtendMatchCmp1:
- // In src's tail, compare 1 byte at a time.
- CMPQ SI, R14
- JAE inlineExtendMatchEnd
- MOVB (R15), AX
- MOVB (SI), BX
- CMPB AX, BX
- JNE inlineExtendMatchEnd
- ADDQ $1, R15
- ADDQ $1, SI
- JMP inlineExtendMatchCmp1
-
-inlineExtendMatchEnd:
- // End inline of the extendMatch call.
- // ----------------------------------------
-
- // ----------------------------------------
- // Begin inline of the emitCopy call.
- //
- // d += emitCopy(dst[d:], base-candidate, s-base)
-
- // !!! length := s - base
- MOVQ SI, AX
- SUBQ R12, AX
-
-inlineEmitCopyLoop0:
- // for length >= 68 { etc }
- CMPL AX, $68
- JLT inlineEmitCopyStep1
-
- // Emit a length 64 copy, encoded as 3 bytes.
- MOVB $0xfe, 0(DI)
- MOVW R11, 1(DI)
- ADDQ $3, DI
- SUBL $64, AX
- JMP inlineEmitCopyLoop0
-
-inlineEmitCopyStep1:
- // if length > 64 { etc }
- CMPL AX, $64
- JLE inlineEmitCopyStep2
-
- // Emit a length 60 copy, encoded as 3 bytes.
- MOVB $0xee, 0(DI)
- MOVW R11, 1(DI)
- ADDQ $3, DI
- SUBL $60, AX
-
-inlineEmitCopyStep2:
- // if length >= 12 || offset >= 2048 { goto inlineEmitCopyStep3 }
- CMPL AX, $12
- JGE inlineEmitCopyStep3
- CMPL R11, $2048
- JGE inlineEmitCopyStep3
-
- // Emit the remaining copy, encoded as 2 bytes.
- MOVB R11, 1(DI)
- SHRL $8, R11
- SHLB $5, R11
- SUBB $4, AX
- SHLB $2, AX
- ORB AX, R11
- ORB $1, R11
- MOVB R11, 0(DI)
- ADDQ $2, DI
- JMP inlineEmitCopyEnd
-
-inlineEmitCopyStep3:
- // Emit the remaining copy, encoded as 3 bytes.
- SUBL $1, AX
- SHLB $2, AX
- ORB $2, AX
- MOVB AX, 0(DI)
- MOVW R11, 1(DI)
- ADDQ $3, DI
-
-inlineEmitCopyEnd:
- // End inline of the emitCopy call.
- // ----------------------------------------
-
- // nextEmit = s
- MOVQ SI, R10
-
- // if s >= sLimit { goto emitRemainder }
- MOVQ SI, AX
- SUBQ DX, AX
- CMPQ AX, R9
- JAE emitRemainder
-
- // As per the encode_other.go code:
- //
- // We could immediately etc.
-
- // x := load64(src, s-1)
- MOVQ -1(SI), R14
-
- // prevHash := hash(uint32(x>>0), shift)
- MOVL R14, R11
- IMULL $0x1e35a7bd, R11
- SHRL CX, R11
-
- // table[prevHash] = uint16(s-1)
- MOVQ SI, AX
- SUBQ DX, AX
- SUBQ $1, AX
-
- // XXX: MOVW AX, table-32768(SP)(R11*2)
- // XXX: 66 42 89 44 5c 78 mov %ax,0x78(%rsp,%r11,2)
- BYTE $0x66
- BYTE $0x42
- BYTE $0x89
- BYTE $0x44
- BYTE $0x5c
- BYTE $0x78
-
- // currHash := hash(uint32(x>>8), shift)
- SHRQ $8, R14
- MOVL R14, R11
- IMULL $0x1e35a7bd, R11
- SHRL CX, R11
-
- // candidate = int(table[currHash])
- // XXX: MOVWQZX table-32768(SP)(R11*2), R15
- // XXX: 4e 0f b7 7c 5c 78 movzwq 0x78(%rsp,%r11,2),%r15
- BYTE $0x4e
- BYTE $0x0f
- BYTE $0xb7
- BYTE $0x7c
- BYTE $0x5c
- BYTE $0x78
-
- // table[currHash] = uint16(s)
- ADDQ $1, AX
-
- // XXX: MOVW AX, table-32768(SP)(R11*2)
- // XXX: 66 42 89 44 5c 78 mov %ax,0x78(%rsp,%r11,2)
- BYTE $0x66
- BYTE $0x42
- BYTE $0x89
- BYTE $0x44
- BYTE $0x5c
- BYTE $0x78
-
- // if uint32(x>>8) == load32(src, candidate) { continue }
- MOVL (DX)(R15*1), BX
- CMPL R14, BX
- JEQ inner1
-
- // nextHash = hash(uint32(x>>16), shift)
- SHRQ $8, R14
- MOVL R14, R11
- IMULL $0x1e35a7bd, R11
- SHRL CX, R11
-
- // s++
- ADDQ $1, SI
-
- // break out of the inner1 for loop, i.e. continue the outer loop.
- JMP outer
-
-emitRemainder:
- // if nextEmit < len(src) { etc }
- MOVQ src_len+32(FP), AX
- ADDQ DX, AX
- CMPQ R10, AX
- JEQ encodeBlockEnd
-
- // d += emitLiteral(dst[d:], src[nextEmit:])
- //
- // Push args.
- MOVQ DI, 0(SP)
- MOVQ $0, 8(SP) // Unnecessary, as the callee ignores it, but conservative.
- MOVQ $0, 16(SP) // Unnecessary, as the callee ignores it, but conservative.
- MOVQ R10, 24(SP)
- SUBQ R10, AX
- MOVQ AX, 32(SP)
- MOVQ AX, 40(SP) // Unnecessary, as the callee ignores it, but conservative.
-
- // Spill local variables (registers) onto the stack; call; unspill.
- MOVQ DI, 80(SP)
- CALL ·emitLiteral(SB)
- MOVQ 80(SP), DI
-
- // Finish the "d +=" part of "d += emitLiteral(etc)".
- ADDQ 48(SP), DI
-
-encodeBlockEnd:
- MOVQ dst_base+0(FP), AX
- SUBQ AX, DI
- MOVQ DI, d+48(FP)
- RET
diff --git a/vendor/github.com/golang/snappy/encode_other.go b/vendor/github.com/golang/snappy/encode_other.go
deleted file mode 100644
index dbcae905e6..0000000000
--- a/vendor/github.com/golang/snappy/encode_other.go
+++ /dev/null
@@ -1,238 +0,0 @@
-// Copyright 2016 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.
-
-// +build !amd64 appengine !gc noasm
-
-package snappy
-
-func load32(b []byte, i int) uint32 {
- b = b[i : i+4 : len(b)] // Help the compiler eliminate bounds checks on the next line.
- return uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24
-}
-
-func load64(b []byte, i int) uint64 {
- b = b[i : i+8 : len(b)] // Help the compiler eliminate bounds checks on the next line.
- return uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 |
- uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56
-}
-
-// emitLiteral writes a literal chunk and returns the number of bytes written.
-//
-// It assumes that:
-// dst is long enough to hold the encoded bytes
-// 1 <= len(lit) && len(lit) <= 65536
-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
- default:
- dst[0] = 61<<2 | tagLiteral
- dst[1] = uint8(n)
- dst[2] = uint8(n >> 8)
- i = 3
- }
- return i + copy(dst[i:], lit)
-}
-
-// emitCopy writes a copy chunk and returns the number of bytes written.
-//
-// It assumes that:
-// dst is long enough to hold the encoded bytes
-// 1 <= offset && offset <= 65535
-// 4 <= length && length <= 65535
-func emitCopy(dst []byte, offset, length int) int {
- i := 0
- // The maximum length for a single tagCopy1 or tagCopy2 op is 64 bytes. The
- // threshold for this loop is a little higher (at 68 = 64 + 4), and the
- // length emitted down below is is a little lower (at 60 = 64 - 4), because
- // it's shorter to encode a length 67 copy as a length 60 tagCopy2 followed
- // by a length 7 tagCopy1 (which encodes as 3+2 bytes) than to encode it as
- // a length 64 tagCopy2 followed by a length 3 tagCopy2 (which encodes as
- // 3+3 bytes). The magic 4 in the 64±4 is because the minimum length for a
- // tagCopy1 op is 4 bytes, which is why a length 3 copy has to be an
- // encodes-as-3-bytes tagCopy2 instead of an encodes-as-2-bytes tagCopy1.
- for length >= 68 {
- // Emit a length 64 copy, encoded as 3 bytes.
- dst[i+0] = 63<<2 | tagCopy2
- dst[i+1] = uint8(offset)
- dst[i+2] = uint8(offset >> 8)
- i += 3
- length -= 64
- }
- if length > 64 {
- // Emit a length 60 copy, encoded as 3 bytes.
- dst[i+0] = 59<<2 | tagCopy2
- dst[i+1] = uint8(offset)
- dst[i+2] = uint8(offset >> 8)
- i += 3
- length -= 60
- }
- if length >= 12 || offset >= 2048 {
- // Emit the remaining copy, encoded as 3 bytes.
- dst[i+0] = uint8(length-1)<<2 | tagCopy2
- dst[i+1] = uint8(offset)
- dst[i+2] = uint8(offset >> 8)
- return i + 3
- }
- // Emit the remaining copy, encoded as 2 bytes.
- dst[i+0] = uint8(offset>>8)<<5 | uint8(length-4)<<2 | tagCopy1
- dst[i+1] = uint8(offset)
- return i + 2
-}
-
-// extendMatch returns the largest k such that k <= len(src) and that
-// src[i:i+k-j] and src[j:k] have the same contents.
-//
-// It assumes that:
-// 0 <= i && i < j && j <= len(src)
-func extendMatch(src []byte, i, j int) int {
- for ; j < len(src) && src[i] == src[j]; i, j = i+1, j+1 {
- }
- return j
-}
-
-func hash(u, shift uint32) uint32 {
- return (u * 0x1e35a7bd) >> shift
-}
-
-// encodeBlock encodes a non-empty src to a guaranteed-large-enough dst. It
-// assumes that the varint-encoded length of the decompressed bytes has already
-// been written.
-//
-// It also assumes that:
-// len(dst) >= MaxEncodedLen(len(src)) &&
-// minNonLiteralBlockSize <= len(src) && len(src) <= maxBlockSize
-func encodeBlock(dst, src []byte) (d int) {
- // Initialize the hash table. Its size ranges from 1<<8 to 1<<14 inclusive.
- // The table element type is uint16, as s < sLimit and sLimit < len(src)
- // and len(src) <= maxBlockSize and maxBlockSize == 65536.
- const (
- maxTableSize = 1 << 14
- // tableMask is redundant, but helps the compiler eliminate bounds
- // checks.
- tableMask = maxTableSize - 1
- )
- shift := uint32(32 - 8)
- for tableSize := 1 << 8; tableSize < maxTableSize && tableSize < len(src); tableSize *= 2 {
- shift--
- }
- // In Go, all array elements are zero-initialized, so there is no advantage
- // to a smaller tableSize per se. However, it matches the C++ algorithm,
- // and in the asm versions of this code, we can get away with zeroing only
- // the first tableSize elements.
- var table [maxTableSize]uint16
-
- // sLimit is when to stop looking for offset/length copies. The inputMargin
- // lets us use a fast path for emitLiteral in the main loop, while we are
- // looking for copies.
- sLimit := len(src) - inputMargin
-
- // nextEmit is where in src the next emitLiteral should start from.
- nextEmit := 0
-
- // The encoded form must start with a literal, as there are no previous
- // bytes to copy, so we start looking for hash matches at s == 1.
- s := 1
- nextHash := hash(load32(src, s), shift)
-
- for {
- // Copied from the C++ snappy implementation:
- //
- // Heuristic match skipping: If 32 bytes are scanned with no matches
- // found, start looking only at every other byte. If 32 more bytes are
- // scanned (or skipped), look at every third byte, etc.. When a match
- // is found, immediately go back to looking at every byte. This is a
- // small loss (~5% performance, ~0.1% density) for compressible data
- // due to more bookkeeping, but for non-compressible data (such as
- // JPEG) it's a huge win since the compressor quickly "realizes" the
- // data is incompressible and doesn't bother looking for matches
- // everywhere.
- //
- // The "skip" variable keeps track of how many bytes there are since
- // the last match; dividing it by 32 (ie. right-shifting by five) gives
- // the number of bytes to move ahead for each iteration.
- skip := 32
-
- nextS := s
- candidate := 0
- for {
- s = nextS
- bytesBetweenHashLookups := skip >> 5
- nextS = s + bytesBetweenHashLookups
- skip += bytesBetweenHashLookups
- if nextS > sLimit {
- goto emitRemainder
- }
- candidate = int(table[nextHash&tableMask])
- table[nextHash&tableMask] = uint16(s)
- nextHash = hash(load32(src, nextS), shift)
- if load32(src, s) == load32(src, candidate) {
- break
- }
- }
-
- // A 4-byte match has been found. We'll later see if more than 4 bytes
- // match. But, prior to the match, src[nextEmit:s] are unmatched. Emit
- // them as literal bytes.
- d += emitLiteral(dst[d:], src[nextEmit:s])
-
- // Call emitCopy, and then see if another emitCopy could be our next
- // move. Repeat until we find no match for the input immediately after
- // what was consumed by the last emitCopy call.
- //
- // If we exit this loop normally then we need to call emitLiteral next,
- // though we don't yet know how big the literal will be. We handle that
- // by proceeding to the next iteration of the main loop. We also can
- // exit this loop via goto if we get close to exhausting the input.
- for {
- // Invariant: we have a 4-byte match at s, and no need to emit any
- // literal bytes prior to s.
- base := s
-
- // Extend the 4-byte match as long as possible.
- //
- // This is an inlined version of:
- // s = extendMatch(src, candidate+4, s+4)
- s += 4
- for i := candidate + 4; s < len(src) && src[i] == src[s]; i, s = i+1, s+1 {
- }
-
- d += emitCopy(dst[d:], base-candidate, s-base)
- nextEmit = s
- if s >= sLimit {
- goto emitRemainder
- }
-
- // We could immediately start working at s now, but to improve
- // compression we first update the hash table at s-1 and at s. If
- // another emitCopy is not our next move, also calculate nextHash
- // at s+1. At least on GOARCH=amd64, these three hash calculations
- // are faster as one load64 call (with some shifts) instead of
- // three load32 calls.
- x := load64(src, s-1)
- prevHash := hash(uint32(x>>0), shift)
- table[prevHash&tableMask] = uint16(s - 1)
- currHash := hash(uint32(x>>8), shift)
- candidate = int(table[currHash&tableMask])
- table[currHash&tableMask] = uint16(s)
- if uint32(x>>8) != load32(src, candidate) {
- nextHash = hash(uint32(x>>16), shift)
- s++
- break
- }
- }
- }
-
-emitRemainder:
- if nextEmit < len(src) {
- d += emitLiteral(dst[d:], src[nextEmit:])
- }
- return d
-}
diff --git a/vendor/github.com/golang/snappy/snappy.go b/vendor/github.com/golang/snappy/snappy.go
deleted file mode 100644
index 0cf5e379c4..0000000000
--- a/vendor/github.com/golang/snappy/snappy.go
+++ /dev/null
@@ -1,87 +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 "github.com/golang/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 issued by most
- encoders. Nonetheless, the offset ranges in [0, 1<<32) and the length in
- [1, 65). The length is 1 + m. The offset is the little-endian unsigned
- integer denoted by the next 4 bytes.
-*/
-const (
- tagLiteral = 0x00
- tagCopy1 = 0x01
- tagCopy2 = 0x02
- tagCopy4 = 0x03
-)
-
-const (
- checksumSize = 4
- chunkHeaderSize = 4
- magicChunk = "\xff\x06\x00\x00" + magicBody
- magicBody = "sNaPpY"
-
- // maxBlockSize is the maximum size of the input to encodeBlock. It is not
- // part of the wire format per se, but some parts of the encoder assume
- // that an offset fits into a uint16.
- //
- // Also, for the framing format (Writer type instead of Encode function),
- // 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".
- maxBlockSize = 65536
-
- // maxEncodedLenOfMaxBlockSize equals MaxEncodedLen(maxBlockSize), but is
- // hard coded to be a const instead of a variable, so that obufLen can also
- // be a const. Their equivalence is confirmed by
- // TestMaxEncodedLenOfMaxBlockSize.
- maxEncodedLenOfMaxBlockSize = 76490
-
- obufHeaderLen = len(magicChunk) + checksumSize + chunkHeaderSize
- obufLen = obufHeaderLen + maxEncodedLenOfMaxBlockSize
-)
-
-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/vendor/github.com/gorilla/websocket/AUTHORS b/vendor/github.com/gorilla/websocket/AUTHORS
deleted file mode 100644
index 1931f40068..0000000000
--- a/vendor/github.com/gorilla/websocket/AUTHORS
+++ /dev/null
@@ -1,9 +0,0 @@
-# This is the official list of Gorilla WebSocket authors for copyright
-# purposes.
-#
-# Please keep the list sorted.
-
-Gary Burd
-Google LLC (https://opensource.google.com/)
-Joachim Bauch
-
diff --git a/vendor/github.com/gorilla/websocket/LICENSE b/vendor/github.com/gorilla/websocket/LICENSE
deleted file mode 100644
index 9171c97225..0000000000
--- a/vendor/github.com/gorilla/websocket/LICENSE
+++ /dev/null
@@ -1,22 +0,0 @@
-Copyright (c) 2013 The Gorilla WebSocket 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.
-
-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.
diff --git a/vendor/github.com/gorilla/websocket/README.md b/vendor/github.com/gorilla/websocket/README.md
deleted file mode 100644
index 0827d059c1..0000000000
--- a/vendor/github.com/gorilla/websocket/README.md
+++ /dev/null
@@ -1,64 +0,0 @@
-# Gorilla WebSocket
-
-[![GoDoc](https://godoc.org/github.com/gorilla/websocket?status.svg)](https://godoc.org/github.com/gorilla/websocket)
-[![CircleCI](https://circleci.com/gh/gorilla/websocket.svg?style=svg)](https://circleci.com/gh/gorilla/websocket)
-
-Gorilla WebSocket is a [Go](http://golang.org/) implementation of the
-[WebSocket](http://www.rfc-editor.org/rfc/rfc6455.txt) protocol.
-
-### Documentation
-
-* [API Reference](http://godoc.org/github.com/gorilla/websocket)
-* [Chat example](https://github.com/gorilla/websocket/tree/master/examples/chat)
-* [Command example](https://github.com/gorilla/websocket/tree/master/examples/command)
-* [Client and server example](https://github.com/gorilla/websocket/tree/master/examples/echo)
-* [File watch example](https://github.com/gorilla/websocket/tree/master/examples/filewatch)
-
-### Status
-
-The Gorilla WebSocket package provides a complete and tested implementation of
-the [WebSocket](http://www.rfc-editor.org/rfc/rfc6455.txt) protocol. The
-package API is stable.
-
-### Installation
-
- go get github.com/gorilla/websocket
-
-### Protocol Compliance
-
-The Gorilla WebSocket package passes the server tests in the [Autobahn Test
-Suite](https://github.com/crossbario/autobahn-testsuite) using the application in the [examples/autobahn
-subdirectory](https://github.com/gorilla/websocket/tree/master/examples/autobahn).
-
-### Gorilla WebSocket compared with other packages
-
-
-
-Notes:
-
-1. Large messages are fragmented in [Chrome's new WebSocket implementation](http://www.ietf.org/mail-archive/web/hybi/current/msg10503.html).
-2. The application can get the type of a received data message by implementing
- a [Codec marshal](http://godoc.org/golang.org/x/net/websocket#Codec.Marshal)
- function.
-3. The go.net io.Reader and io.Writer operate across WebSocket frame boundaries.
- Read returns when the input buffer is full or a frame boundary is
- encountered. Each call to Write sends a single frame message. The Gorilla
- io.Reader and io.WriteCloser operate on a single WebSocket message.
-
diff --git a/vendor/github.com/gorilla/websocket/client.go b/vendor/github.com/gorilla/websocket/client.go
deleted file mode 100644
index 962c06a391..0000000000
--- a/vendor/github.com/gorilla/websocket/client.go
+++ /dev/null
@@ -1,395 +0,0 @@
-// Copyright 2013 The Gorilla WebSocket 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 websocket
-
-import (
- "bytes"
- "context"
- "crypto/tls"
- "errors"
- "io"
- "io/ioutil"
- "net"
- "net/http"
- "net/http/httptrace"
- "net/url"
- "strings"
- "time"
-)
-
-// ErrBadHandshake is returned when the server response to opening handshake is
-// invalid.
-var ErrBadHandshake = errors.New("websocket: bad handshake")
-
-var errInvalidCompression = errors.New("websocket: invalid compression negotiation")
-
-// NewClient creates a new client connection using the given net connection.
-// The URL u specifies the host and request URI. Use requestHeader to specify
-// the origin (Origin), subprotocols (Sec-WebSocket-Protocol) and cookies
-// (Cookie). Use the response.Header to get the selected subprotocol
-// (Sec-WebSocket-Protocol) and cookies (Set-Cookie).
-//
-// If the WebSocket handshake fails, ErrBadHandshake is returned along with a
-// non-nil *http.Response so that callers can handle redirects, authentication,
-// etc.
-//
-// Deprecated: Use Dialer instead.
-func NewClient(netConn net.Conn, u *url.URL, requestHeader http.Header, readBufSize, writeBufSize int) (c *Conn, response *http.Response, err error) {
- d := Dialer{
- ReadBufferSize: readBufSize,
- WriteBufferSize: writeBufSize,
- NetDial: func(net, addr string) (net.Conn, error) {
- return netConn, nil
- },
- }
- return d.Dial(u.String(), requestHeader)
-}
-
-// A Dialer contains options for connecting to WebSocket server.
-type Dialer struct {
- // NetDial specifies the dial function for creating TCP connections. If
- // NetDial is nil, net.Dial is used.
- NetDial func(network, addr string) (net.Conn, error)
-
- // NetDialContext specifies the dial function for creating TCP connections. If
- // NetDialContext is nil, net.DialContext is used.
- NetDialContext func(ctx context.Context, network, addr string) (net.Conn, error)
-
- // Proxy specifies a function to return a proxy for a given
- // Request. If the function returns a non-nil error, the
- // request is aborted with the provided error.
- // If Proxy is nil or returns a nil *URL, no proxy is used.
- Proxy func(*http.Request) (*url.URL, error)
-
- // TLSClientConfig specifies the TLS configuration to use with tls.Client.
- // If nil, the default configuration is used.
- TLSClientConfig *tls.Config
-
- // HandshakeTimeout specifies the duration for the handshake to complete.
- HandshakeTimeout time.Duration
-
- // ReadBufferSize and WriteBufferSize specify I/O buffer sizes in bytes. If a buffer
- // size is zero, then a useful default size is used. The I/O buffer sizes
- // do not limit the size of the messages that can be sent or received.
- ReadBufferSize, WriteBufferSize int
-
- // WriteBufferPool is a pool of buffers for write operations. If the value
- // is not set, then write buffers are allocated to the connection for the
- // lifetime of the connection.
- //
- // A pool is most useful when the application has a modest volume of writes
- // across a large number of connections.
- //
- // Applications should use a single pool for each unique value of
- // WriteBufferSize.
- WriteBufferPool BufferPool
-
- // Subprotocols specifies the client's requested subprotocols.
- Subprotocols []string
-
- // EnableCompression specifies if the client should attempt to negotiate
- // per message compression (RFC 7692). Setting this value to true does not
- // guarantee that compression will be supported. Currently only "no context
- // takeover" modes are supported.
- EnableCompression bool
-
- // Jar specifies the cookie jar.
- // If Jar is nil, cookies are not sent in requests and ignored
- // in responses.
- Jar http.CookieJar
-}
-
-// Dial creates a new client connection by calling DialContext with a background context.
-func (d *Dialer) Dial(urlStr string, requestHeader http.Header) (*Conn, *http.Response, error) {
- return d.DialContext(context.Background(), urlStr, requestHeader)
-}
-
-var errMalformedURL = errors.New("malformed ws or wss URL")
-
-func hostPortNoPort(u *url.URL) (hostPort, hostNoPort string) {
- hostPort = u.Host
- hostNoPort = u.Host
- if i := strings.LastIndex(u.Host, ":"); i > strings.LastIndex(u.Host, "]") {
- hostNoPort = hostNoPort[:i]
- } else {
- switch u.Scheme {
- case "wss":
- hostPort += ":443"
- case "https":
- hostPort += ":443"
- default:
- hostPort += ":80"
- }
- }
- return hostPort, hostNoPort
-}
-
-// DefaultDialer is a dialer with all fields set to the default values.
-var DefaultDialer = &Dialer{
- Proxy: http.ProxyFromEnvironment,
- HandshakeTimeout: 45 * time.Second,
-}
-
-// nilDialer is dialer to use when receiver is nil.
-var nilDialer = *DefaultDialer
-
-// DialContext creates a new client connection. Use requestHeader to specify the
-// origin (Origin), subprotocols (Sec-WebSocket-Protocol) and cookies (Cookie).
-// Use the response.Header to get the selected subprotocol
-// (Sec-WebSocket-Protocol) and cookies (Set-Cookie).
-//
-// The context will be used in the request and in the Dialer.
-//
-// If the WebSocket handshake fails, ErrBadHandshake is returned along with a
-// non-nil *http.Response so that callers can handle redirects, authentication,
-// etcetera. The response body may not contain the entire response and does not
-// need to be closed by the application.
-func (d *Dialer) DialContext(ctx context.Context, urlStr string, requestHeader http.Header) (*Conn, *http.Response, error) {
- if d == nil {
- d = &nilDialer
- }
-
- challengeKey, err := generateChallengeKey()
- if err != nil {
- return nil, nil, err
- }
-
- u, err := url.Parse(urlStr)
- if err != nil {
- return nil, nil, err
- }
-
- switch u.Scheme {
- case "ws":
- u.Scheme = "http"
- case "wss":
- u.Scheme = "https"
- default:
- return nil, nil, errMalformedURL
- }
-
- if u.User != nil {
- // User name and password are not allowed in websocket URIs.
- return nil, nil, errMalformedURL
- }
-
- req := &http.Request{
- Method: "GET",
- URL: u,
- Proto: "HTTP/1.1",
- ProtoMajor: 1,
- ProtoMinor: 1,
- Header: make(http.Header),
- Host: u.Host,
- }
- req = req.WithContext(ctx)
-
- // Set the cookies present in the cookie jar of the dialer
- if d.Jar != nil {
- for _, cookie := range d.Jar.Cookies(u) {
- req.AddCookie(cookie)
- }
- }
-
- // Set the request headers using the capitalization for names and values in
- // RFC examples. Although the capitalization shouldn't matter, there are
- // servers that depend on it. The Header.Set method is not used because the
- // method canonicalizes the header names.
- req.Header["Upgrade"] = []string{"websocket"}
- req.Header["Connection"] = []string{"Upgrade"}
- req.Header["Sec-WebSocket-Key"] = []string{challengeKey}
- req.Header["Sec-WebSocket-Version"] = []string{"13"}
- if len(d.Subprotocols) > 0 {
- req.Header["Sec-WebSocket-Protocol"] = []string{strings.Join(d.Subprotocols, ", ")}
- }
- for k, vs := range requestHeader {
- switch {
- case k == "Host":
- if len(vs) > 0 {
- req.Host = vs[0]
- }
- case k == "Upgrade" ||
- k == "Connection" ||
- k == "Sec-Websocket-Key" ||
- k == "Sec-Websocket-Version" ||
- k == "Sec-Websocket-Extensions" ||
- (k == "Sec-Websocket-Protocol" && len(d.Subprotocols) > 0):
- return nil, nil, errors.New("websocket: duplicate header not allowed: " + k)
- case k == "Sec-Websocket-Protocol":
- req.Header["Sec-WebSocket-Protocol"] = vs
- default:
- req.Header[k] = vs
- }
- }
-
- if d.EnableCompression {
- req.Header["Sec-WebSocket-Extensions"] = []string{"permessage-deflate; server_no_context_takeover; client_no_context_takeover"}
- }
-
- if d.HandshakeTimeout != 0 {
- var cancel func()
- ctx, cancel = context.WithTimeout(ctx, d.HandshakeTimeout)
- defer cancel()
- }
-
- // Get network dial function.
- var netDial func(network, add string) (net.Conn, error)
-
- if d.NetDialContext != nil {
- netDial = func(network, addr string) (net.Conn, error) {
- return d.NetDialContext(ctx, network, addr)
- }
- } else if d.NetDial != nil {
- netDial = d.NetDial
- } else {
- netDialer := &net.Dialer{}
- netDial = func(network, addr string) (net.Conn, error) {
- return netDialer.DialContext(ctx, network, addr)
- }
- }
-
- // If needed, wrap the dial function to set the connection deadline.
- if deadline, ok := ctx.Deadline(); ok {
- forwardDial := netDial
- netDial = func(network, addr string) (net.Conn, error) {
- c, err := forwardDial(network, addr)
- if err != nil {
- return nil, err
- }
- err = c.SetDeadline(deadline)
- if err != nil {
- c.Close()
- return nil, err
- }
- return c, nil
- }
- }
-
- // If needed, wrap the dial function to connect through a proxy.
- if d.Proxy != nil {
- proxyURL, err := d.Proxy(req)
- if err != nil {
- return nil, nil, err
- }
- if proxyURL != nil {
- dialer, err := proxy_FromURL(proxyURL, netDialerFunc(netDial))
- if err != nil {
- return nil, nil, err
- }
- netDial = dialer.Dial
- }
- }
-
- hostPort, hostNoPort := hostPortNoPort(u)
- trace := httptrace.ContextClientTrace(ctx)
- if trace != nil && trace.GetConn != nil {
- trace.GetConn(hostPort)
- }
-
- netConn, err := netDial("tcp", hostPort)
- if trace != nil && trace.GotConn != nil {
- trace.GotConn(httptrace.GotConnInfo{
- Conn: netConn,
- })
- }
- if err != nil {
- return nil, nil, err
- }
-
- defer func() {
- if netConn != nil {
- netConn.Close()
- }
- }()
-
- if u.Scheme == "https" {
- cfg := cloneTLSConfig(d.TLSClientConfig)
- if cfg.ServerName == "" {
- cfg.ServerName = hostNoPort
- }
- tlsConn := tls.Client(netConn, cfg)
- netConn = tlsConn
-
- var err error
- if trace != nil {
- err = doHandshakeWithTrace(trace, tlsConn, cfg)
- } else {
- err = doHandshake(tlsConn, cfg)
- }
-
- if err != nil {
- return nil, nil, err
- }
- }
-
- conn := newConn(netConn, false, d.ReadBufferSize, d.WriteBufferSize, d.WriteBufferPool, nil, nil)
-
- if err := req.Write(netConn); err != nil {
- return nil, nil, err
- }
-
- if trace != nil && trace.GotFirstResponseByte != nil {
- if peek, err := conn.br.Peek(1); err == nil && len(peek) == 1 {
- trace.GotFirstResponseByte()
- }
- }
-
- resp, err := http.ReadResponse(conn.br, req)
- if err != nil {
- return nil, nil, err
- }
-
- if d.Jar != nil {
- if rc := resp.Cookies(); len(rc) > 0 {
- d.Jar.SetCookies(u, rc)
- }
- }
-
- if resp.StatusCode != 101 ||
- !strings.EqualFold(resp.Header.Get("Upgrade"), "websocket") ||
- !strings.EqualFold(resp.Header.Get("Connection"), "upgrade") ||
- resp.Header.Get("Sec-Websocket-Accept") != computeAcceptKey(challengeKey) {
- // Before closing the network connection on return from this
- // function, slurp up some of the response to aid application
- // debugging.
- buf := make([]byte, 1024)
- n, _ := io.ReadFull(resp.Body, buf)
- resp.Body = ioutil.NopCloser(bytes.NewReader(buf[:n]))
- return nil, resp, ErrBadHandshake
- }
-
- for _, ext := range parseExtensions(resp.Header) {
- if ext[""] != "permessage-deflate" {
- continue
- }
- _, snct := ext["server_no_context_takeover"]
- _, cnct := ext["client_no_context_takeover"]
- if !snct || !cnct {
- return nil, resp, errInvalidCompression
- }
- conn.newCompressionWriter = compressNoContextTakeover
- conn.newDecompressionReader = decompressNoContextTakeover
- break
- }
-
- resp.Body = ioutil.NopCloser(bytes.NewReader([]byte{}))
- conn.subprotocol = resp.Header.Get("Sec-Websocket-Protocol")
-
- netConn.SetDeadline(time.Time{})
- netConn = nil // to avoid close in defer.
- return conn, resp, nil
-}
-
-func doHandshake(tlsConn *tls.Conn, cfg *tls.Config) error {
- if err := tlsConn.Handshake(); err != nil {
- return err
- }
- if !cfg.InsecureSkipVerify {
- if err := tlsConn.VerifyHostname(cfg.ServerName); err != nil {
- return err
- }
- }
- return nil
-}
diff --git a/vendor/github.com/gorilla/websocket/client_clone.go b/vendor/github.com/gorilla/websocket/client_clone.go
deleted file mode 100644
index 4f0d943723..0000000000
--- a/vendor/github.com/gorilla/websocket/client_clone.go
+++ /dev/null
@@ -1,16 +0,0 @@
-// Copyright 2013 The Gorilla WebSocket 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 go1.8
-
-package websocket
-
-import "crypto/tls"
-
-func cloneTLSConfig(cfg *tls.Config) *tls.Config {
- if cfg == nil {
- return &tls.Config{}
- }
- return cfg.Clone()
-}
diff --git a/vendor/github.com/gorilla/websocket/client_clone_legacy.go b/vendor/github.com/gorilla/websocket/client_clone_legacy.go
deleted file mode 100644
index babb007fb4..0000000000
--- a/vendor/github.com/gorilla/websocket/client_clone_legacy.go
+++ /dev/null
@@ -1,38 +0,0 @@
-// Copyright 2013 The Gorilla WebSocket 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 !go1.8
-
-package websocket
-
-import "crypto/tls"
-
-// cloneTLSConfig clones all public fields except the fields
-// SessionTicketsDisabled and SessionTicketKey. This avoids copying the
-// sync.Mutex in the sync.Once and makes it safe to call cloneTLSConfig on a
-// config in active use.
-func cloneTLSConfig(cfg *tls.Config) *tls.Config {
- if cfg == nil {
- return &tls.Config{}
- }
- return &tls.Config{
- Rand: cfg.Rand,
- Time: cfg.Time,
- Certificates: cfg.Certificates,
- NameToCertificate: cfg.NameToCertificate,
- GetCertificate: cfg.GetCertificate,
- RootCAs: cfg.RootCAs,
- NextProtos: cfg.NextProtos,
- ServerName: cfg.ServerName,
- ClientAuth: cfg.ClientAuth,
- ClientCAs: cfg.ClientCAs,
- InsecureSkipVerify: cfg.InsecureSkipVerify,
- CipherSuites: cfg.CipherSuites,
- PreferServerCipherSuites: cfg.PreferServerCipherSuites,
- ClientSessionCache: cfg.ClientSessionCache,
- MinVersion: cfg.MinVersion,
- MaxVersion: cfg.MaxVersion,
- CurvePreferences: cfg.CurvePreferences,
- }
-}
diff --git a/vendor/github.com/gorilla/websocket/compression.go b/vendor/github.com/gorilla/websocket/compression.go
deleted file mode 100644
index 813ffb1e84..0000000000
--- a/vendor/github.com/gorilla/websocket/compression.go
+++ /dev/null
@@ -1,148 +0,0 @@
-// Copyright 2017 The Gorilla WebSocket 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 websocket
-
-import (
- "compress/flate"
- "errors"
- "io"
- "strings"
- "sync"
-)
-
-const (
- minCompressionLevel = -2 // flate.HuffmanOnly not defined in Go < 1.6
- maxCompressionLevel = flate.BestCompression
- defaultCompressionLevel = 1
-)
-
-var (
- flateWriterPools [maxCompressionLevel - minCompressionLevel + 1]sync.Pool
- flateReaderPool = sync.Pool{New: func() interface{} {
- return flate.NewReader(nil)
- }}
-)
-
-func decompressNoContextTakeover(r io.Reader) io.ReadCloser {
- const tail =
- // Add four bytes as specified in RFC
- "\x00\x00\xff\xff" +
- // Add final block to squelch unexpected EOF error from flate reader.
- "\x01\x00\x00\xff\xff"
-
- fr, _ := flateReaderPool.Get().(io.ReadCloser)
- fr.(flate.Resetter).Reset(io.MultiReader(r, strings.NewReader(tail)), nil)
- return &flateReadWrapper{fr}
-}
-
-func isValidCompressionLevel(level int) bool {
- return minCompressionLevel <= level && level <= maxCompressionLevel
-}
-
-func compressNoContextTakeover(w io.WriteCloser, level int) io.WriteCloser {
- p := &flateWriterPools[level-minCompressionLevel]
- tw := &truncWriter{w: w}
- fw, _ := p.Get().(*flate.Writer)
- if fw == nil {
- fw, _ = flate.NewWriter(tw, level)
- } else {
- fw.Reset(tw)
- }
- return &flateWriteWrapper{fw: fw, tw: tw, p: p}
-}
-
-// truncWriter is an io.Writer that writes all but the last four bytes of the
-// stream to another io.Writer.
-type truncWriter struct {
- w io.WriteCloser
- n int
- p [4]byte
-}
-
-func (w *truncWriter) Write(p []byte) (int, error) {
- n := 0
-
- // fill buffer first for simplicity.
- if w.n < len(w.p) {
- n = copy(w.p[w.n:], p)
- p = p[n:]
- w.n += n
- if len(p) == 0 {
- return n, nil
- }
- }
-
- m := len(p)
- if m > len(w.p) {
- m = len(w.p)
- }
-
- if nn, err := w.w.Write(w.p[:m]); err != nil {
- return n + nn, err
- }
-
- copy(w.p[:], w.p[m:])
- copy(w.p[len(w.p)-m:], p[len(p)-m:])
- nn, err := w.w.Write(p[:len(p)-m])
- return n + nn, err
-}
-
-type flateWriteWrapper struct {
- fw *flate.Writer
- tw *truncWriter
- p *sync.Pool
-}
-
-func (w *flateWriteWrapper) Write(p []byte) (int, error) {
- if w.fw == nil {
- return 0, errWriteClosed
- }
- return w.fw.Write(p)
-}
-
-func (w *flateWriteWrapper) Close() error {
- if w.fw == nil {
- return errWriteClosed
- }
- err1 := w.fw.Flush()
- w.p.Put(w.fw)
- w.fw = nil
- if w.tw.p != [4]byte{0, 0, 0xff, 0xff} {
- return errors.New("websocket: internal error, unexpected bytes at end of flate stream")
- }
- err2 := w.tw.w.Close()
- if err1 != nil {
- return err1
- }
- return err2
-}
-
-type flateReadWrapper struct {
- fr io.ReadCloser
-}
-
-func (r *flateReadWrapper) Read(p []byte) (int, error) {
- if r.fr == nil {
- return 0, io.ErrClosedPipe
- }
- n, err := r.fr.Read(p)
- if err == io.EOF {
- // Preemptively place the reader back in the pool. This helps with
- // scenarios where the application does not call NextReader() soon after
- // this final read.
- r.Close()
- }
- return n, err
-}
-
-func (r *flateReadWrapper) Close() error {
- if r.fr == nil {
- return io.ErrClosedPipe
- }
- err := r.fr.Close()
- flateReaderPool.Put(r.fr)
- r.fr = nil
- return err
-}
diff --git a/vendor/github.com/gorilla/websocket/conn.go b/vendor/github.com/gorilla/websocket/conn.go
deleted file mode 100644
index 9971ea3630..0000000000
--- a/vendor/github.com/gorilla/websocket/conn.go
+++ /dev/null
@@ -1,1163 +0,0 @@
-// Copyright 2013 The Gorilla WebSocket 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 websocket
-
-import (
- "bufio"
- "encoding/binary"
- "errors"
- "io"
- "io/ioutil"
- "math/rand"
- "net"
- "strconv"
- "sync"
- "time"
- "unicode/utf8"
-)
-
-const (
- // Frame header byte 0 bits from Section 5.2 of RFC 6455
- finalBit = 1 << 7
- rsv1Bit = 1 << 6
- rsv2Bit = 1 << 5
- rsv3Bit = 1 << 4
-
- // Frame header byte 1 bits from Section 5.2 of RFC 6455
- maskBit = 1 << 7
-
- maxFrameHeaderSize = 2 + 8 + 4 // Fixed header + length + mask
- maxControlFramePayloadSize = 125
-
- writeWait = time.Second
-
- defaultReadBufferSize = 4096
- defaultWriteBufferSize = 4096
-
- continuationFrame = 0
- noFrame = -1
-)
-
-// Close codes defined in RFC 6455, section 11.7.
-const (
- CloseNormalClosure = 1000
- CloseGoingAway = 1001
- CloseProtocolError = 1002
- CloseUnsupportedData = 1003
- CloseNoStatusReceived = 1005
- CloseAbnormalClosure = 1006
- CloseInvalidFramePayloadData = 1007
- ClosePolicyViolation = 1008
- CloseMessageTooBig = 1009
- CloseMandatoryExtension = 1010
- CloseInternalServerErr = 1011
- CloseServiceRestart = 1012
- CloseTryAgainLater = 1013
- CloseTLSHandshake = 1015
-)
-
-// The message types are defined in RFC 6455, section 11.8.
-const (
- // TextMessage denotes a text data message. The text message payload is
- // interpreted as UTF-8 encoded text data.
- TextMessage = 1
-
- // BinaryMessage denotes a binary data message.
- BinaryMessage = 2
-
- // CloseMessage denotes a close control message. The optional message
- // payload contains a numeric code and text. Use the FormatCloseMessage
- // function to format a close message payload.
- CloseMessage = 8
-
- // PingMessage denotes a ping control message. The optional message payload
- // is UTF-8 encoded text.
- PingMessage = 9
-
- // PongMessage denotes a pong control message. The optional message payload
- // is UTF-8 encoded text.
- PongMessage = 10
-)
-
-// ErrCloseSent is returned when the application writes a message to the
-// connection after sending a close message.
-var ErrCloseSent = errors.New("websocket: close sent")
-
-// ErrReadLimit is returned when reading a message that is larger than the
-// read limit set for the connection.
-var ErrReadLimit = errors.New("websocket: read limit exceeded")
-
-// netError satisfies the net Error interface.
-type netError struct {
- msg string
- temporary bool
- timeout bool
-}
-
-func (e *netError) Error() string { return e.msg }
-func (e *netError) Temporary() bool { return e.temporary }
-func (e *netError) Timeout() bool { return e.timeout }
-
-// CloseError represents a close message.
-type CloseError struct {
- // Code is defined in RFC 6455, section 11.7.
- Code int
-
- // Text is the optional text payload.
- Text string
-}
-
-func (e *CloseError) Error() string {
- s := []byte("websocket: close ")
- s = strconv.AppendInt(s, int64(e.Code), 10)
- switch e.Code {
- case CloseNormalClosure:
- s = append(s, " (normal)"...)
- case CloseGoingAway:
- s = append(s, " (going away)"...)
- case CloseProtocolError:
- s = append(s, " (protocol error)"...)
- case CloseUnsupportedData:
- s = append(s, " (unsupported data)"...)
- case CloseNoStatusReceived:
- s = append(s, " (no status)"...)
- case CloseAbnormalClosure:
- s = append(s, " (abnormal closure)"...)
- case CloseInvalidFramePayloadData:
- s = append(s, " (invalid payload data)"...)
- case ClosePolicyViolation:
- s = append(s, " (policy violation)"...)
- case CloseMessageTooBig:
- s = append(s, " (message too big)"...)
- case CloseMandatoryExtension:
- s = append(s, " (mandatory extension missing)"...)
- case CloseInternalServerErr:
- s = append(s, " (internal server error)"...)
- case CloseTLSHandshake:
- s = append(s, " (TLS handshake error)"...)
- }
- if e.Text != "" {
- s = append(s, ": "...)
- s = append(s, e.Text...)
- }
- return string(s)
-}
-
-// IsCloseError returns boolean indicating whether the error is a *CloseError
-// with one of the specified codes.
-func IsCloseError(err error, codes ...int) bool {
- if e, ok := err.(*CloseError); ok {
- for _, code := range codes {
- if e.Code == code {
- return true
- }
- }
- }
- return false
-}
-
-// IsUnexpectedCloseError returns boolean indicating whether the error is a
-// *CloseError with a code not in the list of expected codes.
-func IsUnexpectedCloseError(err error, expectedCodes ...int) bool {
- if e, ok := err.(*CloseError); ok {
- for _, code := range expectedCodes {
- if e.Code == code {
- return false
- }
- }
- return true
- }
- return false
-}
-
-var (
- errWriteTimeout = &netError{msg: "websocket: write timeout", timeout: true, temporary: true}
- errUnexpectedEOF = &CloseError{Code: CloseAbnormalClosure, Text: io.ErrUnexpectedEOF.Error()}
- errBadWriteOpCode = errors.New("websocket: bad write message type")
- errWriteClosed = errors.New("websocket: write closed")
- errInvalidControlFrame = errors.New("websocket: invalid control frame")
-)
-
-func newMaskKey() [4]byte {
- n := rand.Uint32()
- return [4]byte{byte(n), byte(n >> 8), byte(n >> 16), byte(n >> 24)}
-}
-
-func hideTempErr(err error) error {
- if e, ok := err.(net.Error); ok && e.Temporary() {
- err = &netError{msg: e.Error(), timeout: e.Timeout()}
- }
- return err
-}
-
-func isControl(frameType int) bool {
- return frameType == CloseMessage || frameType == PingMessage || frameType == PongMessage
-}
-
-func isData(frameType int) bool {
- return frameType == TextMessage || frameType == BinaryMessage
-}
-
-var validReceivedCloseCodes = map[int]bool{
- // see http://www.iana.org/assignments/websocket/websocket.xhtml#close-code-number
-
- CloseNormalClosure: true,
- CloseGoingAway: true,
- CloseProtocolError: true,
- CloseUnsupportedData: true,
- CloseNoStatusReceived: false,
- CloseAbnormalClosure: false,
- CloseInvalidFramePayloadData: true,
- ClosePolicyViolation: true,
- CloseMessageTooBig: true,
- CloseMandatoryExtension: true,
- CloseInternalServerErr: true,
- CloseServiceRestart: true,
- CloseTryAgainLater: true,
- CloseTLSHandshake: false,
-}
-
-func isValidReceivedCloseCode(code int) bool {
- return validReceivedCloseCodes[code] || (code >= 3000 && code <= 4999)
-}
-
-// BufferPool represents a pool of buffers. The *sync.Pool type satisfies this
-// interface. The type of the value stored in a pool is not specified.
-type BufferPool interface {
- // Get gets a value from the pool or returns nil if the pool is empty.
- Get() interface{}
- // Put adds a value to the pool.
- Put(interface{})
-}
-
-// writePoolData is the type added to the write buffer pool. This wrapper is
-// used to prevent applications from peeking at and depending on the values
-// added to the pool.
-type writePoolData struct{ buf []byte }
-
-// The Conn type represents a WebSocket connection.
-type Conn struct {
- conn net.Conn
- isServer bool
- subprotocol string
-
- // Write fields
- mu chan bool // used as mutex to protect write to conn
- writeBuf []byte // frame is constructed in this buffer.
- writePool BufferPool
- writeBufSize int
- writeDeadline time.Time
- writer io.WriteCloser // the current writer returned to the application
- isWriting bool // for best-effort concurrent write detection
-
- writeErrMu sync.Mutex
- writeErr error
-
- enableWriteCompression bool
- compressionLevel int
- newCompressionWriter func(io.WriteCloser, int) io.WriteCloser
-
- // Read fields
- reader io.ReadCloser // the current reader returned to the application
- readErr error
- br *bufio.Reader
- readRemaining int64 // bytes remaining in current frame.
- readFinal bool // true the current message has more frames.
- readLength int64 // Message size.
- readLimit int64 // Maximum message size.
- readMaskPos int
- readMaskKey [4]byte
- handlePong func(string) error
- handlePing func(string) error
- handleClose func(int, string) error
- readErrCount int
- messageReader *messageReader // the current low-level reader
-
- readDecompress bool // whether last read frame had RSV1 set
- newDecompressionReader func(io.Reader) io.ReadCloser
-}
-
-func newConn(conn net.Conn, isServer bool, readBufferSize, writeBufferSize int, writeBufferPool BufferPool, br *bufio.Reader, writeBuf []byte) *Conn {
-
- if br == nil {
- if readBufferSize == 0 {
- readBufferSize = defaultReadBufferSize
- } else if readBufferSize < maxControlFramePayloadSize {
- // must be large enough for control frame
- readBufferSize = maxControlFramePayloadSize
- }
- br = bufio.NewReaderSize(conn, readBufferSize)
- }
-
- if writeBufferSize <= 0 {
- writeBufferSize = defaultWriteBufferSize
- }
- writeBufferSize += maxFrameHeaderSize
-
- if writeBuf == nil && writeBufferPool == nil {
- writeBuf = make([]byte, writeBufferSize)
- }
-
- mu := make(chan bool, 1)
- mu <- true
- c := &Conn{
- isServer: isServer,
- br: br,
- conn: conn,
- mu: mu,
- readFinal: true,
- writeBuf: writeBuf,
- writePool: writeBufferPool,
- writeBufSize: writeBufferSize,
- enableWriteCompression: true,
- compressionLevel: defaultCompressionLevel,
- }
- c.SetCloseHandler(nil)
- c.SetPingHandler(nil)
- c.SetPongHandler(nil)
- return c
-}
-
-// Subprotocol returns the negotiated protocol for the connection.
-func (c *Conn) Subprotocol() string {
- return c.subprotocol
-}
-
-// Close closes the underlying network connection without sending or waiting
-// for a close message.
-func (c *Conn) Close() error {
- return c.conn.Close()
-}
-
-// LocalAddr returns the local network address.
-func (c *Conn) LocalAddr() net.Addr {
- return c.conn.LocalAddr()
-}
-
-// RemoteAddr returns the remote network address.
-func (c *Conn) RemoteAddr() net.Addr {
- return c.conn.RemoteAddr()
-}
-
-// Write methods
-
-func (c *Conn) writeFatal(err error) error {
- err = hideTempErr(err)
- c.writeErrMu.Lock()
- if c.writeErr == nil {
- c.writeErr = err
- }
- c.writeErrMu.Unlock()
- return err
-}
-
-func (c *Conn) read(n int) ([]byte, error) {
- p, err := c.br.Peek(n)
- if err == io.EOF {
- err = errUnexpectedEOF
- }
- c.br.Discard(len(p))
- return p, err
-}
-
-func (c *Conn) write(frameType int, deadline time.Time, buf0, buf1 []byte) error {
- <-c.mu
- defer func() { c.mu <- true }()
-
- c.writeErrMu.Lock()
- err := c.writeErr
- c.writeErrMu.Unlock()
- if err != nil {
- return err
- }
-
- c.conn.SetWriteDeadline(deadline)
- if len(buf1) == 0 {
- _, err = c.conn.Write(buf0)
- } else {
- err = c.writeBufs(buf0, buf1)
- }
- if err != nil {
- return c.writeFatal(err)
- }
- if frameType == CloseMessage {
- c.writeFatal(ErrCloseSent)
- }
- return nil
-}
-
-// WriteControl writes a control message with the given deadline. The allowed
-// message types are CloseMessage, PingMessage and PongMessage.
-func (c *Conn) WriteControl(messageType int, data []byte, deadline time.Time) error {
- if !isControl(messageType) {
- return errBadWriteOpCode
- }
- if len(data) > maxControlFramePayloadSize {
- return errInvalidControlFrame
- }
-
- b0 := byte(messageType) | finalBit
- b1 := byte(len(data))
- if !c.isServer {
- b1 |= maskBit
- }
-
- buf := make([]byte, 0, maxFrameHeaderSize+maxControlFramePayloadSize)
- buf = append(buf, b0, b1)
-
- if c.isServer {
- buf = append(buf, data...)
- } else {
- key := newMaskKey()
- buf = append(buf, key[:]...)
- buf = append(buf, data...)
- maskBytes(key, 0, buf[6:])
- }
-
- d := time.Hour * 1000
- if !deadline.IsZero() {
- d = deadline.Sub(time.Now())
- if d < 0 {
- return errWriteTimeout
- }
- }
-
- timer := time.NewTimer(d)
- select {
- case <-c.mu:
- timer.Stop()
- case <-timer.C:
- return errWriteTimeout
- }
- defer func() { c.mu <- true }()
-
- c.writeErrMu.Lock()
- err := c.writeErr
- c.writeErrMu.Unlock()
- if err != nil {
- return err
- }
-
- c.conn.SetWriteDeadline(deadline)
- _, err = c.conn.Write(buf)
- if err != nil {
- return c.writeFatal(err)
- }
- if messageType == CloseMessage {
- c.writeFatal(ErrCloseSent)
- }
- return err
-}
-
-// beginMessage prepares a connection and message writer for a new message.
-func (c *Conn) beginMessage(mw *messageWriter, messageType int) error {
- // Close previous writer if not already closed by the application. It's
- // probably better to return an error in this situation, but we cannot
- // change this without breaking existing applications.
- if c.writer != nil {
- c.writer.Close()
- c.writer = nil
- }
-
- if !isControl(messageType) && !isData(messageType) {
- return errBadWriteOpCode
- }
-
- c.writeErrMu.Lock()
- err := c.writeErr
- c.writeErrMu.Unlock()
- if err != nil {
- return err
- }
-
- mw.c = c
- mw.frameType = messageType
- mw.pos = maxFrameHeaderSize
-
- if c.writeBuf == nil {
- wpd, ok := c.writePool.Get().(writePoolData)
- if ok {
- c.writeBuf = wpd.buf
- } else {
- c.writeBuf = make([]byte, c.writeBufSize)
- }
- }
- return nil
-}
-
-// NextWriter returns a writer for the next message to send. The writer's Close
-// method flushes the complete message to the network.
-//
-// There can be at most one open writer on a connection. NextWriter closes the
-// previous writer if the application has not already done so.
-//
-// All message types (TextMessage, BinaryMessage, CloseMessage, PingMessage and
-// PongMessage) are supported.
-func (c *Conn) NextWriter(messageType int) (io.WriteCloser, error) {
- var mw messageWriter
- if err := c.beginMessage(&mw, messageType); err != nil {
- return nil, err
- }
- c.writer = &mw
- if c.newCompressionWriter != nil && c.enableWriteCompression && isData(messageType) {
- w := c.newCompressionWriter(c.writer, c.compressionLevel)
- mw.compress = true
- c.writer = w
- }
- return c.writer, nil
-}
-
-type messageWriter struct {
- c *Conn
- compress bool // whether next call to flushFrame should set RSV1
- pos int // end of data in writeBuf.
- frameType int // type of the current frame.
- err error
-}
-
-func (w *messageWriter) endMessage(err error) error {
- if w.err != nil {
- return err
- }
- c := w.c
- w.err = err
- c.writer = nil
- if c.writePool != nil {
- c.writePool.Put(writePoolData{buf: c.writeBuf})
- c.writeBuf = nil
- }
- return err
-}
-
-// flushFrame writes buffered data and extra as a frame to the network. The
-// final argument indicates that this is the last frame in the message.
-func (w *messageWriter) flushFrame(final bool, extra []byte) error {
- c := w.c
- length := w.pos - maxFrameHeaderSize + len(extra)
-
- // Check for invalid control frames.
- if isControl(w.frameType) &&
- (!final || length > maxControlFramePayloadSize) {
- return w.endMessage(errInvalidControlFrame)
- }
-
- b0 := byte(w.frameType)
- if final {
- b0 |= finalBit
- }
- if w.compress {
- b0 |= rsv1Bit
- }
- w.compress = false
-
- b1 := byte(0)
- if !c.isServer {
- b1 |= maskBit
- }
-
- // Assume that the frame starts at beginning of c.writeBuf.
- framePos := 0
- if c.isServer {
- // Adjust up if mask not included in the header.
- framePos = 4
- }
-
- switch {
- case length >= 65536:
- c.writeBuf[framePos] = b0
- c.writeBuf[framePos+1] = b1 | 127
- binary.BigEndian.PutUint64(c.writeBuf[framePos+2:], uint64(length))
- case length > 125:
- framePos += 6
- c.writeBuf[framePos] = b0
- c.writeBuf[framePos+1] = b1 | 126
- binary.BigEndian.PutUint16(c.writeBuf[framePos+2:], uint16(length))
- default:
- framePos += 8
- c.writeBuf[framePos] = b0
- c.writeBuf[framePos+1] = b1 | byte(length)
- }
-
- if !c.isServer {
- key := newMaskKey()
- copy(c.writeBuf[maxFrameHeaderSize-4:], key[:])
- maskBytes(key, 0, c.writeBuf[maxFrameHeaderSize:w.pos])
- if len(extra) > 0 {
- return w.endMessage(c.writeFatal(errors.New("websocket: internal error, extra used in client mode")))
- }
- }
-
- // Write the buffers to the connection with best-effort detection of
- // concurrent writes. See the concurrency section in the package
- // documentation for more info.
-
- if c.isWriting {
- panic("concurrent write to websocket connection")
- }
- c.isWriting = true
-
- err := c.write(w.frameType, c.writeDeadline, c.writeBuf[framePos:w.pos], extra)
-
- if !c.isWriting {
- panic("concurrent write to websocket connection")
- }
- c.isWriting = false
-
- if err != nil {
- return w.endMessage(err)
- }
-
- if final {
- w.endMessage(errWriteClosed)
- return nil
- }
-
- // Setup for next frame.
- w.pos = maxFrameHeaderSize
- w.frameType = continuationFrame
- return nil
-}
-
-func (w *messageWriter) ncopy(max int) (int, error) {
- n := len(w.c.writeBuf) - w.pos
- if n <= 0 {
- if err := w.flushFrame(false, nil); err != nil {
- return 0, err
- }
- n = len(w.c.writeBuf) - w.pos
- }
- if n > max {
- n = max
- }
- return n, nil
-}
-
-func (w *messageWriter) Write(p []byte) (int, error) {
- if w.err != nil {
- return 0, w.err
- }
-
- if len(p) > 2*len(w.c.writeBuf) && w.c.isServer {
- // Don't buffer large messages.
- err := w.flushFrame(false, p)
- if err != nil {
- return 0, err
- }
- return len(p), nil
- }
-
- nn := len(p)
- for len(p) > 0 {
- n, err := w.ncopy(len(p))
- if err != nil {
- return 0, err
- }
- copy(w.c.writeBuf[w.pos:], p[:n])
- w.pos += n
- p = p[n:]
- }
- return nn, nil
-}
-
-func (w *messageWriter) WriteString(p string) (int, error) {
- if w.err != nil {
- return 0, w.err
- }
-
- nn := len(p)
- for len(p) > 0 {
- n, err := w.ncopy(len(p))
- if err != nil {
- return 0, err
- }
- copy(w.c.writeBuf[w.pos:], p[:n])
- w.pos += n
- p = p[n:]
- }
- return nn, nil
-}
-
-func (w *messageWriter) ReadFrom(r io.Reader) (nn int64, err error) {
- if w.err != nil {
- return 0, w.err
- }
- for {
- if w.pos == len(w.c.writeBuf) {
- err = w.flushFrame(false, nil)
- if err != nil {
- break
- }
- }
- var n int
- n, err = r.Read(w.c.writeBuf[w.pos:])
- w.pos += n
- nn += int64(n)
- if err != nil {
- if err == io.EOF {
- err = nil
- }
- break
- }
- }
- return nn, err
-}
-
-func (w *messageWriter) Close() error {
- if w.err != nil {
- return w.err
- }
- return w.flushFrame(true, nil)
-}
-
-// WritePreparedMessage writes prepared message into connection.
-func (c *Conn) WritePreparedMessage(pm *PreparedMessage) error {
- frameType, frameData, err := pm.frame(prepareKey{
- isServer: c.isServer,
- compress: c.newCompressionWriter != nil && c.enableWriteCompression && isData(pm.messageType),
- compressionLevel: c.compressionLevel,
- })
- if err != nil {
- return err
- }
- if c.isWriting {
- panic("concurrent write to websocket connection")
- }
- c.isWriting = true
- err = c.write(frameType, c.writeDeadline, frameData, nil)
- if !c.isWriting {
- panic("concurrent write to websocket connection")
- }
- c.isWriting = false
- return err
-}
-
-// WriteMessage is a helper method for getting a writer using NextWriter,
-// writing the message and closing the writer.
-func (c *Conn) WriteMessage(messageType int, data []byte) error {
-
- if c.isServer && (c.newCompressionWriter == nil || !c.enableWriteCompression) {
- // Fast path with no allocations and single frame.
-
- var mw messageWriter
- if err := c.beginMessage(&mw, messageType); err != nil {
- return err
- }
- n := copy(c.writeBuf[mw.pos:], data)
- mw.pos += n
- data = data[n:]
- return mw.flushFrame(true, data)
- }
-
- w, err := c.NextWriter(messageType)
- if err != nil {
- return err
- }
- if _, err = w.Write(data); err != nil {
- return err
- }
- return w.Close()
-}
-
-// SetWriteDeadline sets the write deadline on the underlying network
-// connection. After a write has timed out, the websocket state is corrupt and
-// all future writes will return an error. A zero value for t means writes will
-// not time out.
-func (c *Conn) SetWriteDeadline(t time.Time) error {
- c.writeDeadline = t
- return nil
-}
-
-// Read methods
-
-func (c *Conn) advanceFrame() (int, error) {
- // 1. Skip remainder of previous frame.
-
- if c.readRemaining > 0 {
- if _, err := io.CopyN(ioutil.Discard, c.br, c.readRemaining); err != nil {
- return noFrame, err
- }
- }
-
- // 2. Read and parse first two bytes of frame header.
-
- p, err := c.read(2)
- if err != nil {
- return noFrame, err
- }
-
- final := p[0]&finalBit != 0
- frameType := int(p[0] & 0xf)
- mask := p[1]&maskBit != 0
- c.readRemaining = int64(p[1] & 0x7f)
-
- c.readDecompress = false
- if c.newDecompressionReader != nil && (p[0]&rsv1Bit) != 0 {
- c.readDecompress = true
- p[0] &^= rsv1Bit
- }
-
- if rsv := p[0] & (rsv1Bit | rsv2Bit | rsv3Bit); rsv != 0 {
- return noFrame, c.handleProtocolError("unexpected reserved bits 0x" + strconv.FormatInt(int64(rsv), 16))
- }
-
- switch frameType {
- case CloseMessage, PingMessage, PongMessage:
- if c.readRemaining > maxControlFramePayloadSize {
- return noFrame, c.handleProtocolError("control frame length > 125")
- }
- if !final {
- return noFrame, c.handleProtocolError("control frame not final")
- }
- case TextMessage, BinaryMessage:
- if !c.readFinal {
- return noFrame, c.handleProtocolError("message start before final message frame")
- }
- c.readFinal = final
- case continuationFrame:
- if c.readFinal {
- return noFrame, c.handleProtocolError("continuation after final message frame")
- }
- c.readFinal = final
- default:
- return noFrame, c.handleProtocolError("unknown opcode " + strconv.Itoa(frameType))
- }
-
- // 3. Read and parse frame length.
-
- switch c.readRemaining {
- case 126:
- p, err := c.read(2)
- if err != nil {
- return noFrame, err
- }
- c.readRemaining = int64(binary.BigEndian.Uint16(p))
- case 127:
- p, err := c.read(8)
- if err != nil {
- return noFrame, err
- }
- c.readRemaining = int64(binary.BigEndian.Uint64(p))
- }
-
- // 4. Handle frame masking.
-
- if mask != c.isServer {
- return noFrame, c.handleProtocolError("incorrect mask flag")
- }
-
- if mask {
- c.readMaskPos = 0
- p, err := c.read(len(c.readMaskKey))
- if err != nil {
- return noFrame, err
- }
- copy(c.readMaskKey[:], p)
- }
-
- // 5. For text and binary messages, enforce read limit and return.
-
- if frameType == continuationFrame || frameType == TextMessage || frameType == BinaryMessage {
-
- c.readLength += c.readRemaining
- if c.readLimit > 0 && c.readLength > c.readLimit {
- c.WriteControl(CloseMessage, FormatCloseMessage(CloseMessageTooBig, ""), time.Now().Add(writeWait))
- return noFrame, ErrReadLimit
- }
-
- return frameType, nil
- }
-
- // 6. Read control frame payload.
-
- var payload []byte
- if c.readRemaining > 0 {
- payload, err = c.read(int(c.readRemaining))
- c.readRemaining = 0
- if err != nil {
- return noFrame, err
- }
- if c.isServer {
- maskBytes(c.readMaskKey, 0, payload)
- }
- }
-
- // 7. Process control frame payload.
-
- switch frameType {
- case PongMessage:
- if err := c.handlePong(string(payload)); err != nil {
- return noFrame, err
- }
- case PingMessage:
- if err := c.handlePing(string(payload)); err != nil {
- return noFrame, err
- }
- case CloseMessage:
- closeCode := CloseNoStatusReceived
- closeText := ""
- if len(payload) >= 2 {
- closeCode = int(binary.BigEndian.Uint16(payload))
- if !isValidReceivedCloseCode(closeCode) {
- return noFrame, c.handleProtocolError("invalid close code")
- }
- closeText = string(payload[2:])
- if !utf8.ValidString(closeText) {
- return noFrame, c.handleProtocolError("invalid utf8 payload in close frame")
- }
- }
- if err := c.handleClose(closeCode, closeText); err != nil {
- return noFrame, err
- }
- return noFrame, &CloseError{Code: closeCode, Text: closeText}
- }
-
- return frameType, nil
-}
-
-func (c *Conn) handleProtocolError(message string) error {
- c.WriteControl(CloseMessage, FormatCloseMessage(CloseProtocolError, message), time.Now().Add(writeWait))
- return errors.New("websocket: " + message)
-}
-
-// NextReader returns the next data message received from the peer. The
-// returned messageType is either TextMessage or BinaryMessage.
-//
-// There can be at most one open reader on a connection. NextReader discards
-// the previous message if the application has not already consumed it.
-//
-// Applications must break out of the application's read loop when this method
-// returns a non-nil error value. Errors returned from this method are
-// permanent. Once this method returns a non-nil error, all subsequent calls to
-// this method return the same error.
-func (c *Conn) NextReader() (messageType int, r io.Reader, err error) {
- // Close previous reader, only relevant for decompression.
- if c.reader != nil {
- c.reader.Close()
- c.reader = nil
- }
-
- c.messageReader = nil
- c.readLength = 0
-
- for c.readErr == nil {
- frameType, err := c.advanceFrame()
- if err != nil {
- c.readErr = hideTempErr(err)
- break
- }
- if frameType == TextMessage || frameType == BinaryMessage {
- c.messageReader = &messageReader{c}
- c.reader = c.messageReader
- if c.readDecompress {
- c.reader = c.newDecompressionReader(c.reader)
- }
- return frameType, c.reader, nil
- }
- }
-
- // Applications that do handle the error returned from this method spin in
- // tight loop on connection failure. To help application developers detect
- // this error, panic on repeated reads to the failed connection.
- c.readErrCount++
- if c.readErrCount >= 1000 {
- panic("repeated read on failed websocket connection")
- }
-
- return noFrame, nil, c.readErr
-}
-
-type messageReader struct{ c *Conn }
-
-func (r *messageReader) Read(b []byte) (int, error) {
- c := r.c
- if c.messageReader != r {
- return 0, io.EOF
- }
-
- for c.readErr == nil {
-
- if c.readRemaining > 0 {
- if int64(len(b)) > c.readRemaining {
- b = b[:c.readRemaining]
- }
- n, err := c.br.Read(b)
- c.readErr = hideTempErr(err)
- if c.isServer {
- c.readMaskPos = maskBytes(c.readMaskKey, c.readMaskPos, b[:n])
- }
- c.readRemaining -= int64(n)
- if c.readRemaining > 0 && c.readErr == io.EOF {
- c.readErr = errUnexpectedEOF
- }
- return n, c.readErr
- }
-
- if c.readFinal {
- c.messageReader = nil
- return 0, io.EOF
- }
-
- frameType, err := c.advanceFrame()
- switch {
- case err != nil:
- c.readErr = hideTempErr(err)
- case frameType == TextMessage || frameType == BinaryMessage:
- c.readErr = errors.New("websocket: internal error, unexpected text or binary in Reader")
- }
- }
-
- err := c.readErr
- if err == io.EOF && c.messageReader == r {
- err = errUnexpectedEOF
- }
- return 0, err
-}
-
-func (r *messageReader) Close() error {
- return nil
-}
-
-// ReadMessage is a helper method for getting a reader using NextReader and
-// reading from that reader to a buffer.
-func (c *Conn) ReadMessage() (messageType int, p []byte, err error) {
- var r io.Reader
- messageType, r, err = c.NextReader()
- if err != nil {
- return messageType, nil, err
- }
- p, err = ioutil.ReadAll(r)
- return messageType, p, err
-}
-
-// SetReadDeadline sets the read deadline on the underlying network connection.
-// After a read has timed out, the websocket connection state is corrupt and
-// all future reads will return an error. A zero value for t means reads will
-// not time out.
-func (c *Conn) SetReadDeadline(t time.Time) error {
- return c.conn.SetReadDeadline(t)
-}
-
-// SetReadLimit sets the maximum size in bytes for a message read from the peer. If a
-// message exceeds the limit, the connection sends a close message to the peer
-// and returns ErrReadLimit to the application.
-func (c *Conn) SetReadLimit(limit int64) {
- c.readLimit = limit
-}
-
-// CloseHandler returns the current close handler
-func (c *Conn) CloseHandler() func(code int, text string) error {
- return c.handleClose
-}
-
-// SetCloseHandler sets the handler for close messages received from the peer.
-// The code argument to h is the received close code or CloseNoStatusReceived
-// if the close message is empty. The default close handler sends a close
-// message back to the peer.
-//
-// The handler function is called from the NextReader, ReadMessage and message
-// reader Read methods. The application must read the connection to process
-// close messages as described in the section on Control Messages above.
-//
-// The connection read methods return a CloseError when a close message is
-// received. Most applications should handle close messages as part of their
-// normal error handling. Applications should only set a close handler when the
-// application must perform some action before sending a close message back to
-// the peer.
-func (c *Conn) SetCloseHandler(h func(code int, text string) error) {
- if h == nil {
- h = func(code int, text string) error {
- message := FormatCloseMessage(code, "")
- c.WriteControl(CloseMessage, message, time.Now().Add(writeWait))
- return nil
- }
- }
- c.handleClose = h
-}
-
-// PingHandler returns the current ping handler
-func (c *Conn) PingHandler() func(appData string) error {
- return c.handlePing
-}
-
-// SetPingHandler sets the handler for ping messages received from the peer.
-// The appData argument to h is the PING message application data. The default
-// ping handler sends a pong to the peer.
-//
-// The handler function is called from the NextReader, ReadMessage and message
-// reader Read methods. The application must read the connection to process
-// ping messages as described in the section on Control Messages above.
-func (c *Conn) SetPingHandler(h func(appData string) error) {
- if h == nil {
- h = func(message string) error {
- err := c.WriteControl(PongMessage, []byte(message), time.Now().Add(writeWait))
- if err == ErrCloseSent {
- return nil
- } else if e, ok := err.(net.Error); ok && e.Temporary() {
- return nil
- }
- return err
- }
- }
- c.handlePing = h
-}
-
-// PongHandler returns the current pong handler
-func (c *Conn) PongHandler() func(appData string) error {
- return c.handlePong
-}
-
-// SetPongHandler sets the handler for pong messages received from the peer.
-// The appData argument to h is the PONG message application data. The default
-// pong handler does nothing.
-//
-// The handler function is called from the NextReader, ReadMessage and message
-// reader Read methods. The application must read the connection to process
-// pong messages as described in the section on Control Messages above.
-func (c *Conn) SetPongHandler(h func(appData string) error) {
- if h == nil {
- h = func(string) error { return nil }
- }
- c.handlePong = h
-}
-
-// UnderlyingConn returns the internal net.Conn. This can be used to further
-// modifications to connection specific flags.
-func (c *Conn) UnderlyingConn() net.Conn {
- return c.conn
-}
-
-// EnableWriteCompression enables and disables write compression of
-// subsequent text and binary messages. This function is a noop if
-// compression was not negotiated with the peer.
-func (c *Conn) EnableWriteCompression(enable bool) {
- c.enableWriteCompression = enable
-}
-
-// SetCompressionLevel sets the flate compression level for subsequent text and
-// binary messages. This function is a noop if compression was not negotiated
-// with the peer. See the compress/flate package for a description of
-// compression levels.
-func (c *Conn) SetCompressionLevel(level int) error {
- if !isValidCompressionLevel(level) {
- return errors.New("websocket: invalid compression level")
- }
- c.compressionLevel = level
- return nil
-}
-
-// FormatCloseMessage formats closeCode and text as a WebSocket close message.
-// An empty message is returned for code CloseNoStatusReceived.
-func FormatCloseMessage(closeCode int, text string) []byte {
- if closeCode == CloseNoStatusReceived {
- // Return empty message because it's illegal to send
- // CloseNoStatusReceived. Return non-nil value in case application
- // checks for nil.
- return []byte{}
- }
- buf := make([]byte, 2+len(text))
- binary.BigEndian.PutUint16(buf, uint16(closeCode))
- copy(buf[2:], text)
- return buf
-}
diff --git a/vendor/github.com/gorilla/websocket/conn_write.go b/vendor/github.com/gorilla/websocket/conn_write.go
deleted file mode 100644
index a509a21f87..0000000000
--- a/vendor/github.com/gorilla/websocket/conn_write.go
+++ /dev/null
@@ -1,15 +0,0 @@
-// Copyright 2016 The Gorilla WebSocket 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 go1.8
-
-package websocket
-
-import "net"
-
-func (c *Conn) writeBufs(bufs ...[]byte) error {
- b := net.Buffers(bufs)
- _, err := b.WriteTo(c.conn)
- return err
-}
diff --git a/vendor/github.com/gorilla/websocket/conn_write_legacy.go b/vendor/github.com/gorilla/websocket/conn_write_legacy.go
deleted file mode 100644
index 37edaff5a5..0000000000
--- a/vendor/github.com/gorilla/websocket/conn_write_legacy.go
+++ /dev/null
@@ -1,18 +0,0 @@
-// Copyright 2016 The Gorilla WebSocket 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 !go1.8
-
-package websocket
-
-func (c *Conn) writeBufs(bufs ...[]byte) error {
- for _, buf := range bufs {
- if len(buf) > 0 {
- if _, err := c.conn.Write(buf); err != nil {
- return err
- }
- }
- }
- return nil
-}
diff --git a/vendor/github.com/gorilla/websocket/doc.go b/vendor/github.com/gorilla/websocket/doc.go
deleted file mode 100644
index c6f4df8960..0000000000
--- a/vendor/github.com/gorilla/websocket/doc.go
+++ /dev/null
@@ -1,227 +0,0 @@
-// Copyright 2013 The Gorilla WebSocket 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 websocket implements the WebSocket protocol defined in RFC 6455.
-//
-// Overview
-//
-// The Conn type represents a WebSocket connection. A server application calls
-// the Upgrader.Upgrade method from an HTTP request handler to get a *Conn:
-//
-// var upgrader = websocket.Upgrader{
-// ReadBufferSize: 1024,
-// WriteBufferSize: 1024,
-// }
-//
-// func handler(w http.ResponseWriter, r *http.Request) {
-// conn, err := upgrader.Upgrade(w, r, nil)
-// if err != nil {
-// log.Println(err)
-// return
-// }
-// ... Use conn to send and receive messages.
-// }
-//
-// Call the connection's WriteMessage and ReadMessage methods to send and
-// receive messages as a slice of bytes. This snippet of code shows how to echo
-// messages using these methods:
-//
-// for {
-// messageType, p, err := conn.ReadMessage()
-// if err != nil {
-// log.Println(err)
-// return
-// }
-// if err := conn.WriteMessage(messageType, p); err != nil {
-// log.Println(err)
-// return
-// }
-// }
-//
-// In above snippet of code, p is a []byte and messageType is an int with value
-// websocket.BinaryMessage or websocket.TextMessage.
-//
-// An application can also send and receive messages using the io.WriteCloser
-// and io.Reader interfaces. To send a message, call the connection NextWriter
-// method to get an io.WriteCloser, write the message to the writer and close
-// the writer when done. To receive a message, call the connection NextReader
-// method to get an io.Reader and read until io.EOF is returned. This snippet
-// shows how to echo messages using the NextWriter and NextReader methods:
-//
-// for {
-// messageType, r, err := conn.NextReader()
-// if err != nil {
-// return
-// }
-// w, err := conn.NextWriter(messageType)
-// if err != nil {
-// return err
-// }
-// if _, err := io.Copy(w, r); err != nil {
-// return err
-// }
-// if err := w.Close(); err != nil {
-// return err
-// }
-// }
-//
-// Data Messages
-//
-// The WebSocket protocol distinguishes between text and binary data messages.
-// Text messages are interpreted as UTF-8 encoded text. The interpretation of
-// binary messages is left to the application.
-//
-// This package uses the TextMessage and BinaryMessage integer constants to
-// identify the two data message types. The ReadMessage and NextReader methods
-// return the type of the received message. The messageType argument to the
-// WriteMessage and NextWriter methods specifies the type of a sent message.
-//
-// It is the application's responsibility to ensure that text messages are
-// valid UTF-8 encoded text.
-//
-// Control Messages
-//
-// The WebSocket protocol defines three types of control messages: close, ping
-// and pong. Call the connection WriteControl, WriteMessage or NextWriter
-// methods to send a control message to the peer.
-//
-// Connections handle received close messages by calling the handler function
-// set with the SetCloseHandler method and by returning a *CloseError from the
-// NextReader, ReadMessage or the message Read method. The default close
-// handler sends a close message to the peer.
-//
-// Connections handle received ping messages by calling the handler function
-// set with the SetPingHandler method. The default ping handler sends a pong
-// message to the peer.
-//
-// Connections handle received pong messages by calling the handler function
-// set with the SetPongHandler method. The default pong handler does nothing.
-// If an application sends ping messages, then the application should set a
-// pong handler to receive the corresponding pong.
-//
-// The control message handler functions are called from the NextReader,
-// ReadMessage and message reader Read methods. The default close and ping
-// handlers can block these methods for a short time when the handler writes to
-// the connection.
-//
-// The application must read the connection to process close, ping and pong
-// messages sent from the peer. If the application is not otherwise interested
-// in messages from the peer, then the application should start a goroutine to
-// read and discard messages from the peer. A simple example is:
-//
-// func readLoop(c *websocket.Conn) {
-// for {
-// if _, _, err := c.NextReader(); err != nil {
-// c.Close()
-// break
-// }
-// }
-// }
-//
-// Concurrency
-//
-// Connections support one concurrent reader and one concurrent writer.
-//
-// Applications are responsible for ensuring that no more than one goroutine
-// calls the write methods (NextWriter, SetWriteDeadline, WriteMessage,
-// WriteJSON, EnableWriteCompression, SetCompressionLevel) concurrently and
-// that no more than one goroutine calls the read methods (NextReader,
-// SetReadDeadline, ReadMessage, ReadJSON, SetPongHandler, SetPingHandler)
-// concurrently.
-//
-// The Close and WriteControl methods can be called concurrently with all other
-// methods.
-//
-// Origin Considerations
-//
-// Web browsers allow Javascript applications to open a WebSocket connection to
-// any host. It's up to the server to enforce an origin policy using the Origin
-// request header sent by the browser.
-//
-// The Upgrader calls the function specified in the CheckOrigin field to check
-// the origin. If the CheckOrigin function returns false, then the Upgrade
-// method fails the WebSocket handshake with HTTP status 403.
-//
-// If the CheckOrigin field is nil, then the Upgrader uses a safe default: fail
-// the handshake if the Origin request header is present and the Origin host is
-// not equal to the Host request header.
-//
-// The deprecated package-level Upgrade function does not perform origin
-// checking. The application is responsible for checking the Origin header
-// before calling the Upgrade function.
-//
-// Buffers
-//
-// Connections buffer network input and output to reduce the number
-// of system calls when reading or writing messages.
-//
-// Write buffers are also used for constructing WebSocket frames. See RFC 6455,
-// Section 5 for a discussion of message framing. A WebSocket frame header is
-// written to the network each time a write buffer is flushed to the network.
-// Decreasing the size of the write buffer can increase the amount of framing
-// overhead on the connection.
-//
-// The buffer sizes in bytes are specified by the ReadBufferSize and
-// WriteBufferSize fields in the Dialer and Upgrader. The Dialer uses a default
-// size of 4096 when a buffer size field is set to zero. The Upgrader reuses
-// buffers created by the HTTP server when a buffer size field is set to zero.
-// The HTTP server buffers have a size of 4096 at the time of this writing.
-//
-// The buffer sizes do not limit the size of a message that can be read or
-// written by a connection.
-//
-// Buffers are held for the lifetime of the connection by default. If the
-// Dialer or Upgrader WriteBufferPool field is set, then a connection holds the
-// write buffer only when writing a message.
-//
-// Applications should tune the buffer sizes to balance memory use and
-// performance. Increasing the buffer size uses more memory, but can reduce the
-// number of system calls to read or write the network. In the case of writing,
-// increasing the buffer size can reduce the number of frame headers written to
-// the network.
-//
-// Some guidelines for setting buffer parameters are:
-//
-// Limit the buffer sizes to the maximum expected message size. Buffers larger
-// than the largest message do not provide any benefit.
-//
-// Depending on the distribution of message sizes, setting the buffer size to
-// to a value less than the maximum expected message size can greatly reduce
-// memory use with a small impact on performance. Here's an example: If 99% of
-// the messages are smaller than 256 bytes and the maximum message size is 512
-// bytes, then a buffer size of 256 bytes will result in 1.01 more system calls
-// than a buffer size of 512 bytes. The memory savings is 50%.
-//
-// A write buffer pool is useful when the application has a modest number
-// writes over a large number of connections. when buffers are pooled, a larger
-// buffer size has a reduced impact on total memory use and has the benefit of
-// reducing system calls and frame overhead.
-//
-// Compression EXPERIMENTAL
-//
-// Per message compression extensions (RFC 7692) are experimentally supported
-// by this package in a limited capacity. Setting the EnableCompression option
-// to true in Dialer or Upgrader will attempt to negotiate per message deflate
-// support.
-//
-// var upgrader = websocket.Upgrader{
-// EnableCompression: true,
-// }
-//
-// If compression was successfully negotiated with the connection's peer, any
-// message received in compressed form will be automatically decompressed.
-// All Read methods will return uncompressed bytes.
-//
-// Per message compression of messages written to a connection can be enabled
-// or disabled by calling the corresponding Conn method:
-//
-// conn.EnableWriteCompression(false)
-//
-// Currently this package does not support compression with "context takeover".
-// This means that messages must be compressed and decompressed in isolation,
-// without retaining sliding window or dictionary state across messages. For
-// more details refer to RFC 7692.
-//
-// Use of compression is experimental and may result in decreased performance.
-package websocket
diff --git a/vendor/github.com/gorilla/websocket/go.mod b/vendor/github.com/gorilla/websocket/go.mod
deleted file mode 100644
index 93a9e924a7..0000000000
--- a/vendor/github.com/gorilla/websocket/go.mod
+++ /dev/null
@@ -1 +0,0 @@
-module github.com/gorilla/websocket
diff --git a/vendor/github.com/gorilla/websocket/go.sum b/vendor/github.com/gorilla/websocket/go.sum
deleted file mode 100644
index cf4fbbaa07..0000000000
--- a/vendor/github.com/gorilla/websocket/go.sum
+++ /dev/null
@@ -1,2 +0,0 @@
-github.com/gorilla/websocket v1.4.0 h1:WDFjx/TMzVgy9VdMMQi2K2Emtwi2QcUQsztZ/zLaH/Q=
-github.com/gorilla/websocket v1.4.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ=
diff --git a/vendor/github.com/gorilla/websocket/join.go b/vendor/github.com/gorilla/websocket/join.go
deleted file mode 100644
index c64f8c8290..0000000000
--- a/vendor/github.com/gorilla/websocket/join.go
+++ /dev/null
@@ -1,42 +0,0 @@
-// Copyright 2019 The Gorilla WebSocket 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 websocket
-
-import (
- "io"
- "strings"
-)
-
-// JoinMessages concatenates received messages to create a single io.Reader.
-// The string term is appended to each message. The returned reader does not
-// support concurrent calls to the Read method.
-func JoinMessages(c *Conn, term string) io.Reader {
- return &joinReader{c: c, term: term}
-}
-
-type joinReader struct {
- c *Conn
- term string
- r io.Reader
-}
-
-func (r *joinReader) Read(p []byte) (int, error) {
- if r.r == nil {
- var err error
- _, r.r, err = r.c.NextReader()
- if err != nil {
- return 0, err
- }
- if r.term != "" {
- r.r = io.MultiReader(r.r, strings.NewReader(r.term))
- }
- }
- n, err := r.r.Read(p)
- if err == io.EOF {
- err = nil
- r.r = nil
- }
- return n, err
-}
diff --git a/vendor/github.com/gorilla/websocket/json.go b/vendor/github.com/gorilla/websocket/json.go
deleted file mode 100644
index dc2c1f6415..0000000000
--- a/vendor/github.com/gorilla/websocket/json.go
+++ /dev/null
@@ -1,60 +0,0 @@
-// Copyright 2013 The Gorilla WebSocket 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 websocket
-
-import (
- "encoding/json"
- "io"
-)
-
-// WriteJSON writes the JSON encoding of v as a message.
-//
-// Deprecated: Use c.WriteJSON instead.
-func WriteJSON(c *Conn, v interface{}) error {
- return c.WriteJSON(v)
-}
-
-// WriteJSON writes the JSON encoding of v as a message.
-//
-// See the documentation for encoding/json Marshal for details about the
-// conversion of Go values to JSON.
-func (c *Conn) WriteJSON(v interface{}) error {
- w, err := c.NextWriter(TextMessage)
- if err != nil {
- return err
- }
- err1 := json.NewEncoder(w).Encode(v)
- err2 := w.Close()
- if err1 != nil {
- return err1
- }
- return err2
-}
-
-// ReadJSON reads the next JSON-encoded message from the connection and stores
-// it in the value pointed to by v.
-//
-// Deprecated: Use c.ReadJSON instead.
-func ReadJSON(c *Conn, v interface{}) error {
- return c.ReadJSON(v)
-}
-
-// ReadJSON reads the next JSON-encoded message from the connection and stores
-// it in the value pointed to by v.
-//
-// See the documentation for the encoding/json Unmarshal function for details
-// about the conversion of JSON to a Go value.
-func (c *Conn) ReadJSON(v interface{}) error {
- _, r, err := c.NextReader()
- if err != nil {
- return err
- }
- err = json.NewDecoder(r).Decode(v)
- if err == io.EOF {
- // One value is expected in the message.
- err = io.ErrUnexpectedEOF
- }
- return err
-}
diff --git a/vendor/github.com/gorilla/websocket/mask.go b/vendor/github.com/gorilla/websocket/mask.go
deleted file mode 100644
index 577fce9efd..0000000000
--- a/vendor/github.com/gorilla/websocket/mask.go
+++ /dev/null
@@ -1,54 +0,0 @@
-// Copyright 2016 The Gorilla WebSocket 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 !appengine
-
-package websocket
-
-import "unsafe"
-
-const wordSize = int(unsafe.Sizeof(uintptr(0)))
-
-func maskBytes(key [4]byte, pos int, b []byte) int {
- // Mask one byte at a time for small buffers.
- if len(b) < 2*wordSize {
- for i := range b {
- b[i] ^= key[pos&3]
- pos++
- }
- return pos & 3
- }
-
- // Mask one byte at a time to word boundary.
- if n := int(uintptr(unsafe.Pointer(&b[0]))) % wordSize; n != 0 {
- n = wordSize - n
- for i := range b[:n] {
- b[i] ^= key[pos&3]
- pos++
- }
- b = b[n:]
- }
-
- // Create aligned word size key.
- var k [wordSize]byte
- for i := range k {
- k[i] = key[(pos+i)&3]
- }
- kw := *(*uintptr)(unsafe.Pointer(&k))
-
- // Mask one word at a time.
- n := (len(b) / wordSize) * wordSize
- for i := 0; i < n; i += wordSize {
- *(*uintptr)(unsafe.Pointer(uintptr(unsafe.Pointer(&b[0])) + uintptr(i))) ^= kw
- }
-
- // Mask one byte at a time for remaining bytes.
- b = b[n:]
- for i := range b {
- b[i] ^= key[pos&3]
- pos++
- }
-
- return pos & 3
-}
diff --git a/vendor/github.com/gorilla/websocket/mask_safe.go b/vendor/github.com/gorilla/websocket/mask_safe.go
deleted file mode 100644
index 2aac060e52..0000000000
--- a/vendor/github.com/gorilla/websocket/mask_safe.go
+++ /dev/null
@@ -1,15 +0,0 @@
-// Copyright 2016 The Gorilla WebSocket 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 appengine
-
-package websocket
-
-func maskBytes(key [4]byte, pos int, b []byte) int {
- for i := range b {
- b[i] ^= key[pos&3]
- pos++
- }
- return pos & 3
-}
diff --git a/vendor/github.com/gorilla/websocket/prepared.go b/vendor/github.com/gorilla/websocket/prepared.go
deleted file mode 100644
index 74ec565d2c..0000000000
--- a/vendor/github.com/gorilla/websocket/prepared.go
+++ /dev/null
@@ -1,102 +0,0 @@
-// Copyright 2017 The Gorilla WebSocket 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 websocket
-
-import (
- "bytes"
- "net"
- "sync"
- "time"
-)
-
-// PreparedMessage caches on the wire representations of a message payload.
-// Use PreparedMessage to efficiently send a message payload to multiple
-// connections. PreparedMessage is especially useful when compression is used
-// because the CPU and memory expensive compression operation can be executed
-// once for a given set of compression options.
-type PreparedMessage struct {
- messageType int
- data []byte
- mu sync.Mutex
- frames map[prepareKey]*preparedFrame
-}
-
-// prepareKey defines a unique set of options to cache prepared frames in PreparedMessage.
-type prepareKey struct {
- isServer bool
- compress bool
- compressionLevel int
-}
-
-// preparedFrame contains data in wire representation.
-type preparedFrame struct {
- once sync.Once
- data []byte
-}
-
-// NewPreparedMessage returns an initialized PreparedMessage. You can then send
-// it to connection using WritePreparedMessage method. Valid wire
-// representation will be calculated lazily only once for a set of current
-// connection options.
-func NewPreparedMessage(messageType int, data []byte) (*PreparedMessage, error) {
- pm := &PreparedMessage{
- messageType: messageType,
- frames: make(map[prepareKey]*preparedFrame),
- data: data,
- }
-
- // Prepare a plain server frame.
- _, frameData, err := pm.frame(prepareKey{isServer: true, compress: false})
- if err != nil {
- return nil, err
- }
-
- // To protect against caller modifying the data argument, remember the data
- // copied to the plain server frame.
- pm.data = frameData[len(frameData)-len(data):]
- return pm, nil
-}
-
-func (pm *PreparedMessage) frame(key prepareKey) (int, []byte, error) {
- pm.mu.Lock()
- frame, ok := pm.frames[key]
- if !ok {
- frame = &preparedFrame{}
- pm.frames[key] = frame
- }
- pm.mu.Unlock()
-
- var err error
- frame.once.Do(func() {
- // Prepare a frame using a 'fake' connection.
- // TODO: Refactor code in conn.go to allow more direct construction of
- // the frame.
- mu := make(chan bool, 1)
- mu <- true
- var nc prepareConn
- c := &Conn{
- conn: &nc,
- mu: mu,
- isServer: key.isServer,
- compressionLevel: key.compressionLevel,
- enableWriteCompression: true,
- writeBuf: make([]byte, defaultWriteBufferSize+maxFrameHeaderSize),
- }
- if key.compress {
- c.newCompressionWriter = compressNoContextTakeover
- }
- err = c.WriteMessage(pm.messageType, pm.data)
- frame.data = nc.buf.Bytes()
- })
- return pm.messageType, frame.data, err
-}
-
-type prepareConn struct {
- buf bytes.Buffer
- net.Conn
-}
-
-func (pc *prepareConn) Write(p []byte) (int, error) { return pc.buf.Write(p) }
-func (pc *prepareConn) SetWriteDeadline(t time.Time) error { return nil }
diff --git a/vendor/github.com/gorilla/websocket/proxy.go b/vendor/github.com/gorilla/websocket/proxy.go
deleted file mode 100644
index e87a8c9f0c..0000000000
--- a/vendor/github.com/gorilla/websocket/proxy.go
+++ /dev/null
@@ -1,77 +0,0 @@
-// Copyright 2017 The Gorilla WebSocket 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 websocket
-
-import (
- "bufio"
- "encoding/base64"
- "errors"
- "net"
- "net/http"
- "net/url"
- "strings"
-)
-
-type netDialerFunc func(network, addr string) (net.Conn, error)
-
-func (fn netDialerFunc) Dial(network, addr string) (net.Conn, error) {
- return fn(network, addr)
-}
-
-func init() {
- proxy_RegisterDialerType("http", func(proxyURL *url.URL, forwardDialer proxy_Dialer) (proxy_Dialer, error) {
- return &httpProxyDialer{proxyURL: proxyURL, forwardDial: forwardDialer.Dial}, nil
- })
-}
-
-type httpProxyDialer struct {
- proxyURL *url.URL
- forwardDial func(network, addr string) (net.Conn, error)
-}
-
-func (hpd *httpProxyDialer) Dial(network string, addr string) (net.Conn, error) {
- hostPort, _ := hostPortNoPort(hpd.proxyURL)
- conn, err := hpd.forwardDial(network, hostPort)
- if err != nil {
- return nil, err
- }
-
- connectHeader := make(http.Header)
- if user := hpd.proxyURL.User; user != nil {
- proxyUser := user.Username()
- if proxyPassword, passwordSet := user.Password(); passwordSet {
- credential := base64.StdEncoding.EncodeToString([]byte(proxyUser + ":" + proxyPassword))
- connectHeader.Set("Proxy-Authorization", "Basic "+credential)
- }
- }
-
- connectReq := &http.Request{
- Method: "CONNECT",
- URL: &url.URL{Opaque: addr},
- Host: addr,
- Header: connectHeader,
- }
-
- if err := connectReq.Write(conn); err != nil {
- conn.Close()
- return nil, err
- }
-
- // Read response. It's OK to use and discard buffered reader here becaue
- // the remote server does not speak until spoken to.
- br := bufio.NewReader(conn)
- resp, err := http.ReadResponse(br, connectReq)
- if err != nil {
- conn.Close()
- return nil, err
- }
-
- if resp.StatusCode != 200 {
- conn.Close()
- f := strings.SplitN(resp.Status, " ", 2)
- return nil, errors.New(f[1])
- }
- return conn, nil
-}
diff --git a/vendor/github.com/gorilla/websocket/server.go b/vendor/github.com/gorilla/websocket/server.go
deleted file mode 100644
index 3d4480a477..0000000000
--- a/vendor/github.com/gorilla/websocket/server.go
+++ /dev/null
@@ -1,363 +0,0 @@
-// Copyright 2013 The Gorilla WebSocket 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 websocket
-
-import (
- "bufio"
- "errors"
- "io"
- "net/http"
- "net/url"
- "strings"
- "time"
-)
-
-// HandshakeError describes an error with the handshake from the peer.
-type HandshakeError struct {
- message string
-}
-
-func (e HandshakeError) Error() string { return e.message }
-
-// Upgrader specifies parameters for upgrading an HTTP connection to a
-// WebSocket connection.
-type Upgrader struct {
- // HandshakeTimeout specifies the duration for the handshake to complete.
- HandshakeTimeout time.Duration
-
- // ReadBufferSize and WriteBufferSize specify I/O buffer sizes in bytes. If a buffer
- // size is zero, then buffers allocated by the HTTP server are used. The
- // I/O buffer sizes do not limit the size of the messages that can be sent
- // or received.
- ReadBufferSize, WriteBufferSize int
-
- // WriteBufferPool is a pool of buffers for write operations. If the value
- // is not set, then write buffers are allocated to the connection for the
- // lifetime of the connection.
- //
- // A pool is most useful when the application has a modest volume of writes
- // across a large number of connections.
- //
- // Applications should use a single pool for each unique value of
- // WriteBufferSize.
- WriteBufferPool BufferPool
-
- // Subprotocols specifies the server's supported protocols in order of
- // preference. If this field is not nil, then the Upgrade method negotiates a
- // subprotocol by selecting the first match in this list with a protocol
- // requested by the client. If there's no match, then no protocol is
- // negotiated (the Sec-Websocket-Protocol header is not included in the
- // handshake response).
- Subprotocols []string
-
- // Error specifies the function for generating HTTP error responses. If Error
- // is nil, then http.Error is used to generate the HTTP response.
- Error func(w http.ResponseWriter, r *http.Request, status int, reason error)
-
- // CheckOrigin returns true if the request Origin header is acceptable. If
- // CheckOrigin is nil, then a safe default is used: return false if the
- // Origin request header is present and the origin host is not equal to
- // request Host header.
- //
- // A CheckOrigin function should carefully validate the request origin to
- // prevent cross-site request forgery.
- CheckOrigin func(r *http.Request) bool
-
- // EnableCompression specify if the server should attempt to negotiate per
- // message compression (RFC 7692). Setting this value to true does not
- // guarantee that compression will be supported. Currently only "no context
- // takeover" modes are supported.
- EnableCompression bool
-}
-
-func (u *Upgrader) returnError(w http.ResponseWriter, r *http.Request, status int, reason string) (*Conn, error) {
- err := HandshakeError{reason}
- if u.Error != nil {
- u.Error(w, r, status, err)
- } else {
- w.Header().Set("Sec-Websocket-Version", "13")
- http.Error(w, http.StatusText(status), status)
- }
- return nil, err
-}
-
-// checkSameOrigin returns true if the origin is not set or is equal to the request host.
-func checkSameOrigin(r *http.Request) bool {
- origin := r.Header["Origin"]
- if len(origin) == 0 {
- return true
- }
- u, err := url.Parse(origin[0])
- if err != nil {
- return false
- }
- return equalASCIIFold(u.Host, r.Host)
-}
-
-func (u *Upgrader) selectSubprotocol(r *http.Request, responseHeader http.Header) string {
- if u.Subprotocols != nil {
- clientProtocols := Subprotocols(r)
- for _, serverProtocol := range u.Subprotocols {
- for _, clientProtocol := range clientProtocols {
- if clientProtocol == serverProtocol {
- return clientProtocol
- }
- }
- }
- } else if responseHeader != nil {
- return responseHeader.Get("Sec-Websocket-Protocol")
- }
- return ""
-}
-
-// Upgrade upgrades the HTTP server connection to the WebSocket protocol.
-//
-// The responseHeader is included in the response to the client's upgrade
-// request. Use the responseHeader to specify cookies (Set-Cookie) and the
-// application negotiated subprotocol (Sec-WebSocket-Protocol).
-//
-// If the upgrade fails, then Upgrade replies to the client with an HTTP error
-// response.
-func (u *Upgrader) Upgrade(w http.ResponseWriter, r *http.Request, responseHeader http.Header) (*Conn, error) {
- const badHandshake = "websocket: the client is not using the websocket protocol: "
-
- if !tokenListContainsValue(r.Header, "Connection", "upgrade") {
- return u.returnError(w, r, http.StatusBadRequest, badHandshake+"'upgrade' token not found in 'Connection' header")
- }
-
- if !tokenListContainsValue(r.Header, "Upgrade", "websocket") {
- return u.returnError(w, r, http.StatusBadRequest, badHandshake+"'websocket' token not found in 'Upgrade' header")
- }
-
- if r.Method != "GET" {
- return u.returnError(w, r, http.StatusMethodNotAllowed, badHandshake+"request method is not GET")
- }
-
- if !tokenListContainsValue(r.Header, "Sec-Websocket-Version", "13") {
- return u.returnError(w, r, http.StatusBadRequest, "websocket: unsupported version: 13 not found in 'Sec-Websocket-Version' header")
- }
-
- if _, ok := responseHeader["Sec-Websocket-Extensions"]; ok {
- return u.returnError(w, r, http.StatusInternalServerError, "websocket: application specific 'Sec-WebSocket-Extensions' headers are unsupported")
- }
-
- checkOrigin := u.CheckOrigin
- if checkOrigin == nil {
- checkOrigin = checkSameOrigin
- }
- if !checkOrigin(r) {
- return u.returnError(w, r, http.StatusForbidden, "websocket: request origin not allowed by Upgrader.CheckOrigin")
- }
-
- challengeKey := r.Header.Get("Sec-Websocket-Key")
- if challengeKey == "" {
- return u.returnError(w, r, http.StatusBadRequest, "websocket: not a websocket handshake: `Sec-WebSocket-Key' header is missing or blank")
- }
-
- subprotocol := u.selectSubprotocol(r, responseHeader)
-
- // Negotiate PMCE
- var compress bool
- if u.EnableCompression {
- for _, ext := range parseExtensions(r.Header) {
- if ext[""] != "permessage-deflate" {
- continue
- }
- compress = true
- break
- }
- }
-
- h, ok := w.(http.Hijacker)
- if !ok {
- return u.returnError(w, r, http.StatusInternalServerError, "websocket: response does not implement http.Hijacker")
- }
- var brw *bufio.ReadWriter
- netConn, brw, err := h.Hijack()
- if err != nil {
- return u.returnError(w, r, http.StatusInternalServerError, err.Error())
- }
-
- if brw.Reader.Buffered() > 0 {
- netConn.Close()
- return nil, errors.New("websocket: client sent data before handshake is complete")
- }
-
- var br *bufio.Reader
- if u.ReadBufferSize == 0 && bufioReaderSize(netConn, brw.Reader) > 256 {
- // Reuse hijacked buffered reader as connection reader.
- br = brw.Reader
- }
-
- buf := bufioWriterBuffer(netConn, brw.Writer)
-
- var writeBuf []byte
- if u.WriteBufferPool == nil && u.WriteBufferSize == 0 && len(buf) >= maxFrameHeaderSize+256 {
- // Reuse hijacked write buffer as connection buffer.
- writeBuf = buf
- }
-
- c := newConn(netConn, true, u.ReadBufferSize, u.WriteBufferSize, u.WriteBufferPool, br, writeBuf)
- c.subprotocol = subprotocol
-
- if compress {
- c.newCompressionWriter = compressNoContextTakeover
- c.newDecompressionReader = decompressNoContextTakeover
- }
-
- // Use larger of hijacked buffer and connection write buffer for header.
- p := buf
- if len(c.writeBuf) > len(p) {
- p = c.writeBuf
- }
- p = p[:0]
-
- p = append(p, "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: "...)
- p = append(p, computeAcceptKey(challengeKey)...)
- p = append(p, "\r\n"...)
- if c.subprotocol != "" {
- p = append(p, "Sec-WebSocket-Protocol: "...)
- p = append(p, c.subprotocol...)
- p = append(p, "\r\n"...)
- }
- if compress {
- p = append(p, "Sec-WebSocket-Extensions: permessage-deflate; server_no_context_takeover; client_no_context_takeover\r\n"...)
- }
- for k, vs := range responseHeader {
- if k == "Sec-Websocket-Protocol" {
- continue
- }
- for _, v := range vs {
- p = append(p, k...)
- p = append(p, ": "...)
- for i := 0; i < len(v); i++ {
- b := v[i]
- if b <= 31 {
- // prevent response splitting.
- b = ' '
- }
- p = append(p, b)
- }
- p = append(p, "\r\n"...)
- }
- }
- p = append(p, "\r\n"...)
-
- // Clear deadlines set by HTTP server.
- netConn.SetDeadline(time.Time{})
-
- if u.HandshakeTimeout > 0 {
- netConn.SetWriteDeadline(time.Now().Add(u.HandshakeTimeout))
- }
- if _, err = netConn.Write(p); err != nil {
- netConn.Close()
- return nil, err
- }
- if u.HandshakeTimeout > 0 {
- netConn.SetWriteDeadline(time.Time{})
- }
-
- return c, nil
-}
-
-// Upgrade upgrades the HTTP server connection to the WebSocket protocol.
-//
-// Deprecated: Use websocket.Upgrader instead.
-//
-// Upgrade does not perform origin checking. The application is responsible for
-// checking the Origin header before calling Upgrade. An example implementation
-// of the same origin policy check is:
-//
-// if req.Header.Get("Origin") != "http://"+req.Host {
-// http.Error(w, "Origin not allowed", http.StatusForbidden)
-// return
-// }
-//
-// If the endpoint supports subprotocols, then the application is responsible
-// for negotiating the protocol used on the connection. Use the Subprotocols()
-// function to get the subprotocols requested by the client. Use the
-// Sec-Websocket-Protocol response header to specify the subprotocol selected
-// by the application.
-//
-// The responseHeader is included in the response to the client's upgrade
-// request. Use the responseHeader to specify cookies (Set-Cookie) and the
-// negotiated subprotocol (Sec-Websocket-Protocol).
-//
-// The connection buffers IO to the underlying network connection. The
-// readBufSize and writeBufSize parameters specify the size of the buffers to
-// use. Messages can be larger than the buffers.
-//
-// If the request is not a valid WebSocket handshake, then Upgrade returns an
-// error of type HandshakeError. Applications should handle this error by
-// replying to the client with an HTTP error response.
-func Upgrade(w http.ResponseWriter, r *http.Request, responseHeader http.Header, readBufSize, writeBufSize int) (*Conn, error) {
- u := Upgrader{ReadBufferSize: readBufSize, WriteBufferSize: writeBufSize}
- u.Error = func(w http.ResponseWriter, r *http.Request, status int, reason error) {
- // don't return errors to maintain backwards compatibility
- }
- u.CheckOrigin = func(r *http.Request) bool {
- // allow all connections by default
- return true
- }
- return u.Upgrade(w, r, responseHeader)
-}
-
-// Subprotocols returns the subprotocols requested by the client in the
-// Sec-Websocket-Protocol header.
-func Subprotocols(r *http.Request) []string {
- h := strings.TrimSpace(r.Header.Get("Sec-Websocket-Protocol"))
- if h == "" {
- return nil
- }
- protocols := strings.Split(h, ",")
- for i := range protocols {
- protocols[i] = strings.TrimSpace(protocols[i])
- }
- return protocols
-}
-
-// IsWebSocketUpgrade returns true if the client requested upgrade to the
-// WebSocket protocol.
-func IsWebSocketUpgrade(r *http.Request) bool {
- return tokenListContainsValue(r.Header, "Connection", "upgrade") &&
- tokenListContainsValue(r.Header, "Upgrade", "websocket")
-}
-
-// bufioReaderSize size returns the size of a bufio.Reader.
-func bufioReaderSize(originalReader io.Reader, br *bufio.Reader) int {
- // This code assumes that peek on a reset reader returns
- // bufio.Reader.buf[:0].
- // TODO: Use bufio.Reader.Size() after Go 1.10
- br.Reset(originalReader)
- if p, err := br.Peek(0); err == nil {
- return cap(p)
- }
- return 0
-}
-
-// writeHook is an io.Writer that records the last slice passed to it vio
-// io.Writer.Write.
-type writeHook struct {
- p []byte
-}
-
-func (wh *writeHook) Write(p []byte) (int, error) {
- wh.p = p
- return len(p), nil
-}
-
-// bufioWriterBuffer grabs the buffer from a bufio.Writer.
-func bufioWriterBuffer(originalWriter io.Writer, bw *bufio.Writer) []byte {
- // This code assumes that bufio.Writer.buf[:1] is passed to the
- // bufio.Writer's underlying writer.
- var wh writeHook
- bw.Reset(&wh)
- bw.WriteByte(0)
- bw.Flush()
-
- bw.Reset(originalWriter)
-
- return wh.p[:cap(wh.p)]
-}
diff --git a/vendor/github.com/gorilla/websocket/trace.go b/vendor/github.com/gorilla/websocket/trace.go
deleted file mode 100644
index 834f122a00..0000000000
--- a/vendor/github.com/gorilla/websocket/trace.go
+++ /dev/null
@@ -1,19 +0,0 @@
-// +build go1.8
-
-package websocket
-
-import (
- "crypto/tls"
- "net/http/httptrace"
-)
-
-func doHandshakeWithTrace(trace *httptrace.ClientTrace, tlsConn *tls.Conn, cfg *tls.Config) error {
- if trace.TLSHandshakeStart != nil {
- trace.TLSHandshakeStart()
- }
- err := doHandshake(tlsConn, cfg)
- if trace.TLSHandshakeDone != nil {
- trace.TLSHandshakeDone(tlsConn.ConnectionState(), err)
- }
- return err
-}
diff --git a/vendor/github.com/gorilla/websocket/trace_17.go b/vendor/github.com/gorilla/websocket/trace_17.go
deleted file mode 100644
index 77d05a0b57..0000000000
--- a/vendor/github.com/gorilla/websocket/trace_17.go
+++ /dev/null
@@ -1,12 +0,0 @@
-// +build !go1.8
-
-package websocket
-
-import (
- "crypto/tls"
- "net/http/httptrace"
-)
-
-func doHandshakeWithTrace(trace *httptrace.ClientTrace, tlsConn *tls.Conn, cfg *tls.Config) error {
- return doHandshake(tlsConn, cfg)
-}
diff --git a/vendor/github.com/gorilla/websocket/util.go b/vendor/github.com/gorilla/websocket/util.go
deleted file mode 100644
index 7bf2f66c67..0000000000
--- a/vendor/github.com/gorilla/websocket/util.go
+++ /dev/null
@@ -1,283 +0,0 @@
-// Copyright 2013 The Gorilla WebSocket 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 websocket
-
-import (
- "crypto/rand"
- "crypto/sha1"
- "encoding/base64"
- "io"
- "net/http"
- "strings"
- "unicode/utf8"
-)
-
-var keyGUID = []byte("258EAFA5-E914-47DA-95CA-C5AB0DC85B11")
-
-func computeAcceptKey(challengeKey string) string {
- h := sha1.New()
- h.Write([]byte(challengeKey))
- h.Write(keyGUID)
- return base64.StdEncoding.EncodeToString(h.Sum(nil))
-}
-
-func generateChallengeKey() (string, error) {
- p := make([]byte, 16)
- if _, err := io.ReadFull(rand.Reader, p); err != nil {
- return "", err
- }
- return base64.StdEncoding.EncodeToString(p), nil
-}
-
-// Token octets per RFC 2616.
-var isTokenOctet = [256]bool{
- '!': true,
- '#': true,
- '$': true,
- '%': true,
- '&': true,
- '\'': true,
- '*': true,
- '+': true,
- '-': true,
- '.': true,
- '0': true,
- '1': true,
- '2': true,
- '3': true,
- '4': true,
- '5': true,
- '6': true,
- '7': true,
- '8': true,
- '9': true,
- 'A': true,
- 'B': true,
- 'C': true,
- 'D': true,
- 'E': true,
- 'F': true,
- 'G': true,
- 'H': true,
- 'I': true,
- 'J': true,
- 'K': true,
- 'L': true,
- 'M': true,
- 'N': true,
- 'O': true,
- 'P': true,
- 'Q': true,
- 'R': true,
- 'S': true,
- 'T': true,
- 'U': true,
- 'W': true,
- 'V': true,
- 'X': true,
- 'Y': true,
- 'Z': true,
- '^': true,
- '_': true,
- '`': true,
- 'a': true,
- 'b': true,
- 'c': true,
- 'd': true,
- 'e': true,
- 'f': true,
- 'g': true,
- 'h': true,
- 'i': true,
- 'j': true,
- 'k': true,
- 'l': true,
- 'm': true,
- 'n': true,
- 'o': true,
- 'p': true,
- 'q': true,
- 'r': true,
- 's': true,
- 't': true,
- 'u': true,
- 'v': true,
- 'w': true,
- 'x': true,
- 'y': true,
- 'z': true,
- '|': true,
- '~': true,
-}
-
-// skipSpace returns a slice of the string s with all leading RFC 2616 linear
-// whitespace removed.
-func skipSpace(s string) (rest string) {
- i := 0
- for ; i < len(s); i++ {
- if b := s[i]; b != ' ' && b != '\t' {
- break
- }
- }
- return s[i:]
-}
-
-// nextToken returns the leading RFC 2616 token of s and the string following
-// the token.
-func nextToken(s string) (token, rest string) {
- i := 0
- for ; i < len(s); i++ {
- if !isTokenOctet[s[i]] {
- break
- }
- }
- return s[:i], s[i:]
-}
-
-// nextTokenOrQuoted returns the leading token or quoted string per RFC 2616
-// and the string following the token or quoted string.
-func nextTokenOrQuoted(s string) (value string, rest string) {
- if !strings.HasPrefix(s, "\"") {
- return nextToken(s)
- }
- s = s[1:]
- for i := 0; i < len(s); i++ {
- switch s[i] {
- case '"':
- return s[:i], s[i+1:]
- case '\\':
- p := make([]byte, len(s)-1)
- j := copy(p, s[:i])
- escape := true
- for i = i + 1; i < len(s); i++ {
- b := s[i]
- switch {
- case escape:
- escape = false
- p[j] = b
- j++
- case b == '\\':
- escape = true
- case b == '"':
- return string(p[:j]), s[i+1:]
- default:
- p[j] = b
- j++
- }
- }
- return "", ""
- }
- }
- return "", ""
-}
-
-// equalASCIIFold returns true if s is equal to t with ASCII case folding as
-// defined in RFC 4790.
-func equalASCIIFold(s, t string) bool {
- for s != "" && t != "" {
- sr, size := utf8.DecodeRuneInString(s)
- s = s[size:]
- tr, size := utf8.DecodeRuneInString(t)
- t = t[size:]
- if sr == tr {
- continue
- }
- if 'A' <= sr && sr <= 'Z' {
- sr = sr + 'a' - 'A'
- }
- if 'A' <= tr && tr <= 'Z' {
- tr = tr + 'a' - 'A'
- }
- if sr != tr {
- return false
- }
- }
- return s == t
-}
-
-// tokenListContainsValue returns true if the 1#token header with the given
-// name contains a token equal to value with ASCII case folding.
-func tokenListContainsValue(header http.Header, name string, value string) bool {
-headers:
- for _, s := range header[name] {
- for {
- var t string
- t, s = nextToken(skipSpace(s))
- if t == "" {
- continue headers
- }
- s = skipSpace(s)
- if s != "" && s[0] != ',' {
- continue headers
- }
- if equalASCIIFold(t, value) {
- return true
- }
- if s == "" {
- continue headers
- }
- s = s[1:]
- }
- }
- return false
-}
-
-// parseExtensions parses WebSocket extensions from a header.
-func parseExtensions(header http.Header) []map[string]string {
- // From RFC 6455:
- //
- // Sec-WebSocket-Extensions = extension-list
- // extension-list = 1#extension
- // extension = extension-token *( ";" extension-param )
- // extension-token = registered-token
- // registered-token = token
- // extension-param = token [ "=" (token | quoted-string) ]
- // ;When using the quoted-string syntax variant, the value
- // ;after quoted-string unescaping MUST conform to the
- // ;'token' ABNF.
-
- var result []map[string]string
-headers:
- for _, s := range header["Sec-Websocket-Extensions"] {
- for {
- var t string
- t, s = nextToken(skipSpace(s))
- if t == "" {
- continue headers
- }
- ext := map[string]string{"": t}
- for {
- s = skipSpace(s)
- if !strings.HasPrefix(s, ";") {
- break
- }
- var k string
- k, s = nextToken(skipSpace(s[1:]))
- if k == "" {
- continue headers
- }
- s = skipSpace(s)
- var v string
- if strings.HasPrefix(s, "=") {
- v, s = nextTokenOrQuoted(skipSpace(s[1:]))
- s = skipSpace(s)
- }
- if s != "" && s[0] != ',' && s[0] != ';' {
- continue headers
- }
- ext[k] = v
- }
- if s != "" && s[0] != ',' {
- continue headers
- }
- result = append(result, ext)
- if s == "" {
- continue headers
- }
- s = s[1:]
- }
- }
- return result
-}
diff --git a/vendor/github.com/gorilla/websocket/x_net_proxy.go b/vendor/github.com/gorilla/websocket/x_net_proxy.go
deleted file mode 100644
index 2e668f6b88..0000000000
--- a/vendor/github.com/gorilla/websocket/x_net_proxy.go
+++ /dev/null
@@ -1,473 +0,0 @@
-// Code generated by golang.org/x/tools/cmd/bundle. DO NOT EDIT.
-//go:generate bundle -o x_net_proxy.go golang.org/x/net/proxy
-
-// Package proxy provides support for a variety of protocols to proxy network
-// data.
-//
-
-package websocket
-
-import (
- "errors"
- "io"
- "net"
- "net/url"
- "os"
- "strconv"
- "strings"
- "sync"
-)
-
-type proxy_direct struct{}
-
-// Direct is a direct proxy: one that makes network connections directly.
-var proxy_Direct = proxy_direct{}
-
-func (proxy_direct) Dial(network, addr string) (net.Conn, error) {
- return net.Dial(network, addr)
-}
-
-// A PerHost directs connections to a default Dialer unless the host name
-// requested matches one of a number of exceptions.
-type proxy_PerHost struct {
- def, bypass proxy_Dialer
-
- bypassNetworks []*net.IPNet
- bypassIPs []net.IP
- bypassZones []string
- bypassHosts []string
-}
-
-// NewPerHost returns a PerHost Dialer that directs connections to either
-// defaultDialer or bypass, depending on whether the connection matches one of
-// the configured rules.
-func proxy_NewPerHost(defaultDialer, bypass proxy_Dialer) *proxy_PerHost {
- return &proxy_PerHost{
- def: defaultDialer,
- bypass: bypass,
- }
-}
-
-// Dial connects to the address addr on the given network through either
-// defaultDialer or bypass.
-func (p *proxy_PerHost) Dial(network, addr string) (c net.Conn, err error) {
- host, _, err := net.SplitHostPort(addr)
- if err != nil {
- return nil, err
- }
-
- return p.dialerForRequest(host).Dial(network, addr)
-}
-
-func (p *proxy_PerHost) dialerForRequest(host string) proxy_Dialer {
- if ip := net.ParseIP(host); ip != nil {
- for _, net := range p.bypassNetworks {
- if net.Contains(ip) {
- return p.bypass
- }
- }
- for _, bypassIP := range p.bypassIPs {
- if bypassIP.Equal(ip) {
- return p.bypass
- }
- }
- return p.def
- }
-
- for _, zone := range p.bypassZones {
- if strings.HasSuffix(host, zone) {
- return p.bypass
- }
- if host == zone[1:] {
- // For a zone ".example.com", we match "example.com"
- // too.
- return p.bypass
- }
- }
- for _, bypassHost := range p.bypassHosts {
- if bypassHost == host {
- return p.bypass
- }
- }
- return p.def
-}
-
-// AddFromString parses a string that contains comma-separated values
-// specifying hosts that should use the bypass proxy. Each value is either an
-// IP address, a CIDR range, a zone (*.example.com) or a host name
-// (localhost). A best effort is made to parse the string and errors are
-// ignored.
-func (p *proxy_PerHost) AddFromString(s string) {
- hosts := strings.Split(s, ",")
- for _, host := range hosts {
- host = strings.TrimSpace(host)
- if len(host) == 0 {
- continue
- }
- if strings.Contains(host, "/") {
- // We assume that it's a CIDR address like 127.0.0.0/8
- if _, net, err := net.ParseCIDR(host); err == nil {
- p.AddNetwork(net)
- }
- continue
- }
- if ip := net.ParseIP(host); ip != nil {
- p.AddIP(ip)
- continue
- }
- if strings.HasPrefix(host, "*.") {
- p.AddZone(host[1:])
- continue
- }
- p.AddHost(host)
- }
-}
-
-// AddIP specifies an IP address that will use the bypass proxy. Note that
-// this will only take effect if a literal IP address is dialed. A connection
-// to a named host will never match an IP.
-func (p *proxy_PerHost) AddIP(ip net.IP) {
- p.bypassIPs = append(p.bypassIPs, ip)
-}
-
-// AddNetwork specifies an IP range that will use the bypass proxy. Note that
-// this will only take effect if a literal IP address is dialed. A connection
-// to a named host will never match.
-func (p *proxy_PerHost) AddNetwork(net *net.IPNet) {
- p.bypassNetworks = append(p.bypassNetworks, net)
-}
-
-// AddZone specifies a DNS suffix that will use the bypass proxy. A zone of
-// "example.com" matches "example.com" and all of its subdomains.
-func (p *proxy_PerHost) AddZone(zone string) {
- if strings.HasSuffix(zone, ".") {
- zone = zone[:len(zone)-1]
- }
- if !strings.HasPrefix(zone, ".") {
- zone = "." + zone
- }
- p.bypassZones = append(p.bypassZones, zone)
-}
-
-// AddHost specifies a host name that will use the bypass proxy.
-func (p *proxy_PerHost) AddHost(host string) {
- if strings.HasSuffix(host, ".") {
- host = host[:len(host)-1]
- }
- p.bypassHosts = append(p.bypassHosts, host)
-}
-
-// A Dialer is a means to establish a connection.
-type proxy_Dialer interface {
- // Dial connects to the given address via the proxy.
- Dial(network, addr string) (c net.Conn, err error)
-}
-
-// Auth contains authentication parameters that specific Dialers may require.
-type proxy_Auth struct {
- User, Password string
-}
-
-// FromEnvironment returns the dialer specified by the proxy related variables in
-// the environment.
-func proxy_FromEnvironment() proxy_Dialer {
- allProxy := proxy_allProxyEnv.Get()
- if len(allProxy) == 0 {
- return proxy_Direct
- }
-
- proxyURL, err := url.Parse(allProxy)
- if err != nil {
- return proxy_Direct
- }
- proxy, err := proxy_FromURL(proxyURL, proxy_Direct)
- if err != nil {
- return proxy_Direct
- }
-
- noProxy := proxy_noProxyEnv.Get()
- if len(noProxy) == 0 {
- return proxy
- }
-
- perHost := proxy_NewPerHost(proxy, proxy_Direct)
- perHost.AddFromString(noProxy)
- return perHost
-}
-
-// proxySchemes is a map from URL schemes to a function that creates a Dialer
-// from a URL with such a scheme.
-var proxy_proxySchemes map[string]func(*url.URL, proxy_Dialer) (proxy_Dialer, error)
-
-// RegisterDialerType takes a URL scheme and a function to generate Dialers from
-// a URL with that scheme and a forwarding Dialer. Registered schemes are used
-// by FromURL.
-func proxy_RegisterDialerType(scheme string, f func(*url.URL, proxy_Dialer) (proxy_Dialer, error)) {
- if proxy_proxySchemes == nil {
- proxy_proxySchemes = make(map[string]func(*url.URL, proxy_Dialer) (proxy_Dialer, error))
- }
- proxy_proxySchemes[scheme] = f
-}
-
-// FromURL returns a Dialer given a URL specification and an underlying
-// Dialer for it to make network requests.
-func proxy_FromURL(u *url.URL, forward proxy_Dialer) (proxy_Dialer, error) {
- var auth *proxy_Auth
- if u.User != nil {
- auth = new(proxy_Auth)
- auth.User = u.User.Username()
- if p, ok := u.User.Password(); ok {
- auth.Password = p
- }
- }
-
- switch u.Scheme {
- case "socks5":
- return proxy_SOCKS5("tcp", u.Host, auth, forward)
- }
-
- // If the scheme doesn't match any of the built-in schemes, see if it
- // was registered by another package.
- if proxy_proxySchemes != nil {
- if f, ok := proxy_proxySchemes[u.Scheme]; ok {
- return f(u, forward)
- }
- }
-
- return nil, errors.New("proxy: unknown scheme: " + u.Scheme)
-}
-
-var (
- proxy_allProxyEnv = &proxy_envOnce{
- names: []string{"ALL_PROXY", "all_proxy"},
- }
- proxy_noProxyEnv = &proxy_envOnce{
- names: []string{"NO_PROXY", "no_proxy"},
- }
-)
-
-// envOnce looks up an environment variable (optionally by multiple
-// names) once. It mitigates expensive lookups on some platforms
-// (e.g. Windows).
-// (Borrowed from net/http/transport.go)
-type proxy_envOnce struct {
- names []string
- once sync.Once
- val string
-}
-
-func (e *proxy_envOnce) Get() string {
- e.once.Do(e.init)
- return e.val
-}
-
-func (e *proxy_envOnce) init() {
- for _, n := range e.names {
- e.val = os.Getenv(n)
- if e.val != "" {
- return
- }
- }
-}
-
-// SOCKS5 returns a Dialer that makes SOCKSv5 connections to the given address
-// with an optional username and password. See RFC 1928 and RFC 1929.
-func proxy_SOCKS5(network, addr string, auth *proxy_Auth, forward proxy_Dialer) (proxy_Dialer, error) {
- s := &proxy_socks5{
- network: network,
- addr: addr,
- forward: forward,
- }
- if auth != nil {
- s.user = auth.User
- s.password = auth.Password
- }
-
- return s, nil
-}
-
-type proxy_socks5 struct {
- user, password string
- network, addr string
- forward proxy_Dialer
-}
-
-const proxy_socks5Version = 5
-
-const (
- proxy_socks5AuthNone = 0
- proxy_socks5AuthPassword = 2
-)
-
-const proxy_socks5Connect = 1
-
-const (
- proxy_socks5IP4 = 1
- proxy_socks5Domain = 3
- proxy_socks5IP6 = 4
-)
-
-var proxy_socks5Errors = []string{
- "",
- "general failure",
- "connection forbidden",
- "network unreachable",
- "host unreachable",
- "connection refused",
- "TTL expired",
- "command not supported",
- "address type not supported",
-}
-
-// Dial connects to the address addr on the given network via the SOCKS5 proxy.
-func (s *proxy_socks5) Dial(network, addr string) (net.Conn, error) {
- switch network {
- case "tcp", "tcp6", "tcp4":
- default:
- return nil, errors.New("proxy: no support for SOCKS5 proxy connections of type " + network)
- }
-
- conn, err := s.forward.Dial(s.network, s.addr)
- if err != nil {
- return nil, err
- }
- if err := s.connect(conn, addr); err != nil {
- conn.Close()
- return nil, err
- }
- return conn, nil
-}
-
-// connect takes an existing connection to a socks5 proxy server,
-// and commands the server to extend that connection to target,
-// which must be a canonical address with a host and port.
-func (s *proxy_socks5) connect(conn net.Conn, target string) error {
- host, portStr, err := net.SplitHostPort(target)
- if err != nil {
- return err
- }
-
- port, err := strconv.Atoi(portStr)
- if err != nil {
- return errors.New("proxy: failed to parse port number: " + portStr)
- }
- if port < 1 || port > 0xffff {
- return errors.New("proxy: port number out of range: " + portStr)
- }
-
- // the size here is just an estimate
- buf := make([]byte, 0, 6+len(host))
-
- buf = append(buf, proxy_socks5Version)
- if len(s.user) > 0 && len(s.user) < 256 && len(s.password) < 256 {
- buf = append(buf, 2 /* num auth methods */, proxy_socks5AuthNone, proxy_socks5AuthPassword)
- } else {
- buf = append(buf, 1 /* num auth methods */, proxy_socks5AuthNone)
- }
-
- if _, err := conn.Write(buf); err != nil {
- return errors.New("proxy: failed to write greeting to SOCKS5 proxy at " + s.addr + ": " + err.Error())
- }
-
- if _, err := io.ReadFull(conn, buf[:2]); err != nil {
- return errors.New("proxy: failed to read greeting from SOCKS5 proxy at " + s.addr + ": " + err.Error())
- }
- if buf[0] != 5 {
- return errors.New("proxy: SOCKS5 proxy at " + s.addr + " has unexpected version " + strconv.Itoa(int(buf[0])))
- }
- if buf[1] == 0xff {
- return errors.New("proxy: SOCKS5 proxy at " + s.addr + " requires authentication")
- }
-
- // See RFC 1929
- if buf[1] == proxy_socks5AuthPassword {
- buf = buf[:0]
- buf = append(buf, 1 /* password protocol version */)
- buf = append(buf, uint8(len(s.user)))
- buf = append(buf, s.user...)
- buf = append(buf, uint8(len(s.password)))
- buf = append(buf, s.password...)
-
- if _, err := conn.Write(buf); err != nil {
- return errors.New("proxy: failed to write authentication request to SOCKS5 proxy at " + s.addr + ": " + err.Error())
- }
-
- if _, err := io.ReadFull(conn, buf[:2]); err != nil {
- return errors.New("proxy: failed to read authentication reply from SOCKS5 proxy at " + s.addr + ": " + err.Error())
- }
-
- if buf[1] != 0 {
- return errors.New("proxy: SOCKS5 proxy at " + s.addr + " rejected username/password")
- }
- }
-
- buf = buf[:0]
- buf = append(buf, proxy_socks5Version, proxy_socks5Connect, 0 /* reserved */)
-
- if ip := net.ParseIP(host); ip != nil {
- if ip4 := ip.To4(); ip4 != nil {
- buf = append(buf, proxy_socks5IP4)
- ip = ip4
- } else {
- buf = append(buf, proxy_socks5IP6)
- }
- buf = append(buf, ip...)
- } else {
- if len(host) > 255 {
- return errors.New("proxy: destination host name too long: " + host)
- }
- buf = append(buf, proxy_socks5Domain)
- buf = append(buf, byte(len(host)))
- buf = append(buf, host...)
- }
- buf = append(buf, byte(port>>8), byte(port))
-
- if _, err := conn.Write(buf); err != nil {
- return errors.New("proxy: failed to write connect request to SOCKS5 proxy at " + s.addr + ": " + err.Error())
- }
-
- if _, err := io.ReadFull(conn, buf[:4]); err != nil {
- return errors.New("proxy: failed to read connect reply from SOCKS5 proxy at " + s.addr + ": " + err.Error())
- }
-
- failure := "unknown error"
- if int(buf[1]) < len(proxy_socks5Errors) {
- failure = proxy_socks5Errors[buf[1]]
- }
-
- if len(failure) > 0 {
- return errors.New("proxy: SOCKS5 proxy at " + s.addr + " failed to connect: " + failure)
- }
-
- bytesToDiscard := 0
- switch buf[3] {
- case proxy_socks5IP4:
- bytesToDiscard = net.IPv4len
- case proxy_socks5IP6:
- bytesToDiscard = net.IPv6len
- case proxy_socks5Domain:
- _, err := io.ReadFull(conn, buf[:1])
- if err != nil {
- return errors.New("proxy: failed to read domain length from SOCKS5 proxy at " + s.addr + ": " + err.Error())
- }
- bytesToDiscard = int(buf[0])
- default:
- return errors.New("proxy: got unknown address type " + strconv.Itoa(int(buf[3])) + " from SOCKS5 proxy at " + s.addr)
- }
-
- if cap(buf) < bytesToDiscard {
- buf = make([]byte, bytesToDiscard)
- } else {
- buf = buf[:bytesToDiscard]
- }
- if _, err := io.ReadFull(conn, buf); err != nil {
- return errors.New("proxy: failed to read address from SOCKS5 proxy at " + s.addr + ": " + err.Error())
- }
-
- // Also need to discard the port number
- if _, err := io.ReadFull(conn, buf[:2]); err != nil {
- return errors.New("proxy: failed to read port from SOCKS5 proxy at " + s.addr + ": " + err.Error())
- }
-
- return nil
-}
diff --git a/vendor/github.com/graph-gophers/graphql-go/Gopkg.lock b/vendor/github.com/graph-gophers/graphql-go/Gopkg.lock
deleted file mode 100644
index 4574275c5d..0000000000
--- a/vendor/github.com/graph-gophers/graphql-go/Gopkg.lock
+++ /dev/null
@@ -1,25 +0,0 @@
-# This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'.
-
-
-[[projects]]
- name = "github.com/opentracing/opentracing-go"
- packages = [
- ".",
- "ext",
- "log"
- ]
- revision = "1949ddbfd147afd4d964a9f00b24eb291e0e7c38"
- version = "v1.0.2"
-
-[[projects]]
- branch = "master"
- name = "golang.org/x/net"
- packages = ["context"]
- revision = "f5dfe339be1d06f81b22525fe34671ee7d2c8904"
-
-[solve-meta]
- analyzer-name = "dep"
- analyzer-version = 1
- inputs-digest = "f417062128566756a9360b1c13ada79bdeeb6bab1f53ee9147a3328d95c1653f"
- solver-name = "gps-cdcl"
- solver-version = 1
diff --git a/vendor/github.com/graph-gophers/graphql-go/Gopkg.toml b/vendor/github.com/graph-gophers/graphql-go/Gopkg.toml
deleted file mode 100644
index 62b9367998..0000000000
--- a/vendor/github.com/graph-gophers/graphql-go/Gopkg.toml
+++ /dev/null
@@ -1,10 +0,0 @@
-# Refer to https://golang.github.io/dep/docs/Gopkg.toml.html
-# for detailed Gopkg.toml documentation.
-
-[[constraint]]
- name = "github.com/opentracing/opentracing-go"
- version = "1.0.2"
-
-[prune]
- go-tests = true
- unused-packages = true
diff --git a/vendor/github.com/graph-gophers/graphql-go/LICENSE b/vendor/github.com/graph-gophers/graphql-go/LICENSE
deleted file mode 100644
index 3907cecacf..0000000000
--- a/vendor/github.com/graph-gophers/graphql-go/LICENSE
+++ /dev/null
@@ -1,24 +0,0 @@
-Copyright (c) 2016 Richard Musiol. 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.
-
-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/vendor/github.com/graph-gophers/graphql-go/README.md b/vendor/github.com/graph-gophers/graphql-go/README.md
deleted file mode 100644
index ef4b4639b5..0000000000
--- a/vendor/github.com/graph-gophers/graphql-go/README.md
+++ /dev/null
@@ -1,100 +0,0 @@
-# graphql-go [![Sourcegraph](https://sourcegraph.com/github.com/graph-gophers/graphql-go/-/badge.svg)](https://sourcegraph.com/github.com/graph-gophers/graphql-go?badge) [![Build Status](https://semaphoreci.com/api/v1/graph-gophers/graphql-go/branches/master/badge.svg)](https://semaphoreci.com/graph-gophers/graphql-go) [![GoDoc](https://godoc.org/github.com/graph-gophers/graphql-go?status.svg)](https://godoc.org/github.com/graph-gophers/graphql-go)
-
-
-
-The goal of this project is to provide full support of the [GraphQL draft specification](https://facebook.github.io/graphql/draft) with a set of idiomatic, easy to use Go packages.
-
-While still under heavy development (`internal` APIs are almost certainly subject to change), this library is
-safe for production use.
-
-## Features
-
-- minimal API
-- support for `context.Context`
-- support for the `OpenTracing` standard
-- schema type-checking against resolvers
-- resolvers are matched to the schema based on method sets (can resolve a GraphQL schema with a Go interface or Go struct).
-- handles panics in resolvers
-- parallel execution of resolvers
-
-## Roadmap
-
-We're trying out the GitHub Project feature to manage `graphql-go`'s [development roadmap](https://github.com/graph-gophers/graphql-go/projects/1).
-Feedback is welcome and appreciated.
-
-## (Some) Documentation
-
-### Basic Sample
-
-```go
-package main
-
-import (
- "log"
- "net/http"
-
- graphql "github.com/graph-gophers/graphql-go"
- "github.com/graph-gophers/graphql-go/relay"
-)
-
-type query struct{}
-
-func (_ *query) Hello() string { return "Hello, world!" }
-
-func main() {
- s := `
- schema {
- query: Query
- }
- type Query {
- hello: String!
- }
- `
- schema := graphql.MustParseSchema(s, &query{})
- http.Handle("/query", &relay.Handler{Schema: schema})
- log.Fatal(http.ListenAndServe(":8080", nil))
-}
-```
-
-To test:
-```sh
-$ curl -XPOST -d '{"query": "{ hello }"}' localhost:8080/query
-```
-
-### Resolvers
-
-A resolver must have one method for each field of the GraphQL type it resolves. The method name has to be [exported](https://golang.org/ref/spec#Exported_identifiers) and match the field's name in a non-case-sensitive way.
-
-The method has up to two arguments:
-
-- Optional `context.Context` argument.
-- Mandatory `*struct { ... }` argument if the corresponding GraphQL field has arguments. The names of the struct fields have to be [exported](https://golang.org/ref/spec#Exported_identifiers) and have to match the names of the GraphQL arguments in a non-case-sensitive way.
-
-The method has up to two results:
-
-- The GraphQL field's value as determined by the resolver.
-- Optional `error` result.
-
-Example for a simple resolver method:
-
-```go
-func (r *helloWorldResolver) Hello() string {
- return "Hello world!"
-}
-```
-
-The following signature is also allowed:
-
-```go
-func (r *helloWorldResolver) Hello(ctx context.Context) (string, error) {
- return "Hello world!", nil
-}
-```
-
-### Community Examples
-
-[tonyghita/graphql-go-example](https://github.com/tonyghita/graphql-go-example) - A more "productionized" version of the Star Wars API example given in this repository.
-
-[deltaskelta/graphql-go-pets-example](https://github.com/deltaskelta/graphql-go-pets-example) - graphql-go resolving against a sqlite database
-
-[OscarYuen/go-graphql-starter](https://github.com/OscarYuen/go-graphql-starter) - a starter application integrated with dataloader, psql and basic authentication
diff --git a/vendor/github.com/graph-gophers/graphql-go/errors/errors.go b/vendor/github.com/graph-gophers/graphql-go/errors/errors.go
deleted file mode 100644
index fdfa62024d..0000000000
--- a/vendor/github.com/graph-gophers/graphql-go/errors/errors.go
+++ /dev/null
@@ -1,41 +0,0 @@
-package errors
-
-import (
- "fmt"
-)
-
-type QueryError struct {
- Message string `json:"message"`
- Locations []Location `json:"locations,omitempty"`
- Path []interface{} `json:"path,omitempty"`
- Rule string `json:"-"`
- ResolverError error `json:"-"`
-}
-
-type Location struct {
- Line int `json:"line"`
- Column int `json:"column"`
-}
-
-func (a Location) Before(b Location) bool {
- return a.Line < b.Line || (a.Line == b.Line && a.Column < b.Column)
-}
-
-func Errorf(format string, a ...interface{}) *QueryError {
- return &QueryError{
- Message: fmt.Sprintf(format, a...),
- }
-}
-
-func (err *QueryError) Error() string {
- if err == nil {
- return ""
- }
- str := fmt.Sprintf("graphql: %s", err.Message)
- for _, loc := range err.Locations {
- str += fmt.Sprintf(" (line %d, column %d)", loc.Line, loc.Column)
- }
- return str
-}
-
-var _ error = &QueryError{}
diff --git a/vendor/github.com/graph-gophers/graphql-go/graphql.go b/vendor/github.com/graph-gophers/graphql-go/graphql.go
deleted file mode 100644
index 06ffd45997..0000000000
--- a/vendor/github.com/graph-gophers/graphql-go/graphql.go
+++ /dev/null
@@ -1,205 +0,0 @@
-package graphql
-
-import (
- "context"
- "fmt"
-
- "encoding/json"
-
- "github.com/graph-gophers/graphql-go/errors"
- "github.com/graph-gophers/graphql-go/internal/common"
- "github.com/graph-gophers/graphql-go/internal/exec"
- "github.com/graph-gophers/graphql-go/internal/exec/resolvable"
- "github.com/graph-gophers/graphql-go/internal/exec/selected"
- "github.com/graph-gophers/graphql-go/internal/query"
- "github.com/graph-gophers/graphql-go/internal/schema"
- "github.com/graph-gophers/graphql-go/internal/validation"
- "github.com/graph-gophers/graphql-go/introspection"
- "github.com/graph-gophers/graphql-go/log"
- "github.com/graph-gophers/graphql-go/trace"
-)
-
-// ParseSchema parses a GraphQL schema and attaches the given root resolver. It returns an error if
-// the Go type signature of the resolvers does not match the schema. If nil is passed as the
-// resolver, then the schema can not be executed, but it may be inspected (e.g. with ToJSON).
-func ParseSchema(schemaString string, resolver interface{}, opts ...SchemaOpt) (*Schema, error) {
- s := &Schema{
- schema: schema.New(),
- maxParallelism: 10,
- tracer: trace.OpenTracingTracer{},
- validationTracer: trace.NoopValidationTracer{},
- logger: &log.DefaultLogger{},
- }
- for _, opt := range opts {
- opt(s)
- }
-
- if err := s.schema.Parse(schemaString); err != nil {
- return nil, err
- }
-
- if resolver != nil {
- r, err := resolvable.ApplyResolver(s.schema, resolver)
- if err != nil {
- return nil, err
- }
- s.res = r
- }
-
- return s, nil
-}
-
-// MustParseSchema calls ParseSchema and panics on error.
-func MustParseSchema(schemaString string, resolver interface{}, opts ...SchemaOpt) *Schema {
- s, err := ParseSchema(schemaString, resolver, opts...)
- if err != nil {
- panic(err)
- }
- return s
-}
-
-// Schema represents a GraphQL schema with an optional resolver.
-type Schema struct {
- schema *schema.Schema
- res *resolvable.Schema
-
- maxDepth int
- maxParallelism int
- tracer trace.Tracer
- validationTracer trace.ValidationTracer
- logger log.Logger
-}
-
-// SchemaOpt is an option to pass to ParseSchema or MustParseSchema.
-type SchemaOpt func(*Schema)
-
-// MaxDepth specifies the maximum field nesting depth in a query. The default is 0 which disables max depth checking.
-func MaxDepth(n int) SchemaOpt {
- return func(s *Schema) {
- s.maxDepth = n
- }
-}
-
-// MaxParallelism specifies the maximum number of resolvers per request allowed to run in parallel. The default is 10.
-func MaxParallelism(n int) SchemaOpt {
- return func(s *Schema) {
- s.maxParallelism = n
- }
-}
-
-// Tracer is used to trace queries and fields. It defaults to trace.OpenTracingTracer.
-func Tracer(tracer trace.Tracer) SchemaOpt {
- return func(s *Schema) {
- s.tracer = tracer
- }
-}
-
-// ValidationTracer is used to trace validation errors. It defaults to trace.NoopValidationTracer.
-func ValidationTracer(tracer trace.ValidationTracer) SchemaOpt {
- return func(s *Schema) {
- s.validationTracer = tracer
- }
-}
-
-// Logger is used to log panics during query execution. It defaults to exec.DefaultLogger.
-func Logger(logger log.Logger) SchemaOpt {
- return func(s *Schema) {
- s.logger = logger
- }
-}
-
-// Response represents a typical response of a GraphQL server. It may be encoded to JSON directly or
-// it may be further processed to a custom response type, for example to include custom error data.
-// Errors are intentionally serialized first based on the advice in https://github.com/facebook/graphql/commit/7b40390d48680b15cb93e02d46ac5eb249689876#diff-757cea6edf0288677a9eea4cfc801d87R107
-type Response struct {
- Errors []*errors.QueryError `json:"errors,omitempty"`
- Data json.RawMessage `json:"data,omitempty"`
- Extensions map[string]interface{} `json:"extensions,omitempty"`
-}
-
-// Validate validates the given query with the schema.
-func (s *Schema) Validate(queryString string) []*errors.QueryError {
- doc, qErr := query.Parse(queryString)
- if qErr != nil {
- return []*errors.QueryError{qErr}
- }
-
- return validation.Validate(s.schema, doc, s.maxDepth)
-}
-
-// Exec executes the given query with the schema's resolver. It panics if the schema was created
-// without a resolver. If the context get cancelled, no further resolvers will be called and a
-// the context error will be returned as soon as possible (not immediately).
-func (s *Schema) Exec(ctx context.Context, queryString string, operationName string, variables map[string]interface{}) *Response {
- if s.res == nil {
- panic("schema created without resolver, can not exec")
- }
- return s.exec(ctx, queryString, operationName, variables, s.res)
-}
-
-func (s *Schema) exec(ctx context.Context, queryString string, operationName string, variables map[string]interface{}, res *resolvable.Schema) *Response {
- doc, qErr := query.Parse(queryString)
- if qErr != nil {
- return &Response{Errors: []*errors.QueryError{qErr}}
- }
-
- validationFinish := s.validationTracer.TraceValidation()
- errs := validation.Validate(s.schema, doc, s.maxDepth)
- validationFinish(errs)
- if len(errs) != 0 {
- return &Response{Errors: errs}
- }
-
- op, err := getOperation(doc, operationName)
- if err != nil {
- return &Response{Errors: []*errors.QueryError{errors.Errorf("%s", err)}}
- }
-
- r := &exec.Request{
- Request: selected.Request{
- Doc: doc,
- Vars: variables,
- Schema: s.schema,
- },
- Limiter: make(chan struct{}, s.maxParallelism),
- Tracer: s.tracer,
- Logger: s.logger,
- }
- varTypes := make(map[string]*introspection.Type)
- for _, v := range op.Vars {
- t, err := common.ResolveType(v.Type, s.schema.Resolve)
- if err != nil {
- return &Response{Errors: []*errors.QueryError{err}}
- }
- varTypes[v.Name.Name] = introspection.WrapType(t)
- }
- traceCtx, finish := s.tracer.TraceQuery(ctx, queryString, operationName, variables, varTypes)
- data, errs := r.Execute(traceCtx, res, op)
- finish(errs)
-
- return &Response{
- Data: data,
- Errors: errs,
- }
-}
-
-func getOperation(document *query.Document, operationName string) (*query.Operation, error) {
- if len(document.Operations) == 0 {
- return nil, fmt.Errorf("no operations in query document")
- }
-
- if operationName == "" {
- if len(document.Operations) > 1 {
- return nil, fmt.Errorf("more than one operation in query document and no operation name given")
- }
- for _, op := range document.Operations {
- return op, nil // return the one and only operation
- }
- }
-
- op := document.Operations.Get(operationName)
- if op == nil {
- return nil, fmt.Errorf("no operation with name %q", operationName)
- }
- return op, nil
-}
diff --git a/vendor/github.com/graph-gophers/graphql-go/id.go b/vendor/github.com/graph-gophers/graphql-go/id.go
deleted file mode 100644
index 52771c413b..0000000000
--- a/vendor/github.com/graph-gophers/graphql-go/id.go
+++ /dev/null
@@ -1,30 +0,0 @@
-package graphql
-
-import (
- "errors"
- "strconv"
-)
-
-// ID represents GraphQL's "ID" scalar type. A custom type may be used instead.
-type ID string
-
-func (ID) ImplementsGraphQLType(name string) bool {
- return name == "ID"
-}
-
-func (id *ID) UnmarshalGraphQL(input interface{}) error {
- var err error
- switch input := input.(type) {
- case string:
- *id = ID(input)
- case int32:
- *id = ID(strconv.Itoa(int(input)))
- default:
- err = errors.New("wrong type")
- }
- return err
-}
-
-func (id ID) MarshalJSON() ([]byte, error) {
- return strconv.AppendQuote(nil, string(id)), nil
-}
diff --git a/vendor/github.com/graph-gophers/graphql-go/internal/common/directive.go b/vendor/github.com/graph-gophers/graphql-go/internal/common/directive.go
deleted file mode 100644
index 62dca47f81..0000000000
--- a/vendor/github.com/graph-gophers/graphql-go/internal/common/directive.go
+++ /dev/null
@@ -1,32 +0,0 @@
-package common
-
-type Directive struct {
- Name Ident
- Args ArgumentList
-}
-
-func ParseDirectives(l *Lexer) DirectiveList {
- var directives DirectiveList
- for l.Peek() == '@' {
- l.ConsumeToken('@')
- d := &Directive{}
- d.Name = l.ConsumeIdentWithLoc()
- d.Name.Loc.Column--
- if l.Peek() == '(' {
- d.Args = ParseArguments(l)
- }
- directives = append(directives, d)
- }
- return directives
-}
-
-type DirectiveList []*Directive
-
-func (l DirectiveList) Get(name string) *Directive {
- for _, d := range l {
- if d.Name.Name == name {
- return d
- }
- }
- return nil
-}
diff --git a/vendor/github.com/graph-gophers/graphql-go/internal/common/lexer.go b/vendor/github.com/graph-gophers/graphql-go/internal/common/lexer.go
deleted file mode 100644
index a38fcbaf70..0000000000
--- a/vendor/github.com/graph-gophers/graphql-go/internal/common/lexer.go
+++ /dev/null
@@ -1,161 +0,0 @@
-package common
-
-import (
- "fmt"
- "strings"
- "text/scanner"
-
- "github.com/graph-gophers/graphql-go/errors"
-)
-
-type syntaxError string
-
-type Lexer struct {
- sc *scanner.Scanner
- next rune
- descComment string
-}
-
-type Ident struct {
- Name string
- Loc errors.Location
-}
-
-func NewLexer(s string) *Lexer {
- sc := &scanner.Scanner{
- Mode: scanner.ScanIdents | scanner.ScanInts | scanner.ScanFloats | scanner.ScanStrings,
- }
- sc.Init(strings.NewReader(s))
-
- return &Lexer{sc: sc}
-}
-
-func (l *Lexer) CatchSyntaxError(f func()) (errRes *errors.QueryError) {
- defer func() {
- if err := recover(); err != nil {
- if err, ok := err.(syntaxError); ok {
- errRes = errors.Errorf("syntax error: %s", err)
- errRes.Locations = []errors.Location{l.Location()}
- return
- }
- panic(err)
- }
- }()
-
- f()
- return
-}
-
-func (l *Lexer) Peek() rune {
- return l.next
-}
-
-// Consume whitespace and tokens equivalent to whitespace (e.g. commas and comments).
-//
-// Consumed comment characters will build the description for the next type or field encountered.
-// The description is available from `DescComment()`, and will be reset every time `Consume()` is
-// executed.
-func (l *Lexer) Consume() {
- l.descComment = ""
- for {
- l.next = l.sc.Scan()
-
- if l.next == ',' {
- // Similar to white space and line terminators, commas (',') are used to improve the
- // legibility of source text and separate lexical tokens but are otherwise syntactically and
- // semantically insignificant within GraphQL documents.
- //
- // http://facebook.github.io/graphql/draft/#sec-Insignificant-Commas
- continue
- }
-
- if l.next == '#' {
- // GraphQL source documents may contain single-line comments, starting with the '#' marker.
- //
- // A comment can contain any Unicode code point except `LineTerminator` so a comment always
- // consists of all code points starting with the '#' character up to but not including the
- // line terminator.
-
- l.consumeComment()
- continue
- }
-
- break
- }
-}
-
-func (l *Lexer) ConsumeIdent() string {
- name := l.sc.TokenText()
- l.ConsumeToken(scanner.Ident)
- return name
-}
-
-func (l *Lexer) ConsumeIdentWithLoc() Ident {
- loc := l.Location()
- name := l.sc.TokenText()
- l.ConsumeToken(scanner.Ident)
- return Ident{name, loc}
-}
-
-func (l *Lexer) ConsumeKeyword(keyword string) {
- if l.next != scanner.Ident || l.sc.TokenText() != keyword {
- l.SyntaxError(fmt.Sprintf("unexpected %q, expecting %q", l.sc.TokenText(), keyword))
- }
- l.Consume()
-}
-
-func (l *Lexer) ConsumeLiteral() *BasicLit {
- lit := &BasicLit{Type: l.next, Text: l.sc.TokenText()}
- l.Consume()
- return lit
-}
-
-func (l *Lexer) ConsumeToken(expected rune) {
- if l.next != expected {
- l.SyntaxError(fmt.Sprintf("unexpected %q, expecting %s", l.sc.TokenText(), scanner.TokenString(expected)))
- }
- l.Consume()
-}
-
-func (l *Lexer) DescComment() string {
- return l.descComment
-}
-
-func (l *Lexer) SyntaxError(message string) {
- panic(syntaxError(message))
-}
-
-func (l *Lexer) Location() errors.Location {
- return errors.Location{
- Line: l.sc.Line,
- Column: l.sc.Column,
- }
-}
-
-// consumeComment consumes all characters from `#` to the first encountered line terminator.
-// The characters are appended to `l.descComment`.
-func (l *Lexer) consumeComment() {
- if l.next != '#' {
- return
- }
-
- // TODO: count and trim whitespace so we can dedent any following lines.
- if l.sc.Peek() == ' ' {
- l.sc.Next()
- }
-
- if l.descComment != "" {
- // TODO: use a bytes.Buffer or strings.Builder instead of this.
- l.descComment += "\n"
- }
-
- for {
- next := l.sc.Next()
- if next == '\r' || next == '\n' || next == scanner.EOF {
- break
- }
-
- // TODO: use a bytes.Buffer or strings.Build instead of this.
- l.descComment += string(next)
- }
-}
diff --git a/vendor/github.com/graph-gophers/graphql-go/internal/common/literals.go b/vendor/github.com/graph-gophers/graphql-go/internal/common/literals.go
deleted file mode 100644
index e7bbe2638e..0000000000
--- a/vendor/github.com/graph-gophers/graphql-go/internal/common/literals.go
+++ /dev/null
@@ -1,206 +0,0 @@
-package common
-
-import (
- "strconv"
- "strings"
- "text/scanner"
-
- "github.com/graph-gophers/graphql-go/errors"
-)
-
-type Literal interface {
- Value(vars map[string]interface{}) interface{}
- String() string
- Location() errors.Location
-}
-
-type BasicLit struct {
- Type rune
- Text string
- Loc errors.Location
-}
-
-func (lit *BasicLit) Value(vars map[string]interface{}) interface{} {
- switch lit.Type {
- case scanner.Int:
- value, err := strconv.ParseInt(lit.Text, 10, 32)
- if err != nil {
- panic(err)
- }
- return int32(value)
-
- case scanner.Float:
- value, err := strconv.ParseFloat(lit.Text, 64)
- if err != nil {
- panic(err)
- }
- return value
-
- case scanner.String:
- value, err := strconv.Unquote(lit.Text)
- if err != nil {
- panic(err)
- }
- return value
-
- case scanner.Ident:
- switch lit.Text {
- case "true":
- return true
- case "false":
- return false
- default:
- return lit.Text
- }
-
- default:
- panic("invalid literal")
- }
-}
-
-func (lit *BasicLit) String() string {
- return lit.Text
-}
-
-func (lit *BasicLit) Location() errors.Location {
- return lit.Loc
-}
-
-type ListLit struct {
- Entries []Literal
- Loc errors.Location
-}
-
-func (lit *ListLit) Value(vars map[string]interface{}) interface{} {
- entries := make([]interface{}, len(lit.Entries))
- for i, entry := range lit.Entries {
- entries[i] = entry.Value(vars)
- }
- return entries
-}
-
-func (lit *ListLit) String() string {
- entries := make([]string, len(lit.Entries))
- for i, entry := range lit.Entries {
- entries[i] = entry.String()
- }
- return "[" + strings.Join(entries, ", ") + "]"
-}
-
-func (lit *ListLit) Location() errors.Location {
- return lit.Loc
-}
-
-type ObjectLit struct {
- Fields []*ObjectLitField
- Loc errors.Location
-}
-
-type ObjectLitField struct {
- Name Ident
- Value Literal
-}
-
-func (lit *ObjectLit) Value(vars map[string]interface{}) interface{} {
- fields := make(map[string]interface{}, len(lit.Fields))
- for _, f := range lit.Fields {
- fields[f.Name.Name] = f.Value.Value(vars)
- }
- return fields
-}
-
-func (lit *ObjectLit) String() string {
- entries := make([]string, 0, len(lit.Fields))
- for _, f := range lit.Fields {
- entries = append(entries, f.Name.Name+": "+f.Value.String())
- }
- return "{" + strings.Join(entries, ", ") + "}"
-}
-
-func (lit *ObjectLit) Location() errors.Location {
- return lit.Loc
-}
-
-type NullLit struct {
- Loc errors.Location
-}
-
-func (lit *NullLit) Value(vars map[string]interface{}) interface{} {
- return nil
-}
-
-func (lit *NullLit) String() string {
- return "null"
-}
-
-func (lit *NullLit) Location() errors.Location {
- return lit.Loc
-}
-
-type Variable struct {
- Name string
- Loc errors.Location
-}
-
-func (v Variable) Value(vars map[string]interface{}) interface{} {
- return vars[v.Name]
-}
-
-func (v Variable) String() string {
- return "$" + v.Name
-}
-
-func (v *Variable) Location() errors.Location {
- return v.Loc
-}
-
-func ParseLiteral(l *Lexer, constOnly bool) Literal {
- loc := l.Location()
- switch l.Peek() {
- case '$':
- if constOnly {
- l.SyntaxError("variable not allowed")
- panic("unreachable")
- }
- l.ConsumeToken('$')
- return &Variable{l.ConsumeIdent(), loc}
-
- case scanner.Int, scanner.Float, scanner.String, scanner.Ident:
- lit := l.ConsumeLiteral()
- if lit.Type == scanner.Ident && lit.Text == "null" {
- return &NullLit{loc}
- }
- lit.Loc = loc
- return lit
- case '-':
- l.ConsumeToken('-')
- lit := l.ConsumeLiteral()
- lit.Text = "-" + lit.Text
- lit.Loc = loc
- return lit
- case '[':
- l.ConsumeToken('[')
- var list []Literal
- for l.Peek() != ']' {
- list = append(list, ParseLiteral(l, constOnly))
- }
- l.ConsumeToken(']')
- return &ListLit{list, loc}
-
- case '{':
- l.ConsumeToken('{')
- var fields []*ObjectLitField
- for l.Peek() != '}' {
- name := l.ConsumeIdentWithLoc()
- l.ConsumeToken(':')
- value := ParseLiteral(l, constOnly)
- fields = append(fields, &ObjectLitField{name, value})
- }
- l.ConsumeToken('}')
- return &ObjectLit{fields, loc}
-
- default:
- l.SyntaxError("invalid value")
- panic("unreachable")
- }
-}
diff --git a/vendor/github.com/graph-gophers/graphql-go/internal/common/types.go b/vendor/github.com/graph-gophers/graphql-go/internal/common/types.go
deleted file mode 100644
index a20ca30906..0000000000
--- a/vendor/github.com/graph-gophers/graphql-go/internal/common/types.go
+++ /dev/null
@@ -1,80 +0,0 @@
-package common
-
-import (
- "github.com/graph-gophers/graphql-go/errors"
-)
-
-type Type interface {
- Kind() string
- String() string
-}
-
-type List struct {
- OfType Type
-}
-
-type NonNull struct {
- OfType Type
-}
-
-type TypeName struct {
- Ident
-}
-
-func (*List) Kind() string { return "LIST" }
-func (*NonNull) Kind() string { return "NON_NULL" }
-func (*TypeName) Kind() string { panic("TypeName needs to be resolved to actual type") }
-
-func (t *List) String() string { return "[" + t.OfType.String() + "]" }
-func (t *NonNull) String() string { return t.OfType.String() + "!" }
-func (*TypeName) String() string { panic("TypeName needs to be resolved to actual type") }
-
-func ParseType(l *Lexer) Type {
- t := parseNullType(l)
- if l.Peek() == '!' {
- l.ConsumeToken('!')
- return &NonNull{OfType: t}
- }
- return t
-}
-
-func parseNullType(l *Lexer) Type {
- if l.Peek() == '[' {
- l.ConsumeToken('[')
- ofType := ParseType(l)
- l.ConsumeToken(']')
- return &List{OfType: ofType}
- }
-
- return &TypeName{Ident: l.ConsumeIdentWithLoc()}
-}
-
-type Resolver func(name string) Type
-
-func ResolveType(t Type, resolver Resolver) (Type, *errors.QueryError) {
- switch t := t.(type) {
- case *List:
- ofType, err := ResolveType(t.OfType, resolver)
- if err != nil {
- return nil, err
- }
- return &List{OfType: ofType}, nil
- case *NonNull:
- ofType, err := ResolveType(t.OfType, resolver)
- if err != nil {
- return nil, err
- }
- return &NonNull{OfType: ofType}, nil
- case *TypeName:
- refT := resolver(t.Name)
- if refT == nil {
- err := errors.Errorf("Unknown type %q.", t.Name)
- err.Rule = "KnownTypeNames"
- err.Locations = []errors.Location{t.Loc}
- return nil, err
- }
- return refT, nil
- default:
- return t, nil
- }
-}
diff --git a/vendor/github.com/graph-gophers/graphql-go/internal/common/values.go b/vendor/github.com/graph-gophers/graphql-go/internal/common/values.go
deleted file mode 100644
index fcd456abfa..0000000000
--- a/vendor/github.com/graph-gophers/graphql-go/internal/common/values.go
+++ /dev/null
@@ -1,78 +0,0 @@
-package common
-
-import (
- "github.com/graph-gophers/graphql-go/errors"
-)
-
-// http://facebook.github.io/graphql/draft/#InputValueDefinition
-type InputValue struct {
- Name Ident
- Type Type
- Default Literal
- Desc string
- Loc errors.Location
- TypeLoc errors.Location
-}
-
-type InputValueList []*InputValue
-
-func (l InputValueList) Get(name string) *InputValue {
- for _, v := range l {
- if v.Name.Name == name {
- return v
- }
- }
- return nil
-}
-
-func ParseInputValue(l *Lexer) *InputValue {
- p := &InputValue{}
- p.Loc = l.Location()
- p.Desc = l.DescComment()
- p.Name = l.ConsumeIdentWithLoc()
- l.ConsumeToken(':')
- p.TypeLoc = l.Location()
- p.Type = ParseType(l)
- if l.Peek() == '=' {
- l.ConsumeToken('=')
- p.Default = ParseLiteral(l, true)
- }
- return p
-}
-
-type Argument struct {
- Name Ident
- Value Literal
-}
-
-type ArgumentList []Argument
-
-func (l ArgumentList) Get(name string) (Literal, bool) {
- for _, arg := range l {
- if arg.Name.Name == name {
- return arg.Value, true
- }
- }
- return nil, false
-}
-
-func (l ArgumentList) MustGet(name string) Literal {
- value, ok := l.Get(name)
- if !ok {
- panic("argument not found")
- }
- return value
-}
-
-func ParseArguments(l *Lexer) ArgumentList {
- var args ArgumentList
- l.ConsumeToken('(')
- for l.Peek() != ')' {
- name := l.ConsumeIdentWithLoc()
- l.ConsumeToken(':')
- value := ParseLiteral(l, false)
- args = append(args, Argument{Name: name, Value: value})
- }
- l.ConsumeToken(')')
- return args
-}
diff --git a/vendor/github.com/graph-gophers/graphql-go/internal/exec/exec.go b/vendor/github.com/graph-gophers/graphql-go/internal/exec/exec.go
deleted file mode 100644
index e6cca7448d..0000000000
--- a/vendor/github.com/graph-gophers/graphql-go/internal/exec/exec.go
+++ /dev/null
@@ -1,305 +0,0 @@
-package exec
-
-import (
- "bytes"
- "context"
- "encoding/json"
- "reflect"
- "sync"
-
- "github.com/graph-gophers/graphql-go/errors"
- "github.com/graph-gophers/graphql-go/internal/common"
- "github.com/graph-gophers/graphql-go/internal/exec/resolvable"
- "github.com/graph-gophers/graphql-go/internal/exec/selected"
- "github.com/graph-gophers/graphql-go/internal/query"
- "github.com/graph-gophers/graphql-go/internal/schema"
- "github.com/graph-gophers/graphql-go/log"
- "github.com/graph-gophers/graphql-go/trace"
-)
-
-type Request struct {
- selected.Request
- Limiter chan struct{}
- Tracer trace.Tracer
- Logger log.Logger
-}
-
-func (r *Request) handlePanic(ctx context.Context) {
- if value := recover(); value != nil {
- r.Logger.LogPanic(ctx, value)
- r.AddError(makePanicError(value))
- }
-}
-
-func makePanicError(value interface{}) *errors.QueryError {
- return errors.Errorf("graphql: panic occurred: %v", value)
-}
-
-func (r *Request) Execute(ctx context.Context, s *resolvable.Schema, op *query.Operation) ([]byte, []*errors.QueryError) {
- var out bytes.Buffer
- func() {
- defer r.handlePanic(ctx)
- sels := selected.ApplyOperation(&r.Request, s, op)
- r.execSelections(ctx, sels, nil, s.Resolver, &out, op.Type == query.Mutation)
- }()
-
- if err := ctx.Err(); err != nil {
- return nil, []*errors.QueryError{errors.Errorf("%s", err)}
- }
-
- return out.Bytes(), r.Errs
-}
-
-type fieldToExec struct {
- field *selected.SchemaField
- sels []selected.Selection
- resolver reflect.Value
- out *bytes.Buffer
-}
-
-func (r *Request) execSelections(ctx context.Context, sels []selected.Selection, path *pathSegment, resolver reflect.Value, out *bytes.Buffer, serially bool) {
- async := !serially && selected.HasAsyncSel(sels)
-
- var fields []*fieldToExec
- collectFieldsToResolve(sels, resolver, &fields, make(map[string]*fieldToExec))
-
- if async {
- var wg sync.WaitGroup
- wg.Add(len(fields))
- for _, f := range fields {
- go func(f *fieldToExec) {
- defer wg.Done()
- defer r.handlePanic(ctx)
- f.out = new(bytes.Buffer)
- execFieldSelection(ctx, r, f, &pathSegment{path, f.field.Alias}, true)
- }(f)
- }
- wg.Wait()
- }
-
- out.WriteByte('{')
- for i, f := range fields {
- if i > 0 {
- out.WriteByte(',')
- }
- out.WriteByte('"')
- out.WriteString(f.field.Alias)
- out.WriteByte('"')
- out.WriteByte(':')
- if async {
- out.Write(f.out.Bytes())
- continue
- }
- f.out = out
- execFieldSelection(ctx, r, f, &pathSegment{path, f.field.Alias}, false)
- }
- out.WriteByte('}')
-}
-
-func collectFieldsToResolve(sels []selected.Selection, resolver reflect.Value, fields *[]*fieldToExec, fieldByAlias map[string]*fieldToExec) {
- for _, sel := range sels {
- switch sel := sel.(type) {
- case *selected.SchemaField:
- field, ok := fieldByAlias[sel.Alias]
- if !ok { // validation already checked for conflict (TODO)
- field = &fieldToExec{field: sel, resolver: resolver}
- fieldByAlias[sel.Alias] = field
- *fields = append(*fields, field)
- }
- field.sels = append(field.sels, sel.Sels...)
-
- case *selected.TypenameField:
- sf := &selected.SchemaField{
- Field: resolvable.MetaFieldTypename,
- Alias: sel.Alias,
- FixedResult: reflect.ValueOf(typeOf(sel, resolver)),
- }
- *fields = append(*fields, &fieldToExec{field: sf, resolver: resolver})
-
- case *selected.TypeAssertion:
- out := resolver.Method(sel.MethodIndex).Call(nil)
- if !out[1].Bool() {
- continue
- }
- collectFieldsToResolve(sel.Sels, out[0], fields, fieldByAlias)
-
- default:
- panic("unreachable")
- }
- }
-}
-
-func typeOf(tf *selected.TypenameField, resolver reflect.Value) string {
- if len(tf.TypeAssertions) == 0 {
- return tf.Name
- }
- for name, a := range tf.TypeAssertions {
- out := resolver.Method(a.MethodIndex).Call(nil)
- if out[1].Bool() {
- return name
- }
- }
- return ""
-}
-
-func execFieldSelection(ctx context.Context, r *Request, f *fieldToExec, path *pathSegment, applyLimiter bool) {
- if applyLimiter {
- r.Limiter <- struct{}{}
- }
-
- var result reflect.Value
- var err *errors.QueryError
-
- traceCtx, finish := r.Tracer.TraceField(ctx, f.field.TraceLabel, f.field.TypeName, f.field.Name, !f.field.Async, f.field.Args)
- defer func() {
- finish(err)
- }()
-
- err = func() (err *errors.QueryError) {
- defer func() {
- if panicValue := recover(); panicValue != nil {
- r.Logger.LogPanic(ctx, panicValue)
- err = makePanicError(panicValue)
- err.Path = path.toSlice()
- }
- }()
-
- if f.field.FixedResult.IsValid() {
- result = f.field.FixedResult
- return nil
- }
-
- if err := traceCtx.Err(); err != nil {
- return errors.Errorf("%s", err) // don't execute any more resolvers if context got cancelled
- }
-
- var in []reflect.Value
- if f.field.HasContext {
- in = append(in, reflect.ValueOf(traceCtx))
- }
- if f.field.ArgsPacker != nil {
- in = append(in, f.field.PackedArgs)
- }
- callOut := f.resolver.Method(f.field.MethodIndex).Call(in)
- result = callOut[0]
- if f.field.HasError && !callOut[1].IsNil() {
- resolverErr := callOut[1].Interface().(error)
- err := errors.Errorf("%s", resolverErr)
- err.Path = path.toSlice()
- err.ResolverError = resolverErr
- return err
- }
- return nil
- }()
-
- if applyLimiter {
- <-r.Limiter
- }
-
- if err != nil {
- r.AddError(err)
- f.out.WriteString("null") // TODO handle non-nil
- return
- }
-
- r.execSelectionSet(traceCtx, f.sels, f.field.Type, path, result, f.out)
-}
-
-func (r *Request) execSelectionSet(ctx context.Context, sels []selected.Selection, typ common.Type, path *pathSegment, resolver reflect.Value, out *bytes.Buffer) {
- t, nonNull := unwrapNonNull(typ)
- switch t := t.(type) {
- case *schema.Object, *schema.Interface, *schema.Union:
- // a reflect.Value of a nil interface will show up as an Invalid value
- if resolver.Kind() == reflect.Invalid || ((resolver.Kind() == reflect.Ptr || resolver.Kind() == reflect.Interface) && resolver.IsNil()) {
- if nonNull {
- panic(errors.Errorf("got nil for non-null %q", t))
- }
- out.WriteString("null")
- return
- }
-
- r.execSelections(ctx, sels, path, resolver, out, false)
- return
- }
-
- if !nonNull {
- if resolver.IsNil() {
- out.WriteString("null")
- return
- }
- resolver = resolver.Elem()
- }
-
- switch t := t.(type) {
- case *common.List:
- l := resolver.Len()
-
- if selected.HasAsyncSel(sels) {
- var wg sync.WaitGroup
- wg.Add(l)
- entryouts := make([]bytes.Buffer, l)
- for i := 0; i < l; i++ {
- go func(i int) {
- defer wg.Done()
- defer r.handlePanic(ctx)
- r.execSelectionSet(ctx, sels, t.OfType, &pathSegment{path, i}, resolver.Index(i), &entryouts[i])
- }(i)
- }
- wg.Wait()
-
- out.WriteByte('[')
- for i, entryout := range entryouts {
- if i > 0 {
- out.WriteByte(',')
- }
- out.Write(entryout.Bytes())
- }
- out.WriteByte(']')
- return
- }
-
- out.WriteByte('[')
- for i := 0; i < l; i++ {
- if i > 0 {
- out.WriteByte(',')
- }
- r.execSelectionSet(ctx, sels, t.OfType, &pathSegment{path, i}, resolver.Index(i), out)
- }
- out.WriteByte(']')
-
- case *schema.Scalar:
- v := resolver.Interface()
- data, err := json.Marshal(v)
- if err != nil {
- panic(errors.Errorf("could not marshal %v: %s", v, err))
- }
- out.Write(data)
-
- case *schema.Enum:
- out.WriteByte('"')
- out.WriteString(resolver.String())
- out.WriteByte('"')
-
- default:
- panic("unreachable")
- }
-}
-
-func unwrapNonNull(t common.Type) (common.Type, bool) {
- if nn, ok := t.(*common.NonNull); ok {
- return nn.OfType, true
- }
- return t, false
-}
-
-type pathSegment struct {
- parent *pathSegment
- value interface{}
-}
-
-func (p *pathSegment) toSlice() []interface{} {
- if p == nil {
- return nil
- }
- return append(p.parent.toSlice(), p.value)
-}
diff --git a/vendor/github.com/graph-gophers/graphql-go/internal/exec/packer/packer.go b/vendor/github.com/graph-gophers/graphql-go/internal/exec/packer/packer.go
deleted file mode 100644
index 22706bcd1f..0000000000
--- a/vendor/github.com/graph-gophers/graphql-go/internal/exec/packer/packer.go
+++ /dev/null
@@ -1,371 +0,0 @@
-package packer
-
-import (
- "fmt"
- "math"
- "reflect"
- "strings"
-
- "github.com/graph-gophers/graphql-go/errors"
- "github.com/graph-gophers/graphql-go/internal/common"
- "github.com/graph-gophers/graphql-go/internal/schema"
-)
-
-type packer interface {
- Pack(value interface{}) (reflect.Value, error)
-}
-
-type Builder struct {
- packerMap map[typePair]*packerMapEntry
- structPackers []*StructPacker
-}
-
-type typePair struct {
- graphQLType common.Type
- resolverType reflect.Type
-}
-
-type packerMapEntry struct {
- packer packer
- targets []*packer
-}
-
-func NewBuilder() *Builder {
- return &Builder{
- packerMap: make(map[typePair]*packerMapEntry),
- }
-}
-
-func (b *Builder) Finish() error {
- for _, entry := range b.packerMap {
- for _, target := range entry.targets {
- *target = entry.packer
- }
- }
-
- for _, p := range b.structPackers {
- p.defaultStruct = reflect.New(p.structType).Elem()
- for _, f := range p.fields {
- if defaultVal := f.field.Default; defaultVal != nil {
- v, err := f.fieldPacker.Pack(defaultVal.Value(nil))
- if err != nil {
- return err
- }
- p.defaultStruct.FieldByIndex(f.fieldIndex).Set(v)
- }
- }
- }
-
- return nil
-}
-
-func (b *Builder) assignPacker(target *packer, schemaType common.Type, reflectType reflect.Type) error {
- k := typePair{schemaType, reflectType}
- ref, ok := b.packerMap[k]
- if !ok {
- ref = &packerMapEntry{}
- b.packerMap[k] = ref
- var err error
- ref.packer, err = b.makePacker(schemaType, reflectType)
- if err != nil {
- return err
- }
- }
- ref.targets = append(ref.targets, target)
- return nil
-}
-
-func (b *Builder) makePacker(schemaType common.Type, reflectType reflect.Type) (packer, error) {
- t, nonNull := unwrapNonNull(schemaType)
- if !nonNull {
- if reflectType.Kind() != reflect.Ptr {
- return nil, fmt.Errorf("%s is not a pointer", reflectType)
- }
- elemType := reflectType.Elem()
- addPtr := true
- if _, ok := t.(*schema.InputObject); ok {
- elemType = reflectType // keep pointer for input objects
- addPtr = false
- }
- elem, err := b.makeNonNullPacker(t, elemType)
- if err != nil {
- return nil, err
- }
- return &nullPacker{
- elemPacker: elem,
- valueType: reflectType,
- addPtr: addPtr,
- }, nil
- }
-
- return b.makeNonNullPacker(t, reflectType)
-}
-
-func (b *Builder) makeNonNullPacker(schemaType common.Type, reflectType reflect.Type) (packer, error) {
- if u, ok := reflect.New(reflectType).Interface().(Unmarshaler); ok {
- if !u.ImplementsGraphQLType(schemaType.String()) {
- return nil, fmt.Errorf("can not unmarshal %s into %s", schemaType, reflectType)
- }
- return &unmarshalerPacker{
- ValueType: reflectType,
- }, nil
- }
-
- switch t := schemaType.(type) {
- case *schema.Scalar:
- return &ValuePacker{
- ValueType: reflectType,
- }, nil
-
- case *schema.Enum:
- if reflectType.Kind() != reflect.String {
- return nil, fmt.Errorf("wrong type, expected %s", reflect.String)
- }
- return &ValuePacker{
- ValueType: reflectType,
- }, nil
-
- case *schema.InputObject:
- e, err := b.MakeStructPacker(t.Values, reflectType)
- if err != nil {
- return nil, err
- }
- return e, nil
-
- case *common.List:
- if reflectType.Kind() != reflect.Slice {
- return nil, fmt.Errorf("expected slice, got %s", reflectType)
- }
- p := &listPacker{
- sliceType: reflectType,
- }
- if err := b.assignPacker(&p.elem, t.OfType, reflectType.Elem()); err != nil {
- return nil, err
- }
- return p, nil
-
- case *schema.Object, *schema.Interface, *schema.Union:
- return nil, fmt.Errorf("type of kind %s can not be used as input", t.Kind())
-
- default:
- panic("unreachable")
- }
-}
-
-func (b *Builder) MakeStructPacker(values common.InputValueList, typ reflect.Type) (*StructPacker, error) {
- structType := typ
- usePtr := false
- if typ.Kind() == reflect.Ptr {
- structType = typ.Elem()
- usePtr = true
- }
- if structType.Kind() != reflect.Struct {
- return nil, fmt.Errorf("expected struct or pointer to struct, got %s", typ)
- }
-
- var fields []*structPackerField
- for _, v := range values {
- fe := &structPackerField{field: v}
- fx := func(n string) bool {
- return strings.EqualFold(stripUnderscore(n), stripUnderscore(v.Name.Name))
- }
-
- sf, ok := structType.FieldByNameFunc(fx)
- if !ok {
- return nil, fmt.Errorf("missing argument %q", v.Name)
- }
- if sf.PkgPath != "" {
- return nil, fmt.Errorf("field %q must be exported", sf.Name)
- }
- fe.fieldIndex = sf.Index
-
- ft := v.Type
- if v.Default != nil {
- ft, _ = unwrapNonNull(ft)
- ft = &common.NonNull{OfType: ft}
- }
-
- if err := b.assignPacker(&fe.fieldPacker, ft, sf.Type); err != nil {
- return nil, fmt.Errorf("field %q: %s", sf.Name, err)
- }
-
- fields = append(fields, fe)
- }
-
- p := &StructPacker{
- structType: structType,
- usePtr: usePtr,
- fields: fields,
- }
- b.structPackers = append(b.structPackers, p)
- return p, nil
-}
-
-type StructPacker struct {
- structType reflect.Type
- usePtr bool
- defaultStruct reflect.Value
- fields []*structPackerField
-}
-
-type structPackerField struct {
- field *common.InputValue
- fieldIndex []int
- fieldPacker packer
-}
-
-func (p *StructPacker) Pack(value interface{}) (reflect.Value, error) {
- if value == nil {
- return reflect.Value{}, errors.Errorf("got null for non-null")
- }
-
- values := value.(map[string]interface{})
- v := reflect.New(p.structType)
- v.Elem().Set(p.defaultStruct)
- for _, f := range p.fields {
- if value, ok := values[f.field.Name.Name]; ok {
- packed, err := f.fieldPacker.Pack(value)
- if err != nil {
- return reflect.Value{}, err
- }
- v.Elem().FieldByIndex(f.fieldIndex).Set(packed)
- }
- }
- if !p.usePtr {
- return v.Elem(), nil
- }
- return v, nil
-}
-
-type listPacker struct {
- sliceType reflect.Type
- elem packer
-}
-
-func (e *listPacker) Pack(value interface{}) (reflect.Value, error) {
- list, ok := value.([]interface{})
- if !ok {
- list = []interface{}{value}
- }
-
- v := reflect.MakeSlice(e.sliceType, len(list), len(list))
- for i := range list {
- packed, err := e.elem.Pack(list[i])
- if err != nil {
- return reflect.Value{}, err
- }
- v.Index(i).Set(packed)
- }
- return v, nil
-}
-
-type nullPacker struct {
- elemPacker packer
- valueType reflect.Type
- addPtr bool
-}
-
-func (p *nullPacker) Pack(value interface{}) (reflect.Value, error) {
- if value == nil {
- return reflect.Zero(p.valueType), nil
- }
-
- v, err := p.elemPacker.Pack(value)
- if err != nil {
- return reflect.Value{}, err
- }
-
- if p.addPtr {
- ptr := reflect.New(p.valueType.Elem())
- ptr.Elem().Set(v)
- return ptr, nil
- }
-
- return v, nil
-}
-
-type ValuePacker struct {
- ValueType reflect.Type
-}
-
-func (p *ValuePacker) Pack(value interface{}) (reflect.Value, error) {
- if value == nil {
- return reflect.Value{}, errors.Errorf("got null for non-null")
- }
-
- coerced, err := unmarshalInput(p.ValueType, value)
- if err != nil {
- return reflect.Value{}, fmt.Errorf("could not unmarshal %#v (%T) into %s: %s", value, value, p.ValueType, err)
- }
- return reflect.ValueOf(coerced), nil
-}
-
-type unmarshalerPacker struct {
- ValueType reflect.Type
-}
-
-func (p *unmarshalerPacker) Pack(value interface{}) (reflect.Value, error) {
- if value == nil {
- return reflect.Value{}, errors.Errorf("got null for non-null")
- }
-
- v := reflect.New(p.ValueType)
- if err := v.Interface().(Unmarshaler).UnmarshalGraphQL(value); err != nil {
- return reflect.Value{}, err
- }
- return v.Elem(), nil
-}
-
-type Unmarshaler interface {
- ImplementsGraphQLType(name string) bool
- UnmarshalGraphQL(input interface{}) error
-}
-
-func unmarshalInput(typ reflect.Type, input interface{}) (interface{}, error) {
- if reflect.TypeOf(input) == typ {
- return input, nil
- }
-
- switch typ.Kind() {
- case reflect.Int32:
- switch input := input.(type) {
- case int:
- if input < math.MinInt32 || input > math.MaxInt32 {
- return nil, fmt.Errorf("not a 32-bit integer")
- }
- return int32(input), nil
- case float64:
- coerced := int32(input)
- if input < math.MinInt32 || input > math.MaxInt32 || float64(coerced) != input {
- return nil, fmt.Errorf("not a 32-bit integer")
- }
- return coerced, nil
- }
-
- case reflect.Float64:
- switch input := input.(type) {
- case int32:
- return float64(input), nil
- case int:
- return float64(input), nil
- }
-
- case reflect.String:
- if reflect.TypeOf(input).ConvertibleTo(typ) {
- return reflect.ValueOf(input).Convert(typ).Interface(), nil
- }
- }
-
- return nil, fmt.Errorf("incompatible type")
-}
-
-func unwrapNonNull(t common.Type) (common.Type, bool) {
- if nn, ok := t.(*common.NonNull); ok {
- return nn.OfType, true
- }
- return t, false
-}
-
-func stripUnderscore(s string) string {
- return strings.Replace(s, "_", "", -1)
-}
diff --git a/vendor/github.com/graph-gophers/graphql-go/internal/exec/resolvable/meta.go b/vendor/github.com/graph-gophers/graphql-go/internal/exec/resolvable/meta.go
deleted file mode 100644
index 826c823484..0000000000
--- a/vendor/github.com/graph-gophers/graphql-go/internal/exec/resolvable/meta.go
+++ /dev/null
@@ -1,58 +0,0 @@
-package resolvable
-
-import (
- "fmt"
- "reflect"
-
- "github.com/graph-gophers/graphql-go/internal/common"
- "github.com/graph-gophers/graphql-go/internal/schema"
- "github.com/graph-gophers/graphql-go/introspection"
-)
-
-var MetaSchema *Object
-var MetaType *Object
-
-func init() {
- var err error
- b := newBuilder(schema.Meta)
-
- metaSchema := schema.Meta.Types["__Schema"].(*schema.Object)
- MetaSchema, err = b.makeObjectExec(metaSchema.Name, metaSchema.Fields, nil, false, reflect.TypeOf(&introspection.Schema{}))
- if err != nil {
- panic(err)
- }
-
- metaType := schema.Meta.Types["__Type"].(*schema.Object)
- MetaType, err = b.makeObjectExec(metaType.Name, metaType.Fields, nil, false, reflect.TypeOf(&introspection.Type{}))
- if err != nil {
- panic(err)
- }
-
- if err := b.finish(); err != nil {
- panic(err)
- }
-}
-
-var MetaFieldTypename = Field{
- Field: schema.Field{
- Name: "__typename",
- Type: &common.NonNull{OfType: schema.Meta.Types["String"]},
- },
- TraceLabel: fmt.Sprintf("GraphQL field: __typename"),
-}
-
-var MetaFieldSchema = Field{
- Field: schema.Field{
- Name: "__schema",
- Type: schema.Meta.Types["__Schema"],
- },
- TraceLabel: fmt.Sprintf("GraphQL field: __schema"),
-}
-
-var MetaFieldType = Field{
- Field: schema.Field{
- Name: "__type",
- Type: schema.Meta.Types["__Type"],
- },
- TraceLabel: fmt.Sprintf("GraphQL field: __type"),
-}
diff --git a/vendor/github.com/graph-gophers/graphql-go/internal/exec/resolvable/resolvable.go b/vendor/github.com/graph-gophers/graphql-go/internal/exec/resolvable/resolvable.go
deleted file mode 100644
index 3e5d9e44d9..0000000000
--- a/vendor/github.com/graph-gophers/graphql-go/internal/exec/resolvable/resolvable.go
+++ /dev/null
@@ -1,331 +0,0 @@
-package resolvable
-
-import (
- "context"
- "fmt"
- "reflect"
- "strings"
-
- "github.com/graph-gophers/graphql-go/internal/common"
- "github.com/graph-gophers/graphql-go/internal/exec/packer"
- "github.com/graph-gophers/graphql-go/internal/schema"
-)
-
-type Schema struct {
- schema.Schema
- Query Resolvable
- Mutation Resolvable
- Resolver reflect.Value
-}
-
-type Resolvable interface {
- isResolvable()
-}
-
-type Object struct {
- Name string
- Fields map[string]*Field
- TypeAssertions map[string]*TypeAssertion
-}
-
-type Field struct {
- schema.Field
- TypeName string
- MethodIndex int
- HasContext bool
- HasError bool
- ArgsPacker *packer.StructPacker
- ValueExec Resolvable
- TraceLabel string
-}
-
-type TypeAssertion struct {
- MethodIndex int
- TypeExec Resolvable
-}
-
-type List struct {
- Elem Resolvable
-}
-
-type Scalar struct{}
-
-func (*Object) isResolvable() {}
-func (*List) isResolvable() {}
-func (*Scalar) isResolvable() {}
-
-func ApplyResolver(s *schema.Schema, resolver interface{}) (*Schema, error) {
- b := newBuilder(s)
-
- var query, mutation Resolvable
-
- if t, ok := s.EntryPoints["query"]; ok {
- if err := b.assignExec(&query, t, reflect.TypeOf(resolver)); err != nil {
- return nil, err
- }
- }
-
- if t, ok := s.EntryPoints["mutation"]; ok {
- if err := b.assignExec(&mutation, t, reflect.TypeOf(resolver)); err != nil {
- return nil, err
- }
- }
-
- if err := b.finish(); err != nil {
- return nil, err
- }
-
- return &Schema{
- Schema: *s,
- Resolver: reflect.ValueOf(resolver),
- Query: query,
- Mutation: mutation,
- }, nil
-}
-
-type execBuilder struct {
- schema *schema.Schema
- resMap map[typePair]*resMapEntry
- packerBuilder *packer.Builder
-}
-
-type typePair struct {
- graphQLType common.Type
- resolverType reflect.Type
-}
-
-type resMapEntry struct {
- exec Resolvable
- targets []*Resolvable
-}
-
-func newBuilder(s *schema.Schema) *execBuilder {
- return &execBuilder{
- schema: s,
- resMap: make(map[typePair]*resMapEntry),
- packerBuilder: packer.NewBuilder(),
- }
-}
-
-func (b *execBuilder) finish() error {
- for _, entry := range b.resMap {
- for _, target := range entry.targets {
- *target = entry.exec
- }
- }
-
- return b.packerBuilder.Finish()
-}
-
-func (b *execBuilder) assignExec(target *Resolvable, t common.Type, resolverType reflect.Type) error {
- k := typePair{t, resolverType}
- ref, ok := b.resMap[k]
- if !ok {
- ref = &resMapEntry{}
- b.resMap[k] = ref
- var err error
- ref.exec, err = b.makeExec(t, resolverType)
- if err != nil {
- return err
- }
- }
- ref.targets = append(ref.targets, target)
- return nil
-}
-
-func (b *execBuilder) makeExec(t common.Type, resolverType reflect.Type) (Resolvable, error) {
- var nonNull bool
- t, nonNull = unwrapNonNull(t)
-
- switch t := t.(type) {
- case *schema.Object:
- return b.makeObjectExec(t.Name, t.Fields, nil, nonNull, resolverType)
-
- case *schema.Interface:
- return b.makeObjectExec(t.Name, t.Fields, t.PossibleTypes, nonNull, resolverType)
-
- case *schema.Union:
- return b.makeObjectExec(t.Name, nil, t.PossibleTypes, nonNull, resolverType)
- }
-
- if !nonNull {
- if resolverType.Kind() != reflect.Ptr {
- return nil, fmt.Errorf("%s is not a pointer", resolverType)
- }
- resolverType = resolverType.Elem()
- }
-
- switch t := t.(type) {
- case *schema.Scalar:
- return makeScalarExec(t, resolverType)
-
- case *schema.Enum:
- return &Scalar{}, nil
-
- case *common.List:
- if resolverType.Kind() != reflect.Slice {
- return nil, fmt.Errorf("%s is not a slice", resolverType)
- }
- e := &List{}
- if err := b.assignExec(&e.Elem, t.OfType, resolverType.Elem()); err != nil {
- return nil, err
- }
- return e, nil
-
- default:
- panic("invalid type: " + t.String())
- }
-}
-
-func makeScalarExec(t *schema.Scalar, resolverType reflect.Type) (Resolvable, error) {
- implementsType := false
- switch r := reflect.New(resolverType).Interface().(type) {
- case *int32:
- implementsType = (t.Name == "Int")
- case *float64:
- implementsType = (t.Name == "Float")
- case *string:
- implementsType = (t.Name == "String")
- case *bool:
- implementsType = (t.Name == "Boolean")
- case packer.Unmarshaler:
- implementsType = r.ImplementsGraphQLType(t.Name)
- }
- if !implementsType {
- return nil, fmt.Errorf("can not use %s as %s", resolverType, t.Name)
- }
- return &Scalar{}, nil
-}
-
-func (b *execBuilder) makeObjectExec(typeName string, fields schema.FieldList, possibleTypes []*schema.Object, nonNull bool, resolverType reflect.Type) (*Object, error) {
- if !nonNull {
- if resolverType.Kind() != reflect.Ptr && resolverType.Kind() != reflect.Interface {
- return nil, fmt.Errorf("%s is not a pointer or interface", resolverType)
- }
- }
-
- methodHasReceiver := resolverType.Kind() != reflect.Interface
-
- Fields := make(map[string]*Field)
- for _, f := range fields {
- methodIndex := findMethod(resolverType, f.Name)
- if methodIndex == -1 {
- hint := ""
- if findMethod(reflect.PtrTo(resolverType), f.Name) != -1 {
- hint = " (hint: the method exists on the pointer type)"
- }
- return nil, fmt.Errorf("%s does not resolve %q: missing method for field %q%s", resolverType, typeName, f.Name, hint)
- }
-
- m := resolverType.Method(methodIndex)
- fe, err := b.makeFieldExec(typeName, f, m, methodIndex, methodHasReceiver)
- if err != nil {
- return nil, fmt.Errorf("%s\n\treturned by (%s).%s", err, resolverType, m.Name)
- }
- Fields[f.Name] = fe
- }
-
- typeAssertions := make(map[string]*TypeAssertion)
- for _, impl := range possibleTypes {
- methodIndex := findMethod(resolverType, "To"+impl.Name)
- if methodIndex == -1 {
- return nil, fmt.Errorf("%s does not resolve %q: missing method %q to convert to %q", resolverType, typeName, "To"+impl.Name, impl.Name)
- }
- if resolverType.Method(methodIndex).Type.NumOut() != 2 {
- return nil, fmt.Errorf("%s does not resolve %q: method %q should return a value and a bool indicating success", resolverType, typeName, "To"+impl.Name)
- }
- a := &TypeAssertion{
- MethodIndex: methodIndex,
- }
- if err := b.assignExec(&a.TypeExec, impl, resolverType.Method(methodIndex).Type.Out(0)); err != nil {
- return nil, err
- }
- typeAssertions[impl.Name] = a
- }
-
- return &Object{
- Name: typeName,
- Fields: Fields,
- TypeAssertions: typeAssertions,
- }, nil
-}
-
-var contextType = reflect.TypeOf((*context.Context)(nil)).Elem()
-var errorType = reflect.TypeOf((*error)(nil)).Elem()
-
-func (b *execBuilder) makeFieldExec(typeName string, f *schema.Field, m reflect.Method, methodIndex int, methodHasReceiver bool) (*Field, error) {
- in := make([]reflect.Type, m.Type.NumIn())
- for i := range in {
- in[i] = m.Type.In(i)
- }
- if methodHasReceiver {
- in = in[1:] // first parameter is receiver
- }
-
- hasContext := len(in) > 0 && in[0] == contextType
- if hasContext {
- in = in[1:]
- }
-
- var argsPacker *packer.StructPacker
- if len(f.Args) > 0 {
- if len(in) == 0 {
- return nil, fmt.Errorf("must have parameter for field arguments")
- }
- var err error
- argsPacker, err = b.packerBuilder.MakeStructPacker(f.Args, in[0])
- if err != nil {
- return nil, err
- }
- in = in[1:]
- }
-
- if len(in) > 0 {
- return nil, fmt.Errorf("too many parameters")
- }
-
- if m.Type.NumOut() > 2 {
- return nil, fmt.Errorf("too many return values")
- }
-
- hasError := m.Type.NumOut() == 2
- if hasError {
- if m.Type.Out(1) != errorType {
- return nil, fmt.Errorf(`must have "error" as its second return value`)
- }
- }
-
- fe := &Field{
- Field: *f,
- TypeName: typeName,
- MethodIndex: methodIndex,
- HasContext: hasContext,
- ArgsPacker: argsPacker,
- HasError: hasError,
- TraceLabel: fmt.Sprintf("GraphQL field: %s.%s", typeName, f.Name),
- }
- if err := b.assignExec(&fe.ValueExec, f.Type, m.Type.Out(0)); err != nil {
- return nil, err
- }
- return fe, nil
-}
-
-func findMethod(t reflect.Type, name string) int {
- for i := 0; i < t.NumMethod(); i++ {
- if strings.EqualFold(stripUnderscore(name), stripUnderscore(t.Method(i).Name)) {
- return i
- }
- }
- return -1
-}
-
-func unwrapNonNull(t common.Type) (common.Type, bool) {
- if nn, ok := t.(*common.NonNull); ok {
- return nn.OfType, true
- }
- return t, false
-}
-
-func stripUnderscore(s string) string {
- return strings.Replace(s, "_", "", -1)
-}
diff --git a/vendor/github.com/graph-gophers/graphql-go/internal/exec/selected/selected.go b/vendor/github.com/graph-gophers/graphql-go/internal/exec/selected/selected.go
deleted file mode 100644
index aed079b671..0000000000
--- a/vendor/github.com/graph-gophers/graphql-go/internal/exec/selected/selected.go
+++ /dev/null
@@ -1,238 +0,0 @@
-package selected
-
-import (
- "fmt"
- "reflect"
- "sync"
-
- "github.com/graph-gophers/graphql-go/errors"
- "github.com/graph-gophers/graphql-go/internal/common"
- "github.com/graph-gophers/graphql-go/internal/exec/packer"
- "github.com/graph-gophers/graphql-go/internal/exec/resolvable"
- "github.com/graph-gophers/graphql-go/internal/query"
- "github.com/graph-gophers/graphql-go/internal/schema"
- "github.com/graph-gophers/graphql-go/introspection"
-)
-
-type Request struct {
- Schema *schema.Schema
- Doc *query.Document
- Vars map[string]interface{}
- Mu sync.Mutex
- Errs []*errors.QueryError
-}
-
-func (r *Request) AddError(err *errors.QueryError) {
- r.Mu.Lock()
- r.Errs = append(r.Errs, err)
- r.Mu.Unlock()
-}
-
-func ApplyOperation(r *Request, s *resolvable.Schema, op *query.Operation) []Selection {
- var obj *resolvable.Object
- switch op.Type {
- case query.Query:
- obj = s.Query.(*resolvable.Object)
- case query.Mutation:
- obj = s.Mutation.(*resolvable.Object)
- }
- return applySelectionSet(r, obj, op.Selections)
-}
-
-type Selection interface {
- isSelection()
-}
-
-type SchemaField struct {
- resolvable.Field
- Alias string
- Args map[string]interface{}
- PackedArgs reflect.Value
- Sels []Selection
- Async bool
- FixedResult reflect.Value
-}
-
-type TypeAssertion struct {
- resolvable.TypeAssertion
- Sels []Selection
-}
-
-type TypenameField struct {
- resolvable.Object
- Alias string
-}
-
-func (*SchemaField) isSelection() {}
-func (*TypeAssertion) isSelection() {}
-func (*TypenameField) isSelection() {}
-
-func applySelectionSet(r *Request, e *resolvable.Object, sels []query.Selection) (flattenedSels []Selection) {
- for _, sel := range sels {
- switch sel := sel.(type) {
- case *query.Field:
- field := sel
- if skipByDirective(r, field.Directives) {
- continue
- }
-
- switch field.Name.Name {
- case "__typename":
- flattenedSels = append(flattenedSels, &TypenameField{
- Object: *e,
- Alias: field.Alias.Name,
- })
-
- case "__schema":
- flattenedSels = append(flattenedSels, &SchemaField{
- Field: resolvable.MetaFieldSchema,
- Alias: field.Alias.Name,
- Sels: applySelectionSet(r, resolvable.MetaSchema, field.Selections),
- Async: true,
- FixedResult: reflect.ValueOf(introspection.WrapSchema(r.Schema)),
- })
-
- case "__type":
- p := packer.ValuePacker{ValueType: reflect.TypeOf("")}
- v, err := p.Pack(field.Arguments.MustGet("name").Value(r.Vars))
- if err != nil {
- r.AddError(errors.Errorf("%s", err))
- return nil
- }
-
- t, ok := r.Schema.Types[v.String()]
- if !ok {
- return nil
- }
-
- flattenedSels = append(flattenedSels, &SchemaField{
- Field: resolvable.MetaFieldType,
- Alias: field.Alias.Name,
- Sels: applySelectionSet(r, resolvable.MetaType, field.Selections),
- Async: true,
- FixedResult: reflect.ValueOf(introspection.WrapType(t)),
- })
-
- default:
- fe := e.Fields[field.Name.Name]
-
- var args map[string]interface{}
- var packedArgs reflect.Value
- if fe.ArgsPacker != nil {
- args = make(map[string]interface{})
- for _, arg := range field.Arguments {
- args[arg.Name.Name] = arg.Value.Value(r.Vars)
- }
- var err error
- packedArgs, err = fe.ArgsPacker.Pack(args)
- if err != nil {
- r.AddError(errors.Errorf("%s", err))
- return
- }
- }
-
- fieldSels := applyField(r, fe.ValueExec, field.Selections)
- flattenedSels = append(flattenedSels, &SchemaField{
- Field: *fe,
- Alias: field.Alias.Name,
- Args: args,
- PackedArgs: packedArgs,
- Sels: fieldSels,
- Async: fe.HasContext || fe.ArgsPacker != nil || fe.HasError || HasAsyncSel(fieldSels),
- })
- }
-
- case *query.InlineFragment:
- frag := sel
- if skipByDirective(r, frag.Directives) {
- continue
- }
- flattenedSels = append(flattenedSels, applyFragment(r, e, &frag.Fragment)...)
-
- case *query.FragmentSpread:
- spread := sel
- if skipByDirective(r, spread.Directives) {
- continue
- }
- flattenedSels = append(flattenedSels, applyFragment(r, e, &r.Doc.Fragments.Get(spread.Name.Name).Fragment)...)
-
- default:
- panic("invalid type")
- }
- }
- return
-}
-
-func applyFragment(r *Request, e *resolvable.Object, frag *query.Fragment) []Selection {
- if frag.On.Name != "" && frag.On.Name != e.Name {
- a, ok := e.TypeAssertions[frag.On.Name]
- if !ok {
- panic(fmt.Errorf("%q does not implement %q", frag.On, e.Name)) // TODO proper error handling
- }
-
- return []Selection{&TypeAssertion{
- TypeAssertion: *a,
- Sels: applySelectionSet(r, a.TypeExec.(*resolvable.Object), frag.Selections),
- }}
- }
- return applySelectionSet(r, e, frag.Selections)
-}
-
-func applyField(r *Request, e resolvable.Resolvable, sels []query.Selection) []Selection {
- switch e := e.(type) {
- case *resolvable.Object:
- return applySelectionSet(r, e, sels)
- case *resolvable.List:
- return applyField(r, e.Elem, sels)
- case *resolvable.Scalar:
- return nil
- default:
- panic("unreachable")
- }
-}
-
-func skipByDirective(r *Request, directives common.DirectiveList) bool {
- if d := directives.Get("skip"); d != nil {
- p := packer.ValuePacker{ValueType: reflect.TypeOf(false)}
- v, err := p.Pack(d.Args.MustGet("if").Value(r.Vars))
- if err != nil {
- r.AddError(errors.Errorf("%s", err))
- }
- if err == nil && v.Bool() {
- return true
- }
- }
-
- if d := directives.Get("include"); d != nil {
- p := packer.ValuePacker{ValueType: reflect.TypeOf(false)}
- v, err := p.Pack(d.Args.MustGet("if").Value(r.Vars))
- if err != nil {
- r.AddError(errors.Errorf("%s", err))
- }
- if err == nil && !v.Bool() {
- return true
- }
- }
-
- return false
-}
-
-func HasAsyncSel(sels []Selection) bool {
- for _, sel := range sels {
- switch sel := sel.(type) {
- case *SchemaField:
- if sel.Async {
- return true
- }
- case *TypeAssertion:
- if HasAsyncSel(sel.Sels) {
- return true
- }
- case *TypenameField:
- // sync
- default:
- panic("unreachable")
- }
- }
- return false
-}
diff --git a/vendor/github.com/graph-gophers/graphql-go/internal/query/query.go b/vendor/github.com/graph-gophers/graphql-go/internal/query/query.go
deleted file mode 100644
index faba4d2ade..0000000000
--- a/vendor/github.com/graph-gophers/graphql-go/internal/query/query.go
+++ /dev/null
@@ -1,234 +0,0 @@
-package query
-
-import (
- "fmt"
- "text/scanner"
-
- "github.com/graph-gophers/graphql-go/errors"
- "github.com/graph-gophers/graphql-go/internal/common"
-)
-
-type Document struct {
- Operations OperationList
- Fragments FragmentList
-}
-
-type OperationList []*Operation
-
-func (l OperationList) Get(name string) *Operation {
- for _, f := range l {
- if f.Name.Name == name {
- return f
- }
- }
- return nil
-}
-
-type FragmentList []*FragmentDecl
-
-func (l FragmentList) Get(name string) *FragmentDecl {
- for _, f := range l {
- if f.Name.Name == name {
- return f
- }
- }
- return nil
-}
-
-type Operation struct {
- Type OperationType
- Name common.Ident
- Vars common.InputValueList
- Selections []Selection
- Directives common.DirectiveList
- Loc errors.Location
-}
-
-type OperationType string
-
-const (
- Query OperationType = "QUERY"
- Mutation = "MUTATION"
- Subscription = "SUBSCRIPTION"
-)
-
-type Fragment struct {
- On common.TypeName
- Selections []Selection
-}
-
-type FragmentDecl struct {
- Fragment
- Name common.Ident
- Directives common.DirectiveList
- Loc errors.Location
-}
-
-type Selection interface {
- isSelection()
-}
-
-type Field struct {
- Alias common.Ident
- Name common.Ident
- Arguments common.ArgumentList
- Directives common.DirectiveList
- Selections []Selection
- SelectionSetLoc errors.Location
-}
-
-type InlineFragment struct {
- Fragment
- Directives common.DirectiveList
- Loc errors.Location
-}
-
-type FragmentSpread struct {
- Name common.Ident
- Directives common.DirectiveList
- Loc errors.Location
-}
-
-func (Field) isSelection() {}
-func (InlineFragment) isSelection() {}
-func (FragmentSpread) isSelection() {}
-
-func Parse(queryString string) (*Document, *errors.QueryError) {
- l := common.NewLexer(queryString)
-
- var doc *Document
- err := l.CatchSyntaxError(func() { doc = parseDocument(l) })
- if err != nil {
- return nil, err
- }
-
- return doc, nil
-}
-
-func parseDocument(l *common.Lexer) *Document {
- d := &Document{}
- l.Consume()
- for l.Peek() != scanner.EOF {
- if l.Peek() == '{' {
- op := &Operation{Type: Query, Loc: l.Location()}
- op.Selections = parseSelectionSet(l)
- d.Operations = append(d.Operations, op)
- continue
- }
-
- loc := l.Location()
- switch x := l.ConsumeIdent(); x {
- case "query":
- op := parseOperation(l, Query)
- op.Loc = loc
- d.Operations = append(d.Operations, op)
-
- case "mutation":
- d.Operations = append(d.Operations, parseOperation(l, Mutation))
-
- case "subscription":
- d.Operations = append(d.Operations, parseOperation(l, Subscription))
-
- case "fragment":
- frag := parseFragment(l)
- frag.Loc = loc
- d.Fragments = append(d.Fragments, frag)
-
- default:
- l.SyntaxError(fmt.Sprintf(`unexpected %q, expecting "fragment"`, x))
- }
- }
- return d
-}
-
-func parseOperation(l *common.Lexer, opType OperationType) *Operation {
- op := &Operation{Type: opType}
- op.Name.Loc = l.Location()
- if l.Peek() == scanner.Ident {
- op.Name = l.ConsumeIdentWithLoc()
- }
- op.Directives = common.ParseDirectives(l)
- if l.Peek() == '(' {
- l.ConsumeToken('(')
- for l.Peek() != ')' {
- loc := l.Location()
- l.ConsumeToken('$')
- iv := common.ParseInputValue(l)
- iv.Loc = loc
- op.Vars = append(op.Vars, iv)
- }
- l.ConsumeToken(')')
- }
- op.Selections = parseSelectionSet(l)
- return op
-}
-
-func parseFragment(l *common.Lexer) *FragmentDecl {
- f := &FragmentDecl{}
- f.Name = l.ConsumeIdentWithLoc()
- l.ConsumeKeyword("on")
- f.On = common.TypeName{Ident: l.ConsumeIdentWithLoc()}
- f.Directives = common.ParseDirectives(l)
- f.Selections = parseSelectionSet(l)
- return f
-}
-
-func parseSelectionSet(l *common.Lexer) []Selection {
- var sels []Selection
- l.ConsumeToken('{')
- for l.Peek() != '}' {
- sels = append(sels, parseSelection(l))
- }
- l.ConsumeToken('}')
- return sels
-}
-
-func parseSelection(l *common.Lexer) Selection {
- if l.Peek() == '.' {
- return parseSpread(l)
- }
- return parseField(l)
-}
-
-func parseField(l *common.Lexer) *Field {
- f := &Field{}
- f.Alias = l.ConsumeIdentWithLoc()
- f.Name = f.Alias
- if l.Peek() == ':' {
- l.ConsumeToken(':')
- f.Name = l.ConsumeIdentWithLoc()
- }
- if l.Peek() == '(' {
- f.Arguments = common.ParseArguments(l)
- }
- f.Directives = common.ParseDirectives(l)
- if l.Peek() == '{' {
- f.SelectionSetLoc = l.Location()
- f.Selections = parseSelectionSet(l)
- }
- return f
-}
-
-func parseSpread(l *common.Lexer) Selection {
- loc := l.Location()
- l.ConsumeToken('.')
- l.ConsumeToken('.')
- l.ConsumeToken('.')
-
- f := &InlineFragment{Loc: loc}
- if l.Peek() == scanner.Ident {
- ident := l.ConsumeIdentWithLoc()
- if ident.Name != "on" {
- fs := &FragmentSpread{
- Name: ident,
- Loc: loc,
- }
- fs.Directives = common.ParseDirectives(l)
- return fs
- }
- f.On = common.TypeName{Ident: l.ConsumeIdentWithLoc()}
- }
- f.Directives = common.ParseDirectives(l)
- f.Selections = parseSelectionSet(l)
- return f
-}
diff --git a/vendor/github.com/graph-gophers/graphql-go/internal/schema/meta.go b/vendor/github.com/graph-gophers/graphql-go/internal/schema/meta.go
deleted file mode 100644
index b48bf7acf2..0000000000
--- a/vendor/github.com/graph-gophers/graphql-go/internal/schema/meta.go
+++ /dev/null
@@ -1,190 +0,0 @@
-package schema
-
-var Meta *Schema
-
-func init() {
- Meta = &Schema{} // bootstrap
- Meta = New()
- if err := Meta.Parse(metaSrc); err != nil {
- panic(err)
- }
-}
-
-var metaSrc = `
- # The ` + "`" + `Int` + "`" + ` scalar type represents non-fractional signed whole numeric values. Int can represent values between -(2^31) and 2^31 - 1.
- scalar Int
-
- # The ` + "`" + `Float` + "`" + ` scalar type represents signed double-precision fractional values as specified by [IEEE 754](http://en.wikipedia.org/wiki/IEEE_floating_point).
- scalar Float
-
- # The ` + "`" + `String` + "`" + ` scalar type represents textual data, represented as UTF-8 character sequences. The String type is most often used by GraphQL to represent free-form human-readable text.
- scalar String
-
- # The ` + "`" + `Boolean` + "`" + ` scalar type represents ` + "`" + `true` + "`" + ` or ` + "`" + `false` + "`" + `.
- scalar Boolean
-
- # The ` + "`" + `ID` + "`" + ` scalar type represents a unique identifier, often used to refetch an object or as key for a cache. The ID type appears in a JSON response as a String; however, it is not intended to be human-readable. When expected as an input type, any string (such as ` + "`" + `"4"` + "`" + `) or integer (such as ` + "`" + `4` + "`" + `) input value will be accepted as an ID.
- scalar ID
-
- # Directs the executor to include this field or fragment only when the ` + "`" + `if` + "`" + ` argument is true.
- directive @include(
- # Included when true.
- if: Boolean!
- ) on FIELD | FRAGMENT_SPREAD | INLINE_FRAGMENT
-
- # Directs the executor to skip this field or fragment when the ` + "`" + `if` + "`" + ` argument is true.
- directive @skip(
- # Skipped when true.
- if: Boolean!
- ) on FIELD | FRAGMENT_SPREAD | INLINE_FRAGMENT
-
- # Marks an element of a GraphQL schema as no longer supported.
- directive @deprecated(
- # Explains why this element was deprecated, usually also including a suggestion
- # for how to access supported similar data. Formatted in
- # [Markdown](https://daringfireball.net/projects/markdown/).
- reason: String = "No longer supported"
- ) on FIELD_DEFINITION | ENUM_VALUE
-
- # A Directive provides a way to describe alternate runtime execution and type validation behavior in a GraphQL document.
- #
- # In some cases, you need to provide options to alter GraphQL's execution behavior
- # in ways field arguments will not suffice, such as conditionally including or
- # skipping a field. Directives provide this by describing additional information
- # to the executor.
- type __Directive {
- name: String!
- description: String
- locations: [__DirectiveLocation!]!
- args: [__InputValue!]!
- }
-
- # A Directive can be adjacent to many parts of the GraphQL language, a
- # __DirectiveLocation describes one such possible adjacencies.
- enum __DirectiveLocation {
- # Location adjacent to a query operation.
- QUERY
- # Location adjacent to a mutation operation.
- MUTATION
- # Location adjacent to a subscription operation.
- SUBSCRIPTION
- # Location adjacent to a field.
- FIELD
- # Location adjacent to a fragment definition.
- FRAGMENT_DEFINITION
- # Location adjacent to a fragment spread.
- FRAGMENT_SPREAD
- # Location adjacent to an inline fragment.
- INLINE_FRAGMENT
- # Location adjacent to a schema definition.
- SCHEMA
- # Location adjacent to a scalar definition.
- SCALAR
- # Location adjacent to an object type definition.
- OBJECT
- # Location adjacent to a field definition.
- FIELD_DEFINITION
- # Location adjacent to an argument definition.
- ARGUMENT_DEFINITION
- # Location adjacent to an interface definition.
- INTERFACE
- # Location adjacent to a union definition.
- UNION
- # Location adjacent to an enum definition.
- ENUM
- # Location adjacent to an enum value definition.
- ENUM_VALUE
- # Location adjacent to an input object type definition.
- INPUT_OBJECT
- # Location adjacent to an input object field definition.
- INPUT_FIELD_DEFINITION
- }
-
- # One possible value for a given Enum. Enum values are unique values, not a
- # placeholder for a string or numeric value. However an Enum value is returned in
- # a JSON response as a string.
- type __EnumValue {
- name: String!
- description: String
- isDeprecated: Boolean!
- deprecationReason: String
- }
-
- # Object and Interface types are described by a list of Fields, each of which has
- # a name, potentially a list of arguments, and a return type.
- type __Field {
- name: String!
- description: String
- args: [__InputValue!]!
- type: __Type!
- isDeprecated: Boolean!
- deprecationReason: String
- }
-
- # Arguments provided to Fields or Directives and the input fields of an
- # InputObject are represented as Input Values which describe their type and
- # optionally a default value.
- type __InputValue {
- name: String!
- description: String
- type: __Type!
- # A GraphQL-formatted string representing the default value for this input value.
- defaultValue: String
- }
-
- # A GraphQL Schema defines the capabilities of a GraphQL server. It exposes all
- # available types and directives on the server, as well as the entry points for
- # query, mutation, and subscription operations.
- type __Schema {
- # A list of all types supported by this server.
- types: [__Type!]!
- # The type that query operations will be rooted at.
- queryType: __Type!
- # If this server supports mutation, the type that mutation operations will be rooted at.
- mutationType: __Type
- # If this server support subscription, the type that subscription operations will be rooted at.
- subscriptionType: __Type
- # A list of all directives supported by this server.
- directives: [__Directive!]!
- }
-
- # The fundamental unit of any GraphQL Schema is the type. There are many kinds of
- # types in GraphQL as represented by the ` + "`" + `__TypeKind` + "`" + ` enum.
- #
- # Depending on the kind of a type, certain fields describe information about that
- # type. Scalar types provide no information beyond a name and description, while
- # Enum types provide their values. Object and Interface types provide the fields
- # they describe. Abstract types, Union and Interface, provide the Object types
- # possible at runtime. List and NonNull types compose other types.
- type __Type {
- kind: __TypeKind!
- name: String
- description: String
- fields(includeDeprecated: Boolean = false): [__Field!]
- interfaces: [__Type!]
- possibleTypes: [__Type!]
- enumValues(includeDeprecated: Boolean = false): [__EnumValue!]
- inputFields: [__InputValue!]
- ofType: __Type
- }
-
- # An enum describing what kind of type a given ` + "`" + `__Type` + "`" + ` is.
- enum __TypeKind {
- # Indicates this type is a scalar.
- SCALAR
- # Indicates this type is an object. ` + "`" + `fields` + "`" + ` and ` + "`" + `interfaces` + "`" + ` are valid fields.
- OBJECT
- # Indicates this type is an interface. ` + "`" + `fields` + "`" + ` and ` + "`" + `possibleTypes` + "`" + ` are valid fields.
- INTERFACE
- # Indicates this type is a union. ` + "`" + `possibleTypes` + "`" + ` is a valid field.
- UNION
- # Indicates this type is an enum. ` + "`" + `enumValues` + "`" + ` is a valid field.
- ENUM
- # Indicates this type is an input object. ` + "`" + `inputFields` + "`" + ` is a valid field.
- INPUT_OBJECT
- # Indicates this type is a list. ` + "`" + `ofType` + "`" + ` is a valid field.
- LIST
- # Indicates this type is a non-null. ` + "`" + `ofType` + "`" + ` is a valid field.
- NON_NULL
- }
-`
diff --git a/vendor/github.com/graph-gophers/graphql-go/internal/schema/schema.go b/vendor/github.com/graph-gophers/graphql-go/internal/schema/schema.go
deleted file mode 100644
index e549f17c07..0000000000
--- a/vendor/github.com/graph-gophers/graphql-go/internal/schema/schema.go
+++ /dev/null
@@ -1,570 +0,0 @@
-package schema
-
-import (
- "fmt"
- "text/scanner"
-
- "github.com/graph-gophers/graphql-go/errors"
- "github.com/graph-gophers/graphql-go/internal/common"
-)
-
-// Schema represents a GraphQL service's collective type system capabilities.
-// A schema is defined in terms of the types and directives it supports as well as the root
-// operation types for each kind of operation: `query`, `mutation`, and `subscription`.
-//
-// For a more formal definition, read the relevant section in the specification:
-//
-// http://facebook.github.io/graphql/draft/#sec-Schema
-type Schema struct {
- // EntryPoints determines the place in the type system where `query`, `mutation`, and
- // `subscription` operations begin.
- //
- // http://facebook.github.io/graphql/draft/#sec-Root-Operation-Types
- //
- // NOTE: The specification refers to this concept as "Root Operation Types".
- // TODO: Rename the `EntryPoints` field to `RootOperationTypes` to align with spec terminology.
- EntryPoints map[string]NamedType
-
- // Types are the fundamental unit of any GraphQL schema.
- // There are six kinds of named types, and two wrapping types.
- //
- // http://facebook.github.io/graphql/draft/#sec-Types
- Types map[string]NamedType
-
- // TODO: Type extensions?
- // http://facebook.github.io/graphql/draft/#sec-Type-Extensions
-
- // Directives are used to annotate various parts of a GraphQL document as an indicator that they
- // should be evaluated differently by a validator, executor, or client tool such as a code
- // generator.
- //
- // http://facebook.github.io/graphql/draft/#sec-Type-System.Directives
- Directives map[string]*DirectiveDecl
-
- entryPointNames map[string]string
- objects []*Object
- unions []*Union
- enums []*Enum
-}
-
-// Resolve a named type in the schema by its name.
-func (s *Schema) Resolve(name string) common.Type {
- return s.Types[name]
-}
-
-// NamedType represents a type with a name.
-//
-// http://facebook.github.io/graphql/draft/#NamedType
-type NamedType interface {
- common.Type
- TypeName() string
- Description() string
-}
-
-// Scalar types represent primitive leaf values (e.g. a string or an integer) in a GraphQL type
-// system.
-//
-// GraphQL responses take the form of a hierarchical tree; the leaves on these trees are GraphQL
-// scalars.
-//
-// http://facebook.github.io/graphql/draft/#sec-Scalars
-type Scalar struct {
- Name string
- Desc string
- // TODO: Add a list of directives?
-}
-
-// Object types represent a list of named fields, each of which yield a value of a specific type.
-//
-// GraphQL queries are hierarchical and composed, describing a tree of information.
-// While Scalar types describe the leaf values of these hierarchical types, Objects describe the
-// intermediate levels.
-//
-// http://facebook.github.io/graphql/draft/#sec-Objects
-type Object struct {
- Name string
- Interfaces []*Interface
- Fields FieldList
- Desc string
- // TODO: Add a list of directives?
-
- interfaceNames []string
-}
-
-// Interface types represent a list of named fields and their arguments.
-//
-// GraphQL objects can then implement these interfaces which requires that the object type will
-// define all fields defined by those interfaces.
-//
-// http://facebook.github.io/graphql/draft/#sec-Interfaces
-type Interface struct {
- Name string
- PossibleTypes []*Object
- Fields FieldList // NOTE: the spec refers to this as `FieldsDefinition`.
- Desc string
- // TODO: Add a list of directives?
-}
-
-// Union types represent objects that could be one of a list of GraphQL object types, but provides no
-// guaranteed fields between those types.
-//
-// They also differ from interfaces in that object types declare what interfaces they implement, but
-// are not aware of what unions contain them.
-//
-// http://facebook.github.io/graphql/draft/#sec-Unions
-type Union struct {
- Name string
- PossibleTypes []*Object // NOTE: the spec refers to this as `UnionMemberTypes`.
- Desc string
- // TODO: Add a list of directives?
-
- typeNames []string
-}
-
-// Enum types describe a set of possible values.
-//
-// Like scalar types, Enum types also represent leaf values in a GraphQL type system.
-//
-// http://facebook.github.io/graphql/draft/#sec-Enums
-type Enum struct {
- Name string
- Values []*EnumValue // NOTE: the spec refers to this as `EnumValuesDefinition`.
- Desc string
- // TODO: Add a list of directives?
-}
-
-// EnumValue types are unique values that may be serialized as a string: the name of the
-// represented value.
-//
-// http://facebook.github.io/graphql/draft/#EnumValueDefinition
-type EnumValue struct {
- Name string
- Directives common.DirectiveList
- Desc string
- // TODO: Add a list of directives?
-}
-
-// InputObject types define a set of input fields; the input fields are either scalars, enums, or
-// other input objects.
-//
-// This allows arguments to accept arbitrarily complex structs.
-//
-// http://facebook.github.io/graphql/draft/#sec-Input-Objects
-type InputObject struct {
- Name string
- Desc string
- Values common.InputValueList
- // TODO: Add a list of directives?
-}
-
-// FieldsList is a list of an Object's Fields.
-//
-// http://facebook.github.io/graphql/draft/#FieldsDefinition
-type FieldList []*Field
-
-// Get iterates over the field list, returning a pointer-to-Field when the field name matches the
-// provided `name` argument.
-// Returns nil when no field was found by that name.
-func (l FieldList) Get(name string) *Field {
- for _, f := range l {
- if f.Name == name {
- return f
- }
- }
- return nil
-}
-
-// Names returns a string slice of the field names in the FieldList.
-func (l FieldList) Names() []string {
- names := make([]string, len(l))
- for i, f := range l {
- names[i] = f.Name
- }
- return names
-}
-
-// http://facebook.github.io/graphql/draft/#sec-Type-System.Directives
-type DirectiveDecl struct {
- Name string
- Desc string
- Locs []string
- Args common.InputValueList
-}
-
-func (*Scalar) Kind() string { return "SCALAR" }
-func (*Object) Kind() string { return "OBJECT" }
-func (*Interface) Kind() string { return "INTERFACE" }
-func (*Union) Kind() string { return "UNION" }
-func (*Enum) Kind() string { return "ENUM" }
-func (*InputObject) Kind() string { return "INPUT_OBJECT" }
-
-func (t *Scalar) String() string { return t.Name }
-func (t *Object) String() string { return t.Name }
-func (t *Interface) String() string { return t.Name }
-func (t *Union) String() string { return t.Name }
-func (t *Enum) String() string { return t.Name }
-func (t *InputObject) String() string { return t.Name }
-
-func (t *Scalar) TypeName() string { return t.Name }
-func (t *Object) TypeName() string { return t.Name }
-func (t *Interface) TypeName() string { return t.Name }
-func (t *Union) TypeName() string { return t.Name }
-func (t *Enum) TypeName() string { return t.Name }
-func (t *InputObject) TypeName() string { return t.Name }
-
-func (t *Scalar) Description() string { return t.Desc }
-func (t *Object) Description() string { return t.Desc }
-func (t *Interface) Description() string { return t.Desc }
-func (t *Union) Description() string { return t.Desc }
-func (t *Enum) Description() string { return t.Desc }
-func (t *InputObject) Description() string { return t.Desc }
-
-// Field is a conceptual function which yields values.
-// http://facebook.github.io/graphql/draft/#FieldDefinition
-type Field struct {
- Name string
- Args common.InputValueList // NOTE: the spec refers to this as `ArgumentsDefinition`.
- Type common.Type
- Directives common.DirectiveList
- Desc string
-}
-
-// New initializes an instance of Schema.
-func New() *Schema {
- s := &Schema{
- entryPointNames: make(map[string]string),
- Types: make(map[string]NamedType),
- Directives: make(map[string]*DirectiveDecl),
- }
- for n, t := range Meta.Types {
- s.Types[n] = t
- }
- for n, d := range Meta.Directives {
- s.Directives[n] = d
- }
- return s
-}
-
-// Parse the schema string.
-func (s *Schema) Parse(schemaString string) error {
- l := common.NewLexer(schemaString)
-
- err := l.CatchSyntaxError(func() { parseSchema(s, l) })
- if err != nil {
- return err
- }
-
- for _, t := range s.Types {
- if err := resolveNamedType(s, t); err != nil {
- return err
- }
- }
- for _, d := range s.Directives {
- for _, arg := range d.Args {
- t, err := common.ResolveType(arg.Type, s.Resolve)
- if err != nil {
- return err
- }
- arg.Type = t
- }
- }
-
- s.EntryPoints = make(map[string]NamedType)
- for key, name := range s.entryPointNames {
- t, ok := s.Types[name]
- if !ok {
- if !ok {
- return errors.Errorf("type %q not found", name)
- }
- }
- s.EntryPoints[key] = t
- }
-
- for _, obj := range s.objects {
- obj.Interfaces = make([]*Interface, len(obj.interfaceNames))
- for i, intfName := range obj.interfaceNames {
- t, ok := s.Types[intfName]
- if !ok {
- return errors.Errorf("interface %q not found", intfName)
- }
- intf, ok := t.(*Interface)
- if !ok {
- return errors.Errorf("type %q is not an interface", intfName)
- }
- obj.Interfaces[i] = intf
- intf.PossibleTypes = append(intf.PossibleTypes, obj)
- }
- }
-
- for _, union := range s.unions {
- union.PossibleTypes = make([]*Object, len(union.typeNames))
- for i, name := range union.typeNames {
- t, ok := s.Types[name]
- if !ok {
- return errors.Errorf("object type %q not found", name)
- }
- obj, ok := t.(*Object)
- if !ok {
- return errors.Errorf("type %q is not an object", name)
- }
- union.PossibleTypes[i] = obj
- }
- }
-
- for _, enum := range s.enums {
- for _, value := range enum.Values {
- if err := resolveDirectives(s, value.Directives); err != nil {
- return err
- }
- }
- }
-
- return nil
-}
-
-func resolveNamedType(s *Schema, t NamedType) error {
- switch t := t.(type) {
- case *Object:
- for _, f := range t.Fields {
- if err := resolveField(s, f); err != nil {
- return err
- }
- }
- case *Interface:
- for _, f := range t.Fields {
- if err := resolveField(s, f); err != nil {
- return err
- }
- }
- case *InputObject:
- if err := resolveInputObject(s, t.Values); err != nil {
- return err
- }
- }
- return nil
-}
-
-func resolveField(s *Schema, f *Field) error {
- t, err := common.ResolveType(f.Type, s.Resolve)
- if err != nil {
- return err
- }
- f.Type = t
- if err := resolveDirectives(s, f.Directives); err != nil {
- return err
- }
- return resolveInputObject(s, f.Args)
-}
-
-func resolveDirectives(s *Schema, directives common.DirectiveList) error {
- for _, d := range directives {
- dirName := d.Name.Name
- dd, ok := s.Directives[dirName]
- if !ok {
- return errors.Errorf("directive %q not found", dirName)
- }
- for _, arg := range d.Args {
- if dd.Args.Get(arg.Name.Name) == nil {
- return errors.Errorf("invalid argument %q for directive %q", arg.Name.Name, dirName)
- }
- }
- for _, arg := range dd.Args {
- if _, ok := d.Args.Get(arg.Name.Name); !ok {
- d.Args = append(d.Args, common.Argument{Name: arg.Name, Value: arg.Default})
- }
- }
- }
- return nil
-}
-
-func resolveInputObject(s *Schema, values common.InputValueList) error {
- for _, v := range values {
- t, err := common.ResolveType(v.Type, s.Resolve)
- if err != nil {
- return err
- }
- v.Type = t
- }
- return nil
-}
-
-func parseSchema(s *Schema, l *common.Lexer) {
- l.Consume()
-
- for l.Peek() != scanner.EOF {
- desc := l.DescComment()
- switch x := l.ConsumeIdent(); x {
-
- case "schema":
- l.ConsumeToken('{')
- for l.Peek() != '}' {
- name := l.ConsumeIdent()
- l.ConsumeToken(':')
- typ := l.ConsumeIdent()
- s.entryPointNames[name] = typ
- }
- l.ConsumeToken('}')
-
- case "type":
- obj := parseObjectDef(l)
- obj.Desc = desc
- s.Types[obj.Name] = obj
- s.objects = append(s.objects, obj)
-
- case "interface":
- iface := parseInterfaceDef(l)
- iface.Desc = desc
- s.Types[iface.Name] = iface
-
- case "union":
- union := parseUnionDef(l)
- union.Desc = desc
- s.Types[union.Name] = union
- s.unions = append(s.unions, union)
-
- case "enum":
- enum := parseEnumDef(l)
- enum.Desc = desc
- s.Types[enum.Name] = enum
- s.enums = append(s.enums, enum)
-
- case "input":
- input := parseInputDef(l)
- input.Desc = desc
- s.Types[input.Name] = input
-
- case "scalar":
- name := l.ConsumeIdent()
- s.Types[name] = &Scalar{Name: name, Desc: desc}
-
- case "directive":
- directive := parseDirectiveDef(l)
- directive.Desc = desc
- s.Directives[directive.Name] = directive
-
- default:
- // TODO: Add support for type extensions.
- l.SyntaxError(fmt.Sprintf(`unexpected %q, expecting "schema", "type", "enum", "interface", "union", "input", "scalar" or "directive"`, x))
- }
- }
-}
-
-func parseObjectDef(l *common.Lexer) *Object {
- object := &Object{Name: l.ConsumeIdent()}
-
- if l.Peek() == scanner.Ident {
- l.ConsumeKeyword("implements")
-
- for l.Peek() != '{' {
- if l.Peek() == '&' {
- l.ConsumeToken('&')
- }
-
- object.interfaceNames = append(object.interfaceNames, l.ConsumeIdent())
- }
- }
-
- l.ConsumeToken('{')
- object.Fields = parseFieldsDef(l)
- l.ConsumeToken('}')
-
- return object
-}
-
-func parseInterfaceDef(l *common.Lexer) *Interface {
- i := &Interface{Name: l.ConsumeIdent()}
-
- l.ConsumeToken('{')
- i.Fields = parseFieldsDef(l)
- l.ConsumeToken('}')
-
- return i
-}
-
-func parseUnionDef(l *common.Lexer) *Union {
- union := &Union{Name: l.ConsumeIdent()}
-
- l.ConsumeToken('=')
- union.typeNames = []string{l.ConsumeIdent()}
- for l.Peek() == '|' {
- l.ConsumeToken('|')
- union.typeNames = append(union.typeNames, l.ConsumeIdent())
- }
-
- return union
-}
-
-func parseInputDef(l *common.Lexer) *InputObject {
- i := &InputObject{}
- i.Name = l.ConsumeIdent()
- l.ConsumeToken('{')
- for l.Peek() != '}' {
- i.Values = append(i.Values, common.ParseInputValue(l))
- }
- l.ConsumeToken('}')
- return i
-}
-
-func parseEnumDef(l *common.Lexer) *Enum {
- enum := &Enum{Name: l.ConsumeIdent()}
-
- l.ConsumeToken('{')
- for l.Peek() != '}' {
- v := &EnumValue{
- Desc: l.DescComment(),
- Name: l.ConsumeIdent(),
- Directives: common.ParseDirectives(l),
- }
-
- enum.Values = append(enum.Values, v)
- }
- l.ConsumeToken('}')
- return enum
-}
-
-func parseDirectiveDef(l *common.Lexer) *DirectiveDecl {
- l.ConsumeToken('@')
- d := &DirectiveDecl{Name: l.ConsumeIdent()}
-
- if l.Peek() == '(' {
- l.ConsumeToken('(')
- for l.Peek() != ')' {
- v := common.ParseInputValue(l)
- d.Args = append(d.Args, v)
- }
- l.ConsumeToken(')')
- }
-
- l.ConsumeKeyword("on")
-
- for {
- loc := l.ConsumeIdent()
- d.Locs = append(d.Locs, loc)
- if l.Peek() != '|' {
- break
- }
- l.ConsumeToken('|')
- }
- return d
-}
-
-func parseFieldsDef(l *common.Lexer) FieldList {
- var fields FieldList
- for l.Peek() != '}' {
- f := &Field{}
- f.Desc = l.DescComment()
- f.Name = l.ConsumeIdent()
- if l.Peek() == '(' {
- l.ConsumeToken('(')
- for l.Peek() != ')' {
- f.Args = append(f.Args, common.ParseInputValue(l))
- }
- l.ConsumeToken(')')
- }
- l.ConsumeToken(':')
- f.Type = common.ParseType(l)
- f.Directives = common.ParseDirectives(l)
- fields = append(fields, f)
- }
- return fields
-}
diff --git a/vendor/github.com/graph-gophers/graphql-go/internal/validation/suggestion.go b/vendor/github.com/graph-gophers/graphql-go/internal/validation/suggestion.go
deleted file mode 100644
index 9702b5f529..0000000000
--- a/vendor/github.com/graph-gophers/graphql-go/internal/validation/suggestion.go
+++ /dev/null
@@ -1,71 +0,0 @@
-package validation
-
-import (
- "fmt"
- "sort"
- "strconv"
- "strings"
-)
-
-func makeSuggestion(prefix string, options []string, input string) string {
- var selected []string
- distances := make(map[string]int)
- for _, opt := range options {
- distance := levenshteinDistance(input, opt)
- threshold := max(len(input)/2, max(len(opt)/2, 1))
- if distance < threshold {
- selected = append(selected, opt)
- distances[opt] = distance
- }
- }
-
- if len(selected) == 0 {
- return ""
- }
- sort.Slice(selected, func(i, j int) bool {
- return distances[selected[i]] < distances[selected[j]]
- })
-
- parts := make([]string, len(selected))
- for i, opt := range selected {
- parts[i] = strconv.Quote(opt)
- }
- if len(parts) > 1 {
- parts[len(parts)-1] = "or " + parts[len(parts)-1]
- }
- return fmt.Sprintf(" %s %s?", prefix, strings.Join(parts, ", "))
-}
-
-func levenshteinDistance(s1, s2 string) int {
- column := make([]int, len(s1)+1)
- for y := range s1 {
- column[y+1] = y + 1
- }
- for x, rx := range s2 {
- column[0] = x + 1
- lastdiag := x
- for y, ry := range s1 {
- olddiag := column[y+1]
- if rx != ry {
- lastdiag++
- }
- column[y+1] = min(column[y+1]+1, min(column[y]+1, lastdiag))
- lastdiag = olddiag
- }
- }
- return column[len(s1)]
-}
-
-func min(a, b int) int {
- if a < b {
- return a
- }
- return b
-}
-
-func max(a, b int) int {
- if a > b {
- return a
- }
- return b
-}
diff --git a/vendor/github.com/graph-gophers/graphql-go/internal/validation/validation.go b/vendor/github.com/graph-gophers/graphql-go/internal/validation/validation.go
deleted file mode 100644
index 94ad5ca7fb..0000000000
--- a/vendor/github.com/graph-gophers/graphql-go/internal/validation/validation.go
+++ /dev/null
@@ -1,909 +0,0 @@
-package validation
-
-import (
- "fmt"
- "math"
- "reflect"
- "strconv"
- "strings"
- "text/scanner"
-
- "github.com/graph-gophers/graphql-go/errors"
- "github.com/graph-gophers/graphql-go/internal/common"
- "github.com/graph-gophers/graphql-go/internal/query"
- "github.com/graph-gophers/graphql-go/internal/schema"
-)
-
-type varSet map[*common.InputValue]struct{}
-
-type selectionPair struct{ a, b query.Selection }
-
-type fieldInfo struct {
- sf *schema.Field
- parent schema.NamedType
-}
-
-type context struct {
- schema *schema.Schema
- doc *query.Document
- errs []*errors.QueryError
- opErrs map[*query.Operation][]*errors.QueryError
- usedVars map[*query.Operation]varSet
- fieldMap map[*query.Field]fieldInfo
- overlapValidated map[selectionPair]struct{}
- maxDepth int
-}
-
-func (c *context) addErr(loc errors.Location, rule string, format string, a ...interface{}) {
- c.addErrMultiLoc([]errors.Location{loc}, rule, format, a...)
-}
-
-func (c *context) addErrMultiLoc(locs []errors.Location, rule string, format string, a ...interface{}) {
- c.errs = append(c.errs, &errors.QueryError{
- Message: fmt.Sprintf(format, a...),
- Locations: locs,
- Rule: rule,
- })
-}
-
-type opContext struct {
- *context
- ops []*query.Operation
-}
-
-func newContext(s *schema.Schema, doc *query.Document, maxDepth int) *context {
- return &context{
- schema: s,
- doc: doc,
- opErrs: make(map[*query.Operation][]*errors.QueryError),
- usedVars: make(map[*query.Operation]varSet),
- fieldMap: make(map[*query.Field]fieldInfo),
- overlapValidated: make(map[selectionPair]struct{}),
- maxDepth: maxDepth,
- }
-}
-
-func Validate(s *schema.Schema, doc *query.Document, maxDepth int) []*errors.QueryError {
- c := newContext(s, doc, maxDepth)
-
- opNames := make(nameSet)
- fragUsedBy := make(map[*query.FragmentDecl][]*query.Operation)
- for _, op := range doc.Operations {
- c.usedVars[op] = make(varSet)
- opc := &opContext{c, []*query.Operation{op}}
-
- // Check if max depth is exceeded, if it's set. If max depth is exceeded,
- // don't continue to validate the document and exit early.
- if validateMaxDepth(opc, op.Selections, 1) {
- return c.errs
- }
-
- if op.Name.Name == "" && len(doc.Operations) != 1 {
- c.addErr(op.Loc, "LoneAnonymousOperation", "This anonymous operation must be the only defined operation.")
- }
- if op.Name.Name != "" {
- validateName(c, opNames, op.Name, "UniqueOperationNames", "operation")
- }
-
- validateDirectives(opc, string(op.Type), op.Directives)
-
- varNames := make(nameSet)
- for _, v := range op.Vars {
- validateName(c, varNames, v.Name, "UniqueVariableNames", "variable")
-
- t := resolveType(c, v.Type)
- if !canBeInput(t) {
- c.addErr(v.TypeLoc, "VariablesAreInputTypes", "Variable %q cannot be non-input type %q.", "$"+v.Name.Name, t)
- }
-
- if v.Default != nil {
- validateLiteral(opc, v.Default)
-
- if t != nil {
- if nn, ok := t.(*common.NonNull); ok {
- c.addErr(v.Default.Location(), "DefaultValuesOfCorrectType", "Variable %q of type %q is required and will not use the default value. Perhaps you meant to use type %q.", "$"+v.Name.Name, t, nn.OfType)
- }
-
- if ok, reason := validateValueType(opc, v.Default, t); !ok {
- c.addErr(v.Default.Location(), "DefaultValuesOfCorrectType", "Variable %q of type %q has invalid default value %s.\n%s", "$"+v.Name.Name, t, v.Default, reason)
- }
- }
- }
- }
-
- var entryPoint schema.NamedType
- switch op.Type {
- case query.Query:
- entryPoint = s.EntryPoints["query"]
- case query.Mutation:
- entryPoint = s.EntryPoints["mutation"]
- case query.Subscription:
- entryPoint = s.EntryPoints["subscription"]
- default:
- panic("unreachable")
- }
-
- validateSelectionSet(opc, op.Selections, entryPoint)
-
- fragUsed := make(map[*query.FragmentDecl]struct{})
- markUsedFragments(c, op.Selections, fragUsed)
- for frag := range fragUsed {
- fragUsedBy[frag] = append(fragUsedBy[frag], op)
- }
- }
-
- fragNames := make(nameSet)
- fragVisited := make(map[*query.FragmentDecl]struct{})
- for _, frag := range doc.Fragments {
- opc := &opContext{c, fragUsedBy[frag]}
-
- validateName(c, fragNames, frag.Name, "UniqueFragmentNames", "fragment")
- validateDirectives(opc, "FRAGMENT_DEFINITION", frag.Directives)
-
- t := unwrapType(resolveType(c, &frag.On))
- // continue even if t is nil
- if t != nil && !canBeFragment(t) {
- c.addErr(frag.On.Loc, "FragmentsOnCompositeTypes", "Fragment %q cannot condition on non composite type %q.", frag.Name.Name, t)
- continue
- }
-
- validateSelectionSet(opc, frag.Selections, t)
-
- if _, ok := fragVisited[frag]; !ok {
- detectFragmentCycle(c, frag.Selections, fragVisited, nil, map[string]int{frag.Name.Name: 0})
- }
- }
-
- for _, frag := range doc.Fragments {
- if len(fragUsedBy[frag]) == 0 {
- c.addErr(frag.Loc, "NoUnusedFragments", "Fragment %q is never used.", frag.Name.Name)
- }
- }
-
- for _, op := range doc.Operations {
- c.errs = append(c.errs, c.opErrs[op]...)
-
- opUsedVars := c.usedVars[op]
- for _, v := range op.Vars {
- if _, ok := opUsedVars[v]; !ok {
- opSuffix := ""
- if op.Name.Name != "" {
- opSuffix = fmt.Sprintf(" in operation %q", op.Name.Name)
- }
- c.addErr(v.Loc, "NoUnusedVariables", "Variable %q is never used%s.", "$"+v.Name.Name, opSuffix)
- }
- }
- }
-
- return c.errs
-}
-
-// validates the query doesn't go deeper than maxDepth (if set). Returns whether
-// or not query validated max depth to avoid excessive recursion.
-func validateMaxDepth(c *opContext, sels []query.Selection, depth int) bool {
- // maxDepth checking is turned off when maxDepth is 0
- if c.maxDepth == 0 {
- return false
- }
-
- exceededMaxDepth := false
-
- for _, sel := range sels {
- switch sel := sel.(type) {
- case *query.Field:
- if depth > c.maxDepth {
- exceededMaxDepth = true
- c.addErr(sel.Alias.Loc, "MaxDepthExceeded", "Field %q has depth %d that exceeds max depth %d", sel.Name.Name, depth, c.maxDepth)
- continue
- }
- exceededMaxDepth = exceededMaxDepth || validateMaxDepth(c, sel.Selections, depth+1)
- case *query.InlineFragment:
- // Depth is not checked because inline fragments resolve to other fields which are checked.
- // Depth is not incremented because inline fragments have the same depth as neighboring fields
- exceededMaxDepth = exceededMaxDepth || validateMaxDepth(c, sel.Selections, depth)
- case *query.FragmentSpread:
- // Depth is not checked because fragments resolve to other fields which are checked.
- frag := c.doc.Fragments.Get(sel.Name.Name)
- if frag == nil {
- // In case of unknown fragment (invalid request), ignore max depth evaluation
- c.addErr(sel.Loc, "MaxDepthEvaluationError", "Unknown fragment %q. Unable to evaluate depth.", sel.Name.Name)
- continue
- }
- // Depth is not incremented because fragments have the same depth as surrounding fields
- exceededMaxDepth = exceededMaxDepth || validateMaxDepth(c, frag.Selections, depth)
- }
- }
-
- return exceededMaxDepth
-}
-
-func validateSelectionSet(c *opContext, sels []query.Selection, t schema.NamedType) {
- for _, sel := range sels {
- validateSelection(c, sel, t)
- }
-
- for i, a := range sels {
- for _, b := range sels[i+1:] {
- c.validateOverlap(a, b, nil, nil)
- }
- }
-}
-
-func validateSelection(c *opContext, sel query.Selection, t schema.NamedType) {
- switch sel := sel.(type) {
- case *query.Field:
- validateDirectives(c, "FIELD", sel.Directives)
-
- fieldName := sel.Name.Name
- var f *schema.Field
- switch fieldName {
- case "__typename":
- f = &schema.Field{
- Name: "__typename",
- Type: c.schema.Types["String"],
- }
- case "__schema":
- f = &schema.Field{
- Name: "__schema",
- Type: c.schema.Types["__Schema"],
- }
- case "__type":
- f = &schema.Field{
- Name: "__type",
- Args: common.InputValueList{
- &common.InputValue{
- Name: common.Ident{Name: "name"},
- Type: &common.NonNull{OfType: c.schema.Types["String"]},
- },
- },
- Type: c.schema.Types["__Type"],
- }
- default:
- f = fields(t).Get(fieldName)
- if f == nil && t != nil {
- suggestion := makeSuggestion("Did you mean", fields(t).Names(), fieldName)
- c.addErr(sel.Alias.Loc, "FieldsOnCorrectType", "Cannot query field %q on type %q.%s", fieldName, t, suggestion)
- }
- }
- c.fieldMap[sel] = fieldInfo{sf: f, parent: t}
-
- validateArgumentLiterals(c, sel.Arguments)
- if f != nil {
- validateArgumentTypes(c, sel.Arguments, f.Args, sel.Alias.Loc,
- func() string { return fmt.Sprintf("field %q of type %q", fieldName, t) },
- func() string { return fmt.Sprintf("Field %q", fieldName) },
- )
- }
-
- var ft common.Type
- if f != nil {
- ft = f.Type
- sf := hasSubfields(ft)
- if sf && sel.Selections == nil {
- c.addErr(sel.Alias.Loc, "ScalarLeafs", "Field %q of type %q must have a selection of subfields. Did you mean \"%s { ... }\"?", fieldName, ft, fieldName)
- }
- if !sf && sel.Selections != nil {
- c.addErr(sel.SelectionSetLoc, "ScalarLeafs", "Field %q must not have a selection since type %q has no subfields.", fieldName, ft)
- }
- }
- if sel.Selections != nil {
- validateSelectionSet(c, sel.Selections, unwrapType(ft))
- }
-
- case *query.InlineFragment:
- validateDirectives(c, "INLINE_FRAGMENT", sel.Directives)
- if sel.On.Name != "" {
- fragTyp := unwrapType(resolveType(c.context, &sel.On))
- if fragTyp != nil && !compatible(t, fragTyp) {
- c.addErr(sel.Loc, "PossibleFragmentSpreads", "Fragment cannot be spread here as objects of type %q can never be of type %q.", t, fragTyp)
- }
- t = fragTyp
- // continue even if t is nil
- }
- if t != nil && !canBeFragment(t) {
- c.addErr(sel.On.Loc, "FragmentsOnCompositeTypes", "Fragment cannot condition on non composite type %q.", t)
- return
- }
- validateSelectionSet(c, sel.Selections, unwrapType(t))
-
- case *query.FragmentSpread:
- validateDirectives(c, "FRAGMENT_SPREAD", sel.Directives)
- frag := c.doc.Fragments.Get(sel.Name.Name)
- if frag == nil {
- c.addErr(sel.Name.Loc, "KnownFragmentNames", "Unknown fragment %q.", sel.Name.Name)
- return
- }
- fragTyp := c.schema.Types[frag.On.Name]
- if !compatible(t, fragTyp) {
- c.addErr(sel.Loc, "PossibleFragmentSpreads", "Fragment %q cannot be spread here as objects of type %q can never be of type %q.", frag.Name.Name, t, fragTyp)
- }
-
- default:
- panic("unreachable")
- }
-}
-
-func compatible(a, b common.Type) bool {
- for _, pta := range possibleTypes(a) {
- for _, ptb := range possibleTypes(b) {
- if pta == ptb {
- return true
- }
- }
- }
- return false
-}
-
-func possibleTypes(t common.Type) []*schema.Object {
- switch t := t.(type) {
- case *schema.Object:
- return []*schema.Object{t}
- case *schema.Interface:
- return t.PossibleTypes
- case *schema.Union:
- return t.PossibleTypes
- default:
- return nil
- }
-}
-
-func markUsedFragments(c *context, sels []query.Selection, fragUsed map[*query.FragmentDecl]struct{}) {
- for _, sel := range sels {
- switch sel := sel.(type) {
- case *query.Field:
- if sel.Selections != nil {
- markUsedFragments(c, sel.Selections, fragUsed)
- }
-
- case *query.InlineFragment:
- markUsedFragments(c, sel.Selections, fragUsed)
-
- case *query.FragmentSpread:
- frag := c.doc.Fragments.Get(sel.Name.Name)
- if frag == nil {
- return
- }
-
- if _, ok := fragUsed[frag]; ok {
- return
- }
- fragUsed[frag] = struct{}{}
- markUsedFragments(c, frag.Selections, fragUsed)
-
- default:
- panic("unreachable")
- }
- }
-}
-
-func detectFragmentCycle(c *context, sels []query.Selection, fragVisited map[*query.FragmentDecl]struct{}, spreadPath []*query.FragmentSpread, spreadPathIndex map[string]int) {
- for _, sel := range sels {
- detectFragmentCycleSel(c, sel, fragVisited, spreadPath, spreadPathIndex)
- }
-}
-
-func detectFragmentCycleSel(c *context, sel query.Selection, fragVisited map[*query.FragmentDecl]struct{}, spreadPath []*query.FragmentSpread, spreadPathIndex map[string]int) {
- switch sel := sel.(type) {
- case *query.Field:
- if sel.Selections != nil {
- detectFragmentCycle(c, sel.Selections, fragVisited, spreadPath, spreadPathIndex)
- }
-
- case *query.InlineFragment:
- detectFragmentCycle(c, sel.Selections, fragVisited, spreadPath, spreadPathIndex)
-
- case *query.FragmentSpread:
- frag := c.doc.Fragments.Get(sel.Name.Name)
- if frag == nil {
- return
- }
-
- spreadPath = append(spreadPath, sel)
- if i, ok := spreadPathIndex[frag.Name.Name]; ok {
- cyclePath := spreadPath[i:]
- via := ""
- if len(cyclePath) > 1 {
- names := make([]string, len(cyclePath)-1)
- for i, frag := range cyclePath[:len(cyclePath)-1] {
- names[i] = frag.Name.Name
- }
- via = " via " + strings.Join(names, ", ")
- }
-
- locs := make([]errors.Location, len(cyclePath))
- for i, frag := range cyclePath {
- locs[i] = frag.Loc
- }
- c.addErrMultiLoc(locs, "NoFragmentCycles", "Cannot spread fragment %q within itself%s.", frag.Name.Name, via)
- return
- }
-
- if _, ok := fragVisited[frag]; ok {
- return
- }
- fragVisited[frag] = struct{}{}
-
- spreadPathIndex[frag.Name.Name] = len(spreadPath)
- detectFragmentCycle(c, frag.Selections, fragVisited, spreadPath, spreadPathIndex)
- delete(spreadPathIndex, frag.Name.Name)
-
- default:
- panic("unreachable")
- }
-}
-
-func (c *context) validateOverlap(a, b query.Selection, reasons *[]string, locs *[]errors.Location) {
- if a == b {
- return
- }
-
- if _, ok := c.overlapValidated[selectionPair{a, b}]; ok {
- return
- }
- c.overlapValidated[selectionPair{a, b}] = struct{}{}
- c.overlapValidated[selectionPair{b, a}] = struct{}{}
-
- switch a := a.(type) {
- case *query.Field:
- switch b := b.(type) {
- case *query.Field:
- if b.Alias.Loc.Before(a.Alias.Loc) {
- a, b = b, a
- }
- if reasons2, locs2 := c.validateFieldOverlap(a, b); len(reasons2) != 0 {
- locs2 = append(locs2, a.Alias.Loc, b.Alias.Loc)
- if reasons == nil {
- c.addErrMultiLoc(locs2, "OverlappingFieldsCanBeMerged", "Fields %q conflict because %s. Use different aliases on the fields to fetch both if this was intentional.", a.Alias.Name, strings.Join(reasons2, " and "))
- return
- }
- for _, r := range reasons2 {
- *reasons = append(*reasons, fmt.Sprintf("subfields %q conflict because %s", a.Alias.Name, r))
- }
- *locs = append(*locs, locs2...)
- }
-
- case *query.InlineFragment:
- for _, sel := range b.Selections {
- c.validateOverlap(a, sel, reasons, locs)
- }
-
- case *query.FragmentSpread:
- if frag := c.doc.Fragments.Get(b.Name.Name); frag != nil {
- for _, sel := range frag.Selections {
- c.validateOverlap(a, sel, reasons, locs)
- }
- }
-
- default:
- panic("unreachable")
- }
-
- case *query.InlineFragment:
- for _, sel := range a.Selections {
- c.validateOverlap(sel, b, reasons, locs)
- }
-
- case *query.FragmentSpread:
- if frag := c.doc.Fragments.Get(a.Name.Name); frag != nil {
- for _, sel := range frag.Selections {
- c.validateOverlap(sel, b, reasons, locs)
- }
- }
-
- default:
- panic("unreachable")
- }
-}
-
-func (c *context) validateFieldOverlap(a, b *query.Field) ([]string, []errors.Location) {
- if a.Alias.Name != b.Alias.Name {
- return nil, nil
- }
-
- if asf := c.fieldMap[a].sf; asf != nil {
- if bsf := c.fieldMap[b].sf; bsf != nil {
- if !typesCompatible(asf.Type, bsf.Type) {
- return []string{fmt.Sprintf("they return conflicting types %s and %s", asf.Type, bsf.Type)}, nil
- }
- }
- }
-
- at := c.fieldMap[a].parent
- bt := c.fieldMap[b].parent
- if at == nil || bt == nil || at == bt {
- if a.Name.Name != b.Name.Name {
- return []string{fmt.Sprintf("%s and %s are different fields", a.Name.Name, b.Name.Name)}, nil
- }
-
- if argumentsConflict(a.Arguments, b.Arguments) {
- return []string{"they have differing arguments"}, nil
- }
- }
-
- var reasons []string
- var locs []errors.Location
- for _, a2 := range a.Selections {
- for _, b2 := range b.Selections {
- c.validateOverlap(a2, b2, &reasons, &locs)
- }
- }
- return reasons, locs
-}
-
-func argumentsConflict(a, b common.ArgumentList) bool {
- if len(a) != len(b) {
- return true
- }
- for _, argA := range a {
- valB, ok := b.Get(argA.Name.Name)
- if !ok || !reflect.DeepEqual(argA.Value.Value(nil), valB.Value(nil)) {
- return true
- }
- }
- return false
-}
-
-func fields(t common.Type) schema.FieldList {
- switch t := t.(type) {
- case *schema.Object:
- return t.Fields
- case *schema.Interface:
- return t.Fields
- default:
- return nil
- }
-}
-
-func unwrapType(t common.Type) schema.NamedType {
- if t == nil {
- return nil
- }
- for {
- switch t2 := t.(type) {
- case schema.NamedType:
- return t2
- case *common.List:
- t = t2.OfType
- case *common.NonNull:
- t = t2.OfType
- default:
- panic("unreachable")
- }
- }
-}
-
-func resolveType(c *context, t common.Type) common.Type {
- t2, err := common.ResolveType(t, c.schema.Resolve)
- if err != nil {
- c.errs = append(c.errs, err)
- }
- return t2
-}
-
-func validateDirectives(c *opContext, loc string, directives common.DirectiveList) {
- directiveNames := make(nameSet)
- for _, d := range directives {
- dirName := d.Name.Name
- validateNameCustomMsg(c.context, directiveNames, d.Name, "UniqueDirectivesPerLocation", func() string {
- return fmt.Sprintf("The directive %q can only be used once at this location.", dirName)
- })
-
- validateArgumentLiterals(c, d.Args)
-
- dd, ok := c.schema.Directives[dirName]
- if !ok {
- c.addErr(d.Name.Loc, "KnownDirectives", "Unknown directive %q.", dirName)
- continue
- }
-
- locOK := false
- for _, allowedLoc := range dd.Locs {
- if loc == allowedLoc {
- locOK = true
- break
- }
- }
- if !locOK {
- c.addErr(d.Name.Loc, "KnownDirectives", "Directive %q may not be used on %s.", dirName, loc)
- }
-
- validateArgumentTypes(c, d.Args, dd.Args, d.Name.Loc,
- func() string { return fmt.Sprintf("directive %q", "@"+dirName) },
- func() string { return fmt.Sprintf("Directive %q", "@"+dirName) },
- )
- }
-}
-
-type nameSet map[string]errors.Location
-
-func validateName(c *context, set nameSet, name common.Ident, rule string, kind string) {
- validateNameCustomMsg(c, set, name, rule, func() string {
- return fmt.Sprintf("There can be only one %s named %q.", kind, name.Name)
- })
-}
-
-func validateNameCustomMsg(c *context, set nameSet, name common.Ident, rule string, msg func() string) {
- if loc, ok := set[name.Name]; ok {
- c.addErrMultiLoc([]errors.Location{loc, name.Loc}, rule, msg())
- return
- }
- set[name.Name] = name.Loc
-}
-
-func validateArgumentTypes(c *opContext, args common.ArgumentList, argDecls common.InputValueList, loc errors.Location, owner1, owner2 func() string) {
- for _, selArg := range args {
- arg := argDecls.Get(selArg.Name.Name)
- if arg == nil {
- c.addErr(selArg.Name.Loc, "KnownArgumentNames", "Unknown argument %q on %s.", selArg.Name.Name, owner1())
- continue
- }
- value := selArg.Value
- if ok, reason := validateValueType(c, value, arg.Type); !ok {
- c.addErr(value.Location(), "ArgumentsOfCorrectType", "Argument %q has invalid value %s.\n%s", arg.Name.Name, value, reason)
- }
- }
- for _, decl := range argDecls {
- if _, ok := decl.Type.(*common.NonNull); ok {
- if _, ok := args.Get(decl.Name.Name); !ok {
- c.addErr(loc, "ProvidedNonNullArguments", "%s argument %q of type %q is required but not provided.", owner2(), decl.Name.Name, decl.Type)
- }
- }
- }
-}
-
-func validateArgumentLiterals(c *opContext, args common.ArgumentList) {
- argNames := make(nameSet)
- for _, arg := range args {
- validateName(c.context, argNames, arg.Name, "UniqueArgumentNames", "argument")
- validateLiteral(c, arg.Value)
- }
-}
-
-func validateLiteral(c *opContext, l common.Literal) {
- switch l := l.(type) {
- case *common.ObjectLit:
- fieldNames := make(nameSet)
- for _, f := range l.Fields {
- validateName(c.context, fieldNames, f.Name, "UniqueInputFieldNames", "input field")
- validateLiteral(c, f.Value)
- }
- case *common.ListLit:
- for _, entry := range l.Entries {
- validateLiteral(c, entry)
- }
- case *common.Variable:
- for _, op := range c.ops {
- v := op.Vars.Get(l.Name)
- if v == nil {
- byOp := ""
- if op.Name.Name != "" {
- byOp = fmt.Sprintf(" by operation %q", op.Name.Name)
- }
- c.opErrs[op] = append(c.opErrs[op], &errors.QueryError{
- Message: fmt.Sprintf("Variable %q is not defined%s.", "$"+l.Name, byOp),
- Locations: []errors.Location{l.Loc, op.Loc},
- Rule: "NoUndefinedVariables",
- })
- continue
- }
- c.usedVars[op][v] = struct{}{}
- }
- }
-}
-
-func validateValueType(c *opContext, v common.Literal, t common.Type) (bool, string) {
- if v, ok := v.(*common.Variable); ok {
- for _, op := range c.ops {
- if v2 := op.Vars.Get(v.Name); v2 != nil {
- t2, err := common.ResolveType(v2.Type, c.schema.Resolve)
- if _, ok := t2.(*common.NonNull); !ok && v2.Default != nil {
- t2 = &common.NonNull{OfType: t2}
- }
- if err == nil && !typeCanBeUsedAs(t2, t) {
- c.addErrMultiLoc([]errors.Location{v2.Loc, v.Loc}, "VariablesInAllowedPosition", "Variable %q of type %q used in position expecting type %q.", "$"+v.Name, t2, t)
- }
- }
- }
- return true, ""
- }
-
- if nn, ok := t.(*common.NonNull); ok {
- if isNull(v) {
- return false, fmt.Sprintf("Expected %q, found null.", t)
- }
- t = nn.OfType
- }
- if isNull(v) {
- return true, ""
- }
-
- switch t := t.(type) {
- case *schema.Scalar, *schema.Enum:
- if lit, ok := v.(*common.BasicLit); ok {
- if validateBasicLit(lit, t) {
- return true, ""
- }
- }
-
- case *common.List:
- list, ok := v.(*common.ListLit)
- if !ok {
- return validateValueType(c, v, t.OfType) // single value instead of list
- }
- for i, entry := range list.Entries {
- if ok, reason := validateValueType(c, entry, t.OfType); !ok {
- return false, fmt.Sprintf("In element #%d: %s", i, reason)
- }
- }
- return true, ""
-
- case *schema.InputObject:
- v, ok := v.(*common.ObjectLit)
- if !ok {
- return false, fmt.Sprintf("Expected %q, found not an object.", t)
- }
- for _, f := range v.Fields {
- name := f.Name.Name
- iv := t.Values.Get(name)
- if iv == nil {
- return false, fmt.Sprintf("In field %q: Unknown field.", name)
- }
- if ok, reason := validateValueType(c, f.Value, iv.Type); !ok {
- return false, fmt.Sprintf("In field %q: %s", name, reason)
- }
- }
- for _, iv := range t.Values {
- found := false
- for _, f := range v.Fields {
- if f.Name.Name == iv.Name.Name {
- found = true
- break
- }
- }
- if !found {
- if _, ok := iv.Type.(*common.NonNull); ok && iv.Default == nil {
- return false, fmt.Sprintf("In field %q: Expected %q, found null.", iv.Name.Name, iv.Type)
- }
- }
- }
- return true, ""
- }
-
- return false, fmt.Sprintf("Expected type %q, found %s.", t, v)
-}
-
-func validateBasicLit(v *common.BasicLit, t common.Type) bool {
- switch t := t.(type) {
- case *schema.Scalar:
- switch t.Name {
- case "Int":
- if v.Type != scanner.Int {
- return false
- }
- f, err := strconv.ParseFloat(v.Text, 64)
- if err != nil {
- panic(err)
- }
- return f >= math.MinInt32 && f <= math.MaxInt32
- case "Float":
- return v.Type == scanner.Int || v.Type == scanner.Float
- case "String":
- return v.Type == scanner.String
- case "Boolean":
- return v.Type == scanner.Ident && (v.Text == "true" || v.Text == "false")
- case "ID":
- return v.Type == scanner.Int || v.Type == scanner.String
- default:
- //TODO: Type-check against expected type by Unmarshalling
- return true
- }
-
- case *schema.Enum:
- if v.Type != scanner.Ident {
- return false
- }
- for _, option := range t.Values {
- if option.Name == v.Text {
- return true
- }
- }
- return false
- }
-
- return false
-}
-
-func canBeFragment(t common.Type) bool {
- switch t.(type) {
- case *schema.Object, *schema.Interface, *schema.Union:
- return true
- default:
- return false
- }
-}
-
-func canBeInput(t common.Type) bool {
- switch t := t.(type) {
- case *schema.InputObject, *schema.Scalar, *schema.Enum:
- return true
- case *common.List:
- return canBeInput(t.OfType)
- case *common.NonNull:
- return canBeInput(t.OfType)
- default:
- return false
- }
-}
-
-func hasSubfields(t common.Type) bool {
- switch t := t.(type) {
- case *schema.Object, *schema.Interface, *schema.Union:
- return true
- case *common.List:
- return hasSubfields(t.OfType)
- case *common.NonNull:
- return hasSubfields(t.OfType)
- default:
- return false
- }
-}
-
-func isLeaf(t common.Type) bool {
- switch t.(type) {
- case *schema.Scalar, *schema.Enum:
- return true
- default:
- return false
- }
-}
-
-func isNull(lit interface{}) bool {
- _, ok := lit.(*common.NullLit)
- return ok
-}
-
-func typesCompatible(a, b common.Type) bool {
- al, aIsList := a.(*common.List)
- bl, bIsList := b.(*common.List)
- if aIsList || bIsList {
- return aIsList && bIsList && typesCompatible(al.OfType, bl.OfType)
- }
-
- ann, aIsNN := a.(*common.NonNull)
- bnn, bIsNN := b.(*common.NonNull)
- if aIsNN || bIsNN {
- return aIsNN && bIsNN && typesCompatible(ann.OfType, bnn.OfType)
- }
-
- if isLeaf(a) || isLeaf(b) {
- return a == b
- }
-
- return true
-}
-
-func typeCanBeUsedAs(t, as common.Type) bool {
- nnT, okT := t.(*common.NonNull)
- if okT {
- t = nnT.OfType
- }
-
- nnAs, okAs := as.(*common.NonNull)
- if okAs {
- as = nnAs.OfType
- if !okT {
- return false // nullable can not be used as non-null
- }
- }
-
- if t == as {
- return true
- }
-
- if lT, ok := t.(*common.List); ok {
- if lAs, ok := as.(*common.List); ok {
- return typeCanBeUsedAs(lT.OfType, lAs.OfType)
- }
- }
- return false
-}
diff --git a/vendor/github.com/graph-gophers/graphql-go/introspection.go b/vendor/github.com/graph-gophers/graphql-go/introspection.go
deleted file mode 100644
index 7e515cf25f..0000000000
--- a/vendor/github.com/graph-gophers/graphql-go/introspection.go
+++ /dev/null
@@ -1,117 +0,0 @@
-package graphql
-
-import (
- "context"
- "encoding/json"
-
- "github.com/graph-gophers/graphql-go/internal/exec/resolvable"
- "github.com/graph-gophers/graphql-go/introspection"
-)
-
-// Inspect allows inspection of the given schema.
-func (s *Schema) Inspect() *introspection.Schema {
- return introspection.WrapSchema(s.schema)
-}
-
-// ToJSON encodes the schema in a JSON format used by tools like Relay.
-func (s *Schema) ToJSON() ([]byte, error) {
- result := s.exec(context.Background(), introspectionQuery, "", nil, &resolvable.Schema{
- Query: &resolvable.Object{},
- Schema: *s.schema,
- })
- if len(result.Errors) != 0 {
- panic(result.Errors[0])
- }
- return json.MarshalIndent(result.Data, "", "\t")
-}
-
-var introspectionQuery = `
- query {
- __schema {
- queryType { name }
- mutationType { name }
- subscriptionType { name }
- types {
- ...FullType
- }
- directives {
- name
- description
- locations
- args {
- ...InputValue
- }
- }
- }
- }
- fragment FullType on __Type {
- kind
- name
- description
- fields(includeDeprecated: true) {
- name
- description
- args {
- ...InputValue
- }
- type {
- ...TypeRef
- }
- isDeprecated
- deprecationReason
- }
- inputFields {
- ...InputValue
- }
- interfaces {
- ...TypeRef
- }
- enumValues(includeDeprecated: true) {
- name
- description
- isDeprecated
- deprecationReason
- }
- possibleTypes {
- ...TypeRef
- }
- }
- fragment InputValue on __InputValue {
- name
- description
- type { ...TypeRef }
- defaultValue
- }
- fragment TypeRef on __Type {
- kind
- name
- ofType {
- kind
- name
- ofType {
- kind
- name
- ofType {
- kind
- name
- ofType {
- kind
- name
- ofType {
- kind
- name
- ofType {
- kind
- name
- ofType {
- kind
- name
- }
- }
- }
- }
- }
- }
- }
- }
-`
diff --git a/vendor/github.com/graph-gophers/graphql-go/introspection/introspection.go b/vendor/github.com/graph-gophers/graphql-go/introspection/introspection.go
deleted file mode 100644
index 2f4acad0a6..0000000000
--- a/vendor/github.com/graph-gophers/graphql-go/introspection/introspection.go
+++ /dev/null
@@ -1,313 +0,0 @@
-package introspection
-
-import (
- "sort"
-
- "github.com/graph-gophers/graphql-go/internal/common"
- "github.com/graph-gophers/graphql-go/internal/schema"
-)
-
-type Schema struct {
- schema *schema.Schema
-}
-
-// WrapSchema is only used internally.
-func WrapSchema(schema *schema.Schema) *Schema {
- return &Schema{schema}
-}
-
-func (r *Schema) Types() []*Type {
- var names []string
- for name := range r.schema.Types {
- names = append(names, name)
- }
- sort.Strings(names)
-
- l := make([]*Type, len(names))
- for i, name := range names {
- l[i] = &Type{r.schema.Types[name]}
- }
- return l
-}
-
-func (r *Schema) Directives() []*Directive {
- var names []string
- for name := range r.schema.Directives {
- names = append(names, name)
- }
- sort.Strings(names)
-
- l := make([]*Directive, len(names))
- for i, name := range names {
- l[i] = &Directive{r.schema.Directives[name]}
- }
- return l
-}
-
-func (r *Schema) QueryType() *Type {
- t, ok := r.schema.EntryPoints["query"]
- if !ok {
- return nil
- }
- return &Type{t}
-}
-
-func (r *Schema) MutationType() *Type {
- t, ok := r.schema.EntryPoints["mutation"]
- if !ok {
- return nil
- }
- return &Type{t}
-}
-
-func (r *Schema) SubscriptionType() *Type {
- t, ok := r.schema.EntryPoints["subscription"]
- if !ok {
- return nil
- }
- return &Type{t}
-}
-
-type Type struct {
- typ common.Type
-}
-
-// WrapType is only used internally.
-func WrapType(typ common.Type) *Type {
- return &Type{typ}
-}
-
-func (r *Type) Kind() string {
- return r.typ.Kind()
-}
-
-func (r *Type) Name() *string {
- if named, ok := r.typ.(schema.NamedType); ok {
- name := named.TypeName()
- return &name
- }
- return nil
-}
-
-func (r *Type) Description() *string {
- if named, ok := r.typ.(schema.NamedType); ok {
- desc := named.Description()
- if desc == "" {
- return nil
- }
- return &desc
- }
- return nil
-}
-
-func (r *Type) Fields(args *struct{ IncludeDeprecated bool }) *[]*Field {
- var fields schema.FieldList
- switch t := r.typ.(type) {
- case *schema.Object:
- fields = t.Fields
- case *schema.Interface:
- fields = t.Fields
- default:
- return nil
- }
-
- var l []*Field
- for _, f := range fields {
- if d := f.Directives.Get("deprecated"); d == nil || args.IncludeDeprecated {
- l = append(l, &Field{f})
- }
- }
- return &l
-}
-
-func (r *Type) Interfaces() *[]*Type {
- t, ok := r.typ.(*schema.Object)
- if !ok {
- return nil
- }
-
- l := make([]*Type, len(t.Interfaces))
- for i, intf := range t.Interfaces {
- l[i] = &Type{intf}
- }
- return &l
-}
-
-func (r *Type) PossibleTypes() *[]*Type {
- var possibleTypes []*schema.Object
- switch t := r.typ.(type) {
- case *schema.Interface:
- possibleTypes = t.PossibleTypes
- case *schema.Union:
- possibleTypes = t.PossibleTypes
- default:
- return nil
- }
-
- l := make([]*Type, len(possibleTypes))
- for i, intf := range possibleTypes {
- l[i] = &Type{intf}
- }
- return &l
-}
-
-func (r *Type) EnumValues(args *struct{ IncludeDeprecated bool }) *[]*EnumValue {
- t, ok := r.typ.(*schema.Enum)
- if !ok {
- return nil
- }
-
- var l []*EnumValue
- for _, v := range t.Values {
- if d := v.Directives.Get("deprecated"); d == nil || args.IncludeDeprecated {
- l = append(l, &EnumValue{v})
- }
- }
- return &l
-}
-
-func (r *Type) InputFields() *[]*InputValue {
- t, ok := r.typ.(*schema.InputObject)
- if !ok {
- return nil
- }
-
- l := make([]*InputValue, len(t.Values))
- for i, v := range t.Values {
- l[i] = &InputValue{v}
- }
- return &l
-}
-
-func (r *Type) OfType() *Type {
- switch t := r.typ.(type) {
- case *common.List:
- return &Type{t.OfType}
- case *common.NonNull:
- return &Type{t.OfType}
- default:
- return nil
- }
-}
-
-type Field struct {
- field *schema.Field
-}
-
-func (r *Field) Name() string {
- return r.field.Name
-}
-
-func (r *Field) Description() *string {
- if r.field.Desc == "" {
- return nil
- }
- return &r.field.Desc
-}
-
-func (r *Field) Args() []*InputValue {
- l := make([]*InputValue, len(r.field.Args))
- for i, v := range r.field.Args {
- l[i] = &InputValue{v}
- }
- return l
-}
-
-func (r *Field) Type() *Type {
- return &Type{r.field.Type}
-}
-
-func (r *Field) IsDeprecated() bool {
- return r.field.Directives.Get("deprecated") != nil
-}
-
-func (r *Field) DeprecationReason() *string {
- d := r.field.Directives.Get("deprecated")
- if d == nil {
- return nil
- }
- reason := d.Args.MustGet("reason").Value(nil).(string)
- return &reason
-}
-
-type InputValue struct {
- value *common.InputValue
-}
-
-func (r *InputValue) Name() string {
- return r.value.Name.Name
-}
-
-func (r *InputValue) Description() *string {
- if r.value.Desc == "" {
- return nil
- }
- return &r.value.Desc
-}
-
-func (r *InputValue) Type() *Type {
- return &Type{r.value.Type}
-}
-
-func (r *InputValue) DefaultValue() *string {
- if r.value.Default == nil {
- return nil
- }
- s := r.value.Default.String()
- return &s
-}
-
-type EnumValue struct {
- value *schema.EnumValue
-}
-
-func (r *EnumValue) Name() string {
- return r.value.Name
-}
-
-func (r *EnumValue) Description() *string {
- if r.value.Desc == "" {
- return nil
- }
- return &r.value.Desc
-}
-
-func (r *EnumValue) IsDeprecated() bool {
- return r.value.Directives.Get("deprecated") != nil
-}
-
-func (r *EnumValue) DeprecationReason() *string {
- d := r.value.Directives.Get("deprecated")
- if d == nil {
- return nil
- }
- reason := d.Args.MustGet("reason").Value(nil).(string)
- return &reason
-}
-
-type Directive struct {
- directive *schema.DirectiveDecl
-}
-
-func (r *Directive) Name() string {
- return r.directive.Name
-}
-
-func (r *Directive) Description() *string {
- if r.directive.Desc == "" {
- return nil
- }
- return &r.directive.Desc
-}
-
-func (r *Directive) Locations() []string {
- return r.directive.Locs
-}
-
-func (r *Directive) Args() []*InputValue {
- l := make([]*InputValue, len(r.directive.Args))
- for i, v := range r.directive.Args {
- l[i] = &InputValue{v}
- }
- return l
-}
diff --git a/vendor/github.com/graph-gophers/graphql-go/log/log.go b/vendor/github.com/graph-gophers/graphql-go/log/log.go
deleted file mode 100644
index 25569af7ca..0000000000
--- a/vendor/github.com/graph-gophers/graphql-go/log/log.go
+++ /dev/null
@@ -1,23 +0,0 @@
-package log
-
-import (
- "context"
- "log"
- "runtime"
-)
-
-// Logger is the interface used to log panics that occur during query execution. It is settable via graphql.ParseSchema
-type Logger interface {
- LogPanic(ctx context.Context, value interface{})
-}
-
-// DefaultLogger is the default logger used to log panics that occur during query execution
-type DefaultLogger struct{}
-
-// LogPanic is used to log recovered panic values that occur during query execution
-func (l *DefaultLogger) LogPanic(_ context.Context, value interface{}) {
- const size = 64 << 10
- buf := make([]byte, size)
- buf = buf[:runtime.Stack(buf, false)]
- log.Printf("graphql: panic occurred: %v\n%s", value, buf)
-}
diff --git a/vendor/github.com/graph-gophers/graphql-go/relay/relay.go b/vendor/github.com/graph-gophers/graphql-go/relay/relay.go
deleted file mode 100644
index 78e4dfdd51..0000000000
--- a/vendor/github.com/graph-gophers/graphql-go/relay/relay.go
+++ /dev/null
@@ -1,70 +0,0 @@
-package relay
-
-import (
- "encoding/base64"
- "encoding/json"
- "errors"
- "fmt"
- "net/http"
- "strings"
-
- graphql "github.com/graph-gophers/graphql-go"
-)
-
-func MarshalID(kind string, spec interface{}) graphql.ID {
- d, err := json.Marshal(spec)
- if err != nil {
- panic(fmt.Errorf("relay.MarshalID: %s", err))
- }
- return graphql.ID(base64.URLEncoding.EncodeToString(append([]byte(kind+":"), d...)))
-}
-
-func UnmarshalKind(id graphql.ID) string {
- s, err := base64.URLEncoding.DecodeString(string(id))
- if err != nil {
- return ""
- }
- i := strings.IndexByte(string(s), ':')
- if i == -1 {
- return ""
- }
- return string(s[:i])
-}
-
-func UnmarshalSpec(id graphql.ID, v interface{}) error {
- s, err := base64.URLEncoding.DecodeString(string(id))
- if err != nil {
- return err
- }
- i := strings.IndexByte(string(s), ':')
- if i == -1 {
- return errors.New("invalid graphql.ID")
- }
- return json.Unmarshal([]byte(s[i+1:]), v)
-}
-
-type Handler struct {
- Schema *graphql.Schema
-}
-
-func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
- var params struct {
- Query string `json:"query"`
- OperationName string `json:"operationName"`
- Variables map[string]interface{} `json:"variables"`
- }
- if err := json.NewDecoder(r.Body).Decode(¶ms); err != nil {
- http.Error(w, err.Error(), http.StatusBadRequest)
- return
- }
-
- response := h.Schema.Exec(r.Context(), params.Query, params.OperationName, params.Variables)
- responseJSON, err := json.Marshal(response)
- if err != nil {
- http.Error(w, err.Error(), http.StatusInternalServerError)
- return
- }
-
- w.Header().Set("Content-Type", "application/json")
- w.Write(responseJSON)
-}
diff --git a/vendor/github.com/graph-gophers/graphql-go/time.go b/vendor/github.com/graph-gophers/graphql-go/time.go
deleted file mode 100644
index 829c502275..0000000000
--- a/vendor/github.com/graph-gophers/graphql-go/time.go
+++ /dev/null
@@ -1,51 +0,0 @@
-package graphql
-
-import (
- "encoding/json"
- "fmt"
- "time"
-)
-
-// Time is a custom GraphQL type to represent an instant in time. It has to be added to a schema
-// via "scalar Time" since it is not a predeclared GraphQL type like "ID".
-type Time struct {
- time.Time
-}
-
-// ImplementsGraphQLType maps this custom Go type
-// to the graphql scalar type in the schema.
-func (Time) ImplementsGraphQLType(name string) bool {
- return name == "Time"
-}
-
-// UnmarshalGraphQL is a custom unmarshaler for Time
-//
-// This function will be called whenever you use the
-// time scalar as an input
-func (t *Time) UnmarshalGraphQL(input interface{}) error {
- switch input := input.(type) {
- case time.Time:
- t.Time = input
- return nil
- case string:
- var err error
- t.Time, err = time.Parse(time.RFC3339, input)
- return err
- case int:
- t.Time = time.Unix(int64(input), 0)
- return nil
- case float64:
- t.Time = time.Unix(int64(input), 0)
- return nil
- default:
- return fmt.Errorf("wrong type")
- }
-}
-
-// MarshalJSON is a custom marshaler for Time
-//
-// This function will be called whenever you
-// query for fields that use the Time type
-func (t Time) MarshalJSON() ([]byte, error) {
- return json.Marshal(t.Time)
-}
diff --git a/vendor/github.com/graph-gophers/graphql-go/trace/trace.go b/vendor/github.com/graph-gophers/graphql-go/trace/trace.go
deleted file mode 100644
index 68b856ae71..0000000000
--- a/vendor/github.com/graph-gophers/graphql-go/trace/trace.go
+++ /dev/null
@@ -1,80 +0,0 @@
-package trace
-
-import (
- "context"
- "fmt"
-
- "github.com/graph-gophers/graphql-go/errors"
- "github.com/graph-gophers/graphql-go/introspection"
- opentracing "github.com/opentracing/opentracing-go"
- "github.com/opentracing/opentracing-go/ext"
- "github.com/opentracing/opentracing-go/log"
-)
-
-type TraceQueryFinishFunc func([]*errors.QueryError)
-type TraceFieldFinishFunc func(*errors.QueryError)
-
-type Tracer interface {
- TraceQuery(ctx context.Context, queryString string, operationName string, variables map[string]interface{}, varTypes map[string]*introspection.Type) (context.Context, TraceQueryFinishFunc)
- TraceField(ctx context.Context, label, typeName, fieldName string, trivial bool, args map[string]interface{}) (context.Context, TraceFieldFinishFunc)
-}
-
-type OpenTracingTracer struct{}
-
-func (OpenTracingTracer) TraceQuery(ctx context.Context, queryString string, operationName string, variables map[string]interface{}, varTypes map[string]*introspection.Type) (context.Context, TraceQueryFinishFunc) {
- span, spanCtx := opentracing.StartSpanFromContext(ctx, "GraphQL request")
- span.SetTag("graphql.query", queryString)
-
- if operationName != "" {
- span.SetTag("graphql.operationName", operationName)
- }
-
- if len(variables) != 0 {
- span.LogFields(log.Object("graphql.variables", variables))
- }
-
- return spanCtx, func(errs []*errors.QueryError) {
- if len(errs) > 0 {
- msg := errs[0].Error()
- if len(errs) > 1 {
- msg += fmt.Sprintf(" (and %d more errors)", len(errs)-1)
- }
- ext.Error.Set(span, true)
- span.SetTag("graphql.error", msg)
- }
- span.Finish()
- }
-}
-
-func (OpenTracingTracer) TraceField(ctx context.Context, label, typeName, fieldName string, trivial bool, args map[string]interface{}) (context.Context, TraceFieldFinishFunc) {
- if trivial {
- return ctx, noop
- }
-
- span, spanCtx := opentracing.StartSpanFromContext(ctx, label)
- span.SetTag("graphql.type", typeName)
- span.SetTag("graphql.field", fieldName)
- for name, value := range args {
- span.SetTag("graphql.args."+name, value)
- }
-
- return spanCtx, func(err *errors.QueryError) {
- if err != nil {
- ext.Error.Set(span, true)
- span.SetTag("graphql.error", err.Error())
- }
- span.Finish()
- }
-}
-
-func noop(*errors.QueryError) {}
-
-type NoopTracer struct{}
-
-func (NoopTracer) TraceQuery(ctx context.Context, queryString string, operationName string, variables map[string]interface{}, varTypes map[string]*introspection.Type) (context.Context, TraceQueryFinishFunc) {
- return ctx, func(errs []*errors.QueryError) {}
-}
-
-func (NoopTracer) TraceField(ctx context.Context, label, typeName, fieldName string, trivial bool, args map[string]interface{}) (context.Context, TraceFieldFinishFunc) {
- return ctx, func(err *errors.QueryError) {}
-}
diff --git a/vendor/github.com/graph-gophers/graphql-go/trace/validation_trace.go b/vendor/github.com/graph-gophers/graphql-go/trace/validation_trace.go
deleted file mode 100644
index e223f0fdbc..0000000000
--- a/vendor/github.com/graph-gophers/graphql-go/trace/validation_trace.go
+++ /dev/null
@@ -1,17 +0,0 @@
-package trace
-
-import (
- "github.com/graph-gophers/graphql-go/errors"
-)
-
-type TraceValidationFinishFunc = TraceQueryFinishFunc
-
-type ValidationTracer interface {
- TraceValidation() TraceValidationFinishFunc
-}
-
-type NoopValidationTracer struct{}
-
-func (NoopValidationTracer) TraceValidation() TraceValidationFinishFunc {
- return func(errs []*errors.QueryError) {}
-}
diff --git a/vendor/github.com/hashicorp/golang-lru/2q.go b/vendor/github.com/hashicorp/golang-lru/2q.go
deleted file mode 100644
index 337d963296..0000000000
--- a/vendor/github.com/hashicorp/golang-lru/2q.go
+++ /dev/null
@@ -1,212 +0,0 @@
-package lru
-
-import (
- "fmt"
- "sync"
-
- "github.com/hashicorp/golang-lru/simplelru"
-)
-
-const (
- // Default2QRecentRatio is the ratio of the 2Q cache dedicated
- // to recently added entries that have only been accessed once.
- Default2QRecentRatio = 0.25
-
- // Default2QGhostEntries is the default ratio of ghost
- // entries kept to track entries recently evicted
- Default2QGhostEntries = 0.50
-)
-
-// TwoQueueCache is a thread-safe fixed size 2Q cache.
-// 2Q is an enhancement over the standard LRU cache
-// in that it tracks both frequently and recently used
-// entries separately. This avoids a burst in access to new
-// entries from evicting frequently used entries. It adds some
-// additional tracking overhead to the standard LRU cache, and is
-// computationally about 2x the cost, and adds some metadata over
-// head. The ARCCache is similar, but does not require setting any
-// parameters.
-type TwoQueueCache struct {
- size int
- recentSize int
-
- recent *simplelru.LRU
- frequent *simplelru.LRU
- recentEvict *simplelru.LRU
- lock sync.RWMutex
-}
-
-// New2Q creates a new TwoQueueCache using the default
-// values for the parameters.
-func New2Q(size int) (*TwoQueueCache, error) {
- return New2QParams(size, Default2QRecentRatio, Default2QGhostEntries)
-}
-
-// New2QParams creates a new TwoQueueCache using the provided
-// parameter values.
-func New2QParams(size int, recentRatio float64, ghostRatio float64) (*TwoQueueCache, error) {
- if size <= 0 {
- return nil, fmt.Errorf("invalid size")
- }
- if recentRatio < 0.0 || recentRatio > 1.0 {
- return nil, fmt.Errorf("invalid recent ratio")
- }
- if ghostRatio < 0.0 || ghostRatio > 1.0 {
- return nil, fmt.Errorf("invalid ghost ratio")
- }
-
- // Determine the sub-sizes
- recentSize := int(float64(size) * recentRatio)
- evictSize := int(float64(size) * ghostRatio)
-
- // Allocate the LRUs
- recent, err := simplelru.NewLRU(size, nil)
- if err != nil {
- return nil, err
- }
- frequent, err := simplelru.NewLRU(size, nil)
- if err != nil {
- return nil, err
- }
- recentEvict, err := simplelru.NewLRU(evictSize, nil)
- if err != nil {
- return nil, err
- }
-
- // Initialize the cache
- c := &TwoQueueCache{
- size: size,
- recentSize: recentSize,
- recent: recent,
- frequent: frequent,
- recentEvict: recentEvict,
- }
- return c, nil
-}
-
-func (c *TwoQueueCache) Get(key interface{}) (interface{}, bool) {
- c.lock.Lock()
- defer c.lock.Unlock()
-
- // Check if this is a frequent value
- if val, ok := c.frequent.Get(key); ok {
- return val, ok
- }
-
- // If the value is contained in recent, then we
- // promote it to frequent
- if val, ok := c.recent.Peek(key); ok {
- c.recent.Remove(key)
- c.frequent.Add(key, val)
- return val, ok
- }
-
- // No hit
- return nil, false
-}
-
-func (c *TwoQueueCache) Add(key, value interface{}) {
- c.lock.Lock()
- defer c.lock.Unlock()
-
- // Check if the value is frequently used already,
- // and just update the value
- if c.frequent.Contains(key) {
- c.frequent.Add(key, value)
- return
- }
-
- // Check if the value is recently used, and promote
- // the value into the frequent list
- if c.recent.Contains(key) {
- c.recent.Remove(key)
- c.frequent.Add(key, value)
- return
- }
-
- // If the value was recently evicted, add it to the
- // frequently used list
- if c.recentEvict.Contains(key) {
- c.ensureSpace(true)
- c.recentEvict.Remove(key)
- c.frequent.Add(key, value)
- return
- }
-
- // Add to the recently seen list
- c.ensureSpace(false)
- c.recent.Add(key, value)
- return
-}
-
-// ensureSpace is used to ensure we have space in the cache
-func (c *TwoQueueCache) ensureSpace(recentEvict bool) {
- // If we have space, nothing to do
- recentLen := c.recent.Len()
- freqLen := c.frequent.Len()
- if recentLen+freqLen < c.size {
- return
- }
-
- // If the recent buffer is larger than
- // the target, evict from there
- if recentLen > 0 && (recentLen > c.recentSize || (recentLen == c.recentSize && !recentEvict)) {
- k, _, _ := c.recent.RemoveOldest()
- c.recentEvict.Add(k, nil)
- return
- }
-
- // Remove from the frequent list otherwise
- c.frequent.RemoveOldest()
-}
-
-func (c *TwoQueueCache) Len() int {
- c.lock.RLock()
- defer c.lock.RUnlock()
- return c.recent.Len() + c.frequent.Len()
-}
-
-func (c *TwoQueueCache) Keys() []interface{} {
- c.lock.RLock()
- defer c.lock.RUnlock()
- k1 := c.frequent.Keys()
- k2 := c.recent.Keys()
- return append(k1, k2...)
-}
-
-func (c *TwoQueueCache) Remove(key interface{}) {
- c.lock.Lock()
- defer c.lock.Unlock()
- if c.frequent.Remove(key) {
- return
- }
- if c.recent.Remove(key) {
- return
- }
- if c.recentEvict.Remove(key) {
- return
- }
-}
-
-func (c *TwoQueueCache) Purge() {
- c.lock.Lock()
- defer c.lock.Unlock()
- c.recent.Purge()
- c.frequent.Purge()
- c.recentEvict.Purge()
-}
-
-func (c *TwoQueueCache) Contains(key interface{}) bool {
- c.lock.RLock()
- defer c.lock.RUnlock()
- return c.frequent.Contains(key) || c.recent.Contains(key)
-}
-
-func (c *TwoQueueCache) Peek(key interface{}) (interface{}, bool) {
- c.lock.RLock()
- defer c.lock.RUnlock()
- if val, ok := c.frequent.Peek(key); ok {
- return val, ok
- }
- return c.recent.Peek(key)
-}
diff --git a/vendor/github.com/hashicorp/golang-lru/LICENSE b/vendor/github.com/hashicorp/golang-lru/LICENSE
deleted file mode 100644
index be2cc4dfb6..0000000000
--- a/vendor/github.com/hashicorp/golang-lru/LICENSE
+++ /dev/null
@@ -1,362 +0,0 @@
-Mozilla Public License, version 2.0
-
-1. Definitions
-
-1.1. "Contributor"
-
- means each individual or legal entity that creates, contributes to the
- creation of, or owns Covered Software.
-
-1.2. "Contributor Version"
-
- means the combination of the Contributions of others (if any) used by a
- Contributor and that particular Contributor's Contribution.
-
-1.3. "Contribution"
-
- means Covered Software of a particular Contributor.
-
-1.4. "Covered Software"
-
- means Source Code Form to which the initial Contributor has attached the
- notice in Exhibit A, the Executable Form of such Source Code Form, and
- Modifications of such Source Code Form, in each case including portions
- thereof.
-
-1.5. "Incompatible With Secondary Licenses"
- means
-
- a. that the initial Contributor has attached the notice described in
- Exhibit B to the Covered Software; or
-
- b. that the Covered Software was made available under the terms of
- version 1.1 or earlier of the License, but not also under the terms of
- a Secondary License.
-
-1.6. "Executable Form"
-
- means any form of the work other than Source Code Form.
-
-1.7. "Larger Work"
-
- means a work that combines Covered Software with other material, in a
- separate file or files, that is not Covered Software.
-
-1.8. "License"
-
- means this document.
-
-1.9. "Licensable"
-
- means having the right to grant, to the maximum extent possible, whether
- at the time of the initial grant or subsequently, any and all of the
- rights conveyed by this License.
-
-1.10. "Modifications"
-
- means any of the following:
-
- a. any file in Source Code Form that results from an addition to,
- deletion from, or modification of the contents of Covered Software; or
-
- b. any new file in Source Code Form that contains any Covered Software.
-
-1.11. "Patent Claims" of a Contributor
-
- means any patent claim(s), including without limitation, method,
- process, and apparatus claims, in any patent Licensable by such
- Contributor that would be infringed, but for the grant of the License,
- by the making, using, selling, offering for sale, having made, import,
- or transfer of either its Contributions or its Contributor Version.
-
-1.12. "Secondary License"
-
- means either the GNU General Public License, Version 2.0, the GNU Lesser
- General Public License, Version 2.1, the GNU Affero General Public
- License, Version 3.0, or any later versions of those licenses.
-
-1.13. "Source Code Form"
-
- means the form of the work preferred for making modifications.
-
-1.14. "You" (or "Your")
-
- means an individual or a legal entity exercising rights under this
- License. For legal entities, "You" includes any entity that controls, is
- controlled by, or is under common control with You. For purposes of this
- definition, "control" means (a) the power, direct or indirect, to cause
- the direction or management of such entity, whether by contract or
- otherwise, or (b) ownership of more than fifty percent (50%) of the
- outstanding shares or beneficial ownership of such entity.
-
-
-2. License Grants and Conditions
-
-2.1. Grants
-
- Each Contributor hereby grants You a world-wide, royalty-free,
- non-exclusive license:
-
- a. under intellectual property rights (other than patent or trademark)
- Licensable by such Contributor to use, reproduce, make available,
- modify, display, perform, distribute, and otherwise exploit its
- Contributions, either on an unmodified basis, with Modifications, or
- as part of a Larger Work; and
-
- b. under Patent Claims of such Contributor to make, use, sell, offer for
- sale, have made, import, and otherwise transfer either its
- Contributions or its Contributor Version.
-
-2.2. Effective Date
-
- The licenses granted in Section 2.1 with respect to any Contribution
- become effective for each Contribution on the date the Contributor first
- distributes such Contribution.
-
-2.3. Limitations on Grant Scope
-
- The licenses granted in this Section 2 are the only rights granted under
- this License. No additional rights or licenses will be implied from the
- distribution or licensing of Covered Software under this License.
- Notwithstanding Section 2.1(b) above, no patent license is granted by a
- Contributor:
-
- a. for any code that a Contributor has removed from Covered Software; or
-
- b. for infringements caused by: (i) Your and any other third party's
- modifications of Covered Software, or (ii) the combination of its
- Contributions with other software (except as part of its Contributor
- Version); or
-
- c. under Patent Claims infringed by Covered Software in the absence of
- its Contributions.
-
- This License does not grant any rights in the trademarks, service marks,
- or logos of any Contributor (except as may be necessary to comply with
- the notice requirements in Section 3.4).
-
-2.4. Subsequent Licenses
-
- No Contributor makes additional grants as a result of Your choice to
- distribute the Covered Software under a subsequent version of this
- License (see Section 10.2) or under the terms of a Secondary License (if
- permitted under the terms of Section 3.3).
-
-2.5. Representation
-
- Each Contributor represents that the Contributor believes its
- Contributions are its original creation(s) or it has sufficient rights to
- grant the rights to its Contributions conveyed by this License.
-
-2.6. Fair Use
-
- This License is not intended to limit any rights You have under
- applicable copyright doctrines of fair use, fair dealing, or other
- equivalents.
-
-2.7. Conditions
-
- Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in
- Section 2.1.
-
-
-3. Responsibilities
-
-3.1. Distribution of Source Form
-
- All distribution of Covered Software in Source Code Form, including any
- Modifications that You create or to which You contribute, must be under
- the terms of this License. You must inform recipients that the Source
- Code Form of the Covered Software is governed by the terms of this
- License, and how they can obtain a copy of this License. You may not
- attempt to alter or restrict the recipients' rights in the Source Code
- Form.
-
-3.2. Distribution of Executable Form
-
- If You distribute Covered Software in Executable Form then:
-
- a. such Covered Software must also be made available in Source Code Form,
- as described in Section 3.1, and You must inform recipients of the
- Executable Form how they can obtain a copy of such Source Code Form by
- reasonable means in a timely manner, at a charge no more than the cost
- of distribution to the recipient; and
-
- b. You may distribute such Executable Form under the terms of this
- License, or sublicense it under different terms, provided that the
- license for the Executable Form does not attempt to limit or alter the
- recipients' rights in the Source Code Form under this License.
-
-3.3. Distribution of a Larger Work
-
- You may create and distribute a Larger Work under terms of Your choice,
- provided that You also comply with the requirements of this License for
- the Covered Software. If the Larger Work is a combination of Covered
- Software with a work governed by one or more Secondary Licenses, and the
- Covered Software is not Incompatible With Secondary Licenses, this
- License permits You to additionally distribute such Covered Software
- under the terms of such Secondary License(s), so that the recipient of
- the Larger Work may, at their option, further distribute the Covered
- Software under the terms of either this License or such Secondary
- License(s).
-
-3.4. Notices
-
- You may not remove or alter the substance of any license notices
- (including copyright notices, patent notices, disclaimers of warranty, or
- limitations of liability) contained within the Source Code Form of the
- Covered Software, except that You may alter any license notices to the
- extent required to remedy known factual inaccuracies.
-
-3.5. Application of Additional Terms
-
- You may choose to offer, and to charge a fee for, warranty, support,
- indemnity or liability obligations to one or more recipients of Covered
- Software. However, You may do so only on Your own behalf, and not on
- behalf of any Contributor. You must make it absolutely clear that any
- such warranty, support, indemnity, or liability obligation is offered by
- You alone, and You hereby agree to indemnify every Contributor for any
- liability incurred by such Contributor as a result of warranty, support,
- indemnity or liability terms You offer. You may include additional
- disclaimers of warranty and limitations of liability specific to any
- jurisdiction.
-
-4. Inability to Comply Due to Statute or Regulation
-
- If it is impossible for You to comply with any of the terms of this License
- with respect to some or all of the Covered Software due to statute,
- judicial order, or regulation then You must: (a) comply with the terms of
- this License to the maximum extent possible; and (b) describe the
- limitations and the code they affect. Such description must be placed in a
- text file included with all distributions of the Covered Software under
- this License. Except to the extent prohibited by statute or regulation,
- such description must be sufficiently detailed for a recipient of ordinary
- skill to be able to understand it.
-
-5. Termination
-
-5.1. The rights granted under this License will terminate automatically if You
- fail to comply with any of its terms. However, if You become compliant,
- then the rights granted under this License from a particular Contributor
- are reinstated (a) provisionally, unless and until such Contributor
- explicitly and finally terminates Your grants, and (b) on an ongoing
- basis, if such Contributor fails to notify You of the non-compliance by
- some reasonable means prior to 60 days after You have come back into
- compliance. Moreover, Your grants from a particular Contributor are
- reinstated on an ongoing basis if such Contributor notifies You of the
- non-compliance by some reasonable means, this is the first time You have
- received notice of non-compliance with this License from such
- Contributor, and You become compliant prior to 30 days after Your receipt
- of the notice.
-
-5.2. If You initiate litigation against any entity by asserting a patent
- infringement claim (excluding declaratory judgment actions,
- counter-claims, and cross-claims) alleging that a Contributor Version
- directly or indirectly infringes any patent, then the rights granted to
- You by any and all Contributors for the Covered Software under Section
- 2.1 of this License shall terminate.
-
-5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user
- license agreements (excluding distributors and resellers) which have been
- validly granted by You or Your distributors under this License prior to
- termination shall survive termination.
-
-6. Disclaimer of Warranty
-
- Covered Software is provided under this License on an "as is" basis,
- without warranty of any kind, either expressed, implied, or statutory,
- including, without limitation, warranties that the Covered Software is free
- of defects, merchantable, fit for a particular purpose or non-infringing.
- The entire risk as to the quality and performance of the Covered Software
- is with You. Should any Covered Software prove defective in any respect,
- You (not any Contributor) assume the cost of any necessary servicing,
- repair, or correction. This disclaimer of warranty constitutes an essential
- part of this License. No use of any Covered Software is authorized under
- this License except under this disclaimer.
-
-7. Limitation of Liability
-
- Under no circumstances and under no legal theory, whether tort (including
- negligence), contract, or otherwise, shall any Contributor, or anyone who
- distributes Covered Software as permitted above, be liable to You for any
- direct, indirect, special, incidental, or consequential damages of any
- character including, without limitation, damages for lost profits, loss of
- goodwill, work stoppage, computer failure or malfunction, or any and all
- other commercial damages or losses, even if such party shall have been
- informed of the possibility of such damages. This limitation of liability
- shall not apply to liability for death or personal injury resulting from
- such party's negligence to the extent applicable law prohibits such
- limitation. Some jurisdictions do not allow the exclusion or limitation of
- incidental or consequential damages, so this exclusion and limitation may
- not apply to You.
-
-8. Litigation
-
- Any litigation relating to this License may be brought only in the courts
- of a jurisdiction where the defendant maintains its principal place of
- business and such litigation shall be governed by laws of that
- jurisdiction, without reference to its conflict-of-law provisions. Nothing
- in this Section shall prevent a party's ability to bring cross-claims or
- counter-claims.
-
-9. Miscellaneous
-
- This License represents the complete agreement concerning the subject
- matter hereof. If any provision of this License is held to be
- unenforceable, such provision shall be reformed only to the extent
- necessary to make it enforceable. Any law or regulation which provides that
- the language of a contract shall be construed against the drafter shall not
- be used to construe this License against a Contributor.
-
-
-10. Versions of the License
-
-10.1. New Versions
-
- Mozilla Foundation is the license steward. Except as provided in Section
- 10.3, no one other than the license steward has the right to modify or
- publish new versions of this License. Each version will be given a
- distinguishing version number.
-
-10.2. Effect of New Versions
-
- You may distribute the Covered Software under the terms of the version
- of the License under which You originally received the Covered Software,
- or under the terms of any subsequent version published by the license
- steward.
-
-10.3. Modified Versions
-
- If you create software not governed by this License, and you want to
- create a new license for such software, you may create and use a
- modified version of this License if you rename the license and remove
- any references to the name of the license steward (except to note that
- such modified license differs from this License).
-
-10.4. Distributing Source Code Form that is Incompatible With Secondary
- Licenses If You choose to distribute Source Code Form that is
- Incompatible With Secondary Licenses under the terms of this version of
- the License, the notice described in Exhibit B of this License must be
- attached.
-
-Exhibit A - Source Code Form License Notice
-
- This Source Code Form is subject to the
- terms of the Mozilla Public License, v.
- 2.0. If a copy of the MPL was not
- distributed with this file, You can
- obtain one at
- http://mozilla.org/MPL/2.0/.
-
-If it is not possible or desirable to put the notice in a particular file,
-then You may include the notice in a location (such as a LICENSE file in a
-relevant directory) where a recipient would be likely to look for such a
-notice.
-
-You may add additional accurate notices of copyright ownership.
-
-Exhibit B - "Incompatible With Secondary Licenses" Notice
-
- This Source Code Form is "Incompatible
- With Secondary Licenses", as defined by
- the Mozilla Public License, v. 2.0.
diff --git a/vendor/github.com/hashicorp/golang-lru/README.md b/vendor/github.com/hashicorp/golang-lru/README.md
deleted file mode 100644
index 33e58cfaf9..0000000000
--- a/vendor/github.com/hashicorp/golang-lru/README.md
+++ /dev/null
@@ -1,25 +0,0 @@
-golang-lru
-==========
-
-This provides the `lru` package which implements a fixed-size
-thread safe LRU cache. It is based on the cache in Groupcache.
-
-Documentation
-=============
-
-Full docs are available on [Godoc](http://godoc.org/github.com/hashicorp/golang-lru)
-
-Example
-=======
-
-Using the LRU is very simple:
-
-```go
-l, _ := New(128)
-for i := 0; i < 256; i++ {
- l.Add(i, nil)
-}
-if l.Len() != 128 {
- panic(fmt.Sprintf("bad len: %v", l.Len()))
-}
-```
diff --git a/vendor/github.com/hashicorp/golang-lru/arc.go b/vendor/github.com/hashicorp/golang-lru/arc.go
deleted file mode 100644
index a2a2528173..0000000000
--- a/vendor/github.com/hashicorp/golang-lru/arc.go
+++ /dev/null
@@ -1,257 +0,0 @@
-package lru
-
-import (
- "sync"
-
- "github.com/hashicorp/golang-lru/simplelru"
-)
-
-// ARCCache is a thread-safe fixed size Adaptive Replacement Cache (ARC).
-// ARC is an enhancement over the standard LRU cache in that tracks both
-// frequency and recency of use. This avoids a burst in access to new
-// entries from evicting the frequently used older entries. It adds some
-// additional tracking overhead to a standard LRU cache, computationally
-// it is roughly 2x the cost, and the extra memory overhead is linear
-// with the size of the cache. ARC has been patented by IBM, but is
-// similar to the TwoQueueCache (2Q) which requires setting parameters.
-type ARCCache struct {
- size int // Size is the total capacity of the cache
- p int // P is the dynamic preference towards T1 or T2
-
- t1 *simplelru.LRU // T1 is the LRU for recently accessed items
- b1 *simplelru.LRU // B1 is the LRU for evictions from t1
-
- t2 *simplelru.LRU // T2 is the LRU for frequently accessed items
- b2 *simplelru.LRU // B2 is the LRU for evictions from t2
-
- lock sync.RWMutex
-}
-
-// NewARC creates an ARC of the given size
-func NewARC(size int) (*ARCCache, error) {
- // Create the sub LRUs
- b1, err := simplelru.NewLRU(size, nil)
- if err != nil {
- return nil, err
- }
- b2, err := simplelru.NewLRU(size, nil)
- if err != nil {
- return nil, err
- }
- t1, err := simplelru.NewLRU(size, nil)
- if err != nil {
- return nil, err
- }
- t2, err := simplelru.NewLRU(size, nil)
- if err != nil {
- return nil, err
- }
-
- // Initialize the ARC
- c := &ARCCache{
- size: size,
- p: 0,
- t1: t1,
- b1: b1,
- t2: t2,
- b2: b2,
- }
- return c, nil
-}
-
-// Get looks up a key's value from the cache.
-func (c *ARCCache) Get(key interface{}) (interface{}, bool) {
- c.lock.Lock()
- defer c.lock.Unlock()
-
- // Ff the value is contained in T1 (recent), then
- // promote it to T2 (frequent)
- if val, ok := c.t1.Peek(key); ok {
- c.t1.Remove(key)
- c.t2.Add(key, val)
- return val, ok
- }
-
- // Check if the value is contained in T2 (frequent)
- if val, ok := c.t2.Get(key); ok {
- return val, ok
- }
-
- // No hit
- return nil, false
-}
-
-// Add adds a value to the cache.
-func (c *ARCCache) Add(key, value interface{}) {
- c.lock.Lock()
- defer c.lock.Unlock()
-
- // Check if the value is contained in T1 (recent), and potentially
- // promote it to frequent T2
- if c.t1.Contains(key) {
- c.t1.Remove(key)
- c.t2.Add(key, value)
- return
- }
-
- // Check if the value is already in T2 (frequent) and update it
- if c.t2.Contains(key) {
- c.t2.Add(key, value)
- return
- }
-
- // Check if this value was recently evicted as part of the
- // recently used list
- if c.b1.Contains(key) {
- // T1 set is too small, increase P appropriately
- delta := 1
- b1Len := c.b1.Len()
- b2Len := c.b2.Len()
- if b2Len > b1Len {
- delta = b2Len / b1Len
- }
- if c.p+delta >= c.size {
- c.p = c.size
- } else {
- c.p += delta
- }
-
- // Potentially need to make room in the cache
- if c.t1.Len()+c.t2.Len() >= c.size {
- c.replace(false)
- }
-
- // Remove from B1
- c.b1.Remove(key)
-
- // Add the key to the frequently used list
- c.t2.Add(key, value)
- return
- }
-
- // Check if this value was recently evicted as part of the
- // frequently used list
- if c.b2.Contains(key) {
- // T2 set is too small, decrease P appropriately
- delta := 1
- b1Len := c.b1.Len()
- b2Len := c.b2.Len()
- if b1Len > b2Len {
- delta = b1Len / b2Len
- }
- if delta >= c.p {
- c.p = 0
- } else {
- c.p -= delta
- }
-
- // Potentially need to make room in the cache
- if c.t1.Len()+c.t2.Len() >= c.size {
- c.replace(true)
- }
-
- // Remove from B2
- c.b2.Remove(key)
-
- // Add the key to the frequntly used list
- c.t2.Add(key, value)
- return
- }
-
- // Potentially need to make room in the cache
- if c.t1.Len()+c.t2.Len() >= c.size {
- c.replace(false)
- }
-
- // Keep the size of the ghost buffers trim
- if c.b1.Len() > c.size-c.p {
- c.b1.RemoveOldest()
- }
- if c.b2.Len() > c.p {
- c.b2.RemoveOldest()
- }
-
- // Add to the recently seen list
- c.t1.Add(key, value)
- return
-}
-
-// replace is used to adaptively evict from either T1 or T2
-// based on the current learned value of P
-func (c *ARCCache) replace(b2ContainsKey bool) {
- t1Len := c.t1.Len()
- if t1Len > 0 && (t1Len > c.p || (t1Len == c.p && b2ContainsKey)) {
- k, _, ok := c.t1.RemoveOldest()
- if ok {
- c.b1.Add(k, nil)
- }
- } else {
- k, _, ok := c.t2.RemoveOldest()
- if ok {
- c.b2.Add(k, nil)
- }
- }
-}
-
-// Len returns the number of cached entries
-func (c *ARCCache) Len() int {
- c.lock.RLock()
- defer c.lock.RUnlock()
- return c.t1.Len() + c.t2.Len()
-}
-
-// Keys returns all the cached keys
-func (c *ARCCache) Keys() []interface{} {
- c.lock.RLock()
- defer c.lock.RUnlock()
- k1 := c.t1.Keys()
- k2 := c.t2.Keys()
- return append(k1, k2...)
-}
-
-// Remove is used to purge a key from the cache
-func (c *ARCCache) Remove(key interface{}) {
- c.lock.Lock()
- defer c.lock.Unlock()
- if c.t1.Remove(key) {
- return
- }
- if c.t2.Remove(key) {
- return
- }
- if c.b1.Remove(key) {
- return
- }
- if c.b2.Remove(key) {
- return
- }
-}
-
-// Purge is used to clear the cache
-func (c *ARCCache) Purge() {
- c.lock.Lock()
- defer c.lock.Unlock()
- c.t1.Purge()
- c.t2.Purge()
- c.b1.Purge()
- c.b2.Purge()
-}
-
-// Contains is used to check if the cache contains a key
-// without updating recency or frequency.
-func (c *ARCCache) Contains(key interface{}) bool {
- c.lock.RLock()
- defer c.lock.RUnlock()
- return c.t1.Contains(key) || c.t2.Contains(key)
-}
-
-// Peek is used to inspect the cache value of a key
-// without updating recency or frequency.
-func (c *ARCCache) Peek(key interface{}) (interface{}, bool) {
- c.lock.RLock()
- defer c.lock.RUnlock()
- if val, ok := c.t1.Peek(key); ok {
- return val, ok
- }
- return c.t2.Peek(key)
-}
diff --git a/vendor/github.com/hashicorp/golang-lru/lru.go b/vendor/github.com/hashicorp/golang-lru/lru.go
deleted file mode 100644
index a6285f989e..0000000000
--- a/vendor/github.com/hashicorp/golang-lru/lru.go
+++ /dev/null
@@ -1,114 +0,0 @@
-// This package provides a simple LRU cache. It is based on the
-// LRU implementation in groupcache:
-// https://github.com/golang/groupcache/tree/master/lru
-package lru
-
-import (
- "sync"
-
- "github.com/hashicorp/golang-lru/simplelru"
-)
-
-// Cache is a thread-safe fixed size LRU cache.
-type Cache struct {
- lru *simplelru.LRU
- lock sync.RWMutex
-}
-
-// New creates an LRU of the given size
-func New(size int) (*Cache, error) {
- return NewWithEvict(size, nil)
-}
-
-// NewWithEvict constructs a fixed size cache with the given eviction
-// callback.
-func NewWithEvict(size int, onEvicted func(key interface{}, value interface{})) (*Cache, error) {
- lru, err := simplelru.NewLRU(size, simplelru.EvictCallback(onEvicted))
- if err != nil {
- return nil, err
- }
- c := &Cache{
- lru: lru,
- }
- return c, nil
-}
-
-// Purge is used to completely clear the cache
-func (c *Cache) Purge() {
- c.lock.Lock()
- c.lru.Purge()
- c.lock.Unlock()
-}
-
-// Add adds a value to the cache. Returns true if an eviction occurred.
-func (c *Cache) Add(key, value interface{}) bool {
- c.lock.Lock()
- defer c.lock.Unlock()
- return c.lru.Add(key, value)
-}
-
-// Get looks up a key's value from the cache.
-func (c *Cache) Get(key interface{}) (interface{}, bool) {
- c.lock.Lock()
- defer c.lock.Unlock()
- return c.lru.Get(key)
-}
-
-// Check if a key is in the cache, without updating the recent-ness
-// or deleting it for being stale.
-func (c *Cache) Contains(key interface{}) bool {
- c.lock.RLock()
- defer c.lock.RUnlock()
- return c.lru.Contains(key)
-}
-
-// Returns the key value (or undefined if not found) without updating
-// the "recently used"-ness of the key.
-func (c *Cache) Peek(key interface{}) (interface{}, bool) {
- c.lock.RLock()
- defer c.lock.RUnlock()
- return c.lru.Peek(key)
-}
-
-// ContainsOrAdd checks if a key is in the cache without updating the
-// recent-ness or deleting it for being stale, and if not, adds the value.
-// Returns whether found and whether an eviction occurred.
-func (c *Cache) ContainsOrAdd(key, value interface{}) (ok, evict bool) {
- c.lock.Lock()
- defer c.lock.Unlock()
-
- if c.lru.Contains(key) {
- return true, false
- } else {
- evict := c.lru.Add(key, value)
- return false, evict
- }
-}
-
-// Remove removes the provided key from the cache.
-func (c *Cache) Remove(key interface{}) {
- c.lock.Lock()
- c.lru.Remove(key)
- c.lock.Unlock()
-}
-
-// RemoveOldest removes the oldest item from the cache.
-func (c *Cache) RemoveOldest() {
- c.lock.Lock()
- c.lru.RemoveOldest()
- c.lock.Unlock()
-}
-
-// Keys returns a slice of the keys in the cache, from oldest to newest.
-func (c *Cache) Keys() []interface{} {
- c.lock.RLock()
- defer c.lock.RUnlock()
- return c.lru.Keys()
-}
-
-// Len returns the number of items in the cache.
-func (c *Cache) Len() int {
- c.lock.RLock()
- defer c.lock.RUnlock()
- return c.lru.Len()
-}
diff --git a/vendor/github.com/hashicorp/golang-lru/simplelru/lru.go b/vendor/github.com/hashicorp/golang-lru/simplelru/lru.go
deleted file mode 100644
index cb416b394f..0000000000
--- a/vendor/github.com/hashicorp/golang-lru/simplelru/lru.go
+++ /dev/null
@@ -1,160 +0,0 @@
-package simplelru
-
-import (
- "container/list"
- "errors"
-)
-
-// EvictCallback is used to get a callback when a cache entry is evicted
-type EvictCallback func(key interface{}, value interface{})
-
-// LRU implements a non-thread safe fixed size LRU cache
-type LRU struct {
- size int
- evictList *list.List
- items map[interface{}]*list.Element
- onEvict EvictCallback
-}
-
-// entry is used to hold a value in the evictList
-type entry struct {
- key interface{}
- value interface{}
-}
-
-// NewLRU constructs an LRU of the given size
-func NewLRU(size int, onEvict EvictCallback) (*LRU, error) {
- if size <= 0 {
- return nil, errors.New("Must provide a positive size")
- }
- c := &LRU{
- size: size,
- evictList: list.New(),
- items: make(map[interface{}]*list.Element),
- onEvict: onEvict,
- }
- return c, nil
-}
-
-// Purge is used to completely clear the cache
-func (c *LRU) Purge() {
- for k, v := range c.items {
- if c.onEvict != nil {
- c.onEvict(k, v.Value.(*entry).value)
- }
- delete(c.items, k)
- }
- c.evictList.Init()
-}
-
-// Add adds a value to the cache. Returns true if an eviction occurred.
-func (c *LRU) Add(key, value interface{}) bool {
- // Check for existing item
- if ent, ok := c.items[key]; ok {
- c.evictList.MoveToFront(ent)
- ent.Value.(*entry).value = value
- return false
- }
-
- // Add new item
- ent := &entry{key, value}
- entry := c.evictList.PushFront(ent)
- c.items[key] = entry
-
- evict := c.evictList.Len() > c.size
- // Verify size not exceeded
- if evict {
- c.removeOldest()
- }
- return evict
-}
-
-// Get looks up a key's value from the cache.
-func (c *LRU) Get(key interface{}) (value interface{}, ok bool) {
- if ent, ok := c.items[key]; ok {
- c.evictList.MoveToFront(ent)
- return ent.Value.(*entry).value, true
- }
- return
-}
-
-// Check if a key is in the cache, without updating the recent-ness
-// or deleting it for being stale.
-func (c *LRU) Contains(key interface{}) (ok bool) {
- _, ok = c.items[key]
- return ok
-}
-
-// Returns the key value (or undefined if not found) without updating
-// the "recently used"-ness of the key.
-func (c *LRU) Peek(key interface{}) (value interface{}, ok bool) {
- if ent, ok := c.items[key]; ok {
- return ent.Value.(*entry).value, true
- }
- return nil, ok
-}
-
-// Remove removes the provided key from the cache, returning if the
-// key was contained.
-func (c *LRU) Remove(key interface{}) bool {
- if ent, ok := c.items[key]; ok {
- c.removeElement(ent)
- return true
- }
- return false
-}
-
-// RemoveOldest removes the oldest item from the cache.
-func (c *LRU) RemoveOldest() (interface{}, interface{}, bool) {
- ent := c.evictList.Back()
- if ent != nil {
- c.removeElement(ent)
- kv := ent.Value.(*entry)
- return kv.key, kv.value, true
- }
- return nil, nil, false
-}
-
-// GetOldest returns the oldest entry
-func (c *LRU) GetOldest() (interface{}, interface{}, bool) {
- ent := c.evictList.Back()
- if ent != nil {
- kv := ent.Value.(*entry)
- return kv.key, kv.value, true
- }
- return nil, nil, false
-}
-
-// Keys returns a slice of the keys in the cache, from oldest to newest.
-func (c *LRU) Keys() []interface{} {
- keys := make([]interface{}, len(c.items))
- i := 0
- for ent := c.evictList.Back(); ent != nil; ent = ent.Prev() {
- keys[i] = ent.Value.(*entry).key
- i++
- }
- return keys
-}
-
-// Len returns the number of items in the cache.
-func (c *LRU) Len() int {
- return c.evictList.Len()
-}
-
-// removeOldest removes the oldest item from the cache.
-func (c *LRU) removeOldest() {
- ent := c.evictList.Back()
- if ent != nil {
- c.removeElement(ent)
- }
-}
-
-// removeElement is used to remove a given list element from the cache
-func (c *LRU) removeElement(e *list.Element) {
- c.evictList.Remove(e)
- kv := e.Value.(*entry)
- delete(c.items, kv.key)
- if c.onEvict != nil {
- c.onEvict(kv.key, kv.value)
- }
-}
diff --git a/vendor/github.com/huin/goupnp/LICENSE b/vendor/github.com/huin/goupnp/LICENSE
deleted file mode 100644
index 252e3d6397..0000000000
--- a/vendor/github.com/huin/goupnp/LICENSE
+++ /dev/null
@@ -1,23 +0,0 @@
-Copyright (c) 2013, John Beisley
-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.
-
-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.
diff --git a/vendor/github.com/huin/goupnp/README.md b/vendor/github.com/huin/goupnp/README.md
deleted file mode 100644
index 433ba5c682..0000000000
--- a/vendor/github.com/huin/goupnp/README.md
+++ /dev/null
@@ -1,44 +0,0 @@
-goupnp is a UPnP client library for Go
-
-Installation
-------------
-
-Run `go get -u github.com/huin/goupnp`.
-
-Documentation
--------------
-
-Supported DCPs (you probably want to start with one of these):
-
-* [![GoDoc](https://godoc.org/github.com/huin/goupnp?status.svg) av1](https://godoc.org/github.com/huin/goupnp/dcps/av1) - Client for UPnP Device Control Protocol MediaServer v1 and MediaRenderer v1.
-* [![GoDoc](https://godoc.org/github.com/huin/goupnp?status.svg) internetgateway1](https://godoc.org/github.com/huin/goupnp/dcps/internetgateway1) - Client for UPnP Device Control Protocol Internet Gateway Device v1.
-* [![GoDoc](https://godoc.org/github.com/huin/goupnp?status.svg) internetgateway2](https://godoc.org/github.com/huin/goupnp/dcps/internetgateway2) - Client for UPnP Device Control Protocol Internet Gateway Device v2.
-
-Core components:
-
-* [![GoDoc](https://godoc.org/github.com/huin/goupnp?status.svg) (goupnp)](https://godoc.org/github.com/huin/goupnp) core library - contains datastructures and utilities typically used by the implemented DCPs.
-* [![GoDoc](https://godoc.org/github.com/huin/goupnp?status.svg) httpu](https://godoc.org/github.com/huin/goupnp/httpu) HTTPU implementation, underlies SSDP.
-* [![GoDoc](https://godoc.org/github.com/huin/goupnp?status.svg) ssdp](https://godoc.org/github.com/huin/goupnp/ssdp) SSDP client implementation (simple service discovery protocol) - used to discover UPnP services on a network.
-* [![GoDoc](https://godoc.org/github.com/huin/goupnp?status.svg) soap](https://godoc.org/github.com/huin/goupnp/soap) SOAP client implementation (simple object access protocol) - used to communicate with discovered services.
-
-
-Regenerating dcps generated source code:
-----------------------------------------
-
-1. Install gotasks: `go get -u github.com/jingweno/gotask`
-2. Change to the gotasks directory: `cd gotasks`
-3. Run specgen task: `gotask specgen`
-
-Supporting additional UPnP devices and services:
-------------------------------------------------
-
-Supporting additional services is, in the trivial case, simply a matter of
-adding the service to the `dcpMetadata` whitelist in `gotasks/specgen_task.go`,
-regenerating the source code (see above), and committing that source code.
-
-However, it would be helpful if anyone needing such a service could test the
-service against the service they have, and then reporting any trouble
-encountered as an [issue on this
-project](https://github.com/huin/goupnp/issues/new). If it just works, then
-please report at least minimal working functionality as an issue, and
-optionally contribute the metadata upstream.
diff --git a/vendor/github.com/huin/goupnp/dcps/internetgateway1/internetgateway1.go b/vendor/github.com/huin/goupnp/dcps/internetgateway1/internetgateway1.go
deleted file mode 100644
index 1e0802cd4e..0000000000
--- a/vendor/github.com/huin/goupnp/dcps/internetgateway1/internetgateway1.go
+++ /dev/null
@@ -1,3717 +0,0 @@
-// Client for UPnP Device Control Protocol Internet Gateway Device v1.
-//
-// This DCP is documented in detail at: http://upnp.org/specs/gw/UPnP-gw-InternetGatewayDevice-v1-Device.pdf
-//
-// Typically, use one of the New* functions to create clients for services.
-package internetgateway1
-
-// Generated file - do not edit by hand. See README.md
-
-import (
- "net/url"
- "time"
-
- "github.com/huin/goupnp"
- "github.com/huin/goupnp/soap"
-)
-
-// Hack to avoid Go complaining if time isn't used.
-var _ time.Time
-
-// Device URNs:
-const (
- URN_LANDevice_1 = "urn:schemas-upnp-org:device:LANDevice:1"
- URN_WANConnectionDevice_1 = "urn:schemas-upnp-org:device:WANConnectionDevice:1"
- URN_WANDevice_1 = "urn:schemas-upnp-org:device:WANDevice:1"
-)
-
-// Service URNs:
-const (
- URN_LANHostConfigManagement_1 = "urn:schemas-upnp-org:service:LANHostConfigManagement:1"
- URN_Layer3Forwarding_1 = "urn:schemas-upnp-org:service:Layer3Forwarding:1"
- URN_WANCableLinkConfig_1 = "urn:schemas-upnp-org:service:WANCableLinkConfig:1"
- URN_WANCommonInterfaceConfig_1 = "urn:schemas-upnp-org:service:WANCommonInterfaceConfig:1"
- URN_WANDSLLinkConfig_1 = "urn:schemas-upnp-org:service:WANDSLLinkConfig:1"
- URN_WANEthernetLinkConfig_1 = "urn:schemas-upnp-org:service:WANEthernetLinkConfig:1"
- URN_WANIPConnection_1 = "urn:schemas-upnp-org:service:WANIPConnection:1"
- URN_WANPOTSLinkConfig_1 = "urn:schemas-upnp-org:service:WANPOTSLinkConfig:1"
- URN_WANPPPConnection_1 = "urn:schemas-upnp-org:service:WANPPPConnection:1"
-)
-
-// LANHostConfigManagement1 is a client for UPnP SOAP service with URN "urn:schemas-upnp-org:service:LANHostConfigManagement:1". See
-// goupnp.ServiceClient, which contains RootDevice and Service attributes which
-// are provided for informational value.
-type LANHostConfigManagement1 struct {
- goupnp.ServiceClient
-}
-
-// NewLANHostConfigManagement1Clients discovers instances of the service on the network,
-// and returns clients to any that are found. errors will contain an error for
-// any devices that replied but which could not be queried, and err will be set
-// if the discovery process failed outright.
-//
-// This is a typical entry calling point into this package.
-func NewLANHostConfigManagement1Clients() (clients []*LANHostConfigManagement1, errors []error, err error) {
- var genericClients []goupnp.ServiceClient
- if genericClients, errors, err = goupnp.NewServiceClients(URN_LANHostConfigManagement_1); err != nil {
- return
- }
- clients = newLANHostConfigManagement1ClientsFromGenericClients(genericClients)
- return
-}
-
-// NewLANHostConfigManagement1ClientsByURL discovers instances of the service at the given
-// URL, and returns clients to any that are found. An error is returned if
-// there was an error probing the service.
-//
-// This is a typical entry calling point into this package when reusing an
-// previously discovered service URL.
-func NewLANHostConfigManagement1ClientsByURL(loc *url.URL) ([]*LANHostConfigManagement1, error) {
- genericClients, err := goupnp.NewServiceClientsByURL(loc, URN_LANHostConfigManagement_1)
- if err != nil {
- return nil, err
- }
- return newLANHostConfigManagement1ClientsFromGenericClients(genericClients), nil
-}
-
-// NewLANHostConfigManagement1ClientsFromRootDevice discovers instances of the service in
-// a given root device, and returns clients to any that are found. An error is
-// returned if there was not at least one instance of the service within the
-// device. The location parameter is simply assigned to the Location attribute
-// of the wrapped ServiceClient(s).
-//
-// This is a typical entry calling point into this package when reusing an
-// previously discovered root device.
-func NewLANHostConfigManagement1ClientsFromRootDevice(rootDevice *goupnp.RootDevice, loc *url.URL) ([]*LANHostConfigManagement1, error) {
- genericClients, err := goupnp.NewServiceClientsFromRootDevice(rootDevice, loc, URN_LANHostConfigManagement_1)
- if err != nil {
- return nil, err
- }
- return newLANHostConfigManagement1ClientsFromGenericClients(genericClients), nil
-}
-
-func newLANHostConfigManagement1ClientsFromGenericClients(genericClients []goupnp.ServiceClient) []*LANHostConfigManagement1 {
- clients := make([]*LANHostConfigManagement1, len(genericClients))
- for i := range genericClients {
- clients[i] = &LANHostConfigManagement1{genericClients[i]}
- }
- return clients
-}
-
-func (client *LANHostConfigManagement1) SetDHCPServerConfigurable(NewDHCPServerConfigurable bool) (err error) {
- // Request structure.
- request := &struct {
- NewDHCPServerConfigurable string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.NewDHCPServerConfigurable, err = soap.MarshalBoolean(NewDHCPServerConfigurable); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_LANHostConfigManagement_1, "SetDHCPServerConfigurable", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *LANHostConfigManagement1) GetDHCPServerConfigurable() (NewDHCPServerConfigurable bool, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewDHCPServerConfigurable string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_LANHostConfigManagement_1, "GetDHCPServerConfigurable", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewDHCPServerConfigurable, err = soap.UnmarshalBoolean(response.NewDHCPServerConfigurable); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *LANHostConfigManagement1) SetDHCPRelay(NewDHCPRelay bool) (err error) {
- // Request structure.
- request := &struct {
- NewDHCPRelay string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.NewDHCPRelay, err = soap.MarshalBoolean(NewDHCPRelay); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_LANHostConfigManagement_1, "SetDHCPRelay", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *LANHostConfigManagement1) GetDHCPRelay() (NewDHCPRelay bool, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewDHCPRelay string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_LANHostConfigManagement_1, "GetDHCPRelay", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewDHCPRelay, err = soap.UnmarshalBoolean(response.NewDHCPRelay); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *LANHostConfigManagement1) SetSubnetMask(NewSubnetMask string) (err error) {
- // Request structure.
- request := &struct {
- NewSubnetMask string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.NewSubnetMask, err = soap.MarshalString(NewSubnetMask); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_LANHostConfigManagement_1, "SetSubnetMask", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *LANHostConfigManagement1) GetSubnetMask() (NewSubnetMask string, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewSubnetMask string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_LANHostConfigManagement_1, "GetSubnetMask", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewSubnetMask, err = soap.UnmarshalString(response.NewSubnetMask); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *LANHostConfigManagement1) SetIPRouter(NewIPRouters string) (err error) {
- // Request structure.
- request := &struct {
- NewIPRouters string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.NewIPRouters, err = soap.MarshalString(NewIPRouters); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_LANHostConfigManagement_1, "SetIPRouter", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *LANHostConfigManagement1) DeleteIPRouter(NewIPRouters string) (err error) {
- // Request structure.
- request := &struct {
- NewIPRouters string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.NewIPRouters, err = soap.MarshalString(NewIPRouters); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_LANHostConfigManagement_1, "DeleteIPRouter", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *LANHostConfigManagement1) GetIPRoutersList() (NewIPRouters string, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewIPRouters string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_LANHostConfigManagement_1, "GetIPRoutersList", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewIPRouters, err = soap.UnmarshalString(response.NewIPRouters); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *LANHostConfigManagement1) SetDomainName(NewDomainName string) (err error) {
- // Request structure.
- request := &struct {
- NewDomainName string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.NewDomainName, err = soap.MarshalString(NewDomainName); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_LANHostConfigManagement_1, "SetDomainName", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *LANHostConfigManagement1) GetDomainName() (NewDomainName string, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewDomainName string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_LANHostConfigManagement_1, "GetDomainName", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewDomainName, err = soap.UnmarshalString(response.NewDomainName); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *LANHostConfigManagement1) SetAddressRange(NewMinAddress string, NewMaxAddress string) (err error) {
- // Request structure.
- request := &struct {
- NewMinAddress string
-
- NewMaxAddress string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.NewMinAddress, err = soap.MarshalString(NewMinAddress); err != nil {
- return
- }
- if request.NewMaxAddress, err = soap.MarshalString(NewMaxAddress); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_LANHostConfigManagement_1, "SetAddressRange", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *LANHostConfigManagement1) GetAddressRange() (NewMinAddress string, NewMaxAddress string, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewMinAddress string
-
- NewMaxAddress string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_LANHostConfigManagement_1, "GetAddressRange", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewMinAddress, err = soap.UnmarshalString(response.NewMinAddress); err != nil {
- return
- }
- if NewMaxAddress, err = soap.UnmarshalString(response.NewMaxAddress); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *LANHostConfigManagement1) SetReservedAddress(NewReservedAddresses string) (err error) {
- // Request structure.
- request := &struct {
- NewReservedAddresses string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.NewReservedAddresses, err = soap.MarshalString(NewReservedAddresses); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_LANHostConfigManagement_1, "SetReservedAddress", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *LANHostConfigManagement1) DeleteReservedAddress(NewReservedAddresses string) (err error) {
- // Request structure.
- request := &struct {
- NewReservedAddresses string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.NewReservedAddresses, err = soap.MarshalString(NewReservedAddresses); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_LANHostConfigManagement_1, "DeleteReservedAddress", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *LANHostConfigManagement1) GetReservedAddresses() (NewReservedAddresses string, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewReservedAddresses string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_LANHostConfigManagement_1, "GetReservedAddresses", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewReservedAddresses, err = soap.UnmarshalString(response.NewReservedAddresses); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *LANHostConfigManagement1) SetDNSServer(NewDNSServers string) (err error) {
- // Request structure.
- request := &struct {
- NewDNSServers string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.NewDNSServers, err = soap.MarshalString(NewDNSServers); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_LANHostConfigManagement_1, "SetDNSServer", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *LANHostConfigManagement1) DeleteDNSServer(NewDNSServers string) (err error) {
- // Request structure.
- request := &struct {
- NewDNSServers string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.NewDNSServers, err = soap.MarshalString(NewDNSServers); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_LANHostConfigManagement_1, "DeleteDNSServer", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *LANHostConfigManagement1) GetDNSServers() (NewDNSServers string, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewDNSServers string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_LANHostConfigManagement_1, "GetDNSServers", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewDNSServers, err = soap.UnmarshalString(response.NewDNSServers); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-// Layer3Forwarding1 is a client for UPnP SOAP service with URN "urn:schemas-upnp-org:service:Layer3Forwarding:1". See
-// goupnp.ServiceClient, which contains RootDevice and Service attributes which
-// are provided for informational value.
-type Layer3Forwarding1 struct {
- goupnp.ServiceClient
-}
-
-// NewLayer3Forwarding1Clients discovers instances of the service on the network,
-// and returns clients to any that are found. errors will contain an error for
-// any devices that replied but which could not be queried, and err will be set
-// if the discovery process failed outright.
-//
-// This is a typical entry calling point into this package.
-func NewLayer3Forwarding1Clients() (clients []*Layer3Forwarding1, errors []error, err error) {
- var genericClients []goupnp.ServiceClient
- if genericClients, errors, err = goupnp.NewServiceClients(URN_Layer3Forwarding_1); err != nil {
- return
- }
- clients = newLayer3Forwarding1ClientsFromGenericClients(genericClients)
- return
-}
-
-// NewLayer3Forwarding1ClientsByURL discovers instances of the service at the given
-// URL, and returns clients to any that are found. An error is returned if
-// there was an error probing the service.
-//
-// This is a typical entry calling point into this package when reusing an
-// previously discovered service URL.
-func NewLayer3Forwarding1ClientsByURL(loc *url.URL) ([]*Layer3Forwarding1, error) {
- genericClients, err := goupnp.NewServiceClientsByURL(loc, URN_Layer3Forwarding_1)
- if err != nil {
- return nil, err
- }
- return newLayer3Forwarding1ClientsFromGenericClients(genericClients), nil
-}
-
-// NewLayer3Forwarding1ClientsFromRootDevice discovers instances of the service in
-// a given root device, and returns clients to any that are found. An error is
-// returned if there was not at least one instance of the service within the
-// device. The location parameter is simply assigned to the Location attribute
-// of the wrapped ServiceClient(s).
-//
-// This is a typical entry calling point into this package when reusing an
-// previously discovered root device.
-func NewLayer3Forwarding1ClientsFromRootDevice(rootDevice *goupnp.RootDevice, loc *url.URL) ([]*Layer3Forwarding1, error) {
- genericClients, err := goupnp.NewServiceClientsFromRootDevice(rootDevice, loc, URN_Layer3Forwarding_1)
- if err != nil {
- return nil, err
- }
- return newLayer3Forwarding1ClientsFromGenericClients(genericClients), nil
-}
-
-func newLayer3Forwarding1ClientsFromGenericClients(genericClients []goupnp.ServiceClient) []*Layer3Forwarding1 {
- clients := make([]*Layer3Forwarding1, len(genericClients))
- for i := range genericClients {
- clients[i] = &Layer3Forwarding1{genericClients[i]}
- }
- return clients
-}
-
-func (client *Layer3Forwarding1) SetDefaultConnectionService(NewDefaultConnectionService string) (err error) {
- // Request structure.
- request := &struct {
- NewDefaultConnectionService string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.NewDefaultConnectionService, err = soap.MarshalString(NewDefaultConnectionService); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_Layer3Forwarding_1, "SetDefaultConnectionService", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *Layer3Forwarding1) GetDefaultConnectionService() (NewDefaultConnectionService string, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewDefaultConnectionService string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_Layer3Forwarding_1, "GetDefaultConnectionService", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewDefaultConnectionService, err = soap.UnmarshalString(response.NewDefaultConnectionService); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-// WANCableLinkConfig1 is a client for UPnP SOAP service with URN "urn:schemas-upnp-org:service:WANCableLinkConfig:1". See
-// goupnp.ServiceClient, which contains RootDevice and Service attributes which
-// are provided for informational value.
-type WANCableLinkConfig1 struct {
- goupnp.ServiceClient
-}
-
-// NewWANCableLinkConfig1Clients discovers instances of the service on the network,
-// and returns clients to any that are found. errors will contain an error for
-// any devices that replied but which could not be queried, and err will be set
-// if the discovery process failed outright.
-//
-// This is a typical entry calling point into this package.
-func NewWANCableLinkConfig1Clients() (clients []*WANCableLinkConfig1, errors []error, err error) {
- var genericClients []goupnp.ServiceClient
- if genericClients, errors, err = goupnp.NewServiceClients(URN_WANCableLinkConfig_1); err != nil {
- return
- }
- clients = newWANCableLinkConfig1ClientsFromGenericClients(genericClients)
- return
-}
-
-// NewWANCableLinkConfig1ClientsByURL discovers instances of the service at the given
-// URL, and returns clients to any that are found. An error is returned if
-// there was an error probing the service.
-//
-// This is a typical entry calling point into this package when reusing an
-// previously discovered service URL.
-func NewWANCableLinkConfig1ClientsByURL(loc *url.URL) ([]*WANCableLinkConfig1, error) {
- genericClients, err := goupnp.NewServiceClientsByURL(loc, URN_WANCableLinkConfig_1)
- if err != nil {
- return nil, err
- }
- return newWANCableLinkConfig1ClientsFromGenericClients(genericClients), nil
-}
-
-// NewWANCableLinkConfig1ClientsFromRootDevice discovers instances of the service in
-// a given root device, and returns clients to any that are found. An error is
-// returned if there was not at least one instance of the service within the
-// device. The location parameter is simply assigned to the Location attribute
-// of the wrapped ServiceClient(s).
-//
-// This is a typical entry calling point into this package when reusing an
-// previously discovered root device.
-func NewWANCableLinkConfig1ClientsFromRootDevice(rootDevice *goupnp.RootDevice, loc *url.URL) ([]*WANCableLinkConfig1, error) {
- genericClients, err := goupnp.NewServiceClientsFromRootDevice(rootDevice, loc, URN_WANCableLinkConfig_1)
- if err != nil {
- return nil, err
- }
- return newWANCableLinkConfig1ClientsFromGenericClients(genericClients), nil
-}
-
-func newWANCableLinkConfig1ClientsFromGenericClients(genericClients []goupnp.ServiceClient) []*WANCableLinkConfig1 {
- clients := make([]*WANCableLinkConfig1, len(genericClients))
- for i := range genericClients {
- clients[i] = &WANCableLinkConfig1{genericClients[i]}
- }
- return clients
-}
-
-//
-// Return values:
-//
-// * NewCableLinkConfigState: allowed values: notReady, dsSyncComplete, usParamAcquired, rangingComplete, ipComplete, todEstablished, paramTransferComplete, registrationComplete, operational, accessDenied
-//
-// * NewLinkType: allowed values: Ethernet
-func (client *WANCableLinkConfig1) GetCableLinkConfigInfo() (NewCableLinkConfigState string, NewLinkType string, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewCableLinkConfigState string
-
- NewLinkType string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANCableLinkConfig_1, "GetCableLinkConfigInfo", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewCableLinkConfigState, err = soap.UnmarshalString(response.NewCableLinkConfigState); err != nil {
- return
- }
- if NewLinkType, err = soap.UnmarshalString(response.NewLinkType); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANCableLinkConfig1) GetDownstreamFrequency() (NewDownstreamFrequency uint32, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewDownstreamFrequency string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANCableLinkConfig_1, "GetDownstreamFrequency", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewDownstreamFrequency, err = soap.UnmarshalUi4(response.NewDownstreamFrequency); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-//
-// Return values:
-//
-// * NewDownstreamModulation: allowed values: 64QAM, 256QAM
-func (client *WANCableLinkConfig1) GetDownstreamModulation() (NewDownstreamModulation string, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewDownstreamModulation string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANCableLinkConfig_1, "GetDownstreamModulation", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewDownstreamModulation, err = soap.UnmarshalString(response.NewDownstreamModulation); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANCableLinkConfig1) GetUpstreamFrequency() (NewUpstreamFrequency uint32, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewUpstreamFrequency string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANCableLinkConfig_1, "GetUpstreamFrequency", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewUpstreamFrequency, err = soap.UnmarshalUi4(response.NewUpstreamFrequency); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-//
-// Return values:
-//
-// * NewUpstreamModulation: allowed values: QPSK, 16QAM
-func (client *WANCableLinkConfig1) GetUpstreamModulation() (NewUpstreamModulation string, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewUpstreamModulation string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANCableLinkConfig_1, "GetUpstreamModulation", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewUpstreamModulation, err = soap.UnmarshalString(response.NewUpstreamModulation); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANCableLinkConfig1) GetUpstreamChannelID() (NewUpstreamChannelID uint32, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewUpstreamChannelID string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANCableLinkConfig_1, "GetUpstreamChannelID", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewUpstreamChannelID, err = soap.UnmarshalUi4(response.NewUpstreamChannelID); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANCableLinkConfig1) GetUpstreamPowerLevel() (NewUpstreamPowerLevel uint32, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewUpstreamPowerLevel string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANCableLinkConfig_1, "GetUpstreamPowerLevel", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewUpstreamPowerLevel, err = soap.UnmarshalUi4(response.NewUpstreamPowerLevel); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANCableLinkConfig1) GetBPIEncryptionEnabled() (NewBPIEncryptionEnabled bool, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewBPIEncryptionEnabled string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANCableLinkConfig_1, "GetBPIEncryptionEnabled", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewBPIEncryptionEnabled, err = soap.UnmarshalBoolean(response.NewBPIEncryptionEnabled); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANCableLinkConfig1) GetConfigFile() (NewConfigFile string, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewConfigFile string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANCableLinkConfig_1, "GetConfigFile", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewConfigFile, err = soap.UnmarshalString(response.NewConfigFile); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANCableLinkConfig1) GetTFTPServer() (NewTFTPServer string, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewTFTPServer string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANCableLinkConfig_1, "GetTFTPServer", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewTFTPServer, err = soap.UnmarshalString(response.NewTFTPServer); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-// WANCommonInterfaceConfig1 is a client for UPnP SOAP service with URN "urn:schemas-upnp-org:service:WANCommonInterfaceConfig:1". See
-// goupnp.ServiceClient, which contains RootDevice and Service attributes which
-// are provided for informational value.
-type WANCommonInterfaceConfig1 struct {
- goupnp.ServiceClient
-}
-
-// NewWANCommonInterfaceConfig1Clients discovers instances of the service on the network,
-// and returns clients to any that are found. errors will contain an error for
-// any devices that replied but which could not be queried, and err will be set
-// if the discovery process failed outright.
-//
-// This is a typical entry calling point into this package.
-func NewWANCommonInterfaceConfig1Clients() (clients []*WANCommonInterfaceConfig1, errors []error, err error) {
- var genericClients []goupnp.ServiceClient
- if genericClients, errors, err = goupnp.NewServiceClients(URN_WANCommonInterfaceConfig_1); err != nil {
- return
- }
- clients = newWANCommonInterfaceConfig1ClientsFromGenericClients(genericClients)
- return
-}
-
-// NewWANCommonInterfaceConfig1ClientsByURL discovers instances of the service at the given
-// URL, and returns clients to any that are found. An error is returned if
-// there was an error probing the service.
-//
-// This is a typical entry calling point into this package when reusing an
-// previously discovered service URL.
-func NewWANCommonInterfaceConfig1ClientsByURL(loc *url.URL) ([]*WANCommonInterfaceConfig1, error) {
- genericClients, err := goupnp.NewServiceClientsByURL(loc, URN_WANCommonInterfaceConfig_1)
- if err != nil {
- return nil, err
- }
- return newWANCommonInterfaceConfig1ClientsFromGenericClients(genericClients), nil
-}
-
-// NewWANCommonInterfaceConfig1ClientsFromRootDevice discovers instances of the service in
-// a given root device, and returns clients to any that are found. An error is
-// returned if there was not at least one instance of the service within the
-// device. The location parameter is simply assigned to the Location attribute
-// of the wrapped ServiceClient(s).
-//
-// This is a typical entry calling point into this package when reusing an
-// previously discovered root device.
-func NewWANCommonInterfaceConfig1ClientsFromRootDevice(rootDevice *goupnp.RootDevice, loc *url.URL) ([]*WANCommonInterfaceConfig1, error) {
- genericClients, err := goupnp.NewServiceClientsFromRootDevice(rootDevice, loc, URN_WANCommonInterfaceConfig_1)
- if err != nil {
- return nil, err
- }
- return newWANCommonInterfaceConfig1ClientsFromGenericClients(genericClients), nil
-}
-
-func newWANCommonInterfaceConfig1ClientsFromGenericClients(genericClients []goupnp.ServiceClient) []*WANCommonInterfaceConfig1 {
- clients := make([]*WANCommonInterfaceConfig1, len(genericClients))
- for i := range genericClients {
- clients[i] = &WANCommonInterfaceConfig1{genericClients[i]}
- }
- return clients
-}
-
-func (client *WANCommonInterfaceConfig1) SetEnabledForInternet(NewEnabledForInternet bool) (err error) {
- // Request structure.
- request := &struct {
- NewEnabledForInternet string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.NewEnabledForInternet, err = soap.MarshalBoolean(NewEnabledForInternet); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANCommonInterfaceConfig_1, "SetEnabledForInternet", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANCommonInterfaceConfig1) GetEnabledForInternet() (NewEnabledForInternet bool, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewEnabledForInternet string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANCommonInterfaceConfig_1, "GetEnabledForInternet", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewEnabledForInternet, err = soap.UnmarshalBoolean(response.NewEnabledForInternet); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-//
-// Return values:
-//
-// * NewWANAccessType: allowed values: DSL, POTS, Cable, Ethernet
-//
-// * NewPhysicalLinkStatus: allowed values: Up, Down
-func (client *WANCommonInterfaceConfig1) GetCommonLinkProperties() (NewWANAccessType string, NewLayer1UpstreamMaxBitRate uint32, NewLayer1DownstreamMaxBitRate uint32, NewPhysicalLinkStatus string, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewWANAccessType string
-
- NewLayer1UpstreamMaxBitRate string
-
- NewLayer1DownstreamMaxBitRate string
-
- NewPhysicalLinkStatus string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANCommonInterfaceConfig_1, "GetCommonLinkProperties", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewWANAccessType, err = soap.UnmarshalString(response.NewWANAccessType); err != nil {
- return
- }
- if NewLayer1UpstreamMaxBitRate, err = soap.UnmarshalUi4(response.NewLayer1UpstreamMaxBitRate); err != nil {
- return
- }
- if NewLayer1DownstreamMaxBitRate, err = soap.UnmarshalUi4(response.NewLayer1DownstreamMaxBitRate); err != nil {
- return
- }
- if NewPhysicalLinkStatus, err = soap.UnmarshalString(response.NewPhysicalLinkStatus); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANCommonInterfaceConfig1) GetWANAccessProvider() (NewWANAccessProvider string, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewWANAccessProvider string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANCommonInterfaceConfig_1, "GetWANAccessProvider", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewWANAccessProvider, err = soap.UnmarshalString(response.NewWANAccessProvider); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-//
-// Return values:
-//
-// * NewMaximumActiveConnections: allowed value range: minimum=1, step=1
-func (client *WANCommonInterfaceConfig1) GetMaximumActiveConnections() (NewMaximumActiveConnections uint16, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewMaximumActiveConnections string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANCommonInterfaceConfig_1, "GetMaximumActiveConnections", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewMaximumActiveConnections, err = soap.UnmarshalUi2(response.NewMaximumActiveConnections); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANCommonInterfaceConfig1) GetTotalBytesSent() (NewTotalBytesSent uint32, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewTotalBytesSent string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANCommonInterfaceConfig_1, "GetTotalBytesSent", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewTotalBytesSent, err = soap.UnmarshalUi4(response.NewTotalBytesSent); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANCommonInterfaceConfig1) GetTotalBytesReceived() (NewTotalBytesReceived uint32, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewTotalBytesReceived string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANCommonInterfaceConfig_1, "GetTotalBytesReceived", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewTotalBytesReceived, err = soap.UnmarshalUi4(response.NewTotalBytesReceived); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANCommonInterfaceConfig1) GetTotalPacketsSent() (NewTotalPacketsSent uint32, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewTotalPacketsSent string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANCommonInterfaceConfig_1, "GetTotalPacketsSent", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewTotalPacketsSent, err = soap.UnmarshalUi4(response.NewTotalPacketsSent); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANCommonInterfaceConfig1) GetTotalPacketsReceived() (NewTotalPacketsReceived uint32, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewTotalPacketsReceived string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANCommonInterfaceConfig_1, "GetTotalPacketsReceived", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewTotalPacketsReceived, err = soap.UnmarshalUi4(response.NewTotalPacketsReceived); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANCommonInterfaceConfig1) GetActiveConnection(NewActiveConnectionIndex uint16) (NewActiveConnDeviceContainer string, NewActiveConnectionServiceID string, err error) {
- // Request structure.
- request := &struct {
- NewActiveConnectionIndex string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.NewActiveConnectionIndex, err = soap.MarshalUi2(NewActiveConnectionIndex); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewActiveConnDeviceContainer string
-
- NewActiveConnectionServiceID string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANCommonInterfaceConfig_1, "GetActiveConnection", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewActiveConnDeviceContainer, err = soap.UnmarshalString(response.NewActiveConnDeviceContainer); err != nil {
- return
- }
- if NewActiveConnectionServiceID, err = soap.UnmarshalString(response.NewActiveConnectionServiceID); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-// WANDSLLinkConfig1 is a client for UPnP SOAP service with URN "urn:schemas-upnp-org:service:WANDSLLinkConfig:1". See
-// goupnp.ServiceClient, which contains RootDevice and Service attributes which
-// are provided for informational value.
-type WANDSLLinkConfig1 struct {
- goupnp.ServiceClient
-}
-
-// NewWANDSLLinkConfig1Clients discovers instances of the service on the network,
-// and returns clients to any that are found. errors will contain an error for
-// any devices that replied but which could not be queried, and err will be set
-// if the discovery process failed outright.
-//
-// This is a typical entry calling point into this package.
-func NewWANDSLLinkConfig1Clients() (clients []*WANDSLLinkConfig1, errors []error, err error) {
- var genericClients []goupnp.ServiceClient
- if genericClients, errors, err = goupnp.NewServiceClients(URN_WANDSLLinkConfig_1); err != nil {
- return
- }
- clients = newWANDSLLinkConfig1ClientsFromGenericClients(genericClients)
- return
-}
-
-// NewWANDSLLinkConfig1ClientsByURL discovers instances of the service at the given
-// URL, and returns clients to any that are found. An error is returned if
-// there was an error probing the service.
-//
-// This is a typical entry calling point into this package when reusing an
-// previously discovered service URL.
-func NewWANDSLLinkConfig1ClientsByURL(loc *url.URL) ([]*WANDSLLinkConfig1, error) {
- genericClients, err := goupnp.NewServiceClientsByURL(loc, URN_WANDSLLinkConfig_1)
- if err != nil {
- return nil, err
- }
- return newWANDSLLinkConfig1ClientsFromGenericClients(genericClients), nil
-}
-
-// NewWANDSLLinkConfig1ClientsFromRootDevice discovers instances of the service in
-// a given root device, and returns clients to any that are found. An error is
-// returned if there was not at least one instance of the service within the
-// device. The location parameter is simply assigned to the Location attribute
-// of the wrapped ServiceClient(s).
-//
-// This is a typical entry calling point into this package when reusing an
-// previously discovered root device.
-func NewWANDSLLinkConfig1ClientsFromRootDevice(rootDevice *goupnp.RootDevice, loc *url.URL) ([]*WANDSLLinkConfig1, error) {
- genericClients, err := goupnp.NewServiceClientsFromRootDevice(rootDevice, loc, URN_WANDSLLinkConfig_1)
- if err != nil {
- return nil, err
- }
- return newWANDSLLinkConfig1ClientsFromGenericClients(genericClients), nil
-}
-
-func newWANDSLLinkConfig1ClientsFromGenericClients(genericClients []goupnp.ServiceClient) []*WANDSLLinkConfig1 {
- clients := make([]*WANDSLLinkConfig1, len(genericClients))
- for i := range genericClients {
- clients[i] = &WANDSLLinkConfig1{genericClients[i]}
- }
- return clients
-}
-
-func (client *WANDSLLinkConfig1) SetDSLLinkType(NewLinkType string) (err error) {
- // Request structure.
- request := &struct {
- NewLinkType string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.NewLinkType, err = soap.MarshalString(NewLinkType); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANDSLLinkConfig_1, "SetDSLLinkType", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-//
-// Return values:
-//
-// * NewLinkStatus: allowed values: Up, Down
-func (client *WANDSLLinkConfig1) GetDSLLinkInfo() (NewLinkType string, NewLinkStatus string, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewLinkType string
-
- NewLinkStatus string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANDSLLinkConfig_1, "GetDSLLinkInfo", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewLinkType, err = soap.UnmarshalString(response.NewLinkType); err != nil {
- return
- }
- if NewLinkStatus, err = soap.UnmarshalString(response.NewLinkStatus); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANDSLLinkConfig1) GetAutoConfig() (NewAutoConfig bool, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewAutoConfig string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANDSLLinkConfig_1, "GetAutoConfig", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewAutoConfig, err = soap.UnmarshalBoolean(response.NewAutoConfig); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANDSLLinkConfig1) GetModulationType() (NewModulationType string, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewModulationType string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANDSLLinkConfig_1, "GetModulationType", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewModulationType, err = soap.UnmarshalString(response.NewModulationType); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANDSLLinkConfig1) SetDestinationAddress(NewDestinationAddress string) (err error) {
- // Request structure.
- request := &struct {
- NewDestinationAddress string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.NewDestinationAddress, err = soap.MarshalString(NewDestinationAddress); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANDSLLinkConfig_1, "SetDestinationAddress", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANDSLLinkConfig1) GetDestinationAddress() (NewDestinationAddress string, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewDestinationAddress string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANDSLLinkConfig_1, "GetDestinationAddress", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewDestinationAddress, err = soap.UnmarshalString(response.NewDestinationAddress); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANDSLLinkConfig1) SetATMEncapsulation(NewATMEncapsulation string) (err error) {
- // Request structure.
- request := &struct {
- NewATMEncapsulation string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.NewATMEncapsulation, err = soap.MarshalString(NewATMEncapsulation); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANDSLLinkConfig_1, "SetATMEncapsulation", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANDSLLinkConfig1) GetATMEncapsulation() (NewATMEncapsulation string, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewATMEncapsulation string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANDSLLinkConfig_1, "GetATMEncapsulation", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewATMEncapsulation, err = soap.UnmarshalString(response.NewATMEncapsulation); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANDSLLinkConfig1) SetFCSPreserved(NewFCSPreserved bool) (err error) {
- // Request structure.
- request := &struct {
- NewFCSPreserved string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.NewFCSPreserved, err = soap.MarshalBoolean(NewFCSPreserved); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANDSLLinkConfig_1, "SetFCSPreserved", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANDSLLinkConfig1) GetFCSPreserved() (NewFCSPreserved bool, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewFCSPreserved string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANDSLLinkConfig_1, "GetFCSPreserved", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewFCSPreserved, err = soap.UnmarshalBoolean(response.NewFCSPreserved); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-// WANEthernetLinkConfig1 is a client for UPnP SOAP service with URN "urn:schemas-upnp-org:service:WANEthernetLinkConfig:1". See
-// goupnp.ServiceClient, which contains RootDevice and Service attributes which
-// are provided for informational value.
-type WANEthernetLinkConfig1 struct {
- goupnp.ServiceClient
-}
-
-// NewWANEthernetLinkConfig1Clients discovers instances of the service on the network,
-// and returns clients to any that are found. errors will contain an error for
-// any devices that replied but which could not be queried, and err will be set
-// if the discovery process failed outright.
-//
-// This is a typical entry calling point into this package.
-func NewWANEthernetLinkConfig1Clients() (clients []*WANEthernetLinkConfig1, errors []error, err error) {
- var genericClients []goupnp.ServiceClient
- if genericClients, errors, err = goupnp.NewServiceClients(URN_WANEthernetLinkConfig_1); err != nil {
- return
- }
- clients = newWANEthernetLinkConfig1ClientsFromGenericClients(genericClients)
- return
-}
-
-// NewWANEthernetLinkConfig1ClientsByURL discovers instances of the service at the given
-// URL, and returns clients to any that are found. An error is returned if
-// there was an error probing the service.
-//
-// This is a typical entry calling point into this package when reusing an
-// previously discovered service URL.
-func NewWANEthernetLinkConfig1ClientsByURL(loc *url.URL) ([]*WANEthernetLinkConfig1, error) {
- genericClients, err := goupnp.NewServiceClientsByURL(loc, URN_WANEthernetLinkConfig_1)
- if err != nil {
- return nil, err
- }
- return newWANEthernetLinkConfig1ClientsFromGenericClients(genericClients), nil
-}
-
-// NewWANEthernetLinkConfig1ClientsFromRootDevice discovers instances of the service in
-// a given root device, and returns clients to any that are found. An error is
-// returned if there was not at least one instance of the service within the
-// device. The location parameter is simply assigned to the Location attribute
-// of the wrapped ServiceClient(s).
-//
-// This is a typical entry calling point into this package when reusing an
-// previously discovered root device.
-func NewWANEthernetLinkConfig1ClientsFromRootDevice(rootDevice *goupnp.RootDevice, loc *url.URL) ([]*WANEthernetLinkConfig1, error) {
- genericClients, err := goupnp.NewServiceClientsFromRootDevice(rootDevice, loc, URN_WANEthernetLinkConfig_1)
- if err != nil {
- return nil, err
- }
- return newWANEthernetLinkConfig1ClientsFromGenericClients(genericClients), nil
-}
-
-func newWANEthernetLinkConfig1ClientsFromGenericClients(genericClients []goupnp.ServiceClient) []*WANEthernetLinkConfig1 {
- clients := make([]*WANEthernetLinkConfig1, len(genericClients))
- for i := range genericClients {
- clients[i] = &WANEthernetLinkConfig1{genericClients[i]}
- }
- return clients
-}
-
-//
-// Return values:
-//
-// * NewEthernetLinkStatus: allowed values: Up, Down
-func (client *WANEthernetLinkConfig1) GetEthernetLinkStatus() (NewEthernetLinkStatus string, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewEthernetLinkStatus string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANEthernetLinkConfig_1, "GetEthernetLinkStatus", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewEthernetLinkStatus, err = soap.UnmarshalString(response.NewEthernetLinkStatus); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-// WANIPConnection1 is a client for UPnP SOAP service with URN "urn:schemas-upnp-org:service:WANIPConnection:1". See
-// goupnp.ServiceClient, which contains RootDevice and Service attributes which
-// are provided for informational value.
-type WANIPConnection1 struct {
- goupnp.ServiceClient
-}
-
-// NewWANIPConnection1Clients discovers instances of the service on the network,
-// and returns clients to any that are found. errors will contain an error for
-// any devices that replied but which could not be queried, and err will be set
-// if the discovery process failed outright.
-//
-// This is a typical entry calling point into this package.
-func NewWANIPConnection1Clients() (clients []*WANIPConnection1, errors []error, err error) {
- var genericClients []goupnp.ServiceClient
- if genericClients, errors, err = goupnp.NewServiceClients(URN_WANIPConnection_1); err != nil {
- return
- }
- clients = newWANIPConnection1ClientsFromGenericClients(genericClients)
- return
-}
-
-// NewWANIPConnection1ClientsByURL discovers instances of the service at the given
-// URL, and returns clients to any that are found. An error is returned if
-// there was an error probing the service.
-//
-// This is a typical entry calling point into this package when reusing an
-// previously discovered service URL.
-func NewWANIPConnection1ClientsByURL(loc *url.URL) ([]*WANIPConnection1, error) {
- genericClients, err := goupnp.NewServiceClientsByURL(loc, URN_WANIPConnection_1)
- if err != nil {
- return nil, err
- }
- return newWANIPConnection1ClientsFromGenericClients(genericClients), nil
-}
-
-// NewWANIPConnection1ClientsFromRootDevice discovers instances of the service in
-// a given root device, and returns clients to any that are found. An error is
-// returned if there was not at least one instance of the service within the
-// device. The location parameter is simply assigned to the Location attribute
-// of the wrapped ServiceClient(s).
-//
-// This is a typical entry calling point into this package when reusing an
-// previously discovered root device.
-func NewWANIPConnection1ClientsFromRootDevice(rootDevice *goupnp.RootDevice, loc *url.URL) ([]*WANIPConnection1, error) {
- genericClients, err := goupnp.NewServiceClientsFromRootDevice(rootDevice, loc, URN_WANIPConnection_1)
- if err != nil {
- return nil, err
- }
- return newWANIPConnection1ClientsFromGenericClients(genericClients), nil
-}
-
-func newWANIPConnection1ClientsFromGenericClients(genericClients []goupnp.ServiceClient) []*WANIPConnection1 {
- clients := make([]*WANIPConnection1, len(genericClients))
- for i := range genericClients {
- clients[i] = &WANIPConnection1{genericClients[i]}
- }
- return clients
-}
-
-func (client *WANIPConnection1) SetConnectionType(NewConnectionType string) (err error) {
- // Request structure.
- request := &struct {
- NewConnectionType string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.NewConnectionType, err = soap.MarshalString(NewConnectionType); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANIPConnection_1, "SetConnectionType", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-//
-// Return values:
-//
-// * NewPossibleConnectionTypes: allowed values: Unconfigured, IP_Routed, IP_Bridged
-func (client *WANIPConnection1) GetConnectionTypeInfo() (NewConnectionType string, NewPossibleConnectionTypes string, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewConnectionType string
-
- NewPossibleConnectionTypes string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANIPConnection_1, "GetConnectionTypeInfo", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewConnectionType, err = soap.UnmarshalString(response.NewConnectionType); err != nil {
- return
- }
- if NewPossibleConnectionTypes, err = soap.UnmarshalString(response.NewPossibleConnectionTypes); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANIPConnection1) RequestConnection() (err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANIPConnection_1, "RequestConnection", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANIPConnection1) RequestTermination() (err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANIPConnection_1, "RequestTermination", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANIPConnection1) ForceTermination() (err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANIPConnection_1, "ForceTermination", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANIPConnection1) SetAutoDisconnectTime(NewAutoDisconnectTime uint32) (err error) {
- // Request structure.
- request := &struct {
- NewAutoDisconnectTime string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.NewAutoDisconnectTime, err = soap.MarshalUi4(NewAutoDisconnectTime); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANIPConnection_1, "SetAutoDisconnectTime", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANIPConnection1) SetIdleDisconnectTime(NewIdleDisconnectTime uint32) (err error) {
- // Request structure.
- request := &struct {
- NewIdleDisconnectTime string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.NewIdleDisconnectTime, err = soap.MarshalUi4(NewIdleDisconnectTime); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANIPConnection_1, "SetIdleDisconnectTime", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANIPConnection1) SetWarnDisconnectDelay(NewWarnDisconnectDelay uint32) (err error) {
- // Request structure.
- request := &struct {
- NewWarnDisconnectDelay string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.NewWarnDisconnectDelay, err = soap.MarshalUi4(NewWarnDisconnectDelay); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANIPConnection_1, "SetWarnDisconnectDelay", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-//
-// Return values:
-//
-// * NewConnectionStatus: allowed values: Unconfigured, Connected, Disconnected
-//
-// * NewLastConnectionError: allowed values: ERROR_NONE
-func (client *WANIPConnection1) GetStatusInfo() (NewConnectionStatus string, NewLastConnectionError string, NewUptime uint32, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewConnectionStatus string
-
- NewLastConnectionError string
-
- NewUptime string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANIPConnection_1, "GetStatusInfo", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewConnectionStatus, err = soap.UnmarshalString(response.NewConnectionStatus); err != nil {
- return
- }
- if NewLastConnectionError, err = soap.UnmarshalString(response.NewLastConnectionError); err != nil {
- return
- }
- if NewUptime, err = soap.UnmarshalUi4(response.NewUptime); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANIPConnection1) GetAutoDisconnectTime() (NewAutoDisconnectTime uint32, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewAutoDisconnectTime string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANIPConnection_1, "GetAutoDisconnectTime", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewAutoDisconnectTime, err = soap.UnmarshalUi4(response.NewAutoDisconnectTime); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANIPConnection1) GetIdleDisconnectTime() (NewIdleDisconnectTime uint32, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewIdleDisconnectTime string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANIPConnection_1, "GetIdleDisconnectTime", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewIdleDisconnectTime, err = soap.UnmarshalUi4(response.NewIdleDisconnectTime); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANIPConnection1) GetWarnDisconnectDelay() (NewWarnDisconnectDelay uint32, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewWarnDisconnectDelay string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANIPConnection_1, "GetWarnDisconnectDelay", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewWarnDisconnectDelay, err = soap.UnmarshalUi4(response.NewWarnDisconnectDelay); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANIPConnection1) GetNATRSIPStatus() (NewRSIPAvailable bool, NewNATEnabled bool, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewRSIPAvailable string
-
- NewNATEnabled string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANIPConnection_1, "GetNATRSIPStatus", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewRSIPAvailable, err = soap.UnmarshalBoolean(response.NewRSIPAvailable); err != nil {
- return
- }
- if NewNATEnabled, err = soap.UnmarshalBoolean(response.NewNATEnabled); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-//
-// Return values:
-//
-// * NewProtocol: allowed values: TCP, UDP
-func (client *WANIPConnection1) GetGenericPortMappingEntry(NewPortMappingIndex uint16) (NewRemoteHost string, NewExternalPort uint16, NewProtocol string, NewInternalPort uint16, NewInternalClient string, NewEnabled bool, NewPortMappingDescription string, NewLeaseDuration uint32, err error) {
- // Request structure.
- request := &struct {
- NewPortMappingIndex string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.NewPortMappingIndex, err = soap.MarshalUi2(NewPortMappingIndex); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewRemoteHost string
-
- NewExternalPort string
-
- NewProtocol string
-
- NewInternalPort string
-
- NewInternalClient string
-
- NewEnabled string
-
- NewPortMappingDescription string
-
- NewLeaseDuration string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANIPConnection_1, "GetGenericPortMappingEntry", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewRemoteHost, err = soap.UnmarshalString(response.NewRemoteHost); err != nil {
- return
- }
- if NewExternalPort, err = soap.UnmarshalUi2(response.NewExternalPort); err != nil {
- return
- }
- if NewProtocol, err = soap.UnmarshalString(response.NewProtocol); err != nil {
- return
- }
- if NewInternalPort, err = soap.UnmarshalUi2(response.NewInternalPort); err != nil {
- return
- }
- if NewInternalClient, err = soap.UnmarshalString(response.NewInternalClient); err != nil {
- return
- }
- if NewEnabled, err = soap.UnmarshalBoolean(response.NewEnabled); err != nil {
- return
- }
- if NewPortMappingDescription, err = soap.UnmarshalString(response.NewPortMappingDescription); err != nil {
- return
- }
- if NewLeaseDuration, err = soap.UnmarshalUi4(response.NewLeaseDuration); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-//
-// Arguments:
-//
-// * NewProtocol: allowed values: TCP, UDP
-
-func (client *WANIPConnection1) GetSpecificPortMappingEntry(NewRemoteHost string, NewExternalPort uint16, NewProtocol string) (NewInternalPort uint16, NewInternalClient string, NewEnabled bool, NewPortMappingDescription string, NewLeaseDuration uint32, err error) {
- // Request structure.
- request := &struct {
- NewRemoteHost string
-
- NewExternalPort string
-
- NewProtocol string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.NewRemoteHost, err = soap.MarshalString(NewRemoteHost); err != nil {
- return
- }
- if request.NewExternalPort, err = soap.MarshalUi2(NewExternalPort); err != nil {
- return
- }
- if request.NewProtocol, err = soap.MarshalString(NewProtocol); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewInternalPort string
-
- NewInternalClient string
-
- NewEnabled string
-
- NewPortMappingDescription string
-
- NewLeaseDuration string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANIPConnection_1, "GetSpecificPortMappingEntry", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewInternalPort, err = soap.UnmarshalUi2(response.NewInternalPort); err != nil {
- return
- }
- if NewInternalClient, err = soap.UnmarshalString(response.NewInternalClient); err != nil {
- return
- }
- if NewEnabled, err = soap.UnmarshalBoolean(response.NewEnabled); err != nil {
- return
- }
- if NewPortMappingDescription, err = soap.UnmarshalString(response.NewPortMappingDescription); err != nil {
- return
- }
- if NewLeaseDuration, err = soap.UnmarshalUi4(response.NewLeaseDuration); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-//
-// Arguments:
-//
-// * NewProtocol: allowed values: TCP, UDP
-
-func (client *WANIPConnection1) AddPortMapping(NewRemoteHost string, NewExternalPort uint16, NewProtocol string, NewInternalPort uint16, NewInternalClient string, NewEnabled bool, NewPortMappingDescription string, NewLeaseDuration uint32) (err error) {
- // Request structure.
- request := &struct {
- NewRemoteHost string
-
- NewExternalPort string
-
- NewProtocol string
-
- NewInternalPort string
-
- NewInternalClient string
-
- NewEnabled string
-
- NewPortMappingDescription string
-
- NewLeaseDuration string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.NewRemoteHost, err = soap.MarshalString(NewRemoteHost); err != nil {
- return
- }
- if request.NewExternalPort, err = soap.MarshalUi2(NewExternalPort); err != nil {
- return
- }
- if request.NewProtocol, err = soap.MarshalString(NewProtocol); err != nil {
- return
- }
- if request.NewInternalPort, err = soap.MarshalUi2(NewInternalPort); err != nil {
- return
- }
- if request.NewInternalClient, err = soap.MarshalString(NewInternalClient); err != nil {
- return
- }
- if request.NewEnabled, err = soap.MarshalBoolean(NewEnabled); err != nil {
- return
- }
- if request.NewPortMappingDescription, err = soap.MarshalString(NewPortMappingDescription); err != nil {
- return
- }
- if request.NewLeaseDuration, err = soap.MarshalUi4(NewLeaseDuration); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANIPConnection_1, "AddPortMapping", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-//
-// Arguments:
-//
-// * NewProtocol: allowed values: TCP, UDP
-
-func (client *WANIPConnection1) DeletePortMapping(NewRemoteHost string, NewExternalPort uint16, NewProtocol string) (err error) {
- // Request structure.
- request := &struct {
- NewRemoteHost string
-
- NewExternalPort string
-
- NewProtocol string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.NewRemoteHost, err = soap.MarshalString(NewRemoteHost); err != nil {
- return
- }
- if request.NewExternalPort, err = soap.MarshalUi2(NewExternalPort); err != nil {
- return
- }
- if request.NewProtocol, err = soap.MarshalString(NewProtocol); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANIPConnection_1, "DeletePortMapping", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANIPConnection1) GetExternalIPAddress() (NewExternalIPAddress string, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewExternalIPAddress string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANIPConnection_1, "GetExternalIPAddress", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewExternalIPAddress, err = soap.UnmarshalString(response.NewExternalIPAddress); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-// WANPOTSLinkConfig1 is a client for UPnP SOAP service with URN "urn:schemas-upnp-org:service:WANPOTSLinkConfig:1". See
-// goupnp.ServiceClient, which contains RootDevice and Service attributes which
-// are provided for informational value.
-type WANPOTSLinkConfig1 struct {
- goupnp.ServiceClient
-}
-
-// NewWANPOTSLinkConfig1Clients discovers instances of the service on the network,
-// and returns clients to any that are found. errors will contain an error for
-// any devices that replied but which could not be queried, and err will be set
-// if the discovery process failed outright.
-//
-// This is a typical entry calling point into this package.
-func NewWANPOTSLinkConfig1Clients() (clients []*WANPOTSLinkConfig1, errors []error, err error) {
- var genericClients []goupnp.ServiceClient
- if genericClients, errors, err = goupnp.NewServiceClients(URN_WANPOTSLinkConfig_1); err != nil {
- return
- }
- clients = newWANPOTSLinkConfig1ClientsFromGenericClients(genericClients)
- return
-}
-
-// NewWANPOTSLinkConfig1ClientsByURL discovers instances of the service at the given
-// URL, and returns clients to any that are found. An error is returned if
-// there was an error probing the service.
-//
-// This is a typical entry calling point into this package when reusing an
-// previously discovered service URL.
-func NewWANPOTSLinkConfig1ClientsByURL(loc *url.URL) ([]*WANPOTSLinkConfig1, error) {
- genericClients, err := goupnp.NewServiceClientsByURL(loc, URN_WANPOTSLinkConfig_1)
- if err != nil {
- return nil, err
- }
- return newWANPOTSLinkConfig1ClientsFromGenericClients(genericClients), nil
-}
-
-// NewWANPOTSLinkConfig1ClientsFromRootDevice discovers instances of the service in
-// a given root device, and returns clients to any that are found. An error is
-// returned if there was not at least one instance of the service within the
-// device. The location parameter is simply assigned to the Location attribute
-// of the wrapped ServiceClient(s).
-//
-// This is a typical entry calling point into this package when reusing an
-// previously discovered root device.
-func NewWANPOTSLinkConfig1ClientsFromRootDevice(rootDevice *goupnp.RootDevice, loc *url.URL) ([]*WANPOTSLinkConfig1, error) {
- genericClients, err := goupnp.NewServiceClientsFromRootDevice(rootDevice, loc, URN_WANPOTSLinkConfig_1)
- if err != nil {
- return nil, err
- }
- return newWANPOTSLinkConfig1ClientsFromGenericClients(genericClients), nil
-}
-
-func newWANPOTSLinkConfig1ClientsFromGenericClients(genericClients []goupnp.ServiceClient) []*WANPOTSLinkConfig1 {
- clients := make([]*WANPOTSLinkConfig1, len(genericClients))
- for i := range genericClients {
- clients[i] = &WANPOTSLinkConfig1{genericClients[i]}
- }
- return clients
-}
-
-//
-// Arguments:
-//
-// * NewLinkType: allowed values: PPP_Dialup
-
-func (client *WANPOTSLinkConfig1) SetISPInfo(NewISPPhoneNumber string, NewISPInfo string, NewLinkType string) (err error) {
- // Request structure.
- request := &struct {
- NewISPPhoneNumber string
-
- NewISPInfo string
-
- NewLinkType string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.NewISPPhoneNumber, err = soap.MarshalString(NewISPPhoneNumber); err != nil {
- return
- }
- if request.NewISPInfo, err = soap.MarshalString(NewISPInfo); err != nil {
- return
- }
- if request.NewLinkType, err = soap.MarshalString(NewLinkType); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANPOTSLinkConfig_1, "SetISPInfo", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANPOTSLinkConfig1) SetCallRetryInfo(NewNumberOfRetries uint32, NewDelayBetweenRetries uint32) (err error) {
- // Request structure.
- request := &struct {
- NewNumberOfRetries string
-
- NewDelayBetweenRetries string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.NewNumberOfRetries, err = soap.MarshalUi4(NewNumberOfRetries); err != nil {
- return
- }
- if request.NewDelayBetweenRetries, err = soap.MarshalUi4(NewDelayBetweenRetries); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANPOTSLinkConfig_1, "SetCallRetryInfo", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-//
-// Return values:
-//
-// * NewLinkType: allowed values: PPP_Dialup
-func (client *WANPOTSLinkConfig1) GetISPInfo() (NewISPPhoneNumber string, NewISPInfo string, NewLinkType string, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewISPPhoneNumber string
-
- NewISPInfo string
-
- NewLinkType string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANPOTSLinkConfig_1, "GetISPInfo", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewISPPhoneNumber, err = soap.UnmarshalString(response.NewISPPhoneNumber); err != nil {
- return
- }
- if NewISPInfo, err = soap.UnmarshalString(response.NewISPInfo); err != nil {
- return
- }
- if NewLinkType, err = soap.UnmarshalString(response.NewLinkType); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANPOTSLinkConfig1) GetCallRetryInfo() (NewNumberOfRetries uint32, NewDelayBetweenRetries uint32, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewNumberOfRetries string
-
- NewDelayBetweenRetries string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANPOTSLinkConfig_1, "GetCallRetryInfo", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewNumberOfRetries, err = soap.UnmarshalUi4(response.NewNumberOfRetries); err != nil {
- return
- }
- if NewDelayBetweenRetries, err = soap.UnmarshalUi4(response.NewDelayBetweenRetries); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANPOTSLinkConfig1) GetFclass() (NewFclass string, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewFclass string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANPOTSLinkConfig_1, "GetFclass", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewFclass, err = soap.UnmarshalString(response.NewFclass); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANPOTSLinkConfig1) GetDataModulationSupported() (NewDataModulationSupported string, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewDataModulationSupported string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANPOTSLinkConfig_1, "GetDataModulationSupported", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewDataModulationSupported, err = soap.UnmarshalString(response.NewDataModulationSupported); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANPOTSLinkConfig1) GetDataProtocol() (NewDataProtocol string, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewDataProtocol string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANPOTSLinkConfig_1, "GetDataProtocol", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewDataProtocol, err = soap.UnmarshalString(response.NewDataProtocol); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANPOTSLinkConfig1) GetDataCompression() (NewDataCompression string, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewDataCompression string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANPOTSLinkConfig_1, "GetDataCompression", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewDataCompression, err = soap.UnmarshalString(response.NewDataCompression); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANPOTSLinkConfig1) GetPlusVTRCommandSupported() (NewPlusVTRCommandSupported bool, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewPlusVTRCommandSupported string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANPOTSLinkConfig_1, "GetPlusVTRCommandSupported", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewPlusVTRCommandSupported, err = soap.UnmarshalBoolean(response.NewPlusVTRCommandSupported); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-// WANPPPConnection1 is a client for UPnP SOAP service with URN "urn:schemas-upnp-org:service:WANPPPConnection:1". See
-// goupnp.ServiceClient, which contains RootDevice and Service attributes which
-// are provided for informational value.
-type WANPPPConnection1 struct {
- goupnp.ServiceClient
-}
-
-// NewWANPPPConnection1Clients discovers instances of the service on the network,
-// and returns clients to any that are found. errors will contain an error for
-// any devices that replied but which could not be queried, and err will be set
-// if the discovery process failed outright.
-//
-// This is a typical entry calling point into this package.
-func NewWANPPPConnection1Clients() (clients []*WANPPPConnection1, errors []error, err error) {
- var genericClients []goupnp.ServiceClient
- if genericClients, errors, err = goupnp.NewServiceClients(URN_WANPPPConnection_1); err != nil {
- return
- }
- clients = newWANPPPConnection1ClientsFromGenericClients(genericClients)
- return
-}
-
-// NewWANPPPConnection1ClientsByURL discovers instances of the service at the given
-// URL, and returns clients to any that are found. An error is returned if
-// there was an error probing the service.
-//
-// This is a typical entry calling point into this package when reusing an
-// previously discovered service URL.
-func NewWANPPPConnection1ClientsByURL(loc *url.URL) ([]*WANPPPConnection1, error) {
- genericClients, err := goupnp.NewServiceClientsByURL(loc, URN_WANPPPConnection_1)
- if err != nil {
- return nil, err
- }
- return newWANPPPConnection1ClientsFromGenericClients(genericClients), nil
-}
-
-// NewWANPPPConnection1ClientsFromRootDevice discovers instances of the service in
-// a given root device, and returns clients to any that are found. An error is
-// returned if there was not at least one instance of the service within the
-// device. The location parameter is simply assigned to the Location attribute
-// of the wrapped ServiceClient(s).
-//
-// This is a typical entry calling point into this package when reusing an
-// previously discovered root device.
-func NewWANPPPConnection1ClientsFromRootDevice(rootDevice *goupnp.RootDevice, loc *url.URL) ([]*WANPPPConnection1, error) {
- genericClients, err := goupnp.NewServiceClientsFromRootDevice(rootDevice, loc, URN_WANPPPConnection_1)
- if err != nil {
- return nil, err
- }
- return newWANPPPConnection1ClientsFromGenericClients(genericClients), nil
-}
-
-func newWANPPPConnection1ClientsFromGenericClients(genericClients []goupnp.ServiceClient) []*WANPPPConnection1 {
- clients := make([]*WANPPPConnection1, len(genericClients))
- for i := range genericClients {
- clients[i] = &WANPPPConnection1{genericClients[i]}
- }
- return clients
-}
-
-func (client *WANPPPConnection1) SetConnectionType(NewConnectionType string) (err error) {
- // Request structure.
- request := &struct {
- NewConnectionType string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.NewConnectionType, err = soap.MarshalString(NewConnectionType); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "SetConnectionType", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-//
-// Return values:
-//
-// * NewPossibleConnectionTypes: allowed values: Unconfigured, IP_Routed, DHCP_Spoofed, PPPoE_Bridged, PPTP_Relay, L2TP_Relay, PPPoE_Relay
-func (client *WANPPPConnection1) GetConnectionTypeInfo() (NewConnectionType string, NewPossibleConnectionTypes string, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewConnectionType string
-
- NewPossibleConnectionTypes string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "GetConnectionTypeInfo", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewConnectionType, err = soap.UnmarshalString(response.NewConnectionType); err != nil {
- return
- }
- if NewPossibleConnectionTypes, err = soap.UnmarshalString(response.NewPossibleConnectionTypes); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANPPPConnection1) ConfigureConnection(NewUserName string, NewPassword string) (err error) {
- // Request structure.
- request := &struct {
- NewUserName string
-
- NewPassword string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.NewUserName, err = soap.MarshalString(NewUserName); err != nil {
- return
- }
- if request.NewPassword, err = soap.MarshalString(NewPassword); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "ConfigureConnection", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANPPPConnection1) RequestConnection() (err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "RequestConnection", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANPPPConnection1) RequestTermination() (err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "RequestTermination", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANPPPConnection1) ForceTermination() (err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "ForceTermination", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANPPPConnection1) SetAutoDisconnectTime(NewAutoDisconnectTime uint32) (err error) {
- // Request structure.
- request := &struct {
- NewAutoDisconnectTime string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.NewAutoDisconnectTime, err = soap.MarshalUi4(NewAutoDisconnectTime); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "SetAutoDisconnectTime", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANPPPConnection1) SetIdleDisconnectTime(NewIdleDisconnectTime uint32) (err error) {
- // Request structure.
- request := &struct {
- NewIdleDisconnectTime string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.NewIdleDisconnectTime, err = soap.MarshalUi4(NewIdleDisconnectTime); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "SetIdleDisconnectTime", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANPPPConnection1) SetWarnDisconnectDelay(NewWarnDisconnectDelay uint32) (err error) {
- // Request structure.
- request := &struct {
- NewWarnDisconnectDelay string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.NewWarnDisconnectDelay, err = soap.MarshalUi4(NewWarnDisconnectDelay); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "SetWarnDisconnectDelay", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-//
-// Return values:
-//
-// * NewConnectionStatus: allowed values: Unconfigured, Connected, Disconnected
-//
-// * NewLastConnectionError: allowed values: ERROR_NONE
-func (client *WANPPPConnection1) GetStatusInfo() (NewConnectionStatus string, NewLastConnectionError string, NewUptime uint32, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewConnectionStatus string
-
- NewLastConnectionError string
-
- NewUptime string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "GetStatusInfo", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewConnectionStatus, err = soap.UnmarshalString(response.NewConnectionStatus); err != nil {
- return
- }
- if NewLastConnectionError, err = soap.UnmarshalString(response.NewLastConnectionError); err != nil {
- return
- }
- if NewUptime, err = soap.UnmarshalUi4(response.NewUptime); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANPPPConnection1) GetLinkLayerMaxBitRates() (NewUpstreamMaxBitRate uint32, NewDownstreamMaxBitRate uint32, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewUpstreamMaxBitRate string
-
- NewDownstreamMaxBitRate string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "GetLinkLayerMaxBitRates", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewUpstreamMaxBitRate, err = soap.UnmarshalUi4(response.NewUpstreamMaxBitRate); err != nil {
- return
- }
- if NewDownstreamMaxBitRate, err = soap.UnmarshalUi4(response.NewDownstreamMaxBitRate); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANPPPConnection1) GetPPPEncryptionProtocol() (NewPPPEncryptionProtocol string, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewPPPEncryptionProtocol string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "GetPPPEncryptionProtocol", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewPPPEncryptionProtocol, err = soap.UnmarshalString(response.NewPPPEncryptionProtocol); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANPPPConnection1) GetPPPCompressionProtocol() (NewPPPCompressionProtocol string, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewPPPCompressionProtocol string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "GetPPPCompressionProtocol", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewPPPCompressionProtocol, err = soap.UnmarshalString(response.NewPPPCompressionProtocol); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANPPPConnection1) GetPPPAuthenticationProtocol() (NewPPPAuthenticationProtocol string, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewPPPAuthenticationProtocol string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "GetPPPAuthenticationProtocol", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewPPPAuthenticationProtocol, err = soap.UnmarshalString(response.NewPPPAuthenticationProtocol); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANPPPConnection1) GetUserName() (NewUserName string, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewUserName string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "GetUserName", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewUserName, err = soap.UnmarshalString(response.NewUserName); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANPPPConnection1) GetPassword() (NewPassword string, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewPassword string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "GetPassword", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewPassword, err = soap.UnmarshalString(response.NewPassword); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANPPPConnection1) GetAutoDisconnectTime() (NewAutoDisconnectTime uint32, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewAutoDisconnectTime string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "GetAutoDisconnectTime", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewAutoDisconnectTime, err = soap.UnmarshalUi4(response.NewAutoDisconnectTime); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANPPPConnection1) GetIdleDisconnectTime() (NewIdleDisconnectTime uint32, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewIdleDisconnectTime string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "GetIdleDisconnectTime", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewIdleDisconnectTime, err = soap.UnmarshalUi4(response.NewIdleDisconnectTime); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANPPPConnection1) GetWarnDisconnectDelay() (NewWarnDisconnectDelay uint32, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewWarnDisconnectDelay string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "GetWarnDisconnectDelay", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewWarnDisconnectDelay, err = soap.UnmarshalUi4(response.NewWarnDisconnectDelay); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANPPPConnection1) GetNATRSIPStatus() (NewRSIPAvailable bool, NewNATEnabled bool, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewRSIPAvailable string
-
- NewNATEnabled string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "GetNATRSIPStatus", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewRSIPAvailable, err = soap.UnmarshalBoolean(response.NewRSIPAvailable); err != nil {
- return
- }
- if NewNATEnabled, err = soap.UnmarshalBoolean(response.NewNATEnabled); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-//
-// Return values:
-//
-// * NewProtocol: allowed values: TCP, UDP
-func (client *WANPPPConnection1) GetGenericPortMappingEntry(NewPortMappingIndex uint16) (NewRemoteHost string, NewExternalPort uint16, NewProtocol string, NewInternalPort uint16, NewInternalClient string, NewEnabled bool, NewPortMappingDescription string, NewLeaseDuration uint32, err error) {
- // Request structure.
- request := &struct {
- NewPortMappingIndex string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.NewPortMappingIndex, err = soap.MarshalUi2(NewPortMappingIndex); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewRemoteHost string
-
- NewExternalPort string
-
- NewProtocol string
-
- NewInternalPort string
-
- NewInternalClient string
-
- NewEnabled string
-
- NewPortMappingDescription string
-
- NewLeaseDuration string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "GetGenericPortMappingEntry", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewRemoteHost, err = soap.UnmarshalString(response.NewRemoteHost); err != nil {
- return
- }
- if NewExternalPort, err = soap.UnmarshalUi2(response.NewExternalPort); err != nil {
- return
- }
- if NewProtocol, err = soap.UnmarshalString(response.NewProtocol); err != nil {
- return
- }
- if NewInternalPort, err = soap.UnmarshalUi2(response.NewInternalPort); err != nil {
- return
- }
- if NewInternalClient, err = soap.UnmarshalString(response.NewInternalClient); err != nil {
- return
- }
- if NewEnabled, err = soap.UnmarshalBoolean(response.NewEnabled); err != nil {
- return
- }
- if NewPortMappingDescription, err = soap.UnmarshalString(response.NewPortMappingDescription); err != nil {
- return
- }
- if NewLeaseDuration, err = soap.UnmarshalUi4(response.NewLeaseDuration); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-//
-// Arguments:
-//
-// * NewProtocol: allowed values: TCP, UDP
-
-func (client *WANPPPConnection1) GetSpecificPortMappingEntry(NewRemoteHost string, NewExternalPort uint16, NewProtocol string) (NewInternalPort uint16, NewInternalClient string, NewEnabled bool, NewPortMappingDescription string, NewLeaseDuration uint32, err error) {
- // Request structure.
- request := &struct {
- NewRemoteHost string
-
- NewExternalPort string
-
- NewProtocol string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.NewRemoteHost, err = soap.MarshalString(NewRemoteHost); err != nil {
- return
- }
- if request.NewExternalPort, err = soap.MarshalUi2(NewExternalPort); err != nil {
- return
- }
- if request.NewProtocol, err = soap.MarshalString(NewProtocol); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewInternalPort string
-
- NewInternalClient string
-
- NewEnabled string
-
- NewPortMappingDescription string
-
- NewLeaseDuration string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "GetSpecificPortMappingEntry", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewInternalPort, err = soap.UnmarshalUi2(response.NewInternalPort); err != nil {
- return
- }
- if NewInternalClient, err = soap.UnmarshalString(response.NewInternalClient); err != nil {
- return
- }
- if NewEnabled, err = soap.UnmarshalBoolean(response.NewEnabled); err != nil {
- return
- }
- if NewPortMappingDescription, err = soap.UnmarshalString(response.NewPortMappingDescription); err != nil {
- return
- }
- if NewLeaseDuration, err = soap.UnmarshalUi4(response.NewLeaseDuration); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-//
-// Arguments:
-//
-// * NewProtocol: allowed values: TCP, UDP
-
-func (client *WANPPPConnection1) AddPortMapping(NewRemoteHost string, NewExternalPort uint16, NewProtocol string, NewInternalPort uint16, NewInternalClient string, NewEnabled bool, NewPortMappingDescription string, NewLeaseDuration uint32) (err error) {
- // Request structure.
- request := &struct {
- NewRemoteHost string
-
- NewExternalPort string
-
- NewProtocol string
-
- NewInternalPort string
-
- NewInternalClient string
-
- NewEnabled string
-
- NewPortMappingDescription string
-
- NewLeaseDuration string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.NewRemoteHost, err = soap.MarshalString(NewRemoteHost); err != nil {
- return
- }
- if request.NewExternalPort, err = soap.MarshalUi2(NewExternalPort); err != nil {
- return
- }
- if request.NewProtocol, err = soap.MarshalString(NewProtocol); err != nil {
- return
- }
- if request.NewInternalPort, err = soap.MarshalUi2(NewInternalPort); err != nil {
- return
- }
- if request.NewInternalClient, err = soap.MarshalString(NewInternalClient); err != nil {
- return
- }
- if request.NewEnabled, err = soap.MarshalBoolean(NewEnabled); err != nil {
- return
- }
- if request.NewPortMappingDescription, err = soap.MarshalString(NewPortMappingDescription); err != nil {
- return
- }
- if request.NewLeaseDuration, err = soap.MarshalUi4(NewLeaseDuration); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "AddPortMapping", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-//
-// Arguments:
-//
-// * NewProtocol: allowed values: TCP, UDP
-
-func (client *WANPPPConnection1) DeletePortMapping(NewRemoteHost string, NewExternalPort uint16, NewProtocol string) (err error) {
- // Request structure.
- request := &struct {
- NewRemoteHost string
-
- NewExternalPort string
-
- NewProtocol string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.NewRemoteHost, err = soap.MarshalString(NewRemoteHost); err != nil {
- return
- }
- if request.NewExternalPort, err = soap.MarshalUi2(NewExternalPort); err != nil {
- return
- }
- if request.NewProtocol, err = soap.MarshalString(NewProtocol); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "DeletePortMapping", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANPPPConnection1) GetExternalIPAddress() (NewExternalIPAddress string, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewExternalIPAddress string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "GetExternalIPAddress", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewExternalIPAddress, err = soap.UnmarshalString(response.NewExternalIPAddress); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
diff --git a/vendor/github.com/huin/goupnp/dcps/internetgateway2/internetgateway2.go b/vendor/github.com/huin/goupnp/dcps/internetgateway2/internetgateway2.go
deleted file mode 100644
index 2d67a4a2e2..0000000000
--- a/vendor/github.com/huin/goupnp/dcps/internetgateway2/internetgateway2.go
+++ /dev/null
@@ -1,5378 +0,0 @@
-// Client for UPnP Device Control Protocol Internet Gateway Device v2.
-//
-// This DCP is documented in detail at: http://upnp.org/specs/gw/UPnP-gw-InternetGatewayDevice-v2-Device.pdf
-//
-// Typically, use one of the New* functions to create clients for services.
-package internetgateway2
-
-// Generated file - do not edit by hand. See README.md
-
-import (
- "net/url"
- "time"
-
- "github.com/huin/goupnp"
- "github.com/huin/goupnp/soap"
-)
-
-// Hack to avoid Go complaining if time isn't used.
-var _ time.Time
-
-// Device URNs:
-const (
- URN_LANDevice_1 = "urn:schemas-upnp-org:device:LANDevice:1"
- URN_WANConnectionDevice_1 = "urn:schemas-upnp-org:device:WANConnectionDevice:1"
- URN_WANConnectionDevice_2 = "urn:schemas-upnp-org:device:WANConnectionDevice:2"
- URN_WANDevice_1 = "urn:schemas-upnp-org:device:WANDevice:1"
- URN_WANDevice_2 = "urn:schemas-upnp-org:device:WANDevice:2"
-)
-
-// Service URNs:
-const (
- URN_DeviceProtection_1 = "urn:schemas-upnp-org:service:DeviceProtection:1"
- URN_LANHostConfigManagement_1 = "urn:schemas-upnp-org:service:LANHostConfigManagement:1"
- URN_Layer3Forwarding_1 = "urn:schemas-upnp-org:service:Layer3Forwarding:1"
- URN_WANCableLinkConfig_1 = "urn:schemas-upnp-org:service:WANCableLinkConfig:1"
- URN_WANCommonInterfaceConfig_1 = "urn:schemas-upnp-org:service:WANCommonInterfaceConfig:1"
- URN_WANDSLLinkConfig_1 = "urn:schemas-upnp-org:service:WANDSLLinkConfig:1"
- URN_WANEthernetLinkConfig_1 = "urn:schemas-upnp-org:service:WANEthernetLinkConfig:1"
- URN_WANIPConnection_1 = "urn:schemas-upnp-org:service:WANIPConnection:1"
- URN_WANIPConnection_2 = "urn:schemas-upnp-org:service:WANIPConnection:2"
- URN_WANIPv6FirewallControl_1 = "urn:schemas-upnp-org:service:WANIPv6FirewallControl:1"
- URN_WANPOTSLinkConfig_1 = "urn:schemas-upnp-org:service:WANPOTSLinkConfig:1"
- URN_WANPPPConnection_1 = "urn:schemas-upnp-org:service:WANPPPConnection:1"
-)
-
-// DeviceProtection1 is a client for UPnP SOAP service with URN "urn:schemas-upnp-org:service:DeviceProtection:1". See
-// goupnp.ServiceClient, which contains RootDevice and Service attributes which
-// are provided for informational value.
-type DeviceProtection1 struct {
- goupnp.ServiceClient
-}
-
-// NewDeviceProtection1Clients discovers instances of the service on the network,
-// and returns clients to any that are found. errors will contain an error for
-// any devices that replied but which could not be queried, and err will be set
-// if the discovery process failed outright.
-//
-// This is a typical entry calling point into this package.
-func NewDeviceProtection1Clients() (clients []*DeviceProtection1, errors []error, err error) {
- var genericClients []goupnp.ServiceClient
- if genericClients, errors, err = goupnp.NewServiceClients(URN_DeviceProtection_1); err != nil {
- return
- }
- clients = newDeviceProtection1ClientsFromGenericClients(genericClients)
- return
-}
-
-// NewDeviceProtection1ClientsByURL discovers instances of the service at the given
-// URL, and returns clients to any that are found. An error is returned if
-// there was an error probing the service.
-//
-// This is a typical entry calling point into this package when reusing an
-// previously discovered service URL.
-func NewDeviceProtection1ClientsByURL(loc *url.URL) ([]*DeviceProtection1, error) {
- genericClients, err := goupnp.NewServiceClientsByURL(loc, URN_DeviceProtection_1)
- if err != nil {
- return nil, err
- }
- return newDeviceProtection1ClientsFromGenericClients(genericClients), nil
-}
-
-// NewDeviceProtection1ClientsFromRootDevice discovers instances of the service in
-// a given root device, and returns clients to any that are found. An error is
-// returned if there was not at least one instance of the service within the
-// device. The location parameter is simply assigned to the Location attribute
-// of the wrapped ServiceClient(s).
-//
-// This is a typical entry calling point into this package when reusing an
-// previously discovered root device.
-func NewDeviceProtection1ClientsFromRootDevice(rootDevice *goupnp.RootDevice, loc *url.URL) ([]*DeviceProtection1, error) {
- genericClients, err := goupnp.NewServiceClientsFromRootDevice(rootDevice, loc, URN_DeviceProtection_1)
- if err != nil {
- return nil, err
- }
- return newDeviceProtection1ClientsFromGenericClients(genericClients), nil
-}
-
-func newDeviceProtection1ClientsFromGenericClients(genericClients []goupnp.ServiceClient) []*DeviceProtection1 {
- clients := make([]*DeviceProtection1, len(genericClients))
- for i := range genericClients {
- clients[i] = &DeviceProtection1{genericClients[i]}
- }
- return clients
-}
-
-func (client *DeviceProtection1) SendSetupMessage(ProtocolType string, InMessage []byte) (OutMessage []byte, err error) {
- // Request structure.
- request := &struct {
- ProtocolType string
-
- InMessage string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.ProtocolType, err = soap.MarshalString(ProtocolType); err != nil {
- return
- }
- if request.InMessage, err = soap.MarshalBinBase64(InMessage); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- OutMessage string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_DeviceProtection_1, "SendSetupMessage", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if OutMessage, err = soap.UnmarshalBinBase64(response.OutMessage); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *DeviceProtection1) GetSupportedProtocols() (ProtocolList string, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- ProtocolList string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_DeviceProtection_1, "GetSupportedProtocols", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if ProtocolList, err = soap.UnmarshalString(response.ProtocolList); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *DeviceProtection1) GetAssignedRoles() (RoleList string, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- RoleList string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_DeviceProtection_1, "GetAssignedRoles", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if RoleList, err = soap.UnmarshalString(response.RoleList); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *DeviceProtection1) GetRolesForAction(DeviceUDN string, ServiceId string, ActionName string) (RoleList string, RestrictedRoleList string, err error) {
- // Request structure.
- request := &struct {
- DeviceUDN string
-
- ServiceId string
-
- ActionName string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.DeviceUDN, err = soap.MarshalString(DeviceUDN); err != nil {
- return
- }
- if request.ServiceId, err = soap.MarshalString(ServiceId); err != nil {
- return
- }
- if request.ActionName, err = soap.MarshalString(ActionName); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- RoleList string
-
- RestrictedRoleList string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_DeviceProtection_1, "GetRolesForAction", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if RoleList, err = soap.UnmarshalString(response.RoleList); err != nil {
- return
- }
- if RestrictedRoleList, err = soap.UnmarshalString(response.RestrictedRoleList); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *DeviceProtection1) GetUserLoginChallenge(ProtocolType string, Name string) (Salt []byte, Challenge []byte, err error) {
- // Request structure.
- request := &struct {
- ProtocolType string
-
- Name string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.ProtocolType, err = soap.MarshalString(ProtocolType); err != nil {
- return
- }
- if request.Name, err = soap.MarshalString(Name); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- Salt string
-
- Challenge string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_DeviceProtection_1, "GetUserLoginChallenge", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if Salt, err = soap.UnmarshalBinBase64(response.Salt); err != nil {
- return
- }
- if Challenge, err = soap.UnmarshalBinBase64(response.Challenge); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *DeviceProtection1) UserLogin(ProtocolType string, Challenge []byte, Authenticator []byte) (err error) {
- // Request structure.
- request := &struct {
- ProtocolType string
-
- Challenge string
-
- Authenticator string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.ProtocolType, err = soap.MarshalString(ProtocolType); err != nil {
- return
- }
- if request.Challenge, err = soap.MarshalBinBase64(Challenge); err != nil {
- return
- }
- if request.Authenticator, err = soap.MarshalBinBase64(Authenticator); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_DeviceProtection_1, "UserLogin", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *DeviceProtection1) UserLogout() (err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_DeviceProtection_1, "UserLogout", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *DeviceProtection1) GetACLData() (ACL string, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- ACL string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_DeviceProtection_1, "GetACLData", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if ACL, err = soap.UnmarshalString(response.ACL); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *DeviceProtection1) AddIdentityList(IdentityList string) (IdentityListResult string, err error) {
- // Request structure.
- request := &struct {
- IdentityList string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.IdentityList, err = soap.MarshalString(IdentityList); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- IdentityListResult string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_DeviceProtection_1, "AddIdentityList", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if IdentityListResult, err = soap.UnmarshalString(response.IdentityListResult); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *DeviceProtection1) RemoveIdentity(Identity string) (err error) {
- // Request structure.
- request := &struct {
- Identity string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.Identity, err = soap.MarshalString(Identity); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_DeviceProtection_1, "RemoveIdentity", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *DeviceProtection1) SetUserLoginPassword(ProtocolType string, Name string, Stored []byte, Salt []byte) (err error) {
- // Request structure.
- request := &struct {
- ProtocolType string
-
- Name string
-
- Stored string
-
- Salt string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.ProtocolType, err = soap.MarshalString(ProtocolType); err != nil {
- return
- }
- if request.Name, err = soap.MarshalString(Name); err != nil {
- return
- }
- if request.Stored, err = soap.MarshalBinBase64(Stored); err != nil {
- return
- }
- if request.Salt, err = soap.MarshalBinBase64(Salt); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_DeviceProtection_1, "SetUserLoginPassword", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *DeviceProtection1) AddRolesForIdentity(Identity string, RoleList string) (err error) {
- // Request structure.
- request := &struct {
- Identity string
-
- RoleList string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.Identity, err = soap.MarshalString(Identity); err != nil {
- return
- }
- if request.RoleList, err = soap.MarshalString(RoleList); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_DeviceProtection_1, "AddRolesForIdentity", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *DeviceProtection1) RemoveRolesForIdentity(Identity string, RoleList string) (err error) {
- // Request structure.
- request := &struct {
- Identity string
-
- RoleList string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.Identity, err = soap.MarshalString(Identity); err != nil {
- return
- }
- if request.RoleList, err = soap.MarshalString(RoleList); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_DeviceProtection_1, "RemoveRolesForIdentity", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-// LANHostConfigManagement1 is a client for UPnP SOAP service with URN "urn:schemas-upnp-org:service:LANHostConfigManagement:1". See
-// goupnp.ServiceClient, which contains RootDevice and Service attributes which
-// are provided for informational value.
-type LANHostConfigManagement1 struct {
- goupnp.ServiceClient
-}
-
-// NewLANHostConfigManagement1Clients discovers instances of the service on the network,
-// and returns clients to any that are found. errors will contain an error for
-// any devices that replied but which could not be queried, and err will be set
-// if the discovery process failed outright.
-//
-// This is a typical entry calling point into this package.
-func NewLANHostConfigManagement1Clients() (clients []*LANHostConfigManagement1, errors []error, err error) {
- var genericClients []goupnp.ServiceClient
- if genericClients, errors, err = goupnp.NewServiceClients(URN_LANHostConfigManagement_1); err != nil {
- return
- }
- clients = newLANHostConfigManagement1ClientsFromGenericClients(genericClients)
- return
-}
-
-// NewLANHostConfigManagement1ClientsByURL discovers instances of the service at the given
-// URL, and returns clients to any that are found. An error is returned if
-// there was an error probing the service.
-//
-// This is a typical entry calling point into this package when reusing an
-// previously discovered service URL.
-func NewLANHostConfigManagement1ClientsByURL(loc *url.URL) ([]*LANHostConfigManagement1, error) {
- genericClients, err := goupnp.NewServiceClientsByURL(loc, URN_LANHostConfigManagement_1)
- if err != nil {
- return nil, err
- }
- return newLANHostConfigManagement1ClientsFromGenericClients(genericClients), nil
-}
-
-// NewLANHostConfigManagement1ClientsFromRootDevice discovers instances of the service in
-// a given root device, and returns clients to any that are found. An error is
-// returned if there was not at least one instance of the service within the
-// device. The location parameter is simply assigned to the Location attribute
-// of the wrapped ServiceClient(s).
-//
-// This is a typical entry calling point into this package when reusing an
-// previously discovered root device.
-func NewLANHostConfigManagement1ClientsFromRootDevice(rootDevice *goupnp.RootDevice, loc *url.URL) ([]*LANHostConfigManagement1, error) {
- genericClients, err := goupnp.NewServiceClientsFromRootDevice(rootDevice, loc, URN_LANHostConfigManagement_1)
- if err != nil {
- return nil, err
- }
- return newLANHostConfigManagement1ClientsFromGenericClients(genericClients), nil
-}
-
-func newLANHostConfigManagement1ClientsFromGenericClients(genericClients []goupnp.ServiceClient) []*LANHostConfigManagement1 {
- clients := make([]*LANHostConfigManagement1, len(genericClients))
- for i := range genericClients {
- clients[i] = &LANHostConfigManagement1{genericClients[i]}
- }
- return clients
-}
-
-func (client *LANHostConfigManagement1) SetDHCPServerConfigurable(NewDHCPServerConfigurable bool) (err error) {
- // Request structure.
- request := &struct {
- NewDHCPServerConfigurable string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.NewDHCPServerConfigurable, err = soap.MarshalBoolean(NewDHCPServerConfigurable); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_LANHostConfigManagement_1, "SetDHCPServerConfigurable", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *LANHostConfigManagement1) GetDHCPServerConfigurable() (NewDHCPServerConfigurable bool, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewDHCPServerConfigurable string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_LANHostConfigManagement_1, "GetDHCPServerConfigurable", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewDHCPServerConfigurable, err = soap.UnmarshalBoolean(response.NewDHCPServerConfigurable); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *LANHostConfigManagement1) SetDHCPRelay(NewDHCPRelay bool) (err error) {
- // Request structure.
- request := &struct {
- NewDHCPRelay string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.NewDHCPRelay, err = soap.MarshalBoolean(NewDHCPRelay); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_LANHostConfigManagement_1, "SetDHCPRelay", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *LANHostConfigManagement1) GetDHCPRelay() (NewDHCPRelay bool, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewDHCPRelay string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_LANHostConfigManagement_1, "GetDHCPRelay", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewDHCPRelay, err = soap.UnmarshalBoolean(response.NewDHCPRelay); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *LANHostConfigManagement1) SetSubnetMask(NewSubnetMask string) (err error) {
- // Request structure.
- request := &struct {
- NewSubnetMask string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.NewSubnetMask, err = soap.MarshalString(NewSubnetMask); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_LANHostConfigManagement_1, "SetSubnetMask", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *LANHostConfigManagement1) GetSubnetMask() (NewSubnetMask string, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewSubnetMask string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_LANHostConfigManagement_1, "GetSubnetMask", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewSubnetMask, err = soap.UnmarshalString(response.NewSubnetMask); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *LANHostConfigManagement1) SetIPRouter(NewIPRouters string) (err error) {
- // Request structure.
- request := &struct {
- NewIPRouters string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.NewIPRouters, err = soap.MarshalString(NewIPRouters); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_LANHostConfigManagement_1, "SetIPRouter", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *LANHostConfigManagement1) DeleteIPRouter(NewIPRouters string) (err error) {
- // Request structure.
- request := &struct {
- NewIPRouters string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.NewIPRouters, err = soap.MarshalString(NewIPRouters); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_LANHostConfigManagement_1, "DeleteIPRouter", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *LANHostConfigManagement1) GetIPRoutersList() (NewIPRouters string, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewIPRouters string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_LANHostConfigManagement_1, "GetIPRoutersList", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewIPRouters, err = soap.UnmarshalString(response.NewIPRouters); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *LANHostConfigManagement1) SetDomainName(NewDomainName string) (err error) {
- // Request structure.
- request := &struct {
- NewDomainName string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.NewDomainName, err = soap.MarshalString(NewDomainName); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_LANHostConfigManagement_1, "SetDomainName", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *LANHostConfigManagement1) GetDomainName() (NewDomainName string, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewDomainName string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_LANHostConfigManagement_1, "GetDomainName", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewDomainName, err = soap.UnmarshalString(response.NewDomainName); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *LANHostConfigManagement1) SetAddressRange(NewMinAddress string, NewMaxAddress string) (err error) {
- // Request structure.
- request := &struct {
- NewMinAddress string
-
- NewMaxAddress string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.NewMinAddress, err = soap.MarshalString(NewMinAddress); err != nil {
- return
- }
- if request.NewMaxAddress, err = soap.MarshalString(NewMaxAddress); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_LANHostConfigManagement_1, "SetAddressRange", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *LANHostConfigManagement1) GetAddressRange() (NewMinAddress string, NewMaxAddress string, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewMinAddress string
-
- NewMaxAddress string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_LANHostConfigManagement_1, "GetAddressRange", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewMinAddress, err = soap.UnmarshalString(response.NewMinAddress); err != nil {
- return
- }
- if NewMaxAddress, err = soap.UnmarshalString(response.NewMaxAddress); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *LANHostConfigManagement1) SetReservedAddress(NewReservedAddresses string) (err error) {
- // Request structure.
- request := &struct {
- NewReservedAddresses string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.NewReservedAddresses, err = soap.MarshalString(NewReservedAddresses); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_LANHostConfigManagement_1, "SetReservedAddress", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *LANHostConfigManagement1) DeleteReservedAddress(NewReservedAddresses string) (err error) {
- // Request structure.
- request := &struct {
- NewReservedAddresses string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.NewReservedAddresses, err = soap.MarshalString(NewReservedAddresses); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_LANHostConfigManagement_1, "DeleteReservedAddress", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *LANHostConfigManagement1) GetReservedAddresses() (NewReservedAddresses string, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewReservedAddresses string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_LANHostConfigManagement_1, "GetReservedAddresses", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewReservedAddresses, err = soap.UnmarshalString(response.NewReservedAddresses); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *LANHostConfigManagement1) SetDNSServer(NewDNSServers string) (err error) {
- // Request structure.
- request := &struct {
- NewDNSServers string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.NewDNSServers, err = soap.MarshalString(NewDNSServers); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_LANHostConfigManagement_1, "SetDNSServer", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *LANHostConfigManagement1) DeleteDNSServer(NewDNSServers string) (err error) {
- // Request structure.
- request := &struct {
- NewDNSServers string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.NewDNSServers, err = soap.MarshalString(NewDNSServers); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_LANHostConfigManagement_1, "DeleteDNSServer", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *LANHostConfigManagement1) GetDNSServers() (NewDNSServers string, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewDNSServers string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_LANHostConfigManagement_1, "GetDNSServers", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewDNSServers, err = soap.UnmarshalString(response.NewDNSServers); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-// Layer3Forwarding1 is a client for UPnP SOAP service with URN "urn:schemas-upnp-org:service:Layer3Forwarding:1". See
-// goupnp.ServiceClient, which contains RootDevice and Service attributes which
-// are provided for informational value.
-type Layer3Forwarding1 struct {
- goupnp.ServiceClient
-}
-
-// NewLayer3Forwarding1Clients discovers instances of the service on the network,
-// and returns clients to any that are found. errors will contain an error for
-// any devices that replied but which could not be queried, and err will be set
-// if the discovery process failed outright.
-//
-// This is a typical entry calling point into this package.
-func NewLayer3Forwarding1Clients() (clients []*Layer3Forwarding1, errors []error, err error) {
- var genericClients []goupnp.ServiceClient
- if genericClients, errors, err = goupnp.NewServiceClients(URN_Layer3Forwarding_1); err != nil {
- return
- }
- clients = newLayer3Forwarding1ClientsFromGenericClients(genericClients)
- return
-}
-
-// NewLayer3Forwarding1ClientsByURL discovers instances of the service at the given
-// URL, and returns clients to any that are found. An error is returned if
-// there was an error probing the service.
-//
-// This is a typical entry calling point into this package when reusing an
-// previously discovered service URL.
-func NewLayer3Forwarding1ClientsByURL(loc *url.URL) ([]*Layer3Forwarding1, error) {
- genericClients, err := goupnp.NewServiceClientsByURL(loc, URN_Layer3Forwarding_1)
- if err != nil {
- return nil, err
- }
- return newLayer3Forwarding1ClientsFromGenericClients(genericClients), nil
-}
-
-// NewLayer3Forwarding1ClientsFromRootDevice discovers instances of the service in
-// a given root device, and returns clients to any that are found. An error is
-// returned if there was not at least one instance of the service within the
-// device. The location parameter is simply assigned to the Location attribute
-// of the wrapped ServiceClient(s).
-//
-// This is a typical entry calling point into this package when reusing an
-// previously discovered root device.
-func NewLayer3Forwarding1ClientsFromRootDevice(rootDevice *goupnp.RootDevice, loc *url.URL) ([]*Layer3Forwarding1, error) {
- genericClients, err := goupnp.NewServiceClientsFromRootDevice(rootDevice, loc, URN_Layer3Forwarding_1)
- if err != nil {
- return nil, err
- }
- return newLayer3Forwarding1ClientsFromGenericClients(genericClients), nil
-}
-
-func newLayer3Forwarding1ClientsFromGenericClients(genericClients []goupnp.ServiceClient) []*Layer3Forwarding1 {
- clients := make([]*Layer3Forwarding1, len(genericClients))
- for i := range genericClients {
- clients[i] = &Layer3Forwarding1{genericClients[i]}
- }
- return clients
-}
-
-func (client *Layer3Forwarding1) SetDefaultConnectionService(NewDefaultConnectionService string) (err error) {
- // Request structure.
- request := &struct {
- NewDefaultConnectionService string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.NewDefaultConnectionService, err = soap.MarshalString(NewDefaultConnectionService); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_Layer3Forwarding_1, "SetDefaultConnectionService", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *Layer3Forwarding1) GetDefaultConnectionService() (NewDefaultConnectionService string, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewDefaultConnectionService string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_Layer3Forwarding_1, "GetDefaultConnectionService", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewDefaultConnectionService, err = soap.UnmarshalString(response.NewDefaultConnectionService); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-// WANCableLinkConfig1 is a client for UPnP SOAP service with URN "urn:schemas-upnp-org:service:WANCableLinkConfig:1". See
-// goupnp.ServiceClient, which contains RootDevice and Service attributes which
-// are provided for informational value.
-type WANCableLinkConfig1 struct {
- goupnp.ServiceClient
-}
-
-// NewWANCableLinkConfig1Clients discovers instances of the service on the network,
-// and returns clients to any that are found. errors will contain an error for
-// any devices that replied but which could not be queried, and err will be set
-// if the discovery process failed outright.
-//
-// This is a typical entry calling point into this package.
-func NewWANCableLinkConfig1Clients() (clients []*WANCableLinkConfig1, errors []error, err error) {
- var genericClients []goupnp.ServiceClient
- if genericClients, errors, err = goupnp.NewServiceClients(URN_WANCableLinkConfig_1); err != nil {
- return
- }
- clients = newWANCableLinkConfig1ClientsFromGenericClients(genericClients)
- return
-}
-
-// NewWANCableLinkConfig1ClientsByURL discovers instances of the service at the given
-// URL, and returns clients to any that are found. An error is returned if
-// there was an error probing the service.
-//
-// This is a typical entry calling point into this package when reusing an
-// previously discovered service URL.
-func NewWANCableLinkConfig1ClientsByURL(loc *url.URL) ([]*WANCableLinkConfig1, error) {
- genericClients, err := goupnp.NewServiceClientsByURL(loc, URN_WANCableLinkConfig_1)
- if err != nil {
- return nil, err
- }
- return newWANCableLinkConfig1ClientsFromGenericClients(genericClients), nil
-}
-
-// NewWANCableLinkConfig1ClientsFromRootDevice discovers instances of the service in
-// a given root device, and returns clients to any that are found. An error is
-// returned if there was not at least one instance of the service within the
-// device. The location parameter is simply assigned to the Location attribute
-// of the wrapped ServiceClient(s).
-//
-// This is a typical entry calling point into this package when reusing an
-// previously discovered root device.
-func NewWANCableLinkConfig1ClientsFromRootDevice(rootDevice *goupnp.RootDevice, loc *url.URL) ([]*WANCableLinkConfig1, error) {
- genericClients, err := goupnp.NewServiceClientsFromRootDevice(rootDevice, loc, URN_WANCableLinkConfig_1)
- if err != nil {
- return nil, err
- }
- return newWANCableLinkConfig1ClientsFromGenericClients(genericClients), nil
-}
-
-func newWANCableLinkConfig1ClientsFromGenericClients(genericClients []goupnp.ServiceClient) []*WANCableLinkConfig1 {
- clients := make([]*WANCableLinkConfig1, len(genericClients))
- for i := range genericClients {
- clients[i] = &WANCableLinkConfig1{genericClients[i]}
- }
- return clients
-}
-
-//
-// Return values:
-//
-// * NewCableLinkConfigState: allowed values: notReady, dsSyncComplete, usParamAcquired, rangingComplete, ipComplete, todEstablished, paramTransferComplete, registrationComplete, operational, accessDenied
-//
-// * NewLinkType: allowed values: Ethernet
-func (client *WANCableLinkConfig1) GetCableLinkConfigInfo() (NewCableLinkConfigState string, NewLinkType string, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewCableLinkConfigState string
-
- NewLinkType string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANCableLinkConfig_1, "GetCableLinkConfigInfo", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewCableLinkConfigState, err = soap.UnmarshalString(response.NewCableLinkConfigState); err != nil {
- return
- }
- if NewLinkType, err = soap.UnmarshalString(response.NewLinkType); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANCableLinkConfig1) GetDownstreamFrequency() (NewDownstreamFrequency uint32, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewDownstreamFrequency string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANCableLinkConfig_1, "GetDownstreamFrequency", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewDownstreamFrequency, err = soap.UnmarshalUi4(response.NewDownstreamFrequency); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-//
-// Return values:
-//
-// * NewDownstreamModulation: allowed values: 64QAM, 256QAM
-func (client *WANCableLinkConfig1) GetDownstreamModulation() (NewDownstreamModulation string, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewDownstreamModulation string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANCableLinkConfig_1, "GetDownstreamModulation", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewDownstreamModulation, err = soap.UnmarshalString(response.NewDownstreamModulation); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANCableLinkConfig1) GetUpstreamFrequency() (NewUpstreamFrequency uint32, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewUpstreamFrequency string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANCableLinkConfig_1, "GetUpstreamFrequency", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewUpstreamFrequency, err = soap.UnmarshalUi4(response.NewUpstreamFrequency); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-//
-// Return values:
-//
-// * NewUpstreamModulation: allowed values: QPSK, 16QAM
-func (client *WANCableLinkConfig1) GetUpstreamModulation() (NewUpstreamModulation string, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewUpstreamModulation string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANCableLinkConfig_1, "GetUpstreamModulation", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewUpstreamModulation, err = soap.UnmarshalString(response.NewUpstreamModulation); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANCableLinkConfig1) GetUpstreamChannelID() (NewUpstreamChannelID uint32, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewUpstreamChannelID string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANCableLinkConfig_1, "GetUpstreamChannelID", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewUpstreamChannelID, err = soap.UnmarshalUi4(response.NewUpstreamChannelID); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANCableLinkConfig1) GetUpstreamPowerLevel() (NewUpstreamPowerLevel uint32, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewUpstreamPowerLevel string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANCableLinkConfig_1, "GetUpstreamPowerLevel", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewUpstreamPowerLevel, err = soap.UnmarshalUi4(response.NewUpstreamPowerLevel); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANCableLinkConfig1) GetBPIEncryptionEnabled() (NewBPIEncryptionEnabled bool, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewBPIEncryptionEnabled string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANCableLinkConfig_1, "GetBPIEncryptionEnabled", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewBPIEncryptionEnabled, err = soap.UnmarshalBoolean(response.NewBPIEncryptionEnabled); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANCableLinkConfig1) GetConfigFile() (NewConfigFile string, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewConfigFile string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANCableLinkConfig_1, "GetConfigFile", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewConfigFile, err = soap.UnmarshalString(response.NewConfigFile); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANCableLinkConfig1) GetTFTPServer() (NewTFTPServer string, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewTFTPServer string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANCableLinkConfig_1, "GetTFTPServer", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewTFTPServer, err = soap.UnmarshalString(response.NewTFTPServer); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-// WANCommonInterfaceConfig1 is a client for UPnP SOAP service with URN "urn:schemas-upnp-org:service:WANCommonInterfaceConfig:1". See
-// goupnp.ServiceClient, which contains RootDevice and Service attributes which
-// are provided for informational value.
-type WANCommonInterfaceConfig1 struct {
- goupnp.ServiceClient
-}
-
-// NewWANCommonInterfaceConfig1Clients discovers instances of the service on the network,
-// and returns clients to any that are found. errors will contain an error for
-// any devices that replied but which could not be queried, and err will be set
-// if the discovery process failed outright.
-//
-// This is a typical entry calling point into this package.
-func NewWANCommonInterfaceConfig1Clients() (clients []*WANCommonInterfaceConfig1, errors []error, err error) {
- var genericClients []goupnp.ServiceClient
- if genericClients, errors, err = goupnp.NewServiceClients(URN_WANCommonInterfaceConfig_1); err != nil {
- return
- }
- clients = newWANCommonInterfaceConfig1ClientsFromGenericClients(genericClients)
- return
-}
-
-// NewWANCommonInterfaceConfig1ClientsByURL discovers instances of the service at the given
-// URL, and returns clients to any that are found. An error is returned if
-// there was an error probing the service.
-//
-// This is a typical entry calling point into this package when reusing an
-// previously discovered service URL.
-func NewWANCommonInterfaceConfig1ClientsByURL(loc *url.URL) ([]*WANCommonInterfaceConfig1, error) {
- genericClients, err := goupnp.NewServiceClientsByURL(loc, URN_WANCommonInterfaceConfig_1)
- if err != nil {
- return nil, err
- }
- return newWANCommonInterfaceConfig1ClientsFromGenericClients(genericClients), nil
-}
-
-// NewWANCommonInterfaceConfig1ClientsFromRootDevice discovers instances of the service in
-// a given root device, and returns clients to any that are found. An error is
-// returned if there was not at least one instance of the service within the
-// device. The location parameter is simply assigned to the Location attribute
-// of the wrapped ServiceClient(s).
-//
-// This is a typical entry calling point into this package when reusing an
-// previously discovered root device.
-func NewWANCommonInterfaceConfig1ClientsFromRootDevice(rootDevice *goupnp.RootDevice, loc *url.URL) ([]*WANCommonInterfaceConfig1, error) {
- genericClients, err := goupnp.NewServiceClientsFromRootDevice(rootDevice, loc, URN_WANCommonInterfaceConfig_1)
- if err != nil {
- return nil, err
- }
- return newWANCommonInterfaceConfig1ClientsFromGenericClients(genericClients), nil
-}
-
-func newWANCommonInterfaceConfig1ClientsFromGenericClients(genericClients []goupnp.ServiceClient) []*WANCommonInterfaceConfig1 {
- clients := make([]*WANCommonInterfaceConfig1, len(genericClients))
- for i := range genericClients {
- clients[i] = &WANCommonInterfaceConfig1{genericClients[i]}
- }
- return clients
-}
-
-func (client *WANCommonInterfaceConfig1) SetEnabledForInternet(NewEnabledForInternet bool) (err error) {
- // Request structure.
- request := &struct {
- NewEnabledForInternet string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.NewEnabledForInternet, err = soap.MarshalBoolean(NewEnabledForInternet); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANCommonInterfaceConfig_1, "SetEnabledForInternet", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANCommonInterfaceConfig1) GetEnabledForInternet() (NewEnabledForInternet bool, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewEnabledForInternet string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANCommonInterfaceConfig_1, "GetEnabledForInternet", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewEnabledForInternet, err = soap.UnmarshalBoolean(response.NewEnabledForInternet); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-//
-// Return values:
-//
-// * NewWANAccessType: allowed values: DSL, POTS, Cable, Ethernet
-//
-// * NewPhysicalLinkStatus: allowed values: Up, Down
-func (client *WANCommonInterfaceConfig1) GetCommonLinkProperties() (NewWANAccessType string, NewLayer1UpstreamMaxBitRate uint32, NewLayer1DownstreamMaxBitRate uint32, NewPhysicalLinkStatus string, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewWANAccessType string
-
- NewLayer1UpstreamMaxBitRate string
-
- NewLayer1DownstreamMaxBitRate string
-
- NewPhysicalLinkStatus string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANCommonInterfaceConfig_1, "GetCommonLinkProperties", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewWANAccessType, err = soap.UnmarshalString(response.NewWANAccessType); err != nil {
- return
- }
- if NewLayer1UpstreamMaxBitRate, err = soap.UnmarshalUi4(response.NewLayer1UpstreamMaxBitRate); err != nil {
- return
- }
- if NewLayer1DownstreamMaxBitRate, err = soap.UnmarshalUi4(response.NewLayer1DownstreamMaxBitRate); err != nil {
- return
- }
- if NewPhysicalLinkStatus, err = soap.UnmarshalString(response.NewPhysicalLinkStatus); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANCommonInterfaceConfig1) GetWANAccessProvider() (NewWANAccessProvider string, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewWANAccessProvider string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANCommonInterfaceConfig_1, "GetWANAccessProvider", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewWANAccessProvider, err = soap.UnmarshalString(response.NewWANAccessProvider); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-//
-// Return values:
-//
-// * NewMaximumActiveConnections: allowed value range: minimum=1, step=1
-func (client *WANCommonInterfaceConfig1) GetMaximumActiveConnections() (NewMaximumActiveConnections uint16, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewMaximumActiveConnections string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANCommonInterfaceConfig_1, "GetMaximumActiveConnections", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewMaximumActiveConnections, err = soap.UnmarshalUi2(response.NewMaximumActiveConnections); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANCommonInterfaceConfig1) GetTotalBytesSent() (NewTotalBytesSent uint32, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewTotalBytesSent string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANCommonInterfaceConfig_1, "GetTotalBytesSent", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewTotalBytesSent, err = soap.UnmarshalUi4(response.NewTotalBytesSent); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANCommonInterfaceConfig1) GetTotalBytesReceived() (NewTotalBytesReceived uint32, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewTotalBytesReceived string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANCommonInterfaceConfig_1, "GetTotalBytesReceived", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewTotalBytesReceived, err = soap.UnmarshalUi4(response.NewTotalBytesReceived); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANCommonInterfaceConfig1) GetTotalPacketsSent() (NewTotalPacketsSent uint32, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewTotalPacketsSent string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANCommonInterfaceConfig_1, "GetTotalPacketsSent", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewTotalPacketsSent, err = soap.UnmarshalUi4(response.NewTotalPacketsSent); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANCommonInterfaceConfig1) GetTotalPacketsReceived() (NewTotalPacketsReceived uint32, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewTotalPacketsReceived string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANCommonInterfaceConfig_1, "GetTotalPacketsReceived", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewTotalPacketsReceived, err = soap.UnmarshalUi4(response.NewTotalPacketsReceived); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANCommonInterfaceConfig1) GetActiveConnection(NewActiveConnectionIndex uint16) (NewActiveConnDeviceContainer string, NewActiveConnectionServiceID string, err error) {
- // Request structure.
- request := &struct {
- NewActiveConnectionIndex string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.NewActiveConnectionIndex, err = soap.MarshalUi2(NewActiveConnectionIndex); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewActiveConnDeviceContainer string
-
- NewActiveConnectionServiceID string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANCommonInterfaceConfig_1, "GetActiveConnection", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewActiveConnDeviceContainer, err = soap.UnmarshalString(response.NewActiveConnDeviceContainer); err != nil {
- return
- }
- if NewActiveConnectionServiceID, err = soap.UnmarshalString(response.NewActiveConnectionServiceID); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-// WANDSLLinkConfig1 is a client for UPnP SOAP service with URN "urn:schemas-upnp-org:service:WANDSLLinkConfig:1". See
-// goupnp.ServiceClient, which contains RootDevice and Service attributes which
-// are provided for informational value.
-type WANDSLLinkConfig1 struct {
- goupnp.ServiceClient
-}
-
-// NewWANDSLLinkConfig1Clients discovers instances of the service on the network,
-// and returns clients to any that are found. errors will contain an error for
-// any devices that replied but which could not be queried, and err will be set
-// if the discovery process failed outright.
-//
-// This is a typical entry calling point into this package.
-func NewWANDSLLinkConfig1Clients() (clients []*WANDSLLinkConfig1, errors []error, err error) {
- var genericClients []goupnp.ServiceClient
- if genericClients, errors, err = goupnp.NewServiceClients(URN_WANDSLLinkConfig_1); err != nil {
- return
- }
- clients = newWANDSLLinkConfig1ClientsFromGenericClients(genericClients)
- return
-}
-
-// NewWANDSLLinkConfig1ClientsByURL discovers instances of the service at the given
-// URL, and returns clients to any that are found. An error is returned if
-// there was an error probing the service.
-//
-// This is a typical entry calling point into this package when reusing an
-// previously discovered service URL.
-func NewWANDSLLinkConfig1ClientsByURL(loc *url.URL) ([]*WANDSLLinkConfig1, error) {
- genericClients, err := goupnp.NewServiceClientsByURL(loc, URN_WANDSLLinkConfig_1)
- if err != nil {
- return nil, err
- }
- return newWANDSLLinkConfig1ClientsFromGenericClients(genericClients), nil
-}
-
-// NewWANDSLLinkConfig1ClientsFromRootDevice discovers instances of the service in
-// a given root device, and returns clients to any that are found. An error is
-// returned if there was not at least one instance of the service within the
-// device. The location parameter is simply assigned to the Location attribute
-// of the wrapped ServiceClient(s).
-//
-// This is a typical entry calling point into this package when reusing an
-// previously discovered root device.
-func NewWANDSLLinkConfig1ClientsFromRootDevice(rootDevice *goupnp.RootDevice, loc *url.URL) ([]*WANDSLLinkConfig1, error) {
- genericClients, err := goupnp.NewServiceClientsFromRootDevice(rootDevice, loc, URN_WANDSLLinkConfig_1)
- if err != nil {
- return nil, err
- }
- return newWANDSLLinkConfig1ClientsFromGenericClients(genericClients), nil
-}
-
-func newWANDSLLinkConfig1ClientsFromGenericClients(genericClients []goupnp.ServiceClient) []*WANDSLLinkConfig1 {
- clients := make([]*WANDSLLinkConfig1, len(genericClients))
- for i := range genericClients {
- clients[i] = &WANDSLLinkConfig1{genericClients[i]}
- }
- return clients
-}
-
-func (client *WANDSLLinkConfig1) SetDSLLinkType(NewLinkType string) (err error) {
- // Request structure.
- request := &struct {
- NewLinkType string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.NewLinkType, err = soap.MarshalString(NewLinkType); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANDSLLinkConfig_1, "SetDSLLinkType", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-//
-// Return values:
-//
-// * NewLinkStatus: allowed values: Up, Down
-func (client *WANDSLLinkConfig1) GetDSLLinkInfo() (NewLinkType string, NewLinkStatus string, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewLinkType string
-
- NewLinkStatus string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANDSLLinkConfig_1, "GetDSLLinkInfo", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewLinkType, err = soap.UnmarshalString(response.NewLinkType); err != nil {
- return
- }
- if NewLinkStatus, err = soap.UnmarshalString(response.NewLinkStatus); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANDSLLinkConfig1) GetAutoConfig() (NewAutoConfig bool, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewAutoConfig string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANDSLLinkConfig_1, "GetAutoConfig", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewAutoConfig, err = soap.UnmarshalBoolean(response.NewAutoConfig); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANDSLLinkConfig1) GetModulationType() (NewModulationType string, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewModulationType string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANDSLLinkConfig_1, "GetModulationType", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewModulationType, err = soap.UnmarshalString(response.NewModulationType); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANDSLLinkConfig1) SetDestinationAddress(NewDestinationAddress string) (err error) {
- // Request structure.
- request := &struct {
- NewDestinationAddress string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.NewDestinationAddress, err = soap.MarshalString(NewDestinationAddress); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANDSLLinkConfig_1, "SetDestinationAddress", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANDSLLinkConfig1) GetDestinationAddress() (NewDestinationAddress string, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewDestinationAddress string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANDSLLinkConfig_1, "GetDestinationAddress", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewDestinationAddress, err = soap.UnmarshalString(response.NewDestinationAddress); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANDSLLinkConfig1) SetATMEncapsulation(NewATMEncapsulation string) (err error) {
- // Request structure.
- request := &struct {
- NewATMEncapsulation string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.NewATMEncapsulation, err = soap.MarshalString(NewATMEncapsulation); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANDSLLinkConfig_1, "SetATMEncapsulation", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANDSLLinkConfig1) GetATMEncapsulation() (NewATMEncapsulation string, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewATMEncapsulation string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANDSLLinkConfig_1, "GetATMEncapsulation", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewATMEncapsulation, err = soap.UnmarshalString(response.NewATMEncapsulation); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANDSLLinkConfig1) SetFCSPreserved(NewFCSPreserved bool) (err error) {
- // Request structure.
- request := &struct {
- NewFCSPreserved string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.NewFCSPreserved, err = soap.MarshalBoolean(NewFCSPreserved); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANDSLLinkConfig_1, "SetFCSPreserved", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANDSLLinkConfig1) GetFCSPreserved() (NewFCSPreserved bool, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewFCSPreserved string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANDSLLinkConfig_1, "GetFCSPreserved", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewFCSPreserved, err = soap.UnmarshalBoolean(response.NewFCSPreserved); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-// WANEthernetLinkConfig1 is a client for UPnP SOAP service with URN "urn:schemas-upnp-org:service:WANEthernetLinkConfig:1". See
-// goupnp.ServiceClient, which contains RootDevice and Service attributes which
-// are provided for informational value.
-type WANEthernetLinkConfig1 struct {
- goupnp.ServiceClient
-}
-
-// NewWANEthernetLinkConfig1Clients discovers instances of the service on the network,
-// and returns clients to any that are found. errors will contain an error for
-// any devices that replied but which could not be queried, and err will be set
-// if the discovery process failed outright.
-//
-// This is a typical entry calling point into this package.
-func NewWANEthernetLinkConfig1Clients() (clients []*WANEthernetLinkConfig1, errors []error, err error) {
- var genericClients []goupnp.ServiceClient
- if genericClients, errors, err = goupnp.NewServiceClients(URN_WANEthernetLinkConfig_1); err != nil {
- return
- }
- clients = newWANEthernetLinkConfig1ClientsFromGenericClients(genericClients)
- return
-}
-
-// NewWANEthernetLinkConfig1ClientsByURL discovers instances of the service at the given
-// URL, and returns clients to any that are found. An error is returned if
-// there was an error probing the service.
-//
-// This is a typical entry calling point into this package when reusing an
-// previously discovered service URL.
-func NewWANEthernetLinkConfig1ClientsByURL(loc *url.URL) ([]*WANEthernetLinkConfig1, error) {
- genericClients, err := goupnp.NewServiceClientsByURL(loc, URN_WANEthernetLinkConfig_1)
- if err != nil {
- return nil, err
- }
- return newWANEthernetLinkConfig1ClientsFromGenericClients(genericClients), nil
-}
-
-// NewWANEthernetLinkConfig1ClientsFromRootDevice discovers instances of the service in
-// a given root device, and returns clients to any that are found. An error is
-// returned if there was not at least one instance of the service within the
-// device. The location parameter is simply assigned to the Location attribute
-// of the wrapped ServiceClient(s).
-//
-// This is a typical entry calling point into this package when reusing an
-// previously discovered root device.
-func NewWANEthernetLinkConfig1ClientsFromRootDevice(rootDevice *goupnp.RootDevice, loc *url.URL) ([]*WANEthernetLinkConfig1, error) {
- genericClients, err := goupnp.NewServiceClientsFromRootDevice(rootDevice, loc, URN_WANEthernetLinkConfig_1)
- if err != nil {
- return nil, err
- }
- return newWANEthernetLinkConfig1ClientsFromGenericClients(genericClients), nil
-}
-
-func newWANEthernetLinkConfig1ClientsFromGenericClients(genericClients []goupnp.ServiceClient) []*WANEthernetLinkConfig1 {
- clients := make([]*WANEthernetLinkConfig1, len(genericClients))
- for i := range genericClients {
- clients[i] = &WANEthernetLinkConfig1{genericClients[i]}
- }
- return clients
-}
-
-//
-// Return values:
-//
-// * NewEthernetLinkStatus: allowed values: Up, Down
-func (client *WANEthernetLinkConfig1) GetEthernetLinkStatus() (NewEthernetLinkStatus string, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewEthernetLinkStatus string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANEthernetLinkConfig_1, "GetEthernetLinkStatus", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewEthernetLinkStatus, err = soap.UnmarshalString(response.NewEthernetLinkStatus); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-// WANIPConnection1 is a client for UPnP SOAP service with URN "urn:schemas-upnp-org:service:WANIPConnection:1". See
-// goupnp.ServiceClient, which contains RootDevice and Service attributes which
-// are provided for informational value.
-type WANIPConnection1 struct {
- goupnp.ServiceClient
-}
-
-// NewWANIPConnection1Clients discovers instances of the service on the network,
-// and returns clients to any that are found. errors will contain an error for
-// any devices that replied but which could not be queried, and err will be set
-// if the discovery process failed outright.
-//
-// This is a typical entry calling point into this package.
-func NewWANIPConnection1Clients() (clients []*WANIPConnection1, errors []error, err error) {
- var genericClients []goupnp.ServiceClient
- if genericClients, errors, err = goupnp.NewServiceClients(URN_WANIPConnection_1); err != nil {
- return
- }
- clients = newWANIPConnection1ClientsFromGenericClients(genericClients)
- return
-}
-
-// NewWANIPConnection1ClientsByURL discovers instances of the service at the given
-// URL, and returns clients to any that are found. An error is returned if
-// there was an error probing the service.
-//
-// This is a typical entry calling point into this package when reusing an
-// previously discovered service URL.
-func NewWANIPConnection1ClientsByURL(loc *url.URL) ([]*WANIPConnection1, error) {
- genericClients, err := goupnp.NewServiceClientsByURL(loc, URN_WANIPConnection_1)
- if err != nil {
- return nil, err
- }
- return newWANIPConnection1ClientsFromGenericClients(genericClients), nil
-}
-
-// NewWANIPConnection1ClientsFromRootDevice discovers instances of the service in
-// a given root device, and returns clients to any that are found. An error is
-// returned if there was not at least one instance of the service within the
-// device. The location parameter is simply assigned to the Location attribute
-// of the wrapped ServiceClient(s).
-//
-// This is a typical entry calling point into this package when reusing an
-// previously discovered root device.
-func NewWANIPConnection1ClientsFromRootDevice(rootDevice *goupnp.RootDevice, loc *url.URL) ([]*WANIPConnection1, error) {
- genericClients, err := goupnp.NewServiceClientsFromRootDevice(rootDevice, loc, URN_WANIPConnection_1)
- if err != nil {
- return nil, err
- }
- return newWANIPConnection1ClientsFromGenericClients(genericClients), nil
-}
-
-func newWANIPConnection1ClientsFromGenericClients(genericClients []goupnp.ServiceClient) []*WANIPConnection1 {
- clients := make([]*WANIPConnection1, len(genericClients))
- for i := range genericClients {
- clients[i] = &WANIPConnection1{genericClients[i]}
- }
- return clients
-}
-
-func (client *WANIPConnection1) SetConnectionType(NewConnectionType string) (err error) {
- // Request structure.
- request := &struct {
- NewConnectionType string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.NewConnectionType, err = soap.MarshalString(NewConnectionType); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANIPConnection_1, "SetConnectionType", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-//
-// Return values:
-//
-// * NewPossibleConnectionTypes: allowed values: Unconfigured, IP_Routed, IP_Bridged
-func (client *WANIPConnection1) GetConnectionTypeInfo() (NewConnectionType string, NewPossibleConnectionTypes string, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewConnectionType string
-
- NewPossibleConnectionTypes string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANIPConnection_1, "GetConnectionTypeInfo", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewConnectionType, err = soap.UnmarshalString(response.NewConnectionType); err != nil {
- return
- }
- if NewPossibleConnectionTypes, err = soap.UnmarshalString(response.NewPossibleConnectionTypes); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANIPConnection1) RequestConnection() (err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANIPConnection_1, "RequestConnection", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANIPConnection1) RequestTermination() (err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANIPConnection_1, "RequestTermination", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANIPConnection1) ForceTermination() (err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANIPConnection_1, "ForceTermination", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANIPConnection1) SetAutoDisconnectTime(NewAutoDisconnectTime uint32) (err error) {
- // Request structure.
- request := &struct {
- NewAutoDisconnectTime string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.NewAutoDisconnectTime, err = soap.MarshalUi4(NewAutoDisconnectTime); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANIPConnection_1, "SetAutoDisconnectTime", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANIPConnection1) SetIdleDisconnectTime(NewIdleDisconnectTime uint32) (err error) {
- // Request structure.
- request := &struct {
- NewIdleDisconnectTime string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.NewIdleDisconnectTime, err = soap.MarshalUi4(NewIdleDisconnectTime); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANIPConnection_1, "SetIdleDisconnectTime", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANIPConnection1) SetWarnDisconnectDelay(NewWarnDisconnectDelay uint32) (err error) {
- // Request structure.
- request := &struct {
- NewWarnDisconnectDelay string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.NewWarnDisconnectDelay, err = soap.MarshalUi4(NewWarnDisconnectDelay); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANIPConnection_1, "SetWarnDisconnectDelay", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-//
-// Return values:
-//
-// * NewConnectionStatus: allowed values: Unconfigured, Connected, Disconnected
-//
-// * NewLastConnectionError: allowed values: ERROR_NONE
-func (client *WANIPConnection1) GetStatusInfo() (NewConnectionStatus string, NewLastConnectionError string, NewUptime uint32, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewConnectionStatus string
-
- NewLastConnectionError string
-
- NewUptime string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANIPConnection_1, "GetStatusInfo", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewConnectionStatus, err = soap.UnmarshalString(response.NewConnectionStatus); err != nil {
- return
- }
- if NewLastConnectionError, err = soap.UnmarshalString(response.NewLastConnectionError); err != nil {
- return
- }
- if NewUptime, err = soap.UnmarshalUi4(response.NewUptime); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANIPConnection1) GetAutoDisconnectTime() (NewAutoDisconnectTime uint32, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewAutoDisconnectTime string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANIPConnection_1, "GetAutoDisconnectTime", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewAutoDisconnectTime, err = soap.UnmarshalUi4(response.NewAutoDisconnectTime); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANIPConnection1) GetIdleDisconnectTime() (NewIdleDisconnectTime uint32, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewIdleDisconnectTime string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANIPConnection_1, "GetIdleDisconnectTime", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewIdleDisconnectTime, err = soap.UnmarshalUi4(response.NewIdleDisconnectTime); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANIPConnection1) GetWarnDisconnectDelay() (NewWarnDisconnectDelay uint32, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewWarnDisconnectDelay string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANIPConnection_1, "GetWarnDisconnectDelay", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewWarnDisconnectDelay, err = soap.UnmarshalUi4(response.NewWarnDisconnectDelay); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANIPConnection1) GetNATRSIPStatus() (NewRSIPAvailable bool, NewNATEnabled bool, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewRSIPAvailable string
-
- NewNATEnabled string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANIPConnection_1, "GetNATRSIPStatus", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewRSIPAvailable, err = soap.UnmarshalBoolean(response.NewRSIPAvailable); err != nil {
- return
- }
- if NewNATEnabled, err = soap.UnmarshalBoolean(response.NewNATEnabled); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-//
-// Return values:
-//
-// * NewProtocol: allowed values: TCP, UDP
-func (client *WANIPConnection1) GetGenericPortMappingEntry(NewPortMappingIndex uint16) (NewRemoteHost string, NewExternalPort uint16, NewProtocol string, NewInternalPort uint16, NewInternalClient string, NewEnabled bool, NewPortMappingDescription string, NewLeaseDuration uint32, err error) {
- // Request structure.
- request := &struct {
- NewPortMappingIndex string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.NewPortMappingIndex, err = soap.MarshalUi2(NewPortMappingIndex); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewRemoteHost string
-
- NewExternalPort string
-
- NewProtocol string
-
- NewInternalPort string
-
- NewInternalClient string
-
- NewEnabled string
-
- NewPortMappingDescription string
-
- NewLeaseDuration string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANIPConnection_1, "GetGenericPortMappingEntry", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewRemoteHost, err = soap.UnmarshalString(response.NewRemoteHost); err != nil {
- return
- }
- if NewExternalPort, err = soap.UnmarshalUi2(response.NewExternalPort); err != nil {
- return
- }
- if NewProtocol, err = soap.UnmarshalString(response.NewProtocol); err != nil {
- return
- }
- if NewInternalPort, err = soap.UnmarshalUi2(response.NewInternalPort); err != nil {
- return
- }
- if NewInternalClient, err = soap.UnmarshalString(response.NewInternalClient); err != nil {
- return
- }
- if NewEnabled, err = soap.UnmarshalBoolean(response.NewEnabled); err != nil {
- return
- }
- if NewPortMappingDescription, err = soap.UnmarshalString(response.NewPortMappingDescription); err != nil {
- return
- }
- if NewLeaseDuration, err = soap.UnmarshalUi4(response.NewLeaseDuration); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-//
-// Arguments:
-//
-// * NewProtocol: allowed values: TCP, UDP
-
-func (client *WANIPConnection1) GetSpecificPortMappingEntry(NewRemoteHost string, NewExternalPort uint16, NewProtocol string) (NewInternalPort uint16, NewInternalClient string, NewEnabled bool, NewPortMappingDescription string, NewLeaseDuration uint32, err error) {
- // Request structure.
- request := &struct {
- NewRemoteHost string
-
- NewExternalPort string
-
- NewProtocol string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.NewRemoteHost, err = soap.MarshalString(NewRemoteHost); err != nil {
- return
- }
- if request.NewExternalPort, err = soap.MarshalUi2(NewExternalPort); err != nil {
- return
- }
- if request.NewProtocol, err = soap.MarshalString(NewProtocol); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewInternalPort string
-
- NewInternalClient string
-
- NewEnabled string
-
- NewPortMappingDescription string
-
- NewLeaseDuration string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANIPConnection_1, "GetSpecificPortMappingEntry", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewInternalPort, err = soap.UnmarshalUi2(response.NewInternalPort); err != nil {
- return
- }
- if NewInternalClient, err = soap.UnmarshalString(response.NewInternalClient); err != nil {
- return
- }
- if NewEnabled, err = soap.UnmarshalBoolean(response.NewEnabled); err != nil {
- return
- }
- if NewPortMappingDescription, err = soap.UnmarshalString(response.NewPortMappingDescription); err != nil {
- return
- }
- if NewLeaseDuration, err = soap.UnmarshalUi4(response.NewLeaseDuration); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-//
-// Arguments:
-//
-// * NewProtocol: allowed values: TCP, UDP
-
-func (client *WANIPConnection1) AddPortMapping(NewRemoteHost string, NewExternalPort uint16, NewProtocol string, NewInternalPort uint16, NewInternalClient string, NewEnabled bool, NewPortMappingDescription string, NewLeaseDuration uint32) (err error) {
- // Request structure.
- request := &struct {
- NewRemoteHost string
-
- NewExternalPort string
-
- NewProtocol string
-
- NewInternalPort string
-
- NewInternalClient string
-
- NewEnabled string
-
- NewPortMappingDescription string
-
- NewLeaseDuration string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.NewRemoteHost, err = soap.MarshalString(NewRemoteHost); err != nil {
- return
- }
- if request.NewExternalPort, err = soap.MarshalUi2(NewExternalPort); err != nil {
- return
- }
- if request.NewProtocol, err = soap.MarshalString(NewProtocol); err != nil {
- return
- }
- if request.NewInternalPort, err = soap.MarshalUi2(NewInternalPort); err != nil {
- return
- }
- if request.NewInternalClient, err = soap.MarshalString(NewInternalClient); err != nil {
- return
- }
- if request.NewEnabled, err = soap.MarshalBoolean(NewEnabled); err != nil {
- return
- }
- if request.NewPortMappingDescription, err = soap.MarshalString(NewPortMappingDescription); err != nil {
- return
- }
- if request.NewLeaseDuration, err = soap.MarshalUi4(NewLeaseDuration); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANIPConnection_1, "AddPortMapping", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-//
-// Arguments:
-//
-// * NewProtocol: allowed values: TCP, UDP
-
-func (client *WANIPConnection1) DeletePortMapping(NewRemoteHost string, NewExternalPort uint16, NewProtocol string) (err error) {
- // Request structure.
- request := &struct {
- NewRemoteHost string
-
- NewExternalPort string
-
- NewProtocol string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.NewRemoteHost, err = soap.MarshalString(NewRemoteHost); err != nil {
- return
- }
- if request.NewExternalPort, err = soap.MarshalUi2(NewExternalPort); err != nil {
- return
- }
- if request.NewProtocol, err = soap.MarshalString(NewProtocol); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANIPConnection_1, "DeletePortMapping", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANIPConnection1) GetExternalIPAddress() (NewExternalIPAddress string, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewExternalIPAddress string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANIPConnection_1, "GetExternalIPAddress", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewExternalIPAddress, err = soap.UnmarshalString(response.NewExternalIPAddress); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-// WANIPConnection2 is a client for UPnP SOAP service with URN "urn:schemas-upnp-org:service:WANIPConnection:2". See
-// goupnp.ServiceClient, which contains RootDevice and Service attributes which
-// are provided for informational value.
-type WANIPConnection2 struct {
- goupnp.ServiceClient
-}
-
-// NewWANIPConnection2Clients discovers instances of the service on the network,
-// and returns clients to any that are found. errors will contain an error for
-// any devices that replied but which could not be queried, and err will be set
-// if the discovery process failed outright.
-//
-// This is a typical entry calling point into this package.
-func NewWANIPConnection2Clients() (clients []*WANIPConnection2, errors []error, err error) {
- var genericClients []goupnp.ServiceClient
- if genericClients, errors, err = goupnp.NewServiceClients(URN_WANIPConnection_2); err != nil {
- return
- }
- clients = newWANIPConnection2ClientsFromGenericClients(genericClients)
- return
-}
-
-// NewWANIPConnection2ClientsByURL discovers instances of the service at the given
-// URL, and returns clients to any that are found. An error is returned if
-// there was an error probing the service.
-//
-// This is a typical entry calling point into this package when reusing an
-// previously discovered service URL.
-func NewWANIPConnection2ClientsByURL(loc *url.URL) ([]*WANIPConnection2, error) {
- genericClients, err := goupnp.NewServiceClientsByURL(loc, URN_WANIPConnection_2)
- if err != nil {
- return nil, err
- }
- return newWANIPConnection2ClientsFromGenericClients(genericClients), nil
-}
-
-// NewWANIPConnection2ClientsFromRootDevice discovers instances of the service in
-// a given root device, and returns clients to any that are found. An error is
-// returned if there was not at least one instance of the service within the
-// device. The location parameter is simply assigned to the Location attribute
-// of the wrapped ServiceClient(s).
-//
-// This is a typical entry calling point into this package when reusing an
-// previously discovered root device.
-func NewWANIPConnection2ClientsFromRootDevice(rootDevice *goupnp.RootDevice, loc *url.URL) ([]*WANIPConnection2, error) {
- genericClients, err := goupnp.NewServiceClientsFromRootDevice(rootDevice, loc, URN_WANIPConnection_2)
- if err != nil {
- return nil, err
- }
- return newWANIPConnection2ClientsFromGenericClients(genericClients), nil
-}
-
-func newWANIPConnection2ClientsFromGenericClients(genericClients []goupnp.ServiceClient) []*WANIPConnection2 {
- clients := make([]*WANIPConnection2, len(genericClients))
- for i := range genericClients {
- clients[i] = &WANIPConnection2{genericClients[i]}
- }
- return clients
-}
-
-func (client *WANIPConnection2) SetConnectionType(NewConnectionType string) (err error) {
- // Request structure.
- request := &struct {
- NewConnectionType string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.NewConnectionType, err = soap.MarshalString(NewConnectionType); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANIPConnection_2, "SetConnectionType", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANIPConnection2) GetConnectionTypeInfo() (NewConnectionType string, NewPossibleConnectionTypes string, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewConnectionType string
-
- NewPossibleConnectionTypes string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANIPConnection_2, "GetConnectionTypeInfo", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewConnectionType, err = soap.UnmarshalString(response.NewConnectionType); err != nil {
- return
- }
- if NewPossibleConnectionTypes, err = soap.UnmarshalString(response.NewPossibleConnectionTypes); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANIPConnection2) RequestConnection() (err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANIPConnection_2, "RequestConnection", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANIPConnection2) RequestTermination() (err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANIPConnection_2, "RequestTermination", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANIPConnection2) ForceTermination() (err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANIPConnection_2, "ForceTermination", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANIPConnection2) SetAutoDisconnectTime(NewAutoDisconnectTime uint32) (err error) {
- // Request structure.
- request := &struct {
- NewAutoDisconnectTime string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.NewAutoDisconnectTime, err = soap.MarshalUi4(NewAutoDisconnectTime); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANIPConnection_2, "SetAutoDisconnectTime", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANIPConnection2) SetIdleDisconnectTime(NewIdleDisconnectTime uint32) (err error) {
- // Request structure.
- request := &struct {
- NewIdleDisconnectTime string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.NewIdleDisconnectTime, err = soap.MarshalUi4(NewIdleDisconnectTime); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANIPConnection_2, "SetIdleDisconnectTime", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANIPConnection2) SetWarnDisconnectDelay(NewWarnDisconnectDelay uint32) (err error) {
- // Request structure.
- request := &struct {
- NewWarnDisconnectDelay string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.NewWarnDisconnectDelay, err = soap.MarshalUi4(NewWarnDisconnectDelay); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANIPConnection_2, "SetWarnDisconnectDelay", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-//
-// Return values:
-//
-// * NewConnectionStatus: allowed values: Unconfigured, Connecting, Connected, PendingDisconnect, Disconnecting, Disconnected
-//
-// * NewLastConnectionError: allowed values: ERROR_NONE, ERROR_COMMAND_ABORTED, ERROR_NOT_ENABLED_FOR_INTERNET, ERROR_USER_DISCONNECT, ERROR_ISP_DISCONNECT, ERROR_IDLE_DISCONNECT, ERROR_FORCED_DISCONNECT, ERROR_NO_CARRIER, ERROR_IP_CONFIGURATION, ERROR_UNKNOWN
-func (client *WANIPConnection2) GetStatusInfo() (NewConnectionStatus string, NewLastConnectionError string, NewUptime uint32, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewConnectionStatus string
-
- NewLastConnectionError string
-
- NewUptime string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANIPConnection_2, "GetStatusInfo", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewConnectionStatus, err = soap.UnmarshalString(response.NewConnectionStatus); err != nil {
- return
- }
- if NewLastConnectionError, err = soap.UnmarshalString(response.NewLastConnectionError); err != nil {
- return
- }
- if NewUptime, err = soap.UnmarshalUi4(response.NewUptime); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANIPConnection2) GetAutoDisconnectTime() (NewAutoDisconnectTime uint32, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewAutoDisconnectTime string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANIPConnection_2, "GetAutoDisconnectTime", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewAutoDisconnectTime, err = soap.UnmarshalUi4(response.NewAutoDisconnectTime); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANIPConnection2) GetIdleDisconnectTime() (NewIdleDisconnectTime uint32, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewIdleDisconnectTime string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANIPConnection_2, "GetIdleDisconnectTime", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewIdleDisconnectTime, err = soap.UnmarshalUi4(response.NewIdleDisconnectTime); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANIPConnection2) GetWarnDisconnectDelay() (NewWarnDisconnectDelay uint32, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewWarnDisconnectDelay string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANIPConnection_2, "GetWarnDisconnectDelay", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewWarnDisconnectDelay, err = soap.UnmarshalUi4(response.NewWarnDisconnectDelay); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANIPConnection2) GetNATRSIPStatus() (NewRSIPAvailable bool, NewNATEnabled bool, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewRSIPAvailable string
-
- NewNATEnabled string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANIPConnection_2, "GetNATRSIPStatus", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewRSIPAvailable, err = soap.UnmarshalBoolean(response.NewRSIPAvailable); err != nil {
- return
- }
- if NewNATEnabled, err = soap.UnmarshalBoolean(response.NewNATEnabled); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-//
-// Return values:
-//
-// * NewProtocol: allowed values: TCP, UDP
-func (client *WANIPConnection2) GetGenericPortMappingEntry(NewPortMappingIndex uint16) (NewRemoteHost string, NewExternalPort uint16, NewProtocol string, NewInternalPort uint16, NewInternalClient string, NewEnabled bool, NewPortMappingDescription string, NewLeaseDuration uint32, err error) {
- // Request structure.
- request := &struct {
- NewPortMappingIndex string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.NewPortMappingIndex, err = soap.MarshalUi2(NewPortMappingIndex); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewRemoteHost string
-
- NewExternalPort string
-
- NewProtocol string
-
- NewInternalPort string
-
- NewInternalClient string
-
- NewEnabled string
-
- NewPortMappingDescription string
-
- NewLeaseDuration string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANIPConnection_2, "GetGenericPortMappingEntry", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewRemoteHost, err = soap.UnmarshalString(response.NewRemoteHost); err != nil {
- return
- }
- if NewExternalPort, err = soap.UnmarshalUi2(response.NewExternalPort); err != nil {
- return
- }
- if NewProtocol, err = soap.UnmarshalString(response.NewProtocol); err != nil {
- return
- }
- if NewInternalPort, err = soap.UnmarshalUi2(response.NewInternalPort); err != nil {
- return
- }
- if NewInternalClient, err = soap.UnmarshalString(response.NewInternalClient); err != nil {
- return
- }
- if NewEnabled, err = soap.UnmarshalBoolean(response.NewEnabled); err != nil {
- return
- }
- if NewPortMappingDescription, err = soap.UnmarshalString(response.NewPortMappingDescription); err != nil {
- return
- }
- if NewLeaseDuration, err = soap.UnmarshalUi4(response.NewLeaseDuration); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-//
-// Arguments:
-//
-// * NewProtocol: allowed values: TCP, UDP
-
-func (client *WANIPConnection2) GetSpecificPortMappingEntry(NewRemoteHost string, NewExternalPort uint16, NewProtocol string) (NewInternalPort uint16, NewInternalClient string, NewEnabled bool, NewPortMappingDescription string, NewLeaseDuration uint32, err error) {
- // Request structure.
- request := &struct {
- NewRemoteHost string
-
- NewExternalPort string
-
- NewProtocol string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.NewRemoteHost, err = soap.MarshalString(NewRemoteHost); err != nil {
- return
- }
- if request.NewExternalPort, err = soap.MarshalUi2(NewExternalPort); err != nil {
- return
- }
- if request.NewProtocol, err = soap.MarshalString(NewProtocol); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewInternalPort string
-
- NewInternalClient string
-
- NewEnabled string
-
- NewPortMappingDescription string
-
- NewLeaseDuration string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANIPConnection_2, "GetSpecificPortMappingEntry", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewInternalPort, err = soap.UnmarshalUi2(response.NewInternalPort); err != nil {
- return
- }
- if NewInternalClient, err = soap.UnmarshalString(response.NewInternalClient); err != nil {
- return
- }
- if NewEnabled, err = soap.UnmarshalBoolean(response.NewEnabled); err != nil {
- return
- }
- if NewPortMappingDescription, err = soap.UnmarshalString(response.NewPortMappingDescription); err != nil {
- return
- }
- if NewLeaseDuration, err = soap.UnmarshalUi4(response.NewLeaseDuration); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-//
-// Arguments:
-//
-// * NewProtocol: allowed values: TCP, UDP
-
-func (client *WANIPConnection2) AddPortMapping(NewRemoteHost string, NewExternalPort uint16, NewProtocol string, NewInternalPort uint16, NewInternalClient string, NewEnabled bool, NewPortMappingDescription string, NewLeaseDuration uint32) (err error) {
- // Request structure.
- request := &struct {
- NewRemoteHost string
-
- NewExternalPort string
-
- NewProtocol string
-
- NewInternalPort string
-
- NewInternalClient string
-
- NewEnabled string
-
- NewPortMappingDescription string
-
- NewLeaseDuration string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.NewRemoteHost, err = soap.MarshalString(NewRemoteHost); err != nil {
- return
- }
- if request.NewExternalPort, err = soap.MarshalUi2(NewExternalPort); err != nil {
- return
- }
- if request.NewProtocol, err = soap.MarshalString(NewProtocol); err != nil {
- return
- }
- if request.NewInternalPort, err = soap.MarshalUi2(NewInternalPort); err != nil {
- return
- }
- if request.NewInternalClient, err = soap.MarshalString(NewInternalClient); err != nil {
- return
- }
- if request.NewEnabled, err = soap.MarshalBoolean(NewEnabled); err != nil {
- return
- }
- if request.NewPortMappingDescription, err = soap.MarshalString(NewPortMappingDescription); err != nil {
- return
- }
- if request.NewLeaseDuration, err = soap.MarshalUi4(NewLeaseDuration); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANIPConnection_2, "AddPortMapping", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-//
-// Arguments:
-//
-// * NewProtocol: allowed values: TCP, UDP
-
-func (client *WANIPConnection2) DeletePortMapping(NewRemoteHost string, NewExternalPort uint16, NewProtocol string) (err error) {
- // Request structure.
- request := &struct {
- NewRemoteHost string
-
- NewExternalPort string
-
- NewProtocol string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.NewRemoteHost, err = soap.MarshalString(NewRemoteHost); err != nil {
- return
- }
- if request.NewExternalPort, err = soap.MarshalUi2(NewExternalPort); err != nil {
- return
- }
- if request.NewProtocol, err = soap.MarshalString(NewProtocol); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANIPConnection_2, "DeletePortMapping", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-//
-// Arguments:
-//
-// * NewProtocol: allowed values: TCP, UDP
-
-func (client *WANIPConnection2) DeletePortMappingRange(NewStartPort uint16, NewEndPort uint16, NewProtocol string, NewManage bool) (err error) {
- // Request structure.
- request := &struct {
- NewStartPort string
-
- NewEndPort string
-
- NewProtocol string
-
- NewManage string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.NewStartPort, err = soap.MarshalUi2(NewStartPort); err != nil {
- return
- }
- if request.NewEndPort, err = soap.MarshalUi2(NewEndPort); err != nil {
- return
- }
- if request.NewProtocol, err = soap.MarshalString(NewProtocol); err != nil {
- return
- }
- if request.NewManage, err = soap.MarshalBoolean(NewManage); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANIPConnection_2, "DeletePortMappingRange", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANIPConnection2) GetExternalIPAddress() (NewExternalIPAddress string, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewExternalIPAddress string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANIPConnection_2, "GetExternalIPAddress", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewExternalIPAddress, err = soap.UnmarshalString(response.NewExternalIPAddress); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-//
-// Arguments:
-//
-// * NewProtocol: allowed values: TCP, UDP
-
-func (client *WANIPConnection2) GetListOfPortMappings(NewStartPort uint16, NewEndPort uint16, NewProtocol string, NewManage bool, NewNumberOfPorts uint16) (NewPortListing string, err error) {
- // Request structure.
- request := &struct {
- NewStartPort string
-
- NewEndPort string
-
- NewProtocol string
-
- NewManage string
-
- NewNumberOfPorts string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.NewStartPort, err = soap.MarshalUi2(NewStartPort); err != nil {
- return
- }
- if request.NewEndPort, err = soap.MarshalUi2(NewEndPort); err != nil {
- return
- }
- if request.NewProtocol, err = soap.MarshalString(NewProtocol); err != nil {
- return
- }
- if request.NewManage, err = soap.MarshalBoolean(NewManage); err != nil {
- return
- }
- if request.NewNumberOfPorts, err = soap.MarshalUi2(NewNumberOfPorts); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewPortListing string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANIPConnection_2, "GetListOfPortMappings", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewPortListing, err = soap.UnmarshalString(response.NewPortListing); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-//
-// Arguments:
-//
-// * NewProtocol: allowed values: TCP, UDP
-
-func (client *WANIPConnection2) AddAnyPortMapping(NewRemoteHost string, NewExternalPort uint16, NewProtocol string, NewInternalPort uint16, NewInternalClient string, NewEnabled bool, NewPortMappingDescription string, NewLeaseDuration uint32) (NewReservedPort uint16, err error) {
- // Request structure.
- request := &struct {
- NewRemoteHost string
-
- NewExternalPort string
-
- NewProtocol string
-
- NewInternalPort string
-
- NewInternalClient string
-
- NewEnabled string
-
- NewPortMappingDescription string
-
- NewLeaseDuration string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.NewRemoteHost, err = soap.MarshalString(NewRemoteHost); err != nil {
- return
- }
- if request.NewExternalPort, err = soap.MarshalUi2(NewExternalPort); err != nil {
- return
- }
- if request.NewProtocol, err = soap.MarshalString(NewProtocol); err != nil {
- return
- }
- if request.NewInternalPort, err = soap.MarshalUi2(NewInternalPort); err != nil {
- return
- }
- if request.NewInternalClient, err = soap.MarshalString(NewInternalClient); err != nil {
- return
- }
- if request.NewEnabled, err = soap.MarshalBoolean(NewEnabled); err != nil {
- return
- }
- if request.NewPortMappingDescription, err = soap.MarshalString(NewPortMappingDescription); err != nil {
- return
- }
- if request.NewLeaseDuration, err = soap.MarshalUi4(NewLeaseDuration); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewReservedPort string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANIPConnection_2, "AddAnyPortMapping", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewReservedPort, err = soap.UnmarshalUi2(response.NewReservedPort); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-// WANIPv6FirewallControl1 is a client for UPnP SOAP service with URN "urn:schemas-upnp-org:service:WANIPv6FirewallControl:1". See
-// goupnp.ServiceClient, which contains RootDevice and Service attributes which
-// are provided for informational value.
-type WANIPv6FirewallControl1 struct {
- goupnp.ServiceClient
-}
-
-// NewWANIPv6FirewallControl1Clients discovers instances of the service on the network,
-// and returns clients to any that are found. errors will contain an error for
-// any devices that replied but which could not be queried, and err will be set
-// if the discovery process failed outright.
-//
-// This is a typical entry calling point into this package.
-func NewWANIPv6FirewallControl1Clients() (clients []*WANIPv6FirewallControl1, errors []error, err error) {
- var genericClients []goupnp.ServiceClient
- if genericClients, errors, err = goupnp.NewServiceClients(URN_WANIPv6FirewallControl_1); err != nil {
- return
- }
- clients = newWANIPv6FirewallControl1ClientsFromGenericClients(genericClients)
- return
-}
-
-// NewWANIPv6FirewallControl1ClientsByURL discovers instances of the service at the given
-// URL, and returns clients to any that are found. An error is returned if
-// there was an error probing the service.
-//
-// This is a typical entry calling point into this package when reusing an
-// previously discovered service URL.
-func NewWANIPv6FirewallControl1ClientsByURL(loc *url.URL) ([]*WANIPv6FirewallControl1, error) {
- genericClients, err := goupnp.NewServiceClientsByURL(loc, URN_WANIPv6FirewallControl_1)
- if err != nil {
- return nil, err
- }
- return newWANIPv6FirewallControl1ClientsFromGenericClients(genericClients), nil
-}
-
-// NewWANIPv6FirewallControl1ClientsFromRootDevice discovers instances of the service in
-// a given root device, and returns clients to any that are found. An error is
-// returned if there was not at least one instance of the service within the
-// device. The location parameter is simply assigned to the Location attribute
-// of the wrapped ServiceClient(s).
-//
-// This is a typical entry calling point into this package when reusing an
-// previously discovered root device.
-func NewWANIPv6FirewallControl1ClientsFromRootDevice(rootDevice *goupnp.RootDevice, loc *url.URL) ([]*WANIPv6FirewallControl1, error) {
- genericClients, err := goupnp.NewServiceClientsFromRootDevice(rootDevice, loc, URN_WANIPv6FirewallControl_1)
- if err != nil {
- return nil, err
- }
- return newWANIPv6FirewallControl1ClientsFromGenericClients(genericClients), nil
-}
-
-func newWANIPv6FirewallControl1ClientsFromGenericClients(genericClients []goupnp.ServiceClient) []*WANIPv6FirewallControl1 {
- clients := make([]*WANIPv6FirewallControl1, len(genericClients))
- for i := range genericClients {
- clients[i] = &WANIPv6FirewallControl1{genericClients[i]}
- }
- return clients
-}
-
-func (client *WANIPv6FirewallControl1) GetFirewallStatus() (FirewallEnabled bool, InboundPinholeAllowed bool, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- FirewallEnabled string
-
- InboundPinholeAllowed string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANIPv6FirewallControl_1, "GetFirewallStatus", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if FirewallEnabled, err = soap.UnmarshalBoolean(response.FirewallEnabled); err != nil {
- return
- }
- if InboundPinholeAllowed, err = soap.UnmarshalBoolean(response.InboundPinholeAllowed); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANIPv6FirewallControl1) GetOutboundPinholeTimeout(RemoteHost string, RemotePort uint16, InternalClient string, InternalPort uint16, Protocol uint16) (OutboundPinholeTimeout uint32, err error) {
- // Request structure.
- request := &struct {
- RemoteHost string
-
- RemotePort string
-
- InternalClient string
-
- InternalPort string
-
- Protocol string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.RemoteHost, err = soap.MarshalString(RemoteHost); err != nil {
- return
- }
- if request.RemotePort, err = soap.MarshalUi2(RemotePort); err != nil {
- return
- }
- if request.InternalClient, err = soap.MarshalString(InternalClient); err != nil {
- return
- }
- if request.InternalPort, err = soap.MarshalUi2(InternalPort); err != nil {
- return
- }
- if request.Protocol, err = soap.MarshalUi2(Protocol); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- OutboundPinholeTimeout string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANIPv6FirewallControl_1, "GetOutboundPinholeTimeout", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if OutboundPinholeTimeout, err = soap.UnmarshalUi4(response.OutboundPinholeTimeout); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-//
-// Arguments:
-//
-// * LeaseTime: allowed value range: minimum=1, maximum=86400
-
-func (client *WANIPv6FirewallControl1) AddPinhole(RemoteHost string, RemotePort uint16, InternalClient string, InternalPort uint16, Protocol uint16, LeaseTime uint32) (UniqueID uint16, err error) {
- // Request structure.
- request := &struct {
- RemoteHost string
-
- RemotePort string
-
- InternalClient string
-
- InternalPort string
-
- Protocol string
-
- LeaseTime string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.RemoteHost, err = soap.MarshalString(RemoteHost); err != nil {
- return
- }
- if request.RemotePort, err = soap.MarshalUi2(RemotePort); err != nil {
- return
- }
- if request.InternalClient, err = soap.MarshalString(InternalClient); err != nil {
- return
- }
- if request.InternalPort, err = soap.MarshalUi2(InternalPort); err != nil {
- return
- }
- if request.Protocol, err = soap.MarshalUi2(Protocol); err != nil {
- return
- }
- if request.LeaseTime, err = soap.MarshalUi4(LeaseTime); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- UniqueID string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANIPv6FirewallControl_1, "AddPinhole", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if UniqueID, err = soap.UnmarshalUi2(response.UniqueID); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-//
-// Arguments:
-//
-// * NewLeaseTime: allowed value range: minimum=1, maximum=86400
-
-func (client *WANIPv6FirewallControl1) UpdatePinhole(UniqueID uint16, NewLeaseTime uint32) (err error) {
- // Request structure.
- request := &struct {
- UniqueID string
-
- NewLeaseTime string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.UniqueID, err = soap.MarshalUi2(UniqueID); err != nil {
- return
- }
- if request.NewLeaseTime, err = soap.MarshalUi4(NewLeaseTime); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANIPv6FirewallControl_1, "UpdatePinhole", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANIPv6FirewallControl1) DeletePinhole(UniqueID uint16) (err error) {
- // Request structure.
- request := &struct {
- UniqueID string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.UniqueID, err = soap.MarshalUi2(UniqueID); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANIPv6FirewallControl_1, "DeletePinhole", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANIPv6FirewallControl1) GetPinholePackets(UniqueID uint16) (PinholePackets uint32, err error) {
- // Request structure.
- request := &struct {
- UniqueID string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.UniqueID, err = soap.MarshalUi2(UniqueID); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- PinholePackets string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANIPv6FirewallControl_1, "GetPinholePackets", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if PinholePackets, err = soap.UnmarshalUi4(response.PinholePackets); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANIPv6FirewallControl1) CheckPinholeWorking(UniqueID uint16) (IsWorking bool, err error) {
- // Request structure.
- request := &struct {
- UniqueID string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.UniqueID, err = soap.MarshalUi2(UniqueID); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- IsWorking string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANIPv6FirewallControl_1, "CheckPinholeWorking", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if IsWorking, err = soap.UnmarshalBoolean(response.IsWorking); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-// WANPOTSLinkConfig1 is a client for UPnP SOAP service with URN "urn:schemas-upnp-org:service:WANPOTSLinkConfig:1". See
-// goupnp.ServiceClient, which contains RootDevice and Service attributes which
-// are provided for informational value.
-type WANPOTSLinkConfig1 struct {
- goupnp.ServiceClient
-}
-
-// NewWANPOTSLinkConfig1Clients discovers instances of the service on the network,
-// and returns clients to any that are found. errors will contain an error for
-// any devices that replied but which could not be queried, and err will be set
-// if the discovery process failed outright.
-//
-// This is a typical entry calling point into this package.
-func NewWANPOTSLinkConfig1Clients() (clients []*WANPOTSLinkConfig1, errors []error, err error) {
- var genericClients []goupnp.ServiceClient
- if genericClients, errors, err = goupnp.NewServiceClients(URN_WANPOTSLinkConfig_1); err != nil {
- return
- }
- clients = newWANPOTSLinkConfig1ClientsFromGenericClients(genericClients)
- return
-}
-
-// NewWANPOTSLinkConfig1ClientsByURL discovers instances of the service at the given
-// URL, and returns clients to any that are found. An error is returned if
-// there was an error probing the service.
-//
-// This is a typical entry calling point into this package when reusing an
-// previously discovered service URL.
-func NewWANPOTSLinkConfig1ClientsByURL(loc *url.URL) ([]*WANPOTSLinkConfig1, error) {
- genericClients, err := goupnp.NewServiceClientsByURL(loc, URN_WANPOTSLinkConfig_1)
- if err != nil {
- return nil, err
- }
- return newWANPOTSLinkConfig1ClientsFromGenericClients(genericClients), nil
-}
-
-// NewWANPOTSLinkConfig1ClientsFromRootDevice discovers instances of the service in
-// a given root device, and returns clients to any that are found. An error is
-// returned if there was not at least one instance of the service within the
-// device. The location parameter is simply assigned to the Location attribute
-// of the wrapped ServiceClient(s).
-//
-// This is a typical entry calling point into this package when reusing an
-// previously discovered root device.
-func NewWANPOTSLinkConfig1ClientsFromRootDevice(rootDevice *goupnp.RootDevice, loc *url.URL) ([]*WANPOTSLinkConfig1, error) {
- genericClients, err := goupnp.NewServiceClientsFromRootDevice(rootDevice, loc, URN_WANPOTSLinkConfig_1)
- if err != nil {
- return nil, err
- }
- return newWANPOTSLinkConfig1ClientsFromGenericClients(genericClients), nil
-}
-
-func newWANPOTSLinkConfig1ClientsFromGenericClients(genericClients []goupnp.ServiceClient) []*WANPOTSLinkConfig1 {
- clients := make([]*WANPOTSLinkConfig1, len(genericClients))
- for i := range genericClients {
- clients[i] = &WANPOTSLinkConfig1{genericClients[i]}
- }
- return clients
-}
-
-//
-// Arguments:
-//
-// * NewLinkType: allowed values: PPP_Dialup
-
-func (client *WANPOTSLinkConfig1) SetISPInfo(NewISPPhoneNumber string, NewISPInfo string, NewLinkType string) (err error) {
- // Request structure.
- request := &struct {
- NewISPPhoneNumber string
-
- NewISPInfo string
-
- NewLinkType string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.NewISPPhoneNumber, err = soap.MarshalString(NewISPPhoneNumber); err != nil {
- return
- }
- if request.NewISPInfo, err = soap.MarshalString(NewISPInfo); err != nil {
- return
- }
- if request.NewLinkType, err = soap.MarshalString(NewLinkType); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANPOTSLinkConfig_1, "SetISPInfo", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANPOTSLinkConfig1) SetCallRetryInfo(NewNumberOfRetries uint32, NewDelayBetweenRetries uint32) (err error) {
- // Request structure.
- request := &struct {
- NewNumberOfRetries string
-
- NewDelayBetweenRetries string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.NewNumberOfRetries, err = soap.MarshalUi4(NewNumberOfRetries); err != nil {
- return
- }
- if request.NewDelayBetweenRetries, err = soap.MarshalUi4(NewDelayBetweenRetries); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANPOTSLinkConfig_1, "SetCallRetryInfo", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-//
-// Return values:
-//
-// * NewLinkType: allowed values: PPP_Dialup
-func (client *WANPOTSLinkConfig1) GetISPInfo() (NewISPPhoneNumber string, NewISPInfo string, NewLinkType string, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewISPPhoneNumber string
-
- NewISPInfo string
-
- NewLinkType string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANPOTSLinkConfig_1, "GetISPInfo", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewISPPhoneNumber, err = soap.UnmarshalString(response.NewISPPhoneNumber); err != nil {
- return
- }
- if NewISPInfo, err = soap.UnmarshalString(response.NewISPInfo); err != nil {
- return
- }
- if NewLinkType, err = soap.UnmarshalString(response.NewLinkType); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANPOTSLinkConfig1) GetCallRetryInfo() (NewNumberOfRetries uint32, NewDelayBetweenRetries uint32, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewNumberOfRetries string
-
- NewDelayBetweenRetries string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANPOTSLinkConfig_1, "GetCallRetryInfo", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewNumberOfRetries, err = soap.UnmarshalUi4(response.NewNumberOfRetries); err != nil {
- return
- }
- if NewDelayBetweenRetries, err = soap.UnmarshalUi4(response.NewDelayBetweenRetries); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANPOTSLinkConfig1) GetFclass() (NewFclass string, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewFclass string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANPOTSLinkConfig_1, "GetFclass", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewFclass, err = soap.UnmarshalString(response.NewFclass); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANPOTSLinkConfig1) GetDataModulationSupported() (NewDataModulationSupported string, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewDataModulationSupported string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANPOTSLinkConfig_1, "GetDataModulationSupported", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewDataModulationSupported, err = soap.UnmarshalString(response.NewDataModulationSupported); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANPOTSLinkConfig1) GetDataProtocol() (NewDataProtocol string, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewDataProtocol string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANPOTSLinkConfig_1, "GetDataProtocol", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewDataProtocol, err = soap.UnmarshalString(response.NewDataProtocol); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANPOTSLinkConfig1) GetDataCompression() (NewDataCompression string, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewDataCompression string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANPOTSLinkConfig_1, "GetDataCompression", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewDataCompression, err = soap.UnmarshalString(response.NewDataCompression); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANPOTSLinkConfig1) GetPlusVTRCommandSupported() (NewPlusVTRCommandSupported bool, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewPlusVTRCommandSupported string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANPOTSLinkConfig_1, "GetPlusVTRCommandSupported", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewPlusVTRCommandSupported, err = soap.UnmarshalBoolean(response.NewPlusVTRCommandSupported); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-// WANPPPConnection1 is a client for UPnP SOAP service with URN "urn:schemas-upnp-org:service:WANPPPConnection:1". See
-// goupnp.ServiceClient, which contains RootDevice and Service attributes which
-// are provided for informational value.
-type WANPPPConnection1 struct {
- goupnp.ServiceClient
-}
-
-// NewWANPPPConnection1Clients discovers instances of the service on the network,
-// and returns clients to any that are found. errors will contain an error for
-// any devices that replied but which could not be queried, and err will be set
-// if the discovery process failed outright.
-//
-// This is a typical entry calling point into this package.
-func NewWANPPPConnection1Clients() (clients []*WANPPPConnection1, errors []error, err error) {
- var genericClients []goupnp.ServiceClient
- if genericClients, errors, err = goupnp.NewServiceClients(URN_WANPPPConnection_1); err != nil {
- return
- }
- clients = newWANPPPConnection1ClientsFromGenericClients(genericClients)
- return
-}
-
-// NewWANPPPConnection1ClientsByURL discovers instances of the service at the given
-// URL, and returns clients to any that are found. An error is returned if
-// there was an error probing the service.
-//
-// This is a typical entry calling point into this package when reusing an
-// previously discovered service URL.
-func NewWANPPPConnection1ClientsByURL(loc *url.URL) ([]*WANPPPConnection1, error) {
- genericClients, err := goupnp.NewServiceClientsByURL(loc, URN_WANPPPConnection_1)
- if err != nil {
- return nil, err
- }
- return newWANPPPConnection1ClientsFromGenericClients(genericClients), nil
-}
-
-// NewWANPPPConnection1ClientsFromRootDevice discovers instances of the service in
-// a given root device, and returns clients to any that are found. An error is
-// returned if there was not at least one instance of the service within the
-// device. The location parameter is simply assigned to the Location attribute
-// of the wrapped ServiceClient(s).
-//
-// This is a typical entry calling point into this package when reusing an
-// previously discovered root device.
-func NewWANPPPConnection1ClientsFromRootDevice(rootDevice *goupnp.RootDevice, loc *url.URL) ([]*WANPPPConnection1, error) {
- genericClients, err := goupnp.NewServiceClientsFromRootDevice(rootDevice, loc, URN_WANPPPConnection_1)
- if err != nil {
- return nil, err
- }
- return newWANPPPConnection1ClientsFromGenericClients(genericClients), nil
-}
-
-func newWANPPPConnection1ClientsFromGenericClients(genericClients []goupnp.ServiceClient) []*WANPPPConnection1 {
- clients := make([]*WANPPPConnection1, len(genericClients))
- for i := range genericClients {
- clients[i] = &WANPPPConnection1{genericClients[i]}
- }
- return clients
-}
-
-func (client *WANPPPConnection1) SetConnectionType(NewConnectionType string) (err error) {
- // Request structure.
- request := &struct {
- NewConnectionType string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.NewConnectionType, err = soap.MarshalString(NewConnectionType); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "SetConnectionType", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-//
-// Return values:
-//
-// * NewPossibleConnectionTypes: allowed values: Unconfigured, IP_Routed, DHCP_Spoofed, PPPoE_Bridged, PPTP_Relay, L2TP_Relay, PPPoE_Relay
-func (client *WANPPPConnection1) GetConnectionTypeInfo() (NewConnectionType string, NewPossibleConnectionTypes string, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewConnectionType string
-
- NewPossibleConnectionTypes string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "GetConnectionTypeInfo", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewConnectionType, err = soap.UnmarshalString(response.NewConnectionType); err != nil {
- return
- }
- if NewPossibleConnectionTypes, err = soap.UnmarshalString(response.NewPossibleConnectionTypes); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANPPPConnection1) ConfigureConnection(NewUserName string, NewPassword string) (err error) {
- // Request structure.
- request := &struct {
- NewUserName string
-
- NewPassword string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.NewUserName, err = soap.MarshalString(NewUserName); err != nil {
- return
- }
- if request.NewPassword, err = soap.MarshalString(NewPassword); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "ConfigureConnection", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANPPPConnection1) RequestConnection() (err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "RequestConnection", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANPPPConnection1) RequestTermination() (err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "RequestTermination", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANPPPConnection1) ForceTermination() (err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "ForceTermination", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANPPPConnection1) SetAutoDisconnectTime(NewAutoDisconnectTime uint32) (err error) {
- // Request structure.
- request := &struct {
- NewAutoDisconnectTime string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.NewAutoDisconnectTime, err = soap.MarshalUi4(NewAutoDisconnectTime); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "SetAutoDisconnectTime", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANPPPConnection1) SetIdleDisconnectTime(NewIdleDisconnectTime uint32) (err error) {
- // Request structure.
- request := &struct {
- NewIdleDisconnectTime string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.NewIdleDisconnectTime, err = soap.MarshalUi4(NewIdleDisconnectTime); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "SetIdleDisconnectTime", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANPPPConnection1) SetWarnDisconnectDelay(NewWarnDisconnectDelay uint32) (err error) {
- // Request structure.
- request := &struct {
- NewWarnDisconnectDelay string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.NewWarnDisconnectDelay, err = soap.MarshalUi4(NewWarnDisconnectDelay); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "SetWarnDisconnectDelay", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-//
-// Return values:
-//
-// * NewConnectionStatus: allowed values: Unconfigured, Connected, Disconnected
-//
-// * NewLastConnectionError: allowed values: ERROR_NONE
-func (client *WANPPPConnection1) GetStatusInfo() (NewConnectionStatus string, NewLastConnectionError string, NewUptime uint32, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewConnectionStatus string
-
- NewLastConnectionError string
-
- NewUptime string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "GetStatusInfo", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewConnectionStatus, err = soap.UnmarshalString(response.NewConnectionStatus); err != nil {
- return
- }
- if NewLastConnectionError, err = soap.UnmarshalString(response.NewLastConnectionError); err != nil {
- return
- }
- if NewUptime, err = soap.UnmarshalUi4(response.NewUptime); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANPPPConnection1) GetLinkLayerMaxBitRates() (NewUpstreamMaxBitRate uint32, NewDownstreamMaxBitRate uint32, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewUpstreamMaxBitRate string
-
- NewDownstreamMaxBitRate string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "GetLinkLayerMaxBitRates", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewUpstreamMaxBitRate, err = soap.UnmarshalUi4(response.NewUpstreamMaxBitRate); err != nil {
- return
- }
- if NewDownstreamMaxBitRate, err = soap.UnmarshalUi4(response.NewDownstreamMaxBitRate); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANPPPConnection1) GetPPPEncryptionProtocol() (NewPPPEncryptionProtocol string, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewPPPEncryptionProtocol string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "GetPPPEncryptionProtocol", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewPPPEncryptionProtocol, err = soap.UnmarshalString(response.NewPPPEncryptionProtocol); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANPPPConnection1) GetPPPCompressionProtocol() (NewPPPCompressionProtocol string, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewPPPCompressionProtocol string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "GetPPPCompressionProtocol", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewPPPCompressionProtocol, err = soap.UnmarshalString(response.NewPPPCompressionProtocol); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANPPPConnection1) GetPPPAuthenticationProtocol() (NewPPPAuthenticationProtocol string, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewPPPAuthenticationProtocol string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "GetPPPAuthenticationProtocol", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewPPPAuthenticationProtocol, err = soap.UnmarshalString(response.NewPPPAuthenticationProtocol); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANPPPConnection1) GetUserName() (NewUserName string, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewUserName string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "GetUserName", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewUserName, err = soap.UnmarshalString(response.NewUserName); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANPPPConnection1) GetPassword() (NewPassword string, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewPassword string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "GetPassword", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewPassword, err = soap.UnmarshalString(response.NewPassword); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANPPPConnection1) GetAutoDisconnectTime() (NewAutoDisconnectTime uint32, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewAutoDisconnectTime string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "GetAutoDisconnectTime", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewAutoDisconnectTime, err = soap.UnmarshalUi4(response.NewAutoDisconnectTime); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANPPPConnection1) GetIdleDisconnectTime() (NewIdleDisconnectTime uint32, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewIdleDisconnectTime string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "GetIdleDisconnectTime", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewIdleDisconnectTime, err = soap.UnmarshalUi4(response.NewIdleDisconnectTime); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANPPPConnection1) GetWarnDisconnectDelay() (NewWarnDisconnectDelay uint32, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewWarnDisconnectDelay string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "GetWarnDisconnectDelay", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewWarnDisconnectDelay, err = soap.UnmarshalUi4(response.NewWarnDisconnectDelay); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANPPPConnection1) GetNATRSIPStatus() (NewRSIPAvailable bool, NewNATEnabled bool, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewRSIPAvailable string
-
- NewNATEnabled string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "GetNATRSIPStatus", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewRSIPAvailable, err = soap.UnmarshalBoolean(response.NewRSIPAvailable); err != nil {
- return
- }
- if NewNATEnabled, err = soap.UnmarshalBoolean(response.NewNATEnabled); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-//
-// Return values:
-//
-// * NewProtocol: allowed values: TCP, UDP
-func (client *WANPPPConnection1) GetGenericPortMappingEntry(NewPortMappingIndex uint16) (NewRemoteHost string, NewExternalPort uint16, NewProtocol string, NewInternalPort uint16, NewInternalClient string, NewEnabled bool, NewPortMappingDescription string, NewLeaseDuration uint32, err error) {
- // Request structure.
- request := &struct {
- NewPortMappingIndex string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.NewPortMappingIndex, err = soap.MarshalUi2(NewPortMappingIndex); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewRemoteHost string
-
- NewExternalPort string
-
- NewProtocol string
-
- NewInternalPort string
-
- NewInternalClient string
-
- NewEnabled string
-
- NewPortMappingDescription string
-
- NewLeaseDuration string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "GetGenericPortMappingEntry", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewRemoteHost, err = soap.UnmarshalString(response.NewRemoteHost); err != nil {
- return
- }
- if NewExternalPort, err = soap.UnmarshalUi2(response.NewExternalPort); err != nil {
- return
- }
- if NewProtocol, err = soap.UnmarshalString(response.NewProtocol); err != nil {
- return
- }
- if NewInternalPort, err = soap.UnmarshalUi2(response.NewInternalPort); err != nil {
- return
- }
- if NewInternalClient, err = soap.UnmarshalString(response.NewInternalClient); err != nil {
- return
- }
- if NewEnabled, err = soap.UnmarshalBoolean(response.NewEnabled); err != nil {
- return
- }
- if NewPortMappingDescription, err = soap.UnmarshalString(response.NewPortMappingDescription); err != nil {
- return
- }
- if NewLeaseDuration, err = soap.UnmarshalUi4(response.NewLeaseDuration); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-//
-// Arguments:
-//
-// * NewProtocol: allowed values: TCP, UDP
-
-func (client *WANPPPConnection1) GetSpecificPortMappingEntry(NewRemoteHost string, NewExternalPort uint16, NewProtocol string) (NewInternalPort uint16, NewInternalClient string, NewEnabled bool, NewPortMappingDescription string, NewLeaseDuration uint32, err error) {
- // Request structure.
- request := &struct {
- NewRemoteHost string
-
- NewExternalPort string
-
- NewProtocol string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.NewRemoteHost, err = soap.MarshalString(NewRemoteHost); err != nil {
- return
- }
- if request.NewExternalPort, err = soap.MarshalUi2(NewExternalPort); err != nil {
- return
- }
- if request.NewProtocol, err = soap.MarshalString(NewProtocol); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewInternalPort string
-
- NewInternalClient string
-
- NewEnabled string
-
- NewPortMappingDescription string
-
- NewLeaseDuration string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "GetSpecificPortMappingEntry", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewInternalPort, err = soap.UnmarshalUi2(response.NewInternalPort); err != nil {
- return
- }
- if NewInternalClient, err = soap.UnmarshalString(response.NewInternalClient); err != nil {
- return
- }
- if NewEnabled, err = soap.UnmarshalBoolean(response.NewEnabled); err != nil {
- return
- }
- if NewPortMappingDescription, err = soap.UnmarshalString(response.NewPortMappingDescription); err != nil {
- return
- }
- if NewLeaseDuration, err = soap.UnmarshalUi4(response.NewLeaseDuration); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
-
-//
-// Arguments:
-//
-// * NewProtocol: allowed values: TCP, UDP
-
-func (client *WANPPPConnection1) AddPortMapping(NewRemoteHost string, NewExternalPort uint16, NewProtocol string, NewInternalPort uint16, NewInternalClient string, NewEnabled bool, NewPortMappingDescription string, NewLeaseDuration uint32) (err error) {
- // Request structure.
- request := &struct {
- NewRemoteHost string
-
- NewExternalPort string
-
- NewProtocol string
-
- NewInternalPort string
-
- NewInternalClient string
-
- NewEnabled string
-
- NewPortMappingDescription string
-
- NewLeaseDuration string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.NewRemoteHost, err = soap.MarshalString(NewRemoteHost); err != nil {
- return
- }
- if request.NewExternalPort, err = soap.MarshalUi2(NewExternalPort); err != nil {
- return
- }
- if request.NewProtocol, err = soap.MarshalString(NewProtocol); err != nil {
- return
- }
- if request.NewInternalPort, err = soap.MarshalUi2(NewInternalPort); err != nil {
- return
- }
- if request.NewInternalClient, err = soap.MarshalString(NewInternalClient); err != nil {
- return
- }
- if request.NewEnabled, err = soap.MarshalBoolean(NewEnabled); err != nil {
- return
- }
- if request.NewPortMappingDescription, err = soap.MarshalString(NewPortMappingDescription); err != nil {
- return
- }
- if request.NewLeaseDuration, err = soap.MarshalUi4(NewLeaseDuration); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "AddPortMapping", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-//
-// Arguments:
-//
-// * NewProtocol: allowed values: TCP, UDP
-
-func (client *WANPPPConnection1) DeletePortMapping(NewRemoteHost string, NewExternalPort uint16, NewProtocol string) (err error) {
- // Request structure.
- request := &struct {
- NewRemoteHost string
-
- NewExternalPort string
-
- NewProtocol string
- }{}
- // BEGIN Marshal arguments into request.
-
- if request.NewRemoteHost, err = soap.MarshalString(NewRemoteHost); err != nil {
- return
- }
- if request.NewExternalPort, err = soap.MarshalUi2(NewExternalPort); err != nil {
- return
- }
- if request.NewProtocol, err = soap.MarshalString(NewProtocol); err != nil {
- return
- }
- // END Marshal arguments into request.
-
- // Response structure.
- response := interface{}(nil)
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "DeletePortMapping", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- // END Unmarshal arguments from response.
- return
-}
-
-func (client *WANPPPConnection1) GetExternalIPAddress() (NewExternalIPAddress string, err error) {
- // Request structure.
- request := interface{}(nil)
- // BEGIN Marshal arguments into request.
-
- // END Marshal arguments into request.
-
- // Response structure.
- response := &struct {
- NewExternalIPAddress string
- }{}
-
- // Perform the SOAP call.
- if err = client.SOAPClient.PerformAction(URN_WANPPPConnection_1, "GetExternalIPAddress", request, response); err != nil {
- return
- }
-
- // BEGIN Unmarshal arguments from response.
-
- if NewExternalIPAddress, err = soap.UnmarshalString(response.NewExternalIPAddress); err != nil {
- return
- }
- // END Unmarshal arguments from response.
- return
-}
diff --git a/vendor/github.com/huin/goupnp/device.go b/vendor/github.com/huin/goupnp/device.go
deleted file mode 100644
index e5b658b21a..0000000000
--- a/vendor/github.com/huin/goupnp/device.go
+++ /dev/null
@@ -1,184 +0,0 @@
-// This file contains XML structures for communicating with UPnP devices.
-
-package goupnp
-
-import (
- "encoding/xml"
- "errors"
- "fmt"
- "net/url"
-
- "github.com/huin/goupnp/scpd"
- "github.com/huin/goupnp/soap"
-)
-
-const (
- DeviceXMLNamespace = "urn:schemas-upnp-org:device-1-0"
-)
-
-// RootDevice is the device description as described by section 2.3 "Device
-// description" in
-// http://upnp.org/specs/arch/UPnP-arch-DeviceArchitecture-v1.1.pdf
-type RootDevice struct {
- XMLName xml.Name `xml:"root"`
- SpecVersion SpecVersion `xml:"specVersion"`
- URLBase url.URL `xml:"-"`
- URLBaseStr string `xml:"URLBase"`
- Device Device `xml:"device"`
-}
-
-// SetURLBase sets the URLBase for the RootDevice and its underlying components.
-func (root *RootDevice) SetURLBase(urlBase *url.URL) {
- root.URLBase = *urlBase
- root.URLBaseStr = urlBase.String()
- root.Device.SetURLBase(urlBase)
-}
-
-// SpecVersion is part of a RootDevice, describes the version of the
-// specification that the data adheres to.
-type SpecVersion struct {
- Major int32 `xml:"major"`
- Minor int32 `xml:"minor"`
-}
-
-// Device is a UPnP device. It can have child devices.
-type Device struct {
- DeviceType string `xml:"deviceType"`
- FriendlyName string `xml:"friendlyName"`
- Manufacturer string `xml:"manufacturer"`
- ManufacturerURL URLField `xml:"manufacturerURL"`
- ModelDescription string `xml:"modelDescription"`
- ModelName string `xml:"modelName"`
- ModelNumber string `xml:"modelNumber"`
- ModelURL URLField `xml:"modelURL"`
- SerialNumber string `xml:"serialNumber"`
- UDN string `xml:"UDN"`
- UPC string `xml:"UPC,omitempty"`
- Icons []Icon `xml:"iconList>icon,omitempty"`
- Services []Service `xml:"serviceList>service,omitempty"`
- Devices []Device `xml:"deviceList>device,omitempty"`
-
- // Extra observed elements:
- PresentationURL URLField `xml:"presentationURL"`
-}
-
-// VisitDevices calls visitor for the device, and all its descendent devices.
-func (device *Device) VisitDevices(visitor func(*Device)) {
- visitor(device)
- for i := range device.Devices {
- device.Devices[i].VisitDevices(visitor)
- }
-}
-
-// VisitServices calls visitor for all Services under the device and all its
-// descendent devices.
-func (device *Device) VisitServices(visitor func(*Service)) {
- device.VisitDevices(func(d *Device) {
- for i := range d.Services {
- visitor(&d.Services[i])
- }
- })
-}
-
-// FindService finds all (if any) Services under the device and its descendents
-// that have the given ServiceType.
-func (device *Device) FindService(serviceType string) []*Service {
- var services []*Service
- device.VisitServices(func(s *Service) {
- if s.ServiceType == serviceType {
- services = append(services, s)
- }
- })
- return services
-}
-
-// SetURLBase sets the URLBase for the Device and its underlying components.
-func (device *Device) SetURLBase(urlBase *url.URL) {
- device.ManufacturerURL.SetURLBase(urlBase)
- device.ModelURL.SetURLBase(urlBase)
- device.PresentationURL.SetURLBase(urlBase)
- for i := range device.Icons {
- device.Icons[i].SetURLBase(urlBase)
- }
- for i := range device.Services {
- device.Services[i].SetURLBase(urlBase)
- }
- for i := range device.Devices {
- device.Devices[i].SetURLBase(urlBase)
- }
-}
-
-func (device *Device) String() string {
- return fmt.Sprintf("Device ID %s : %s (%s)", device.UDN, device.DeviceType, device.FriendlyName)
-}
-
-// Icon is a representative image that a device might include in its
-// description.
-type Icon struct {
- Mimetype string `xml:"mimetype"`
- Width int32 `xml:"width"`
- Height int32 `xml:"height"`
- Depth int32 `xml:"depth"`
- URL URLField `xml:"url"`
-}
-
-// SetURLBase sets the URLBase for the Icon.
-func (icon *Icon) SetURLBase(url *url.URL) {
- icon.URL.SetURLBase(url)
-}
-
-// Service is a service provided by a UPnP Device.
-type Service struct {
- ServiceType string `xml:"serviceType"`
- ServiceId string `xml:"serviceId"`
- SCPDURL URLField `xml:"SCPDURL"`
- ControlURL URLField `xml:"controlURL"`
- EventSubURL URLField `xml:"eventSubURL"`
-}
-
-// SetURLBase sets the URLBase for the Service.
-func (srv *Service) SetURLBase(urlBase *url.URL) {
- srv.SCPDURL.SetURLBase(urlBase)
- srv.ControlURL.SetURLBase(urlBase)
- srv.EventSubURL.SetURLBase(urlBase)
-}
-
-func (srv *Service) String() string {
- return fmt.Sprintf("Service ID %s : %s", srv.ServiceId, srv.ServiceType)
-}
-
-// RequestSCDP requests the SCPD (soap actions and state variables description)
-// for the service.
-func (srv *Service) RequestSCDP() (*scpd.SCPD, error) {
- if !srv.SCPDURL.Ok {
- return nil, errors.New("bad/missing SCPD URL, or no URLBase has been set")
- }
- s := new(scpd.SCPD)
- if err := requestXml(srv.SCPDURL.URL.String(), scpd.SCPDXMLNamespace, s); err != nil {
- return nil, err
- }
- return s, nil
-}
-
-func (srv *Service) NewSOAPClient() *soap.SOAPClient {
- return soap.NewSOAPClient(srv.ControlURL.URL)
-}
-
-// URLField is a URL that is part of a device description.
-type URLField struct {
- URL url.URL `xml:"-"`
- Ok bool `xml:"-"`
- Str string `xml:",chardata"`
-}
-
-func (uf *URLField) SetURLBase(urlBase *url.URL) {
- refUrl, err := url.Parse(uf.Str)
- if err != nil {
- uf.URL = url.URL{}
- uf.Ok = false
- return
- }
-
- uf.URL = *urlBase.ResolveReference(refUrl)
- uf.Ok = true
-}
diff --git a/vendor/github.com/huin/goupnp/goupnp.go b/vendor/github.com/huin/goupnp/goupnp.go
deleted file mode 100644
index fcb8dcd23d..0000000000
--- a/vendor/github.com/huin/goupnp/goupnp.go
+++ /dev/null
@@ -1,131 +0,0 @@
-// goupnp is an implementation of a client for various UPnP services.
-//
-// For most uses, it is recommended to use the code-generated packages under
-// github.com/huin/goupnp/dcps. Example use is shown at
-// http://godoc.org/github.com/huin/goupnp/example
-//
-// A commonly used client is internetgateway1.WANPPPConnection1:
-// http://godoc.org/github.com/huin/goupnp/dcps/internetgateway1#WANPPPConnection1
-//
-// Currently only a couple of schemas have code generated for them from the
-// UPnP example XML specifications. Not all methods will work on these clients,
-// because the generated stubs contain the full set of specified methods from
-// the XML specifications, and the discovered services will likely support a
-// subset of those methods.
-package goupnp
-
-import (
- "encoding/xml"
- "fmt"
- "net/http"
- "net/url"
- "time"
-
- "golang.org/x/net/html/charset"
-
- "github.com/huin/goupnp/httpu"
- "github.com/huin/goupnp/ssdp"
-)
-
-// ContextError is an error that wraps an error with some context information.
-type ContextError struct {
- Context string
- Err error
-}
-
-func (err ContextError) Error() string {
- return fmt.Sprintf("%s: %v", err.Context, err.Err)
-}
-
-// MaybeRootDevice contains either a RootDevice or an error.
-type MaybeRootDevice struct {
- // Set iff Err == nil.
- Root *RootDevice
-
- // The location the device was discovered at. This can be used with
- // DeviceByURL, assuming the device is still present. A location represents
- // the discovery of a device, regardless of if there was an error probing it.
- Location *url.URL
-
- // Any error encountered probing a discovered device.
- Err error
-}
-
-// DiscoverDevices attempts to find targets of the given type. This is
-// typically the entry-point for this package. searchTarget is typically a URN
-// in the form "urn:schemas-upnp-org:device:..." or
-// "urn:schemas-upnp-org:service:...". A single error is returned for errors
-// while attempting to send the query. An error or RootDevice is returned for
-// each discovered RootDevice.
-func DiscoverDevices(searchTarget string) ([]MaybeRootDevice, error) {
- httpu, err := httpu.NewHTTPUClient()
- if err != nil {
- return nil, err
- }
- defer httpu.Close()
- responses, err := ssdp.SSDPRawSearch(httpu, string(searchTarget), 2, 3)
- if err != nil {
- return nil, err
- }
-
- results := make([]MaybeRootDevice, len(responses))
- for i, response := range responses {
- maybe := &results[i]
- loc, err := response.Location()
- if err != nil {
- maybe.Err = ContextError{"unexpected bad location from search", err}
- continue
- }
- maybe.Location = loc
- if root, err := DeviceByURL(loc); err != nil {
- maybe.Err = err
- } else {
- maybe.Root = root
- }
- }
-
- return results, nil
-}
-
-func DeviceByURL(loc *url.URL) (*RootDevice, error) {
- locStr := loc.String()
- root := new(RootDevice)
- if err := requestXml(locStr, DeviceXMLNamespace, root); err != nil {
- return nil, ContextError{fmt.Sprintf("error requesting root device details from %q", locStr), err}
- }
- var urlBaseStr string
- if root.URLBaseStr != "" {
- urlBaseStr = root.URLBaseStr
- } else {
- urlBaseStr = locStr
- }
- urlBase, err := url.Parse(urlBaseStr)
- if err != nil {
- return nil, ContextError{fmt.Sprintf("error parsing location URL %q", locStr), err}
- }
- root.SetURLBase(urlBase)
- return root, nil
-}
-
-func requestXml(url string, defaultSpace string, doc interface{}) error {
- timeout := time.Duration(3 * time.Second)
- client := http.Client{
- Timeout: timeout,
- }
- resp, err := client.Get(url)
- if err != nil {
- return err
- }
- defer resp.Body.Close()
-
- if resp.StatusCode != 200 {
- return fmt.Errorf("goupnp: got response status %s from %q",
- resp.Status, url)
- }
-
- decoder := xml.NewDecoder(resp.Body)
- decoder.DefaultSpace = defaultSpace
- decoder.CharsetReader = charset.NewReaderLabel
-
- return decoder.Decode(doc)
-}
diff --git a/vendor/github.com/huin/goupnp/httpu/httpu.go b/vendor/github.com/huin/goupnp/httpu/httpu.go
deleted file mode 100644
index f52dad68b1..0000000000
--- a/vendor/github.com/huin/goupnp/httpu/httpu.go
+++ /dev/null
@@ -1,132 +0,0 @@
-package httpu
-
-import (
- "bufio"
- "bytes"
- "errors"
- "fmt"
- "log"
- "net"
- "net/http"
- "sync"
- "time"
-)
-
-// HTTPUClient is a client for dealing with HTTPU (HTTP over UDP). Its typical
-// function is for HTTPMU, and particularly SSDP.
-type HTTPUClient struct {
- connLock sync.Mutex // Protects use of conn.
- conn net.PacketConn
-}
-
-// NewHTTPUClient creates a new HTTPUClient, opening up a new UDP socket for the
-// purpose.
-func NewHTTPUClient() (*HTTPUClient, error) {
- conn, err := net.ListenPacket("udp", ":0")
- if err != nil {
- return nil, err
- }
- return &HTTPUClient{conn: conn}, nil
-}
-
-// NewHTTPUClientAddr creates a new HTTPUClient which will broadcast packets
-// from the specified address, opening up a new UDP socket for the purpose
-func NewHTTPUClientAddr(addr string) (*HTTPUClient, error) {
- ip := net.ParseIP(addr)
- if ip == nil {
- return nil, errors.New("Invalid listening address")
- }
- conn, err := net.ListenPacket("udp", ip.String()+":0")
- if err != nil {
- return nil, err
- }
- return &HTTPUClient{conn: conn}, nil
-}
-
-// Close shuts down the client. The client will no longer be useful following
-// this.
-func (httpu *HTTPUClient) Close() error {
- httpu.connLock.Lock()
- defer httpu.connLock.Unlock()
- return httpu.conn.Close()
-}
-
-// Do performs a request. The timeout is how long to wait for before returning
-// the responses that were received. An error is only returned for failing to
-// send the request. Failures in receipt simply do not add to the resulting
-// responses.
-//
-// Note that at present only one concurrent connection will happen per
-// HTTPUClient.
-func (httpu *HTTPUClient) Do(req *http.Request, timeout time.Duration, numSends int) ([]*http.Response, error) {
- httpu.connLock.Lock()
- defer httpu.connLock.Unlock()
-
- // Create the request. This is a subset of what http.Request.Write does
- // deliberately to avoid creating extra fields which may confuse some
- // devices.
- var requestBuf bytes.Buffer
- method := req.Method
- if method == "" {
- method = "GET"
- }
- if _, err := fmt.Fprintf(&requestBuf, "%s %s HTTP/1.1\r\n", method, req.URL.RequestURI()); err != nil {
- return nil, err
- }
- if err := req.Header.Write(&requestBuf); err != nil {
- return nil, err
- }
- if _, err := requestBuf.Write([]byte{'\r', '\n'}); err != nil {
- return nil, err
- }
-
- destAddr, err := net.ResolveUDPAddr("udp", req.Host)
- if err != nil {
- return nil, err
- }
- if err = httpu.conn.SetDeadline(time.Now().Add(timeout)); err != nil {
- return nil, err
- }
-
- // Send request.
- for i := 0; i < numSends; i++ {
- if n, err := httpu.conn.WriteTo(requestBuf.Bytes(), destAddr); err != nil {
- return nil, err
- } else if n < len(requestBuf.Bytes()) {
- return nil, fmt.Errorf("httpu: wrote %d bytes rather than full %d in request",
- n, len(requestBuf.Bytes()))
- }
- time.Sleep(5 * time.Millisecond)
- }
-
- // Await responses until timeout.
- var responses []*http.Response
- responseBytes := make([]byte, 2048)
- for {
- // 2048 bytes should be sufficient for most networks.
- n, _, err := httpu.conn.ReadFrom(responseBytes)
- if err != nil {
- if err, ok := err.(net.Error); ok {
- if err.Timeout() {
- break
- }
- if err.Temporary() {
- // Sleep in case this is a persistent error to avoid pegging CPU until deadline.
- time.Sleep(10 * time.Millisecond)
- continue
- }
- }
- return nil, err
- }
-
- // Parse response.
- response, err := http.ReadResponse(bufio.NewReader(bytes.NewBuffer(responseBytes[:n])), req)
- if err != nil {
- log.Print("httpu: error while parsing response: %v", err)
- continue
- }
-
- responses = append(responses, response)
- }
- return responses, err
-}
diff --git a/vendor/github.com/huin/goupnp/httpu/serve.go b/vendor/github.com/huin/goupnp/httpu/serve.go
deleted file mode 100644
index 9f67af85b7..0000000000
--- a/vendor/github.com/huin/goupnp/httpu/serve.go
+++ /dev/null
@@ -1,108 +0,0 @@
-package httpu
-
-import (
- "bufio"
- "bytes"
- "log"
- "net"
- "net/http"
- "regexp"
-)
-
-const (
- DefaultMaxMessageBytes = 2048
-)
-
-var (
- trailingWhitespaceRx = regexp.MustCompile(" +\r\n")
- crlf = []byte("\r\n")
-)
-
-// Handler is the interface by which received HTTPU messages are passed to
-// handling code.
-type Handler interface {
- // ServeMessage is called for each HTTPU message received. peerAddr contains
- // the address that the message was received from.
- ServeMessage(r *http.Request)
-}
-
-// HandlerFunc is a function-to-Handler adapter.
-type HandlerFunc func(r *http.Request)
-
-func (f HandlerFunc) ServeMessage(r *http.Request) {
- f(r)
-}
-
-// A Server defines parameters for running an HTTPU server.
-type Server struct {
- Addr string // UDP address to listen on
- Multicast bool // Should listen for multicast?
- Interface *net.Interface // Network interface to listen on for multicast, nil for default multicast interface
- Handler Handler // handler to invoke
- MaxMessageBytes int // maximum number of bytes to read from a packet, DefaultMaxMessageBytes if 0
-}
-
-// ListenAndServe listens on the UDP network address srv.Addr. If srv.Multicast
-// is true, then a multicast UDP listener will be used on srv.Interface (or
-// default interface if nil).
-func (srv *Server) ListenAndServe() error {
- var err error
-
- var addr *net.UDPAddr
- if addr, err = net.ResolveUDPAddr("udp", srv.Addr); err != nil {
- log.Fatal(err)
- }
-
- var conn net.PacketConn
- if srv.Multicast {
- if conn, err = net.ListenMulticastUDP("udp", srv.Interface, addr); err != nil {
- return err
- }
- } else {
- if conn, err = net.ListenUDP("udp", addr); err != nil {
- return err
- }
- }
-
- return srv.Serve(conn)
-}
-
-// Serve messages received on the given packet listener to the srv.Handler.
-func (srv *Server) Serve(l net.PacketConn) error {
- maxMessageBytes := DefaultMaxMessageBytes
- if srv.MaxMessageBytes != 0 {
- maxMessageBytes = srv.MaxMessageBytes
- }
- for {
- buf := make([]byte, maxMessageBytes)
- n, peerAddr, err := l.ReadFrom(buf)
- if err != nil {
- return err
- }
- buf = buf[:n]
-
- go func(buf []byte, peerAddr net.Addr) {
- // At least one router's UPnP implementation has added a trailing space
- // after "HTTP/1.1" - trim it.
- buf = trailingWhitespaceRx.ReplaceAllLiteral(buf, crlf)
-
- req, err := http.ReadRequest(bufio.NewReader(bytes.NewBuffer(buf)))
- if err != nil {
- log.Printf("httpu: Failed to parse request: %v", err)
- return
- }
- req.RemoteAddr = peerAddr.String()
- srv.Handler.ServeMessage(req)
- // No need to call req.Body.Close - underlying reader is bytes.Buffer.
- }(buf, peerAddr)
- }
-}
-
-// Serve messages received on the given packet listener to the given handler.
-func Serve(l net.PacketConn, handler Handler) error {
- srv := Server{
- Handler: handler,
- MaxMessageBytes: DefaultMaxMessageBytes,
- }
- return srv.Serve(l)
-}
diff --git a/vendor/github.com/huin/goupnp/scpd/scpd.go b/vendor/github.com/huin/goupnp/scpd/scpd.go
deleted file mode 100644
index c9d2e69e81..0000000000
--- a/vendor/github.com/huin/goupnp/scpd/scpd.go
+++ /dev/null
@@ -1,167 +0,0 @@
-package scpd
-
-import (
- "encoding/xml"
- "strings"
-)
-
-const (
- SCPDXMLNamespace = "urn:schemas-upnp-org:service-1-0"
-)
-
-func cleanWhitespace(s *string) {
- *s = strings.TrimSpace(*s)
-}
-
-// SCPD is the service description as described by section 2.5 "Service
-// description" in
-// http://upnp.org/specs/arch/UPnP-arch-DeviceArchitecture-v1.1.pdf
-type SCPD struct {
- XMLName xml.Name `xml:"scpd"`
- ConfigId string `xml:"configId,attr"`
- SpecVersion SpecVersion `xml:"specVersion"`
- Actions []Action `xml:"actionList>action"`
- StateVariables []StateVariable `xml:"serviceStateTable>stateVariable"`
-}
-
-// Clean attempts to remove stray whitespace etc. in the structure. It seems
-// unfortunately common for stray whitespace to be present in SCPD documents,
-// this method attempts to make it easy to clean them out.
-func (scpd *SCPD) Clean() {
- cleanWhitespace(&scpd.ConfigId)
- for i := range scpd.Actions {
- scpd.Actions[i].clean()
- }
- for i := range scpd.StateVariables {
- scpd.StateVariables[i].clean()
- }
-}
-
-func (scpd *SCPD) GetStateVariable(variable string) *StateVariable {
- for i := range scpd.StateVariables {
- v := &scpd.StateVariables[i]
- if v.Name == variable {
- return v
- }
- }
- return nil
-}
-
-func (scpd *SCPD) GetAction(action string) *Action {
- for i := range scpd.Actions {
- a := &scpd.Actions[i]
- if a.Name == action {
- return a
- }
- }
- return nil
-}
-
-// SpecVersion is part of a SCPD document, describes the version of the
-// specification that the data adheres to.
-type SpecVersion struct {
- Major int32 `xml:"major"`
- Minor int32 `xml:"minor"`
-}
-
-type Action struct {
- Name string `xml:"name"`
- Arguments []Argument `xml:"argumentList>argument"`
-}
-
-func (action *Action) clean() {
- cleanWhitespace(&action.Name)
- for i := range action.Arguments {
- action.Arguments[i].clean()
- }
-}
-
-func (action *Action) InputArguments() []*Argument {
- var result []*Argument
- for i := range action.Arguments {
- arg := &action.Arguments[i]
- if arg.IsInput() {
- result = append(result, arg)
- }
- }
- return result
-}
-
-func (action *Action) OutputArguments() []*Argument {
- var result []*Argument
- for i := range action.Arguments {
- arg := &action.Arguments[i]
- if arg.IsOutput() {
- result = append(result, arg)
- }
- }
- return result
-}
-
-type Argument struct {
- Name string `xml:"name"`
- Direction string `xml:"direction"` // in|out
- RelatedStateVariable string `xml:"relatedStateVariable"` // ?
- Retval string `xml:"retval"` // ?
-}
-
-func (arg *Argument) clean() {
- cleanWhitespace(&arg.Name)
- cleanWhitespace(&arg.Direction)
- cleanWhitespace(&arg.RelatedStateVariable)
- cleanWhitespace(&arg.Retval)
-}
-
-func (arg *Argument) IsInput() bool {
- return arg.Direction == "in"
-}
-
-func (arg *Argument) IsOutput() bool {
- return arg.Direction == "out"
-}
-
-type StateVariable struct {
- Name string `xml:"name"`
- SendEvents string `xml:"sendEvents,attr"` // yes|no
- Multicast string `xml:"multicast,attr"` // yes|no
- DataType DataType `xml:"dataType"`
- DefaultValue string `xml:"defaultValue"`
- AllowedValueRange *AllowedValueRange `xml:"allowedValueRange"`
- AllowedValues []string `xml:"allowedValueList>allowedValue"`
-}
-
-func (v *StateVariable) clean() {
- cleanWhitespace(&v.Name)
- cleanWhitespace(&v.SendEvents)
- cleanWhitespace(&v.Multicast)
- v.DataType.clean()
- cleanWhitespace(&v.DefaultValue)
- if v.AllowedValueRange != nil {
- v.AllowedValueRange.clean()
- }
- for i := range v.AllowedValues {
- cleanWhitespace(&v.AllowedValues[i])
- }
-}
-
-type AllowedValueRange struct {
- Minimum string `xml:"minimum"`
- Maximum string `xml:"maximum"`
- Step string `xml:"step"`
-}
-
-func (r *AllowedValueRange) clean() {
- cleanWhitespace(&r.Minimum)
- cleanWhitespace(&r.Maximum)
- cleanWhitespace(&r.Step)
-}
-
-type DataType struct {
- Name string `xml:",chardata"`
- Type string `xml:"type,attr"`
-}
-
-func (dt *DataType) clean() {
- cleanWhitespace(&dt.Name)
- cleanWhitespace(&dt.Type)
-}
diff --git a/vendor/github.com/huin/goupnp/service_client.go b/vendor/github.com/huin/goupnp/service_client.go
deleted file mode 100644
index 9111c93cb5..0000000000
--- a/vendor/github.com/huin/goupnp/service_client.go
+++ /dev/null
@@ -1,88 +0,0 @@
-package goupnp
-
-import (
- "fmt"
- "net/url"
-
- "github.com/huin/goupnp/soap"
-)
-
-// ServiceClient is a SOAP client, root device and the service for the SOAP
-// client rolled into one value. The root device, location, and service are
-// intended to be informational. Location can be used to later recreate a
-// ServiceClient with NewServiceClientByURL if the service is still present;
-// bypassing the discovery process.
-type ServiceClient struct {
- SOAPClient *soap.SOAPClient
- RootDevice *RootDevice
- Location *url.URL
- Service *Service
-}
-
-// NewServiceClients discovers services, and returns clients for them. err will
-// report any error with the discovery process (blocking any device/service
-// discovery), errors reports errors on a per-root-device basis.
-func NewServiceClients(searchTarget string) (clients []ServiceClient, errors []error, err error) {
- var maybeRootDevices []MaybeRootDevice
- if maybeRootDevices, err = DiscoverDevices(searchTarget); err != nil {
- return
- }
-
- clients = make([]ServiceClient, 0, len(maybeRootDevices))
-
- for _, maybeRootDevice := range maybeRootDevices {
- if maybeRootDevice.Err != nil {
- errors = append(errors, maybeRootDevice.Err)
- continue
- }
-
- deviceClients, err := NewServiceClientsFromRootDevice(maybeRootDevice.Root, maybeRootDevice.Location, searchTarget)
- if err != nil {
- errors = append(errors, err)
- continue
- }
- clients = append(clients, deviceClients...)
- }
-
- return
-}
-
-// NewServiceClientsByURL creates client(s) for the given service URN, for a
-// root device at the given URL.
-func NewServiceClientsByURL(loc *url.URL, searchTarget string) ([]ServiceClient, error) {
- rootDevice, err := DeviceByURL(loc)
- if err != nil {
- return nil, err
- }
- return NewServiceClientsFromRootDevice(rootDevice, loc, searchTarget)
-}
-
-// NewServiceClientsFromDevice creates client(s) for the given service URN, in
-// a given root device. The loc parameter is simply assigned to the
-// Location attribute of the returned ServiceClient(s).
-func NewServiceClientsFromRootDevice(rootDevice *RootDevice, loc *url.URL, searchTarget string) ([]ServiceClient, error) {
- device := &rootDevice.Device
- srvs := device.FindService(searchTarget)
- if len(srvs) == 0 {
- return nil, fmt.Errorf("goupnp: service %q not found within device %q (UDN=%q)",
- searchTarget, device.FriendlyName, device.UDN)
- }
-
- clients := make([]ServiceClient, 0, len(srvs))
- for _, srv := range srvs {
- clients = append(clients, ServiceClient{
- SOAPClient: srv.NewSOAPClient(),
- RootDevice: rootDevice,
- Location: loc,
- Service: srv,
- })
- }
- return clients, nil
-}
-
-// GetServiceClient returns the ServiceClient itself. This is provided so that the
-// service client attributes can be accessed via an interface method on a
-// wrapping type.
-func (client *ServiceClient) GetServiceClient() *ServiceClient {
- return client
-}
diff --git a/vendor/github.com/huin/goupnp/soap/soap.go b/vendor/github.com/huin/goupnp/soap/soap.go
deleted file mode 100644
index 815610734c..0000000000
--- a/vendor/github.com/huin/goupnp/soap/soap.go
+++ /dev/null
@@ -1,157 +0,0 @@
-// Definition for the SOAP structure required for UPnP's SOAP usage.
-
-package soap
-
-import (
- "bytes"
- "encoding/xml"
- "fmt"
- "io/ioutil"
- "net/http"
- "net/url"
- "reflect"
-)
-
-const (
- soapEncodingStyle = "http://schemas.xmlsoap.org/soap/encoding/"
- soapPrefix = xml.Header + ``
- soapSuffix = ``
-)
-
-type SOAPClient struct {
- EndpointURL url.URL
- HTTPClient http.Client
-}
-
-func NewSOAPClient(endpointURL url.URL) *SOAPClient {
- return &SOAPClient{
- EndpointURL: endpointURL,
- }
-}
-
-// PerformSOAPAction makes a SOAP request, with the given action.
-// inAction and outAction must both be pointers to structs with string fields
-// only.
-func (client *SOAPClient) PerformAction(actionNamespace, actionName string, inAction interface{}, outAction interface{}) error {
- requestBytes, err := encodeRequestAction(actionNamespace, actionName, inAction)
- if err != nil {
- return err
- }
-
- response, err := client.HTTPClient.Do(&http.Request{
- Method: "POST",
- URL: &client.EndpointURL,
- Header: http.Header{
- "SOAPACTION": []string{`"` + actionNamespace + "#" + actionName + `"`},
- "CONTENT-TYPE": []string{"text/xml; charset=\"utf-8\""},
- },
- Body: ioutil.NopCloser(bytes.NewBuffer(requestBytes)),
- // Set ContentLength to avoid chunked encoding - some servers might not support it.
- ContentLength: int64(len(requestBytes)),
- })
- if err != nil {
- return fmt.Errorf("goupnp: error performing SOAP HTTP request: %v", err)
- }
- defer response.Body.Close()
- if response.StatusCode != 200 {
- return fmt.Errorf("goupnp: SOAP request got HTTP %s", response.Status)
- }
-
- responseEnv := newSOAPEnvelope()
- decoder := xml.NewDecoder(response.Body)
- if err := decoder.Decode(responseEnv); err != nil {
- return fmt.Errorf("goupnp: error decoding response body: %v", err)
- }
-
- if responseEnv.Body.Fault != nil {
- return responseEnv.Body.Fault
- }
-
- if outAction != nil {
- if err := xml.Unmarshal(responseEnv.Body.RawAction, outAction); err != nil {
- return fmt.Errorf("goupnp: error unmarshalling out action: %v, %v", err, responseEnv.Body.RawAction)
- }
- }
-
- return nil
-}
-
-// newSOAPAction creates a soapEnvelope with the given action and arguments.
-func newSOAPEnvelope() *soapEnvelope {
- return &soapEnvelope{
- EncodingStyle: soapEncodingStyle,
- }
-}
-
-// encodeRequestAction is a hacky way to create an encoded SOAP envelope
-// containing the given action. Experiments with one router have shown that it
-// 500s for requests where the outer default xmlns is set to the SOAP
-// namespace, and then reassigning the default namespace within that to the
-// service namespace. Hand-coding the outer XML to work-around this.
-func encodeRequestAction(actionNamespace, actionName string, inAction interface{}) ([]byte, error) {
- requestBuf := new(bytes.Buffer)
- requestBuf.WriteString(soapPrefix)
- requestBuf.WriteString(``)
- if inAction != nil {
- if err := encodeRequestArgs(requestBuf, inAction); err != nil {
- return nil, err
- }
- }
- requestBuf.WriteString(``)
- requestBuf.WriteString(soapSuffix)
- return requestBuf.Bytes(), nil
-}
-
-func encodeRequestArgs(w *bytes.Buffer, inAction interface{}) error {
- in := reflect.Indirect(reflect.ValueOf(inAction))
- if in.Kind() != reflect.Struct {
- return fmt.Errorf("goupnp: SOAP inAction is not a struct but of type %v", in.Type())
- }
- enc := xml.NewEncoder(w)
- nFields := in.NumField()
- inType := in.Type()
- for i := 0; i < nFields; i++ {
- field := inType.Field(i)
- argName := field.Name
- if nameOverride := field.Tag.Get("soap"); nameOverride != "" {
- argName = nameOverride
- }
- value := in.Field(i)
- if value.Kind() != reflect.String {
- return fmt.Errorf("goupnp: SOAP arg %q is not of type string, but of type %v", argName, value.Type())
- }
- if err := enc.EncodeElement(value.Interface(), xml.StartElement{xml.Name{"", argName}, nil}); err != nil {
- return fmt.Errorf("goupnp: error encoding SOAP arg %q: %v", argName, err)
- }
- }
- enc.Flush()
- return nil
-}
-
-type soapEnvelope struct {
- XMLName xml.Name `xml:"http://schemas.xmlsoap.org/soap/envelope/ Envelope"`
- EncodingStyle string `xml:"http://schemas.xmlsoap.org/soap/envelope/ encodingStyle,attr"`
- Body soapBody `xml:"http://schemas.xmlsoap.org/soap/envelope/ Body"`
-}
-
-type soapBody struct {
- Fault *SOAPFaultError `xml:"Fault"`
- RawAction []byte `xml:",innerxml"`
-}
-
-// SOAPFaultError implements error, and contains SOAP fault information.
-type SOAPFaultError struct {
- FaultCode string `xml:"faultcode"`
- FaultString string `xml:"faultstring"`
- Detail string `xml:"detail"`
-}
-
-func (err *SOAPFaultError) Error() string {
- return fmt.Sprintf("SOAP fault: %s", err.FaultString)
-}
diff --git a/vendor/github.com/huin/goupnp/soap/types.go b/vendor/github.com/huin/goupnp/soap/types.go
deleted file mode 100644
index fdbeec8d42..0000000000
--- a/vendor/github.com/huin/goupnp/soap/types.go
+++ /dev/null
@@ -1,519 +0,0 @@
-package soap
-
-import (
- "encoding/base64"
- "encoding/hex"
- "errors"
- "fmt"
- "net/url"
- "regexp"
- "strconv"
- "strings"
- "time"
- "unicode/utf8"
-)
-
-var (
- // localLoc acts like time.Local for this package, but is faked out by the
- // unit tests to ensure that things stay constant (especially when running
- // this test in a place where local time is UTC which might mask bugs).
- localLoc = time.Local
-)
-
-func MarshalUi1(v uint8) (string, error) {
- return strconv.FormatUint(uint64(v), 10), nil
-}
-
-func UnmarshalUi1(s string) (uint8, error) {
- v, err := strconv.ParseUint(s, 10, 8)
- return uint8(v), err
-}
-
-func MarshalUi2(v uint16) (string, error) {
- return strconv.FormatUint(uint64(v), 10), nil
-}
-
-func UnmarshalUi2(s string) (uint16, error) {
- v, err := strconv.ParseUint(s, 10, 16)
- return uint16(v), err
-}
-
-func MarshalUi4(v uint32) (string, error) {
- return strconv.FormatUint(uint64(v), 10), nil
-}
-
-func UnmarshalUi4(s string) (uint32, error) {
- v, err := strconv.ParseUint(s, 10, 32)
- return uint32(v), err
-}
-
-func MarshalI1(v int8) (string, error) {
- return strconv.FormatInt(int64(v), 10), nil
-}
-
-func UnmarshalI1(s string) (int8, error) {
- v, err := strconv.ParseInt(s, 10, 8)
- return int8(v), err
-}
-
-func MarshalI2(v int16) (string, error) {
- return strconv.FormatInt(int64(v), 10), nil
-}
-
-func UnmarshalI2(s string) (int16, error) {
- v, err := strconv.ParseInt(s, 10, 16)
- return int16(v), err
-}
-
-func MarshalI4(v int32) (string, error) {
- return strconv.FormatInt(int64(v), 10), nil
-}
-
-func UnmarshalI4(s string) (int32, error) {
- v, err := strconv.ParseInt(s, 10, 32)
- return int32(v), err
-}
-
-func MarshalInt(v int64) (string, error) {
- return strconv.FormatInt(v, 10), nil
-}
-
-func UnmarshalInt(s string) (int64, error) {
- return strconv.ParseInt(s, 10, 64)
-}
-
-func MarshalR4(v float32) (string, error) {
- return strconv.FormatFloat(float64(v), 'G', -1, 32), nil
-}
-
-func UnmarshalR4(s string) (float32, error) {
- v, err := strconv.ParseFloat(s, 32)
- return float32(v), err
-}
-
-func MarshalR8(v float64) (string, error) {
- return strconv.FormatFloat(v, 'G', -1, 64), nil
-}
-
-func UnmarshalR8(s string) (float64, error) {
- v, err := strconv.ParseFloat(s, 64)
- return float64(v), err
-}
-
-// MarshalFixed14_4 marshals float64 to SOAP "fixed.14.4" type.
-func MarshalFixed14_4(v float64) (string, error) {
- if v >= 1e14 || v <= -1e14 {
- return "", fmt.Errorf("soap fixed14.4: value %v out of bounds", v)
- }
- return strconv.FormatFloat(v, 'f', 4, 64), nil
-}
-
-// UnmarshalFixed14_4 unmarshals float64 from SOAP "fixed.14.4" type.
-func UnmarshalFixed14_4(s string) (float64, error) {
- v, err := strconv.ParseFloat(s, 64)
- if err != nil {
- return 0, err
- }
- if v >= 1e14 || v <= -1e14 {
- return 0, fmt.Errorf("soap fixed14.4: value %q out of bounds", s)
- }
- return v, nil
-}
-
-// MarshalChar marshals rune to SOAP "char" type.
-func MarshalChar(v rune) (string, error) {
- if v == 0 {
- return "", errors.New("soap char: rune 0 is not allowed")
- }
- return string(v), nil
-}
-
-// UnmarshalChar unmarshals rune from SOAP "char" type.
-func UnmarshalChar(s string) (rune, error) {
- if len(s) == 0 {
- return 0, errors.New("soap char: got empty string")
- }
- r, n := utf8.DecodeRune([]byte(s))
- if n != len(s) {
- return 0, fmt.Errorf("soap char: value %q is not a single rune", s)
- }
- return r, nil
-}
-
-func MarshalString(v string) (string, error) {
- return v, nil
-}
-
-func UnmarshalString(v string) (string, error) {
- return v, nil
-}
-
-func parseInt(s string, err *error) int {
- v, parseErr := strconv.ParseInt(s, 10, 64)
- if parseErr != nil {
- *err = parseErr
- }
- return int(v)
-}
-
-var dateRegexps = []*regexp.Regexp{
- // yyyy[-mm[-dd]]
- regexp.MustCompile(`^(\d{4})(?:-(\d{2})(?:-(\d{2}))?)?$`),
- // yyyy[mm[dd]]
- regexp.MustCompile(`^(\d{4})(?:(\d{2})(?:(\d{2}))?)?$`),
-}
-
-func parseDateParts(s string) (year, month, day int, err error) {
- var parts []string
- for _, re := range dateRegexps {
- parts = re.FindStringSubmatch(s)
- if parts != nil {
- break
- }
- }
- if parts == nil {
- err = fmt.Errorf("soap date: value %q is not in a recognized ISO8601 date format", s)
- return
- }
-
- year = parseInt(parts[1], &err)
- month = 1
- day = 1
- if len(parts[2]) != 0 {
- month = parseInt(parts[2], &err)
- if len(parts[3]) != 0 {
- day = parseInt(parts[3], &err)
- }
- }
-
- if err != nil {
- err = fmt.Errorf("soap date: %q: %v", s, err)
- }
-
- return
-}
-
-var timeRegexps = []*regexp.Regexp{
- // hh[:mm[:ss]]
- regexp.MustCompile(`^(\d{2})(?::(\d{2})(?::(\d{2}))?)?$`),
- // hh[mm[ss]]
- regexp.MustCompile(`^(\d{2})(?:(\d{2})(?:(\d{2}))?)?$`),
-}
-
-func parseTimeParts(s string) (hour, minute, second int, err error) {
- var parts []string
- for _, re := range timeRegexps {
- parts = re.FindStringSubmatch(s)
- if parts != nil {
- break
- }
- }
- if parts == nil {
- err = fmt.Errorf("soap time: value %q is not in ISO8601 time format", s)
- return
- }
-
- hour = parseInt(parts[1], &err)
- if len(parts[2]) != 0 {
- minute = parseInt(parts[2], &err)
- if len(parts[3]) != 0 {
- second = parseInt(parts[3], &err)
- }
- }
-
- if err != nil {
- err = fmt.Errorf("soap time: %q: %v", s, err)
- }
-
- return
-}
-
-// (+|-)hh[[:]mm]
-var timezoneRegexp = regexp.MustCompile(`^([+-])(\d{2})(?::?(\d{2}))?$`)
-
-func parseTimezone(s string) (offset int, err error) {
- if s == "Z" {
- return 0, nil
- }
- parts := timezoneRegexp.FindStringSubmatch(s)
- if parts == nil {
- err = fmt.Errorf("soap timezone: value %q is not in ISO8601 timezone format", s)
- return
- }
-
- offset = parseInt(parts[2], &err) * 3600
- if len(parts[3]) != 0 {
- offset += parseInt(parts[3], &err) * 60
- }
- if parts[1] == "-" {
- offset = -offset
- }
-
- if err != nil {
- err = fmt.Errorf("soap timezone: %q: %v", s, err)
- }
-
- return
-}
-
-var completeDateTimeZoneRegexp = regexp.MustCompile(`^([^T]+)(?:T([^-+Z]+)(.+)?)?$`)
-
-// splitCompleteDateTimeZone splits date, time and timezone apart from an
-// ISO8601 string. It does not ensure that the contents of each part are
-// correct, it merely splits on certain delimiters.
-// e.g "2010-09-08T12:15:10+0700" => "2010-09-08", "12:15:10", "+0700".
-// Timezone can only be present if time is also present.
-func splitCompleteDateTimeZone(s string) (dateStr, timeStr, zoneStr string, err error) {
- parts := completeDateTimeZoneRegexp.FindStringSubmatch(s)
- if parts == nil {
- err = fmt.Errorf("soap date/time/zone: value %q is not in ISO8601 datetime format", s)
- return
- }
- dateStr = parts[1]
- timeStr = parts[2]
- zoneStr = parts[3]
- return
-}
-
-// MarshalDate marshals time.Time to SOAP "date" type. Note that this converts
-// to local time, and discards the time-of-day components.
-func MarshalDate(v time.Time) (string, error) {
- return v.In(localLoc).Format("2006-01-02"), nil
-}
-
-var dateFmts = []string{"2006-01-02", "20060102"}
-
-// UnmarshalDate unmarshals time.Time from SOAP "date" type. This outputs the
-// date as midnight in the local time zone.
-func UnmarshalDate(s string) (time.Time, error) {
- year, month, day, err := parseDateParts(s)
- if err != nil {
- return time.Time{}, err
- }
- return time.Date(year, time.Month(month), day, 0, 0, 0, 0, localLoc), nil
-}
-
-// TimeOfDay is used in cases where SOAP "time" or "time.tz" is used.
-type TimeOfDay struct {
- // Duration of time since midnight.
- FromMidnight time.Duration
-
- // Set to true if Offset is specified. If false, then the timezone is
- // unspecified (and by ISO8601 - implies some "local" time).
- HasOffset bool
-
- // Offset is non-zero only if time.tz is used. It is otherwise ignored. If
- // non-zero, then it is regarded as a UTC offset in seconds. Note that the
- // sub-minutes is ignored by the marshal function.
- Offset int
-}
-
-// MarshalTimeOfDay marshals TimeOfDay to the "time" type.
-func MarshalTimeOfDay(v TimeOfDay) (string, error) {
- d := int64(v.FromMidnight / time.Second)
- hour := d / 3600
- d = d % 3600
- minute := d / 60
- second := d % 60
-
- return fmt.Sprintf("%02d:%02d:%02d", hour, minute, second), nil
-}
-
-// UnmarshalTimeOfDay unmarshals TimeOfDay from the "time" type.
-func UnmarshalTimeOfDay(s string) (TimeOfDay, error) {
- t, err := UnmarshalTimeOfDayTz(s)
- if err != nil {
- return TimeOfDay{}, err
- } else if t.HasOffset {
- return TimeOfDay{}, fmt.Errorf("soap time: value %q contains unexpected timezone")
- }
- return t, nil
-}
-
-// MarshalTimeOfDayTz marshals TimeOfDay to the "time.tz" type.
-func MarshalTimeOfDayTz(v TimeOfDay) (string, error) {
- d := int64(v.FromMidnight / time.Second)
- hour := d / 3600
- d = d % 3600
- minute := d / 60
- second := d % 60
-
- tz := ""
- if v.HasOffset {
- if v.Offset == 0 {
- tz = "Z"
- } else {
- offsetMins := v.Offset / 60
- sign := '+'
- if offsetMins < 1 {
- offsetMins = -offsetMins
- sign = '-'
- }
- tz = fmt.Sprintf("%c%02d:%02d", sign, offsetMins/60, offsetMins%60)
- }
- }
-
- return fmt.Sprintf("%02d:%02d:%02d%s", hour, minute, second, tz), nil
-}
-
-// UnmarshalTimeOfDayTz unmarshals TimeOfDay from the "time.tz" type.
-func UnmarshalTimeOfDayTz(s string) (tod TimeOfDay, err error) {
- zoneIndex := strings.IndexAny(s, "Z+-")
- var timePart string
- var hasOffset bool
- var offset int
- if zoneIndex == -1 {
- hasOffset = false
- timePart = s
- } else {
- hasOffset = true
- timePart = s[:zoneIndex]
- if offset, err = parseTimezone(s[zoneIndex:]); err != nil {
- return
- }
- }
-
- hour, minute, second, err := parseTimeParts(timePart)
- if err != nil {
- return
- }
-
- fromMidnight := time.Duration(hour*3600+minute*60+second) * time.Second
-
- // ISO8601 special case - values up to 24:00:00 are allowed, so using
- // strictly greater-than for the maximum value.
- if fromMidnight > 24*time.Hour || minute >= 60 || second >= 60 {
- return TimeOfDay{}, fmt.Errorf("soap time.tz: value %q has value(s) out of range", s)
- }
-
- return TimeOfDay{
- FromMidnight: time.Duration(hour*3600+minute*60+second) * time.Second,
- HasOffset: hasOffset,
- Offset: offset,
- }, nil
-}
-
-// MarshalDateTime marshals time.Time to SOAP "dateTime" type. Note that this
-// converts to local time.
-func MarshalDateTime(v time.Time) (string, error) {
- return v.In(localLoc).Format("2006-01-02T15:04:05"), nil
-}
-
-// UnmarshalDateTime unmarshals time.Time from the SOAP "dateTime" type. This
-// returns a value in the local timezone.
-func UnmarshalDateTime(s string) (result time.Time, err error) {
- dateStr, timeStr, zoneStr, err := splitCompleteDateTimeZone(s)
- if err != nil {
- return
- }
-
- if len(zoneStr) != 0 {
- err = fmt.Errorf("soap datetime: unexpected timezone in %q", s)
- return
- }
-
- year, month, day, err := parseDateParts(dateStr)
- if err != nil {
- return
- }
-
- var hour, minute, second int
- if len(timeStr) != 0 {
- hour, minute, second, err = parseTimeParts(timeStr)
- if err != nil {
- return
- }
- }
-
- result = time.Date(year, time.Month(month), day, hour, minute, second, 0, localLoc)
- return
-}
-
-// MarshalDateTimeTz marshals time.Time to SOAP "dateTime.tz" type.
-func MarshalDateTimeTz(v time.Time) (string, error) {
- return v.Format("2006-01-02T15:04:05-07:00"), nil
-}
-
-// UnmarshalDateTimeTz unmarshals time.Time from the SOAP "dateTime.tz" type.
-// This returns a value in the local timezone when the timezone is unspecified.
-func UnmarshalDateTimeTz(s string) (result time.Time, err error) {
- dateStr, timeStr, zoneStr, err := splitCompleteDateTimeZone(s)
- if err != nil {
- return
- }
-
- year, month, day, err := parseDateParts(dateStr)
- if err != nil {
- return
- }
-
- var hour, minute, second int
- var location *time.Location = localLoc
- if len(timeStr) != 0 {
- hour, minute, second, err = parseTimeParts(timeStr)
- if err != nil {
- return
- }
- if len(zoneStr) != 0 {
- var offset int
- offset, err = parseTimezone(zoneStr)
- if offset == 0 {
- location = time.UTC
- } else {
- location = time.FixedZone("", offset)
- }
- }
- }
-
- result = time.Date(year, time.Month(month), day, hour, minute, second, 0, location)
- return
-}
-
-// MarshalBoolean marshals bool to SOAP "boolean" type.
-func MarshalBoolean(v bool) (string, error) {
- if v {
- return "1", nil
- }
- return "0", nil
-}
-
-// UnmarshalBoolean unmarshals bool from the SOAP "boolean" type.
-func UnmarshalBoolean(s string) (bool, error) {
- switch s {
- case "0", "false", "no":
- return false, nil
- case "1", "true", "yes":
- return true, nil
- }
- return false, fmt.Errorf("soap boolean: %q is not a valid boolean value", s)
-}
-
-// MarshalBinBase64 marshals []byte to SOAP "bin.base64" type.
-func MarshalBinBase64(v []byte) (string, error) {
- return base64.StdEncoding.EncodeToString(v), nil
-}
-
-// UnmarshalBinBase64 unmarshals []byte from the SOAP "bin.base64" type.
-func UnmarshalBinBase64(s string) ([]byte, error) {
- return base64.StdEncoding.DecodeString(s)
-}
-
-// MarshalBinHex marshals []byte to SOAP "bin.hex" type.
-func MarshalBinHex(v []byte) (string, error) {
- return hex.EncodeToString(v), nil
-}
-
-// UnmarshalBinHex unmarshals []byte from the SOAP "bin.hex" type.
-func UnmarshalBinHex(s string) ([]byte, error) {
- return hex.DecodeString(s)
-}
-
-// MarshalURI marshals *url.URL to SOAP "uri" type.
-func MarshalURI(v *url.URL) (string, error) {
- return v.String(), nil
-}
-
-// UnmarshalURI unmarshals *url.URL from the SOAP "uri" type.
-func UnmarshalURI(s string) (*url.URL, error) {
- return url.Parse(s)
-}
diff --git a/vendor/github.com/huin/goupnp/ssdp/registry.go b/vendor/github.com/huin/goupnp/ssdp/registry.go
deleted file mode 100644
index d3bc114463..0000000000
--- a/vendor/github.com/huin/goupnp/ssdp/registry.go
+++ /dev/null
@@ -1,312 +0,0 @@
-package ssdp
-
-import (
- "fmt"
- "log"
- "net/http"
- "net/url"
- "regexp"
- "strconv"
- "sync"
- "time"
-
- "github.com/huin/goupnp/httpu"
-)
-
-const (
- maxExpiryTimeSeconds = 24 * 60 * 60
-)
-
-var (
- maxAgeRx = regexp.MustCompile("max-age= *([0-9]+)")
-)
-
-const (
- EventAlive = EventType(iota)
- EventUpdate
- EventByeBye
-)
-
-type EventType int8
-
-func (et EventType) String() string {
- switch et {
- case EventAlive:
- return "EventAlive"
- case EventUpdate:
- return "EventUpdate"
- case EventByeBye:
- return "EventByeBye"
- default:
- return fmt.Sprintf("EventUnknown(%d)", int8(et))
- }
-}
-
-type Update struct {
- // The USN of the service.
- USN string
- // What happened.
- EventType EventType
- // The entry, which is nil if the service was not known and
- // EventType==EventByeBye. The contents of this must not be modified as it is
- // shared with the registry and other listeners. Once created, the Registry
- // does not modify the Entry value - any updates are replaced with a new
- // Entry value.
- Entry *Entry
-}
-
-type Entry struct {
- // The address that the entry data was actually received from.
- RemoteAddr string
- // Unique Service Name. Identifies a unique instance of a device or service.
- USN string
- // Notfication Type. The type of device or service being announced.
- NT string
- // Server's self-identifying string.
- Server string
- Host string
- // Location of the UPnP root device description.
- Location url.URL
-
- // Despite BOOTID,CONFIGID being required fields, apparently they are not
- // always set by devices. Set to -1 if not present.
-
- BootID int32
- ConfigID int32
-
- SearchPort uint16
-
- // When the last update was received for this entry identified by this USN.
- LastUpdate time.Time
- // When the last update's cached values are advised to expire.
- CacheExpiry time.Time
-}
-
-func newEntryFromRequest(r *http.Request) (*Entry, error) {
- now := time.Now()
- expiryDuration, err := parseCacheControlMaxAge(r.Header.Get("CACHE-CONTROL"))
- if err != nil {
- return nil, fmt.Errorf("ssdp: error parsing CACHE-CONTROL max age: %v", err)
- }
-
- loc, err := url.Parse(r.Header.Get("LOCATION"))
- if err != nil {
- return nil, fmt.Errorf("ssdp: error parsing entry Location URL: %v", err)
- }
-
- bootID, err := parseUpnpIntHeader(r.Header, "BOOTID.UPNP.ORG", -1)
- if err != nil {
- return nil, err
- }
- configID, err := parseUpnpIntHeader(r.Header, "CONFIGID.UPNP.ORG", -1)
- if err != nil {
- return nil, err
- }
- searchPort, err := parseUpnpIntHeader(r.Header, "SEARCHPORT.UPNP.ORG", ssdpSearchPort)
- if err != nil {
- return nil, err
- }
-
- if searchPort < 1 || searchPort > 65535 {
- return nil, fmt.Errorf("ssdp: search port %d is out of range", searchPort)
- }
-
- return &Entry{
- RemoteAddr: r.RemoteAddr,
- USN: r.Header.Get("USN"),
- NT: r.Header.Get("NT"),
- Server: r.Header.Get("SERVER"),
- Host: r.Header.Get("HOST"),
- Location: *loc,
- BootID: bootID,
- ConfigID: configID,
- SearchPort: uint16(searchPort),
- LastUpdate: now,
- CacheExpiry: now.Add(expiryDuration),
- }, nil
-}
-
-func parseCacheControlMaxAge(cc string) (time.Duration, error) {
- matches := maxAgeRx.FindStringSubmatch(cc)
- if len(matches) != 2 {
- return 0, fmt.Errorf("did not find exactly one max-age in cache control header: %q", cc)
- }
- expirySeconds, err := strconv.ParseInt(matches[1], 10, 16)
- if err != nil {
- return 0, err
- }
- if expirySeconds < 1 || expirySeconds > maxExpiryTimeSeconds {
- return 0, fmt.Errorf("rejecting bad expiry time of %d seconds", expirySeconds)
- }
- return time.Duration(expirySeconds) * time.Second, nil
-}
-
-// parseUpnpIntHeader is intended to parse the
-// {BOOT,CONFIGID,SEARCHPORT}.UPNP.ORG header fields. It returns the def if
-// the head is empty or missing.
-func parseUpnpIntHeader(headers http.Header, headerName string, def int32) (int32, error) {
- s := headers.Get(headerName)
- if s == "" {
- return def, nil
- }
- v, err := strconv.ParseInt(s, 10, 32)
- if err != nil {
- return 0, fmt.Errorf("ssdp: could not parse header %s: %v", headerName, err)
- }
- return int32(v), nil
-}
-
-var _ httpu.Handler = new(Registry)
-
-// Registry maintains knowledge of discovered devices and services.
-//
-// NOTE: the interface for this is experimental and may change, or go away
-// entirely.
-type Registry struct {
- lock sync.Mutex
- byUSN map[string]*Entry
-
- listenersLock sync.RWMutex
- listeners map[chan<- Update]struct{}
-}
-
-func NewRegistry() *Registry {
- return &Registry{
- byUSN: make(map[string]*Entry),
- listeners: make(map[chan<- Update]struct{}),
- }
-}
-
-// NewServerAndRegistry is a convenience function to create a registry, and an
-// httpu server to pass it messages. Call ListenAndServe on the server for
-// messages to be processed.
-func NewServerAndRegistry() (*httpu.Server, *Registry) {
- reg := NewRegistry()
- srv := &httpu.Server{
- Addr: ssdpUDP4Addr,
- Multicast: true,
- Handler: reg,
- }
- return srv, reg
-}
-
-func (reg *Registry) AddListener(c chan<- Update) {
- reg.listenersLock.Lock()
- defer reg.listenersLock.Unlock()
- reg.listeners[c] = struct{}{}
-}
-
-func (reg *Registry) RemoveListener(c chan<- Update) {
- reg.listenersLock.Lock()
- defer reg.listenersLock.Unlock()
- delete(reg.listeners, c)
-}
-
-func (reg *Registry) sendUpdate(u Update) {
- reg.listenersLock.RLock()
- defer reg.listenersLock.RUnlock()
- for c := range reg.listeners {
- c <- u
- }
-}
-
-// GetService returns known service (or device) entries for the given service
-// URN.
-func (reg *Registry) GetService(serviceURN string) []*Entry {
- // Currently assumes that the map is small, so we do a linear search rather
- // than indexed to avoid maintaining two maps.
- var results []*Entry
- reg.lock.Lock()
- defer reg.lock.Unlock()
- for _, entry := range reg.byUSN {
- if entry.NT == serviceURN {
- results = append(results, entry)
- }
- }
- return results
-}
-
-// ServeMessage implements httpu.Handler, and uses SSDP NOTIFY requests to
-// maintain the registry of devices and services.
-func (reg *Registry) ServeMessage(r *http.Request) {
- if r.Method != methodNotify {
- return
- }
-
- nts := r.Header.Get("nts")
-
- var err error
- switch nts {
- case ntsAlive:
- err = reg.handleNTSAlive(r)
- case ntsUpdate:
- err = reg.handleNTSUpdate(r)
- case ntsByebye:
- err = reg.handleNTSByebye(r)
- default:
- err = fmt.Errorf("unknown NTS value: %q", nts)
- }
- if err != nil {
- log.Printf("goupnp/ssdp: failed to handle %s message from %s: %v", nts, r.RemoteAddr, err)
- }
-}
-
-func (reg *Registry) handleNTSAlive(r *http.Request) error {
- entry, err := newEntryFromRequest(r)
- if err != nil {
- return err
- }
-
- reg.lock.Lock()
- reg.byUSN[entry.USN] = entry
- reg.lock.Unlock()
-
- reg.sendUpdate(Update{
- USN: entry.USN,
- EventType: EventAlive,
- Entry: entry,
- })
-
- return nil
-}
-
-func (reg *Registry) handleNTSUpdate(r *http.Request) error {
- entry, err := newEntryFromRequest(r)
- if err != nil {
- return err
- }
- nextBootID, err := parseUpnpIntHeader(r.Header, "NEXTBOOTID.UPNP.ORG", -1)
- if err != nil {
- return err
- }
- entry.BootID = nextBootID
-
- reg.lock.Lock()
- reg.byUSN[entry.USN] = entry
- reg.lock.Unlock()
-
- reg.sendUpdate(Update{
- USN: entry.USN,
- EventType: EventUpdate,
- Entry: entry,
- })
-
- return nil
-}
-
-func (reg *Registry) handleNTSByebye(r *http.Request) error {
- usn := r.Header.Get("USN")
-
- reg.lock.Lock()
- entry := reg.byUSN[usn]
- delete(reg.byUSN, usn)
- reg.lock.Unlock()
-
- reg.sendUpdate(Update{
- USN: usn,
- EventType: EventByeBye,
- Entry: entry,
- })
-
- return nil
-}
diff --git a/vendor/github.com/huin/goupnp/ssdp/ssdp.go b/vendor/github.com/huin/goupnp/ssdp/ssdp.go
deleted file mode 100644
index 8178f5d948..0000000000
--- a/vendor/github.com/huin/goupnp/ssdp/ssdp.go
+++ /dev/null
@@ -1,83 +0,0 @@
-package ssdp
-
-import (
- "errors"
- "log"
- "net/http"
- "net/url"
- "strconv"
- "time"
-
- "github.com/huin/goupnp/httpu"
-)
-
-const (
- ssdpDiscover = `"ssdp:discover"`
- ntsAlive = `ssdp:alive`
- ntsByebye = `ssdp:byebye`
- ntsUpdate = `ssdp:update`
- ssdpUDP4Addr = "239.255.255.250:1900"
- ssdpSearchPort = 1900
- methodSearch = "M-SEARCH"
- methodNotify = "NOTIFY"
-)
-
-// SSDPRawSearch performs a fairly raw SSDP search request, and returns the
-// unique response(s) that it receives. Each response has the requested
-// searchTarget, a USN, and a valid location. maxWaitSeconds states how long to
-// wait for responses in seconds, and must be a minimum of 1 (the
-// implementation waits an additional 100ms for responses to arrive), 2 is a
-// reasonable value for this. numSends is the number of requests to send - 3 is
-// a reasonable value for this.
-func SSDPRawSearch(httpu *httpu.HTTPUClient, searchTarget string, maxWaitSeconds int, numSends int) ([]*http.Response, error) {
- if maxWaitSeconds < 1 {
- return nil, errors.New("ssdp: maxWaitSeconds must be >= 1")
- }
-
- seenUsns := make(map[string]bool)
- var responses []*http.Response
- req := http.Request{
- Method: methodSearch,
- // TODO: Support both IPv4 and IPv6.
- Host: ssdpUDP4Addr,
- URL: &url.URL{Opaque: "*"},
- Header: http.Header{
- // Putting headers in here avoids them being title-cased.
- // (The UPnP discovery protocol uses case-sensitive headers)
- "HOST": []string{ssdpUDP4Addr},
- "MX": []string{strconv.FormatInt(int64(maxWaitSeconds), 10)},
- "MAN": []string{ssdpDiscover},
- "ST": []string{searchTarget},
- },
- }
- allResponses, err := httpu.Do(&req, time.Duration(maxWaitSeconds)*time.Second+100*time.Millisecond, numSends)
- if err != nil {
- return nil, err
- }
- for _, response := range allResponses {
- if response.StatusCode != 200 {
- log.Printf("ssdp: got response status code %q in search response", response.Status)
- continue
- }
- if st := response.Header.Get("ST"); st != searchTarget {
- log.Printf("ssdp: got unexpected search target result %q", st)
- continue
- }
- location, err := response.Location()
- if err != nil {
- log.Printf("ssdp: no usable location in search response (discarding): %v", err)
- continue
- }
- usn := response.Header.Get("USN")
- if usn == "" {
- log.Printf("ssdp: empty/missing USN in search response (using location instead): %v", err)
- usn = location.String()
- }
- if _, alreadySeen := seenUsns[usn]; !alreadySeen {
- seenUsns[usn] = true
- responses = append(responses, response)
- }
- }
-
- return responses, nil
-}
diff --git a/vendor/github.com/influxdata/influxdb/LICENSE b/vendor/github.com/influxdata/influxdb/LICENSE
deleted file mode 100644
index 63cef79ba6..0000000000
--- a/vendor/github.com/influxdata/influxdb/LICENSE
+++ /dev/null
@@ -1,20 +0,0 @@
-The MIT License (MIT)
-
-Copyright (c) 2013-2016 Errplane Inc.
-
-Permission is hereby granted, free of charge, to any person obtaining a copy of
-this software and associated documentation files (the "Software"), to deal in
-the Software without restriction, including without limitation the rights to
-use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
-the Software, and to permit persons to whom the Software is furnished to do so,
-subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
-FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
-COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
-IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
-CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
diff --git a/vendor/github.com/influxdata/influxdb/LICENSE_OF_DEPENDENCIES.md b/vendor/github.com/influxdata/influxdb/LICENSE_OF_DEPENDENCIES.md
deleted file mode 100644
index ea6fc69f30..0000000000
--- a/vendor/github.com/influxdata/influxdb/LICENSE_OF_DEPENDENCIES.md
+++ /dev/null
@@ -1,62 +0,0 @@
-- # List
-- bootstrap 3.3.5 [MIT LICENSE](https://github.com/twbs/bootstrap/blob/master/LICENSE)
-- collectd.org [ISC LICENSE](https://github.com/collectd/go-collectd/blob/master/LICENSE)
-- github.com/BurntSushi/toml [MIT LICENSE](https://github.com/BurntSushi/toml/blob/master/COPYING)
-- github.com/RoaringBitmap/roaring [APACHE LICENSE](https://github.com/RoaringBitmap/roaring/blob/master/LICENSE)
-- github.com/beorn7/perks [MIT LICENSE](https://github.com/beorn7/perks/blob/master/LICENSE)
-- github.com/bmizerany/pat [MIT LICENSE](https://github.com/bmizerany/pat#license)
-- github.com/boltdb/bolt [MIT LICENSE](https://github.com/boltdb/bolt/blob/master/LICENSE)
-- github.com/cespare/xxhash [MIT LICENSE](https://github.com/cespare/xxhash/blob/master/LICENSE.txt)
-- github.com/clarkduvall/hyperloglog [MIT LICENSE](https://github.com/clarkduvall/hyperloglog/blob/master/LICENSE)
-- github.com/davecgh/go-spew/spew [ISC LICENSE](https://github.com/davecgh/go-spew/blob/master/LICENSE)
-- github.com/dgrijalva/jwt-go [MIT LICENSE](https://github.com/dgrijalva/jwt-go/blob/master/LICENSE)
-- github.com/dgryski/go-bits [MIT LICENSE](https://github.com/dgryski/go-bits/blob/master/LICENSE)
-- github.com/dgryski/go-bitstream [MIT LICENSE](https://github.com/dgryski/go-bitstream/blob/master/LICENSE)
-- github.com/glycerine/go-unsnap-stream [MIT LICENSE](https://github.com/glycerine/go-unsnap-stream/blob/master/LICENSE)
-- github.com/gogo/protobuf/proto [BSD LICENSE](https://github.com/gogo/protobuf/blob/master/LICENSE)
-- github.com/golang/protobuf [BSD LICENSE](https://github.com/golang/protobuf/blob/master/LICENSE)
-- github.com/golang/snappy [BSD LICENSE](https://github.com/golang/snappy/blob/master/LICENSE)
-- github.com/google/go-cmp [BSD LICENSE](https://github.com/google/go-cmp/blob/master/LICENSE)
-- github.com/influxdata/influxql [MIT LICENSE](https://github.com/influxdata/influxql/blob/master/LICENSE)
-- github.com/influxdata/usage-client [MIT LICENSE](https://github.com/influxdata/usage-client/blob/master/LICENSE.txt)
-- github.com/influxdata/yamux [MOZILLA PUBLIC LICENSE](https://github.com/influxdata/yamux/blob/master/LICENSE)
-- github.com/influxdata/yarpc [MIT LICENSE](https://github.com/influxdata/yarpc/blob/master/LICENSE)
-- github.com/jsternberg/zap-logfmt [MIT LICENSE](https://github.com/jsternberg/zap-logfmt/blob/master/LICENSE)
-- github.com/jwilder/encoding [MIT LICENSE](https://github.com/jwilder/encoding/blob/master/LICENSE)
-- github.com/mattn/go-isatty [MIT LICENSE](https://github.com/mattn/go-isatty/blob/master/LICENSE)
-- github.com/matttproud/golang_protobuf_extensions [APACHE LICENSE](https://github.com/matttproud/golang_protobuf_extensions/blob/master/LICENSE)
-- github.com/opentracing/opentracing-go [MIT LICENSE](https://github.com/opentracing/opentracing-go/blob/master/LICENSE)
-- github.com/paulbellamy/ratecounter [MIT LICENSE](https://github.com/paulbellamy/ratecounter/blob/master/LICENSE)
-- github.com/peterh/liner [MIT LICENSE](https://github.com/peterh/liner/blob/master/COPYING)
-- github.com/philhofer/fwd [MIT LICENSE](https://github.com/philhofer/fwd/blob/master/LICENSE.md)
-- github.com/prometheus/client_golang [MIT LICENSE](https://github.com/prometheus/client_golang/blob/master/LICENSE)
-- github.com/prometheus/client_model [MIT LICENSE](https://github.com/prometheus/client_model/blob/master/LICENSE)
-- github.com/prometheus/common [APACHE LICENSE](https://github.com/prometheus/common/blob/master/LICENSE)
-- github.com/prometheus/procfs [APACHE LICENSE](https://github.com/prometheus/procfs/blob/master/LICENSE)
-- github.com/rakyll/statik [APACHE LICENSE](https://github.com/rakyll/statik/blob/master/LICENSE)
-- github.com/retailnext/hllpp [BSD LICENSE](https://github.com/retailnext/hllpp/blob/master/LICENSE)
-- github.com/tinylib/msgp [MIT LICENSE](https://github.com/tinylib/msgp/blob/master/LICENSE)
-- go.uber.org/atomic [MIT LICENSE](https://github.com/uber-go/atomic/blob/master/LICENSE.txt)
-- go.uber.org/multierr [MIT LICENSE](https://github.com/uber-go/multierr/blob/master/LICENSE.txt)
-- go.uber.org/zap [MIT LICENSE](https://github.com/uber-go/zap/blob/master/LICENSE.txt)
-- golang.org/x/crypto [BSD LICENSE](https://github.com/golang/crypto/blob/master/LICENSE)
-- golang.org/x/net [BSD LICENSE](https://github.com/golang/net/blob/master/LICENSE)
-- golang.org/x/sys [BSD LICENSE](https://github.com/golang/sys/blob/master/LICENSE)
-- golang.org/x/text [BSD LICENSE](https://github.com/golang/text/blob/master/LICENSE)
-- golang.org/x/time [BSD LICENSE](https://github.com/golang/time/blob/master/LICENSE)
-- jquery 2.1.4 [MIT LICENSE](https://github.com/jquery/jquery/blob/master/LICENSE.txt)
-- github.com/xlab/treeprint [MIT LICENSE](https://github.com/xlab/treeprint/blob/master/LICENSE)
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/vendor/github.com/influxdata/influxdb/client/README.md b/vendor/github.com/influxdata/influxdb/client/README.md
deleted file mode 100644
index 773a111228..0000000000
--- a/vendor/github.com/influxdata/influxdb/client/README.md
+++ /dev/null
@@ -1,306 +0,0 @@
-# InfluxDB Client
-
-[![GoDoc](https://godoc.org/github.com/influxdata/influxdb?status.svg)](http://godoc.org/github.com/influxdata/influxdb/client/v2)
-
-## Description
-
-**NOTE:** The Go client library now has a "v2" version, with the old version
-being deprecated. The new version can be imported at
-`import "github.com/influxdata/influxdb/client/v2"`. It is not backwards-compatible.
-
-A Go client library written and maintained by the **InfluxDB** team.
-This package provides convenience functions to read and write time series data.
-It uses the HTTP protocol to communicate with your **InfluxDB** cluster.
-
-
-## Getting Started
-
-### Connecting To Your Database
-
-Connecting to an **InfluxDB** database is straightforward. You will need a host
-name, a port and the cluster user credentials if applicable. The default port is
-8086. You can customize these settings to your specific installation via the
-**InfluxDB** configuration file.
-
-Though not necessary for experimentation, you may want to create a new user
-and authenticate the connection to your database.
-
-For more information please check out the
-[Admin Docs](https://docs.influxdata.com/influxdb/latest/administration/).
-
-For the impatient, you can create a new admin user _bubba_ by firing off the
-[InfluxDB CLI](https://github.com/influxdata/influxdb/blob/master/cmd/influx/main.go).
-
-```shell
-influx
-> create user bubba with password 'bumblebeetuna'
-> grant all privileges to bubba
-```
-
-And now for good measure set the credentials in you shell environment.
-In the example below we will use $INFLUX_USER and $INFLUX_PWD
-
-Now with the administrivia out of the way, let's connect to our database.
-
-NOTE: If you've opted out of creating a user, you can omit Username and Password in
-the configuration below.
-
-```go
-package main
-
-import (
- "log"
- "time"
-
- "github.com/influxdata/influxdb/client/v2"
-)
-
-const (
- MyDB = "square_holes"
- username = "bubba"
- password = "bumblebeetuna"
-)
-
-
-func main() {
- // Create a new HTTPClient
- c, err := client.NewHTTPClient(client.HTTPConfig{
- Addr: "http://localhost:8086",
- Username: username,
- Password: password,
- })
- if err != nil {
- log.Fatal(err)
- }
-
- // Create a new point batch
- bp, err := client.NewBatchPoints(client.BatchPointsConfig{
- Database: MyDB,
- Precision: "s",
- })
- if err != nil {
- log.Fatal(err)
- }
-
- // Create a point and add to batch
- tags := map[string]string{"cpu": "cpu-total"}
- fields := map[string]interface{}{
- "idle": 10.1,
- "system": 53.3,
- "user": 46.6,
- }
-
- pt, err := client.NewPoint("cpu_usage", tags, fields, time.Now())
- if err != nil {
- log.Fatal(err)
- }
- bp.AddPoint(pt)
-
- // Write the batch
- if err := c.Write(bp); err != nil {
- log.Fatal(err)
- }
-}
-
-```
-
-### Inserting Data
-
-Time series data aka *points* are written to the database using batch inserts.
-The mechanism is to create one or more points and then create a batch aka
-*batch points* and write these to a given database and series. A series is a
-combination of a measurement (time/values) and a set of tags.
-
-In this sample we will create a batch of a 1,000 points. Each point has a time and
-a single value as well as 2 tags indicating a shape and color. We write these points
-to a database called _square_holes_ using a measurement named _shapes_.
-
-NOTE: You can specify a RetentionPolicy as part of the batch points. If not
-provided InfluxDB will use the database _default_ retention policy.
-
-```go
-
-func writePoints(clnt client.Client) {
- sampleSize := 1000
-
- bp, err := client.NewBatchPoints(client.BatchPointsConfig{
- Database: "systemstats",
- Precision: "us",
- })
- if err != nil {
- log.Fatal(err)
- }
-
- rand.Seed(time.Now().UnixNano())
- for i := 0; i < sampleSize; i++ {
- regions := []string{"us-west1", "us-west2", "us-west3", "us-east1"}
- tags := map[string]string{
- "cpu": "cpu-total",
- "host": fmt.Sprintf("host%d", rand.Intn(1000)),
- "region": regions[rand.Intn(len(regions))],
- }
-
- idle := rand.Float64() * 100.0
- fields := map[string]interface{}{
- "idle": idle,
- "busy": 100.0 - idle,
- }
-
- pt, err := client.NewPoint(
- "cpu_usage",
- tags,
- fields,
- time.Now(),
- )
- if err != nil {
- log.Fatal(err)
- }
- bp.AddPoint(pt)
- }
-
- if err := clnt.Write(bp); err != nil {
- log.Fatal(err)
- }
-}
-```
-
-#### Uint64 Support
-
-The `uint64` data type is supported if your server is version `1.4.0` or
-greater. To write a data point as an unsigned integer, you must insert
-the point as `uint64`. You cannot use `uint` or any of the other
-derivatives because previous versions of the client have supported
-writing those types as an integer.
-
-### Querying Data
-
-One nice advantage of using **InfluxDB** the ability to query your data using familiar
-SQL constructs. In this example we can create a convenience function to query the database
-as follows:
-
-```go
-// queryDB convenience function to query the database
-func queryDB(clnt client.Client, cmd string) (res []client.Result, err error) {
- q := client.Query{
- Command: cmd,
- Database: MyDB,
- }
- if response, err := clnt.Query(q); err == nil {
- if response.Error() != nil {
- return res, response.Error()
- }
- res = response.Results
- } else {
- return res, err
- }
- return res, nil
-}
-```
-
-#### Creating a Database
-
-```go
-_, err := queryDB(clnt, fmt.Sprintf("CREATE DATABASE %s", MyDB))
-if err != nil {
- log.Fatal(err)
-}
-```
-
-#### Count Records
-
-```go
-q := fmt.Sprintf("SELECT count(%s) FROM %s", "value", MyMeasurement)
-res, err := queryDB(clnt, q)
-if err != nil {
- log.Fatal(err)
-}
-count := res[0].Series[0].Values[0][1]
-log.Printf("Found a total of %v records\n", count)
-```
-
-#### Find the last 10 _shapes_ records
-
-```go
-q := fmt.Sprintf("SELECT * FROM %s LIMIT %d", MyMeasurement, 10)
-res, err = queryDB(clnt, q)
-if err != nil {
- log.Fatal(err)
-}
-
-for i, row := range res[0].Series[0].Values {
- t, err := time.Parse(time.RFC3339, row[0].(string))
- if err != nil {
- log.Fatal(err)
- }
- val := row[1].(string)
- log.Printf("[%2d] %s: %s\n", i, t.Format(time.Stamp), val)
-}
-```
-
-### Using the UDP Client
-
-The **InfluxDB** client also supports writing over UDP.
-
-```go
-func WriteUDP() {
- // Make client
- c, err := client.NewUDPClient("localhost:8089")
- if err != nil {
- panic(err.Error())
- }
-
- // Create a new point batch
- bp, _ := client.NewBatchPoints(client.BatchPointsConfig{
- Precision: "s",
- })
-
- // Create a point and add to batch
- tags := map[string]string{"cpu": "cpu-total"}
- fields := map[string]interface{}{
- "idle": 10.1,
- "system": 53.3,
- "user": 46.6,
- }
- pt, err := client.NewPoint("cpu_usage", tags, fields, time.Now())
- if err != nil {
- panic(err.Error())
- }
- bp.AddPoint(pt)
-
- // Write the batch
- c.Write(bp)
-}
-```
-
-### Point Splitting
-
-The UDP client now supports splitting single points that exceed the configured
-payload size. The logic for processing each point is listed here, starting with
-an empty payload.
-
-1. If adding the point to the current (non-empty) payload would exceed the
- configured size, send the current payload. Otherwise, add it to the current
- payload.
-1. If the point is smaller than the configured size, add it to the payload.
-1. If the point has no timestamp, just try to send the entire point as a single
- UDP payload, and process the next point.
-1. Since the point has a timestamp, re-use the existing measurement name,
- tagset, and timestamp and create multiple new points by splitting up the
- fields. The per-point length will be kept close to the configured size,
- staying under it if possible. This does mean that one large field, maybe a
- long string, could be sent as a larger-than-configured payload.
-
-The above logic attempts to respect configured payload sizes, but not sacrifice
-any data integrity. Points without a timestamp can't be split, as that may
-cause fields to have differing timestamps when processed by the server.
-
-## Go Docs
-
-Please refer to
-[http://godoc.org/github.com/influxdata/influxdb/client/v2](http://godoc.org/github.com/influxdata/influxdb/client/v2)
-for documentation.
-
-## See Also
-
-You can also examine how the client library is used by the
-[InfluxDB CLI](https://github.com/influxdata/influxdb/blob/master/cmd/influx/main.go).
diff --git a/vendor/github.com/influxdata/influxdb/client/influxdb.go b/vendor/github.com/influxdata/influxdb/client/influxdb.go
deleted file mode 100644
index 98d362d50a..0000000000
--- a/vendor/github.com/influxdata/influxdb/client/influxdb.go
+++ /dev/null
@@ -1,840 +0,0 @@
-// Package client implements a now-deprecated client for InfluxDB;
-// use github.com/influxdata/influxdb/client/v2 instead.
-package client // import "github.com/influxdata/influxdb/client"
-
-import (
- "bytes"
- "context"
- "crypto/tls"
- "encoding/json"
- "errors"
- "fmt"
- "io"
- "io/ioutil"
- "net"
- "net/http"
- "net/url"
- "strconv"
- "strings"
- "time"
-
- "github.com/influxdata/influxdb/models"
-)
-
-const (
- // DefaultHost is the default host used to connect to an InfluxDB instance
- DefaultHost = "localhost"
-
- // DefaultPort is the default port used to connect to an InfluxDB instance
- DefaultPort = 8086
-
- // DefaultTimeout is the default connection timeout used to connect to an InfluxDB instance
- DefaultTimeout = 0
-)
-
-// Query is used to send a command to the server. Both Command and Database are required.
-type Query struct {
- Command string
- Database string
-
- // Chunked tells the server to send back chunked responses. This places
- // less load on the server by sending back chunks of the response rather
- // than waiting for the entire response all at once.
- Chunked bool
-
- // ChunkSize sets the maximum number of rows that will be returned per
- // chunk. Chunks are either divided based on their series or if they hit
- // the chunk size limit.
- //
- // Chunked must be set to true for this option to be used.
- ChunkSize int
-}
-
-// ParseConnectionString will parse a string to create a valid connection URL
-func ParseConnectionString(path string, ssl bool) (url.URL, error) {
- var host string
- var port int
-
- h, p, err := net.SplitHostPort(path)
- if err != nil {
- if path == "" {
- host = DefaultHost
- } else {
- host = path
- }
- // If they didn't specify a port, always use the default port
- port = DefaultPort
- } else {
- host = h
- port, err = strconv.Atoi(p)
- if err != nil {
- return url.URL{}, fmt.Errorf("invalid port number %q: %s\n", path, err)
- }
- }
-
- u := url.URL{
- Scheme: "http",
- }
- if ssl {
- u.Scheme = "https"
- }
-
- u.Host = net.JoinHostPort(host, strconv.Itoa(port))
-
- return u, nil
-}
-
-// Config is used to specify what server to connect to.
-// URL: The URL of the server connecting to.
-// Username/Password are optional. They will be passed via basic auth if provided.
-// UserAgent: If not provided, will default "InfluxDBClient",
-// Timeout: If not provided, will default to 0 (no timeout)
-type Config struct {
- URL url.URL
- UnixSocket string
- Username string
- Password string
- UserAgent string
- Timeout time.Duration
- Precision string
- WriteConsistency string
- UnsafeSsl bool
-}
-
-// NewConfig will create a config to be used in connecting to the client
-func NewConfig() Config {
- return Config{
- Timeout: DefaultTimeout,
- }
-}
-
-// Client is used to make calls to the server.
-type Client struct {
- url url.URL
- unixSocket string
- username string
- password string
- httpClient *http.Client
- userAgent string
- precision string
-}
-
-const (
- // ConsistencyOne requires at least one data node acknowledged a write.
- ConsistencyOne = "one"
-
- // ConsistencyAll requires all data nodes to acknowledge a write.
- ConsistencyAll = "all"
-
- // ConsistencyQuorum requires a quorum of data nodes to acknowledge a write.
- ConsistencyQuorum = "quorum"
-
- // ConsistencyAny allows for hinted hand off, potentially no write happened yet.
- ConsistencyAny = "any"
-)
-
-// NewClient will instantiate and return a connected client to issue commands to the server.
-func NewClient(c Config) (*Client, error) {
- tlsConfig := &tls.Config{
- InsecureSkipVerify: c.UnsafeSsl,
- }
-
- tr := &http.Transport{
- TLSClientConfig: tlsConfig,
- }
-
- if c.UnixSocket != "" {
- // No need for compression in local communications.
- tr.DisableCompression = true
-
- tr.DialContext = func(_ context.Context, _, _ string) (net.Conn, error) {
- return net.Dial("unix", c.UnixSocket)
- }
- }
-
- client := Client{
- url: c.URL,
- unixSocket: c.UnixSocket,
- username: c.Username,
- password: c.Password,
- httpClient: &http.Client{Timeout: c.Timeout, Transport: tr},
- userAgent: c.UserAgent,
- precision: c.Precision,
- }
- if client.userAgent == "" {
- client.userAgent = "InfluxDBClient"
- }
- return &client, nil
-}
-
-// SetAuth will update the username and passwords
-func (c *Client) SetAuth(u, p string) {
- c.username = u
- c.password = p
-}
-
-// SetPrecision will update the precision
-func (c *Client) SetPrecision(precision string) {
- c.precision = precision
-}
-
-// Query sends a command to the server and returns the Response
-func (c *Client) Query(q Query) (*Response, error) {
- return c.QueryContext(context.Background(), q)
-}
-
-// QueryContext sends a command to the server and returns the Response
-// It uses a context that can be cancelled by the command line client
-func (c *Client) QueryContext(ctx context.Context, q Query) (*Response, error) {
- u := c.url
-
- u.Path = "query"
- values := u.Query()
- values.Set("q", q.Command)
- values.Set("db", q.Database)
- if q.Chunked {
- values.Set("chunked", "true")
- if q.ChunkSize > 0 {
- values.Set("chunk_size", strconv.Itoa(q.ChunkSize))
- }
- }
- if c.precision != "" {
- values.Set("epoch", c.precision)
- }
- u.RawQuery = values.Encode()
-
- req, err := http.NewRequest("POST", u.String(), nil)
- if err != nil {
- return nil, err
- }
- req.Header.Set("User-Agent", c.userAgent)
- if c.username != "" {
- req.SetBasicAuth(c.username, c.password)
- }
-
- req = req.WithContext(ctx)
-
- resp, err := c.httpClient.Do(req)
- if err != nil {
- return nil, err
- }
- defer resp.Body.Close()
-
- var response Response
- if q.Chunked {
- cr := NewChunkedResponse(resp.Body)
- for {
- r, err := cr.NextResponse()
- if err != nil {
- // If we got an error while decoding the response, send that back.
- return nil, err
- }
-
- if r == nil {
- break
- }
-
- response.Results = append(response.Results, r.Results...)
- if r.Err != nil {
- response.Err = r.Err
- break
- }
- }
- } else {
- dec := json.NewDecoder(resp.Body)
- dec.UseNumber()
- if err := dec.Decode(&response); err != nil {
- // Ignore EOF errors if we got an invalid status code.
- if !(err == io.EOF && resp.StatusCode != http.StatusOK) {
- return nil, err
- }
- }
- }
-
- // If we don't have an error in our json response, and didn't get StatusOK,
- // then send back an error.
- if resp.StatusCode != http.StatusOK && response.Error() == nil {
- return &response, fmt.Errorf("received status code %d from server", resp.StatusCode)
- }
- return &response, nil
-}
-
-// Write takes BatchPoints and allows for writing of multiple points with defaults
-// If successful, error is nil and Response is nil
-// If an error occurs, Response may contain additional information if populated.
-func (c *Client) Write(bp BatchPoints) (*Response, error) {
- u := c.url
- u.Path = "write"
-
- var b bytes.Buffer
- for _, p := range bp.Points {
- err := checkPointTypes(p)
- if err != nil {
- return nil, err
- }
- if p.Raw != "" {
- if _, err := b.WriteString(p.Raw); err != nil {
- return nil, err
- }
- } else {
- for k, v := range bp.Tags {
- if p.Tags == nil {
- p.Tags = make(map[string]string, len(bp.Tags))
- }
- p.Tags[k] = v
- }
-
- if _, err := b.WriteString(p.MarshalString()); err != nil {
- return nil, err
- }
- }
-
- if err := b.WriteByte('\n'); err != nil {
- return nil, err
- }
- }
-
- req, err := http.NewRequest("POST", u.String(), &b)
- if err != nil {
- return nil, err
- }
- req.Header.Set("Content-Type", "")
- req.Header.Set("User-Agent", c.userAgent)
- if c.username != "" {
- req.SetBasicAuth(c.username, c.password)
- }
-
- precision := bp.Precision
- if precision == "" {
- precision = "ns"
- }
-
- params := req.URL.Query()
- params.Set("db", bp.Database)
- params.Set("rp", bp.RetentionPolicy)
- params.Set("precision", precision)
- params.Set("consistency", bp.WriteConsistency)
- req.URL.RawQuery = params.Encode()
-
- resp, err := c.httpClient.Do(req)
- if err != nil {
- return nil, err
- }
- defer resp.Body.Close()
-
- var response Response
- body, err := ioutil.ReadAll(resp.Body)
- if err != nil {
- return nil, err
- }
-
- if resp.StatusCode != http.StatusNoContent && resp.StatusCode != http.StatusOK {
- var err = fmt.Errorf(string(body))
- response.Err = err
- return &response, err
- }
-
- return nil, nil
-}
-
-// WriteLineProtocol takes a string with line returns to delimit each write
-// If successful, error is nil and Response is nil
-// If an error occurs, Response may contain additional information if populated.
-func (c *Client) WriteLineProtocol(data, database, retentionPolicy, precision, writeConsistency string) (*Response, error) {
- u := c.url
- u.Path = "write"
-
- r := strings.NewReader(data)
-
- req, err := http.NewRequest("POST", u.String(), r)
- if err != nil {
- return nil, err
- }
- req.Header.Set("Content-Type", "")
- req.Header.Set("User-Agent", c.userAgent)
- if c.username != "" {
- req.SetBasicAuth(c.username, c.password)
- }
- params := req.URL.Query()
- params.Set("db", database)
- params.Set("rp", retentionPolicy)
- params.Set("precision", precision)
- params.Set("consistency", writeConsistency)
- req.URL.RawQuery = params.Encode()
-
- resp, err := c.httpClient.Do(req)
- if err != nil {
- return nil, err
- }
- defer resp.Body.Close()
-
- var response Response
- body, err := ioutil.ReadAll(resp.Body)
- if err != nil {
- return nil, err
- }
-
- if resp.StatusCode != http.StatusNoContent && resp.StatusCode != http.StatusOK {
- err := fmt.Errorf(string(body))
- response.Err = err
- return &response, err
- }
-
- return nil, nil
-}
-
-// Ping will check to see if the server is up
-// Ping returns how long the request took, the version of the server it connected to, and an error if one occurred.
-func (c *Client) Ping() (time.Duration, string, error) {
- now := time.Now()
- u := c.url
- u.Path = "ping"
-
- req, err := http.NewRequest("GET", u.String(), nil)
- if err != nil {
- return 0, "", err
- }
- req.Header.Set("User-Agent", c.userAgent)
- if c.username != "" {
- req.SetBasicAuth(c.username, c.password)
- }
-
- resp, err := c.httpClient.Do(req)
- if err != nil {
- return 0, "", err
- }
- defer resp.Body.Close()
-
- version := resp.Header.Get("X-Influxdb-Version")
- return time.Since(now), version, nil
-}
-
-// Structs
-
-// Message represents a user message.
-type Message struct {
- Level string `json:"level,omitempty"`
- Text string `json:"text,omitempty"`
-}
-
-// Result represents a resultset returned from a single statement.
-type Result struct {
- Series []models.Row
- Messages []*Message
- Err error
-}
-
-// MarshalJSON encodes the result into JSON.
-func (r *Result) MarshalJSON() ([]byte, error) {
- // Define a struct that outputs "error" as a string.
- var o struct {
- Series []models.Row `json:"series,omitempty"`
- Messages []*Message `json:"messages,omitempty"`
- Err string `json:"error,omitempty"`
- }
-
- // Copy fields to output struct.
- o.Series = r.Series
- o.Messages = r.Messages
- if r.Err != nil {
- o.Err = r.Err.Error()
- }
-
- return json.Marshal(&o)
-}
-
-// UnmarshalJSON decodes the data into the Result struct
-func (r *Result) UnmarshalJSON(b []byte) error {
- var o struct {
- Series []models.Row `json:"series,omitempty"`
- Messages []*Message `json:"messages,omitempty"`
- Err string `json:"error,omitempty"`
- }
-
- dec := json.NewDecoder(bytes.NewBuffer(b))
- dec.UseNumber()
- err := dec.Decode(&o)
- if err != nil {
- return err
- }
- r.Series = o.Series
- r.Messages = o.Messages
- if o.Err != "" {
- r.Err = errors.New(o.Err)
- }
- return nil
-}
-
-// Response represents a list of statement results.
-type Response struct {
- Results []Result
- Err error
-}
-
-// MarshalJSON encodes the response into JSON.
-func (r *Response) MarshalJSON() ([]byte, error) {
- // Define a struct that outputs "error" as a string.
- var o struct {
- Results []Result `json:"results,omitempty"`
- Err string `json:"error,omitempty"`
- }
-
- // Copy fields to output struct.
- o.Results = r.Results
- if r.Err != nil {
- o.Err = r.Err.Error()
- }
-
- return json.Marshal(&o)
-}
-
-// UnmarshalJSON decodes the data into the Response struct
-func (r *Response) UnmarshalJSON(b []byte) error {
- var o struct {
- Results []Result `json:"results,omitempty"`
- Err string `json:"error,omitempty"`
- }
-
- dec := json.NewDecoder(bytes.NewBuffer(b))
- dec.UseNumber()
- err := dec.Decode(&o)
- if err != nil {
- return err
- }
- r.Results = o.Results
- if o.Err != "" {
- r.Err = errors.New(o.Err)
- }
- return nil
-}
-
-// Error returns the first error from any statement.
-// Returns nil if no errors occurred on any statements.
-func (r *Response) Error() error {
- if r.Err != nil {
- return r.Err
- }
- for _, result := range r.Results {
- if result.Err != nil {
- return result.Err
- }
- }
- return nil
-}
-
-// duplexReader reads responses and writes it to another writer while
-// satisfying the reader interface.
-type duplexReader struct {
- r io.Reader
- w io.Writer
-}
-
-func (r *duplexReader) Read(p []byte) (n int, err error) {
- n, err = r.r.Read(p)
- if err == nil {
- r.w.Write(p[:n])
- }
- return n, err
-}
-
-// ChunkedResponse represents a response from the server that
-// uses chunking to stream the output.
-type ChunkedResponse struct {
- dec *json.Decoder
- duplex *duplexReader
- buf bytes.Buffer
-}
-
-// NewChunkedResponse reads a stream and produces responses from the stream.
-func NewChunkedResponse(r io.Reader) *ChunkedResponse {
- resp := &ChunkedResponse{}
- resp.duplex = &duplexReader{r: r, w: &resp.buf}
- resp.dec = json.NewDecoder(resp.duplex)
- resp.dec.UseNumber()
- return resp
-}
-
-// NextResponse reads the next line of the stream and returns a response.
-func (r *ChunkedResponse) NextResponse() (*Response, error) {
- var response Response
- if err := r.dec.Decode(&response); err != nil {
- if err == io.EOF {
- return nil, nil
- }
- // A decoding error happened. This probably means the server crashed
- // and sent a last-ditch error message to us. Ensure we have read the
- // entirety of the connection to get any remaining error text.
- io.Copy(ioutil.Discard, r.duplex)
- return nil, errors.New(strings.TrimSpace(r.buf.String()))
- }
- r.buf.Reset()
- return &response, nil
-}
-
-// Point defines the fields that will be written to the database
-// Measurement, Time, and Fields are required
-// Precision can be specified if the time is in epoch format (integer).
-// Valid values for Precision are n, u, ms, s, m, and h
-type Point struct {
- Measurement string
- Tags map[string]string
- Time time.Time
- Fields map[string]interface{}
- Precision string
- Raw string
-}
-
-// MarshalJSON will format the time in RFC3339Nano
-// Precision is also ignored as it is only used for writing, not reading
-// Or another way to say it is we always send back in nanosecond precision
-func (p *Point) MarshalJSON() ([]byte, error) {
- point := struct {
- Measurement string `json:"measurement,omitempty"`
- Tags map[string]string `json:"tags,omitempty"`
- Time string `json:"time,omitempty"`
- Fields map[string]interface{} `json:"fields,omitempty"`
- Precision string `json:"precision,omitempty"`
- }{
- Measurement: p.Measurement,
- Tags: p.Tags,
- Fields: p.Fields,
- Precision: p.Precision,
- }
- // Let it omit empty if it's really zero
- if !p.Time.IsZero() {
- point.Time = p.Time.UTC().Format(time.RFC3339Nano)
- }
- return json.Marshal(&point)
-}
-
-// MarshalString renders string representation of a Point with specified
-// precision. The default precision is nanoseconds.
-func (p *Point) MarshalString() string {
- pt, err := models.NewPoint(p.Measurement, models.NewTags(p.Tags), p.Fields, p.Time)
- if err != nil {
- return "# ERROR: " + err.Error() + " " + p.Measurement
- }
- if p.Precision == "" || p.Precision == "ns" || p.Precision == "n" {
- return pt.String()
- }
- return pt.PrecisionString(p.Precision)
-}
-
-// UnmarshalJSON decodes the data into the Point struct
-func (p *Point) UnmarshalJSON(b []byte) error {
- var normal struct {
- Measurement string `json:"measurement"`
- Tags map[string]string `json:"tags"`
- Time time.Time `json:"time"`
- Precision string `json:"precision"`
- Fields map[string]interface{} `json:"fields"`
- }
- var epoch struct {
- Measurement string `json:"measurement"`
- Tags map[string]string `json:"tags"`
- Time *int64 `json:"time"`
- Precision string `json:"precision"`
- Fields map[string]interface{} `json:"fields"`
- }
-
- if err := func() error {
- var err error
- dec := json.NewDecoder(bytes.NewBuffer(b))
- dec.UseNumber()
- if err = dec.Decode(&epoch); err != nil {
- return err
- }
- // Convert from epoch to time.Time, but only if Time
- // was actually set.
- var ts time.Time
- if epoch.Time != nil {
- ts, err = EpochToTime(*epoch.Time, epoch.Precision)
- if err != nil {
- return err
- }
- }
- p.Measurement = epoch.Measurement
- p.Tags = epoch.Tags
- p.Time = ts
- p.Precision = epoch.Precision
- p.Fields = normalizeFields(epoch.Fields)
- return nil
- }(); err == nil {
- return nil
- }
-
- dec := json.NewDecoder(bytes.NewBuffer(b))
- dec.UseNumber()
- if err := dec.Decode(&normal); err != nil {
- return err
- }
- normal.Time = SetPrecision(normal.Time, normal.Precision)
- p.Measurement = normal.Measurement
- p.Tags = normal.Tags
- p.Time = normal.Time
- p.Precision = normal.Precision
- p.Fields = normalizeFields(normal.Fields)
-
- return nil
-}
-
-// Remove any notion of json.Number
-func normalizeFields(fields map[string]interface{}) map[string]interface{} {
- newFields := map[string]interface{}{}
-
- for k, v := range fields {
- switch v := v.(type) {
- case json.Number:
- jv, e := v.Float64()
- if e != nil {
- panic(fmt.Sprintf("unable to convert json.Number to float64: %s", e))
- }
- newFields[k] = jv
- default:
- newFields[k] = v
- }
- }
- return newFields
-}
-
-// BatchPoints is used to send batched data in a single write.
-// Database and Points are required
-// If no retention policy is specified, it will use the databases default retention policy.
-// If tags are specified, they will be "merged" with all points. If a point already has that tag, it will be ignored.
-// If time is specified, it will be applied to any point with an empty time.
-// Precision can be specified if the time is in epoch format (integer).
-// Valid values for Precision are n, u, ms, s, m, and h
-type BatchPoints struct {
- Points []Point `json:"points,omitempty"`
- Database string `json:"database,omitempty"`
- RetentionPolicy string `json:"retentionPolicy,omitempty"`
- Tags map[string]string `json:"tags,omitempty"`
- Time time.Time `json:"time,omitempty"`
- Precision string `json:"precision,omitempty"`
- WriteConsistency string `json:"-"`
-}
-
-// UnmarshalJSON decodes the data into the BatchPoints struct
-func (bp *BatchPoints) UnmarshalJSON(b []byte) error {
- var normal struct {
- Points []Point `json:"points"`
- Database string `json:"database"`
- RetentionPolicy string `json:"retentionPolicy"`
- Tags map[string]string `json:"tags"`
- Time time.Time `json:"time"`
- Precision string `json:"precision"`
- }
- var epoch struct {
- Points []Point `json:"points"`
- Database string `json:"database"`
- RetentionPolicy string `json:"retentionPolicy"`
- Tags map[string]string `json:"tags"`
- Time *int64 `json:"time"`
- Precision string `json:"precision"`
- }
-
- if err := func() error {
- var err error
- if err = json.Unmarshal(b, &epoch); err != nil {
- return err
- }
- // Convert from epoch to time.Time
- var ts time.Time
- if epoch.Time != nil {
- ts, err = EpochToTime(*epoch.Time, epoch.Precision)
- if err != nil {
- return err
- }
- }
- bp.Points = epoch.Points
- bp.Database = epoch.Database
- bp.RetentionPolicy = epoch.RetentionPolicy
- bp.Tags = epoch.Tags
- bp.Time = ts
- bp.Precision = epoch.Precision
- return nil
- }(); err == nil {
- return nil
- }
-
- if err := json.Unmarshal(b, &normal); err != nil {
- return err
- }
- normal.Time = SetPrecision(normal.Time, normal.Precision)
- bp.Points = normal.Points
- bp.Database = normal.Database
- bp.RetentionPolicy = normal.RetentionPolicy
- bp.Tags = normal.Tags
- bp.Time = normal.Time
- bp.Precision = normal.Precision
-
- return nil
-}
-
-// utility functions
-
-// Addr provides the current url as a string of the server the client is connected to.
-func (c *Client) Addr() string {
- if c.unixSocket != "" {
- return c.unixSocket
- }
- return c.url.String()
-}
-
-// checkPointTypes ensures no unsupported types are submitted to influxdb, returning error if they are found.
-func checkPointTypes(p Point) error {
- for _, v := range p.Fields {
- switch v.(type) {
- case int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, float32, float64, bool, string, nil:
- return nil
- default:
- return fmt.Errorf("unsupported point type: %T", v)
- }
- }
- return nil
-}
-
-// helper functions
-
-// EpochToTime takes a unix epoch time and uses precision to return back a time.Time
-func EpochToTime(epoch int64, precision string) (time.Time, error) {
- if precision == "" {
- precision = "s"
- }
- var t time.Time
- switch precision {
- case "h":
- t = time.Unix(0, epoch*int64(time.Hour))
- case "m":
- t = time.Unix(0, epoch*int64(time.Minute))
- case "s":
- t = time.Unix(0, epoch*int64(time.Second))
- case "ms":
- t = time.Unix(0, epoch*int64(time.Millisecond))
- case "u":
- t = time.Unix(0, epoch*int64(time.Microsecond))
- case "n":
- t = time.Unix(0, epoch)
- default:
- return time.Time{}, fmt.Errorf("Unknown precision %q", precision)
- }
- return t, nil
-}
-
-// SetPrecision will round a time to the specified precision
-func SetPrecision(t time.Time, precision string) time.Time {
- switch precision {
- case "n":
- case "u":
- return t.Round(time.Microsecond)
- case "ms":
- return t.Round(time.Millisecond)
- case "s":
- return t.Round(time.Second)
- case "m":
- return t.Round(time.Minute)
- case "h":
- return t.Round(time.Hour)
- }
- return t
-}
diff --git a/vendor/github.com/influxdata/influxdb/models/consistency.go b/vendor/github.com/influxdata/influxdb/models/consistency.go
deleted file mode 100644
index 2a3269bca1..0000000000
--- a/vendor/github.com/influxdata/influxdb/models/consistency.go
+++ /dev/null
@@ -1,48 +0,0 @@
-package models
-
-import (
- "errors"
- "strings"
-)
-
-// ConsistencyLevel represent a required replication criteria before a write can
-// be returned as successful.
-//
-// The consistency level is handled in open-source InfluxDB but only applicable to clusters.
-type ConsistencyLevel int
-
-const (
- // ConsistencyLevelAny allows for hinted handoff, potentially no write happened yet.
- ConsistencyLevelAny ConsistencyLevel = iota
-
- // ConsistencyLevelOne requires at least one data node acknowledged a write.
- ConsistencyLevelOne
-
- // ConsistencyLevelQuorum requires a quorum of data nodes to acknowledge a write.
- ConsistencyLevelQuorum
-
- // ConsistencyLevelAll requires all data nodes to acknowledge a write.
- ConsistencyLevelAll
-)
-
-var (
- // ErrInvalidConsistencyLevel is returned when parsing the string version
- // of a consistency level.
- ErrInvalidConsistencyLevel = errors.New("invalid consistency level")
-)
-
-// ParseConsistencyLevel converts a consistency level string to the corresponding ConsistencyLevel const.
-func ParseConsistencyLevel(level string) (ConsistencyLevel, error) {
- switch strings.ToLower(level) {
- case "any":
- return ConsistencyLevelAny, nil
- case "one":
- return ConsistencyLevelOne, nil
- case "quorum":
- return ConsistencyLevelQuorum, nil
- case "all":
- return ConsistencyLevelAll, nil
- default:
- return 0, ErrInvalidConsistencyLevel
- }
-}
diff --git a/vendor/github.com/influxdata/influxdb/models/inline_fnv.go b/vendor/github.com/influxdata/influxdb/models/inline_fnv.go
deleted file mode 100644
index eec1ae8b01..0000000000
--- a/vendor/github.com/influxdata/influxdb/models/inline_fnv.go
+++ /dev/null
@@ -1,32 +0,0 @@
-package models // import "github.com/influxdata/influxdb/models"
-
-// from stdlib hash/fnv/fnv.go
-const (
- prime64 = 1099511628211
- offset64 = 14695981039346656037
-)
-
-// InlineFNV64a is an alloc-free port of the standard library's fnv64a.
-// See https://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function.
-type InlineFNV64a uint64
-
-// NewInlineFNV64a returns a new instance of InlineFNV64a.
-func NewInlineFNV64a() InlineFNV64a {
- return offset64
-}
-
-// Write adds data to the running hash.
-func (s *InlineFNV64a) Write(data []byte) (int, error) {
- hash := uint64(*s)
- for _, c := range data {
- hash ^= uint64(c)
- hash *= prime64
- }
- *s = InlineFNV64a(hash)
- return len(data), nil
-}
-
-// Sum64 returns the uint64 of the current resulting hash.
-func (s *InlineFNV64a) Sum64() uint64 {
- return uint64(*s)
-}
diff --git a/vendor/github.com/influxdata/influxdb/models/inline_strconv_parse.go b/vendor/github.com/influxdata/influxdb/models/inline_strconv_parse.go
deleted file mode 100644
index 8db4837384..0000000000
--- a/vendor/github.com/influxdata/influxdb/models/inline_strconv_parse.go
+++ /dev/null
@@ -1,44 +0,0 @@
-package models // import "github.com/influxdata/influxdb/models"
-
-import (
- "reflect"
- "strconv"
- "unsafe"
-)
-
-// parseIntBytes is a zero-alloc wrapper around strconv.ParseInt.
-func parseIntBytes(b []byte, base int, bitSize int) (i int64, err error) {
- s := unsafeBytesToString(b)
- return strconv.ParseInt(s, base, bitSize)
-}
-
-// parseUintBytes is a zero-alloc wrapper around strconv.ParseUint.
-func parseUintBytes(b []byte, base int, bitSize int) (i uint64, err error) {
- s := unsafeBytesToString(b)
- return strconv.ParseUint(s, base, bitSize)
-}
-
-// parseFloatBytes is a zero-alloc wrapper around strconv.ParseFloat.
-func parseFloatBytes(b []byte, bitSize int) (float64, error) {
- s := unsafeBytesToString(b)
- return strconv.ParseFloat(s, bitSize)
-}
-
-// parseBoolBytes is a zero-alloc wrapper around strconv.ParseBool.
-func parseBoolBytes(b []byte) (bool, error) {
- return strconv.ParseBool(unsafeBytesToString(b))
-}
-
-// unsafeBytesToString converts a []byte to a string without a heap allocation.
-//
-// It is unsafe, and is intended to prepare input to short-lived functions
-// that require strings.
-func unsafeBytesToString(in []byte) string {
- src := *(*reflect.SliceHeader)(unsafe.Pointer(&in))
- dst := reflect.StringHeader{
- Data: src.Data,
- Len: src.Len,
- }
- s := *(*string)(unsafe.Pointer(&dst))
- return s
-}
diff --git a/vendor/github.com/influxdata/influxdb/models/points.go b/vendor/github.com/influxdata/influxdb/models/points.go
deleted file mode 100644
index ad80a816bf..0000000000
--- a/vendor/github.com/influxdata/influxdb/models/points.go
+++ /dev/null
@@ -1,2337 +0,0 @@
-// Package models implements basic objects used throughout the TICK stack.
-package models // import "github.com/influxdata/influxdb/models"
-
-import (
- "bytes"
- "encoding/binary"
- "errors"
- "fmt"
- "io"
- "math"
- "sort"
- "strconv"
- "strings"
- "time"
-
- "github.com/influxdata/influxdb/pkg/escape"
-)
-
-var (
- measurementEscapeCodes = map[byte][]byte{
- ',': []byte(`\,`),
- ' ': []byte(`\ `),
- }
-
- tagEscapeCodes = map[byte][]byte{
- ',': []byte(`\,`),
- ' ': []byte(`\ `),
- '=': []byte(`\=`),
- }
-
- // ErrPointMustHaveAField is returned when operating on a point that does not have any fields.
- ErrPointMustHaveAField = errors.New("point without fields is unsupported")
-
- // ErrInvalidNumber is returned when a number is expected but not provided.
- ErrInvalidNumber = errors.New("invalid number")
-
- // ErrInvalidPoint is returned when a point cannot be parsed correctly.
- ErrInvalidPoint = errors.New("point is invalid")
-)
-
-const (
- // MaxKeyLength is the largest allowed size of the combined measurement and tag keys.
- MaxKeyLength = 65535
-)
-
-// enableUint64Support will enable uint64 support if set to true.
-var enableUint64Support = false
-
-// EnableUintSupport manually enables uint support for the point parser.
-// This function will be removed in the future and only exists for unit tests during the
-// transition.
-func EnableUintSupport() {
- enableUint64Support = true
-}
-
-// Point defines the values that will be written to the database.
-type Point interface {
- // Name return the measurement name for the point.
- Name() []byte
-
- // SetName updates the measurement name for the point.
- SetName(string)
-
- // Tags returns the tag set for the point.
- Tags() Tags
-
- // AddTag adds or replaces a tag value for a point.
- AddTag(key, value string)
-
- // SetTags replaces the tags for the point.
- SetTags(tags Tags)
-
- // HasTag returns true if the tag exists for the point.
- HasTag(tag []byte) bool
-
- // Fields returns the fields for the point.
- Fields() (Fields, error)
-
- // Time return the timestamp for the point.
- Time() time.Time
-
- // SetTime updates the timestamp for the point.
- SetTime(t time.Time)
-
- // UnixNano returns the timestamp of the point as nanoseconds since Unix epoch.
- UnixNano() int64
-
- // HashID returns a non-cryptographic checksum of the point's key.
- HashID() uint64
-
- // Key returns the key (measurement joined with tags) of the point.
- Key() []byte
-
- // String returns a string representation of the point. If there is a
- // timestamp associated with the point then it will be specified with the default
- // precision of nanoseconds.
- String() string
-
- // MarshalBinary returns a binary representation of the point.
- MarshalBinary() ([]byte, error)
-
- // PrecisionString returns a string representation of the point. If there
- // is a timestamp associated with the point then it will be specified in the
- // given unit.
- PrecisionString(precision string) string
-
- // RoundedString returns a string representation of the point. If there
- // is a timestamp associated with the point, then it will be rounded to the
- // given duration.
- RoundedString(d time.Duration) string
-
- // Split will attempt to return multiple points with the same timestamp whose
- // string representations are no longer than size. Points with a single field or
- // a point without a timestamp may exceed the requested size.
- Split(size int) []Point
-
- // Round will round the timestamp of the point to the given duration.
- Round(d time.Duration)
-
- // StringSize returns the length of the string that would be returned by String().
- StringSize() int
-
- // AppendString appends the result of String() to the provided buffer and returns
- // the result, potentially reducing string allocations.
- AppendString(buf []byte) []byte
-
- // FieldIterator retuns a FieldIterator that can be used to traverse the
- // fields of a point without constructing the in-memory map.
- FieldIterator() FieldIterator
-}
-
-// FieldType represents the type of a field.
-type FieldType int
-
-const (
- // Integer indicates the field's type is integer.
- Integer FieldType = iota
-
- // Float indicates the field's type is float.
- Float
-
- // Boolean indicates the field's type is boolean.
- Boolean
-
- // String indicates the field's type is string.
- String
-
- // Empty is used to indicate that there is no field.
- Empty
-
- // Unsigned indicates the field's type is an unsigned integer.
- Unsigned
-)
-
-// FieldIterator provides a low-allocation interface to iterate through a point's fields.
-type FieldIterator interface {
- // Next indicates whether there any fields remaining.
- Next() bool
-
- // FieldKey returns the key of the current field.
- FieldKey() []byte
-
- // Type returns the FieldType of the current field.
- Type() FieldType
-
- // StringValue returns the string value of the current field.
- StringValue() string
-
- // IntegerValue returns the integer value of the current field.
- IntegerValue() (int64, error)
-
- // UnsignedValue returns the unsigned value of the current field.
- UnsignedValue() (uint64, error)
-
- // BooleanValue returns the boolean value of the current field.
- BooleanValue() (bool, error)
-
- // FloatValue returns the float value of the current field.
- FloatValue() (float64, error)
-
- // Reset resets the iterator to its initial state.
- Reset()
-}
-
-// Points represents a sortable list of points by timestamp.
-type Points []Point
-
-// Len implements sort.Interface.
-func (a Points) Len() int { return len(a) }
-
-// Less implements sort.Interface.
-func (a Points) Less(i, j int) bool { return a[i].Time().Before(a[j].Time()) }
-
-// Swap implements sort.Interface.
-func (a Points) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
-
-// point is the default implementation of Point.
-type point struct {
- time time.Time
-
- // text encoding of measurement and tags
- // key must always be stored sorted by tags, if the original line was not sorted,
- // we need to resort it
- key []byte
-
- // text encoding of field data
- fields []byte
-
- // text encoding of timestamp
- ts []byte
-
- // cached version of parsed fields from data
- cachedFields map[string]interface{}
-
- // cached version of parsed name from key
- cachedName string
-
- // cached version of parsed tags
- cachedTags Tags
-
- it fieldIterator
-}
-
-// type assertions
-var (
- _ Point = (*point)(nil)
- _ FieldIterator = (*point)(nil)
-)
-
-const (
- // the number of characters for the largest possible int64 (9223372036854775807)
- maxInt64Digits = 19
-
- // the number of characters for the smallest possible int64 (-9223372036854775808)
- minInt64Digits = 20
-
- // the number of characters for the largest possible uint64 (18446744073709551615)
- maxUint64Digits = 20
-
- // the number of characters required for the largest float64 before a range check
- // would occur during parsing
- maxFloat64Digits = 25
-
- // the number of characters required for smallest float64 before a range check occur
- // would occur during parsing
- minFloat64Digits = 27
-)
-
-// ParsePoints returns a slice of Points from a text representation of a point
-// with each point separated by newlines. If any points fail to parse, a non-nil error
-// will be returned in addition to the points that parsed successfully.
-func ParsePoints(buf []byte) ([]Point, error) {
- return ParsePointsWithPrecision(buf, time.Now().UTC(), "n")
-}
-
-// ParsePointsString is identical to ParsePoints but accepts a string.
-func ParsePointsString(buf string) ([]Point, error) {
- return ParsePoints([]byte(buf))
-}
-
-// ParseKey returns the measurement name and tags from a point.
-//
-// NOTE: to minimize heap allocations, the returned Tags will refer to subslices of buf.
-// This can have the unintended effect preventing buf from being garbage collected.
-func ParseKey(buf []byte) (string, Tags) {
- meas, tags := ParseKeyBytes(buf)
- return string(meas), tags
-}
-
-func ParseKeyBytes(buf []byte) ([]byte, Tags) {
- // Ignore the error because scanMeasurement returns "missing fields" which we ignore
- // when just parsing a key
- state, i, _ := scanMeasurement(buf, 0)
-
- var tags Tags
- if state == tagKeyState {
- tags = parseTags(buf)
- // scanMeasurement returns the location of the comma if there are tags, strip that off
- return buf[:i-1], tags
- }
- return buf[:i], tags
-}
-
-func ParseTags(buf []byte) Tags {
- return parseTags(buf)
-}
-
-func ParseName(buf []byte) ([]byte, error) {
- // Ignore the error because scanMeasurement returns "missing fields" which we ignore
- // when just parsing a key
- state, i, _ := scanMeasurement(buf, 0)
- if state == tagKeyState {
- return buf[:i-1], nil
- }
- return buf[:i], nil
-}
-
-// ParsePointsWithPrecision is similar to ParsePoints, but allows the
-// caller to provide a precision for time.
-//
-// NOTE: to minimize heap allocations, the returned Points will refer to subslices of buf.
-// This can have the unintended effect preventing buf from being garbage collected.
-func ParsePointsWithPrecision(buf []byte, defaultTime time.Time, precision string) ([]Point, error) {
- points := make([]Point, 0, bytes.Count(buf, []byte{'\n'})+1)
- var (
- pos int
- block []byte
- failed []string
- )
- for pos < len(buf) {
- pos, block = scanLine(buf, pos)
- pos++
-
- if len(block) == 0 {
- continue
- }
-
- // lines which start with '#' are comments
- start := skipWhitespace(block, 0)
-
- // If line is all whitespace, just skip it
- if start >= len(block) {
- continue
- }
-
- if block[start] == '#' {
- continue
- }
-
- // strip the newline if one is present
- if block[len(block)-1] == '\n' {
- block = block[:len(block)-1]
- }
-
- pt, err := parsePoint(block[start:], defaultTime, precision)
- if err != nil {
- failed = append(failed, fmt.Sprintf("unable to parse '%s': %v", string(block[start:]), err))
- } else {
- points = append(points, pt)
- }
-
- }
- if len(failed) > 0 {
- return points, fmt.Errorf("%s", strings.Join(failed, "\n"))
- }
- return points, nil
-
-}
-
-func parsePoint(buf []byte, defaultTime time.Time, precision string) (Point, error) {
- // scan the first block which is measurement[,tag1=value1,tag2=value=2...]
- pos, key, err := scanKey(buf, 0)
- if err != nil {
- return nil, err
- }
-
- // measurement name is required
- if len(key) == 0 {
- return nil, fmt.Errorf("missing measurement")
- }
-
- if len(key) > MaxKeyLength {
- return nil, fmt.Errorf("max key length exceeded: %v > %v", len(key), MaxKeyLength)
- }
-
- // scan the second block is which is field1=value1[,field2=value2,...]
- pos, fields, err := scanFields(buf, pos)
- if err != nil {
- return nil, err
- }
-
- // at least one field is required
- if len(fields) == 0 {
- return nil, fmt.Errorf("missing fields")
- }
-
- var maxKeyErr error
- walkFields(fields, func(k, v []byte) bool {
- if sz := seriesKeySize(key, k); sz > MaxKeyLength {
- maxKeyErr = fmt.Errorf("max key length exceeded: %v > %v", sz, MaxKeyLength)
- return false
- }
- return true
- })
-
- if maxKeyErr != nil {
- return nil, maxKeyErr
- }
-
- // scan the last block which is an optional integer timestamp
- pos, ts, err := scanTime(buf, pos)
- if err != nil {
- return nil, err
- }
-
- pt := &point{
- key: key,
- fields: fields,
- ts: ts,
- }
-
- if len(ts) == 0 {
- pt.time = defaultTime
- pt.SetPrecision(precision)
- } else {
- ts, err := parseIntBytes(ts, 10, 64)
- if err != nil {
- return nil, err
- }
- pt.time, err = SafeCalcTime(ts, precision)
- if err != nil {
- return nil, err
- }
-
- // Determine if there are illegal non-whitespace characters after the
- // timestamp block.
- for pos < len(buf) {
- if buf[pos] != ' ' {
- return nil, ErrInvalidPoint
- }
- pos++
- }
- }
- return pt, nil
-}
-
-// GetPrecisionMultiplier will return a multiplier for the precision specified.
-func GetPrecisionMultiplier(precision string) int64 {
- d := time.Nanosecond
- switch precision {
- case "u":
- d = time.Microsecond
- case "ms":
- d = time.Millisecond
- case "s":
- d = time.Second
- case "m":
- d = time.Minute
- case "h":
- d = time.Hour
- }
- return int64(d)
-}
-
-// scanKey scans buf starting at i for the measurement and tag portion of the point.
-// It returns the ending position and the byte slice of key within buf. If there
-// are tags, they will be sorted if they are not already.
-func scanKey(buf []byte, i int) (int, []byte, error) {
- start := skipWhitespace(buf, i)
-
- i = start
-
- // Determines whether the tags are sort, assume they are
- sorted := true
-
- // indices holds the indexes within buf of the start of each tag. For example,
- // a buf of 'cpu,host=a,region=b,zone=c' would have indices slice of [4,11,20]
- // which indicates that the first tag starts at buf[4], seconds at buf[11], and
- // last at buf[20]
- indices := make([]int, 100)
-
- // tracks how many commas we've seen so we know how many values are indices.
- // Since indices is an arbitrarily large slice,
- // we need to know how many values in the buffer are in use.
- commas := 0
-
- // First scan the Point's measurement.
- state, i, err := scanMeasurement(buf, i)
- if err != nil {
- return i, buf[start:i], err
- }
-
- // Optionally scan tags if needed.
- if state == tagKeyState {
- i, commas, indices, err = scanTags(buf, i, indices)
- if err != nil {
- return i, buf[start:i], err
- }
- }
-
- // Now we know where the key region is within buf, and the location of tags, we
- // need to determine if duplicate tags exist and if the tags are sorted. This iterates
- // over the list comparing each tag in the sequence with each other.
- for j := 0; j < commas-1; j++ {
- // get the left and right tags
- _, left := scanTo(buf[indices[j]:indices[j+1]-1], 0, '=')
- _, right := scanTo(buf[indices[j+1]:indices[j+2]-1], 0, '=')
-
- // If left is greater than right, the tags are not sorted. We do not have to
- // continue because the short path no longer works.
- // If the tags are equal, then there are duplicate tags, and we should abort.
- // If the tags are not sorted, this pass may not find duplicate tags and we
- // need to do a more exhaustive search later.
- if cmp := bytes.Compare(left, right); cmp > 0 {
- sorted = false
- break
- } else if cmp == 0 {
- return i, buf[start:i], fmt.Errorf("duplicate tags")
- }
- }
-
- // If the tags are not sorted, then sort them. This sort is inline and
- // uses the tag indices we created earlier. The actual buffer is not sorted, the
- // indices are using the buffer for value comparison. After the indices are sorted,
- // the buffer is reconstructed from the sorted indices.
- if !sorted && commas > 0 {
- // Get the measurement name for later
- measurement := buf[start : indices[0]-1]
-
- // Sort the indices
- indices := indices[:commas]
- insertionSort(0, commas, buf, indices)
-
- // Create a new key using the measurement and sorted indices
- b := make([]byte, len(buf[start:i]))
- pos := copy(b, measurement)
- for _, i := range indices {
- b[pos] = ','
- pos++
- _, v := scanToSpaceOr(buf, i, ',')
- pos += copy(b[pos:], v)
- }
-
- // Check again for duplicate tags now that the tags are sorted.
- for j := 0; j < commas-1; j++ {
- // get the left and right tags
- _, left := scanTo(buf[indices[j]:], 0, '=')
- _, right := scanTo(buf[indices[j+1]:], 0, '=')
-
- // If the tags are equal, then there are duplicate tags, and we should abort.
- // If the tags are not sorted, this pass may not find duplicate tags and we
- // need to do a more exhaustive search later.
- if bytes.Equal(left, right) {
- return i, b, fmt.Errorf("duplicate tags")
- }
- }
-
- return i, b, nil
- }
-
- return i, buf[start:i], nil
-}
-
-// The following constants allow us to specify which state to move to
-// next, when scanning sections of a Point.
-const (
- tagKeyState = iota
- tagValueState
- fieldsState
-)
-
-// scanMeasurement examines the measurement part of a Point, returning
-// the next state to move to, and the current location in the buffer.
-func scanMeasurement(buf []byte, i int) (int, int, error) {
- // Check first byte of measurement, anything except a comma is fine.
- // It can't be a space, since whitespace is stripped prior to this
- // function call.
- if i >= len(buf) || buf[i] == ',' {
- return -1, i, fmt.Errorf("missing measurement")
- }
-
- for {
- i++
- if i >= len(buf) {
- // cpu
- return -1, i, fmt.Errorf("missing fields")
- }
-
- if buf[i-1] == '\\' {
- // Skip character (it's escaped).
- continue
- }
-
- // Unescaped comma; move onto scanning the tags.
- if buf[i] == ',' {
- return tagKeyState, i + 1, nil
- }
-
- // Unescaped space; move onto scanning the fields.
- if buf[i] == ' ' {
- // cpu value=1.0
- return fieldsState, i, nil
- }
- }
-}
-
-// scanTags examines all the tags in a Point, keeping track of and
-// returning the updated indices slice, number of commas and location
-// in buf where to start examining the Point fields.
-func scanTags(buf []byte, i int, indices []int) (int, int, []int, error) {
- var (
- err error
- commas int
- state = tagKeyState
- )
-
- for {
- switch state {
- case tagKeyState:
- // Grow our indices slice if we have too many tags.
- if commas >= len(indices) {
- newIndics := make([]int, cap(indices)*2)
- copy(newIndics, indices)
- indices = newIndics
- }
- indices[commas] = i
- commas++
-
- i, err = scanTagsKey(buf, i)
- state = tagValueState // tag value always follows a tag key
- case tagValueState:
- state, i, err = scanTagsValue(buf, i)
- case fieldsState:
- indices[commas] = i + 1
- return i, commas, indices, nil
- }
-
- if err != nil {
- return i, commas, indices, err
- }
- }
-}
-
-// scanTagsKey scans each character in a tag key.
-func scanTagsKey(buf []byte, i int) (int, error) {
- // First character of the key.
- if i >= len(buf) || buf[i] == ' ' || buf[i] == ',' || buf[i] == '=' {
- // cpu,{'', ' ', ',', '='}
- return i, fmt.Errorf("missing tag key")
- }
-
- // Examine each character in the tag key until we hit an unescaped
- // equals (the tag value), or we hit an error (i.e., unescaped
- // space or comma).
- for {
- i++
-
- // Either we reached the end of the buffer or we hit an
- // unescaped comma or space.
- if i >= len(buf) ||
- ((buf[i] == ' ' || buf[i] == ',') && buf[i-1] != '\\') {
- // cpu,tag{'', ' ', ','}
- return i, fmt.Errorf("missing tag value")
- }
-
- if buf[i] == '=' && buf[i-1] != '\\' {
- // cpu,tag=
- return i + 1, nil
- }
- }
-}
-
-// scanTagsValue scans each character in a tag value.
-func scanTagsValue(buf []byte, i int) (int, int, error) {
- // Tag value cannot be empty.
- if i >= len(buf) || buf[i] == ',' || buf[i] == ' ' {
- // cpu,tag={',', ' '}
- return -1, i, fmt.Errorf("missing tag value")
- }
-
- // Examine each character in the tag value until we hit an unescaped
- // comma (move onto next tag key), an unescaped space (move onto
- // fields), or we error out.
- for {
- i++
- if i >= len(buf) {
- // cpu,tag=value
- return -1, i, fmt.Errorf("missing fields")
- }
-
- // An unescaped equals sign is an invalid tag value.
- if buf[i] == '=' && buf[i-1] != '\\' {
- // cpu,tag={'=', 'fo=o'}
- return -1, i, fmt.Errorf("invalid tag format")
- }
-
- if buf[i] == ',' && buf[i-1] != '\\' {
- // cpu,tag=foo,
- return tagKeyState, i + 1, nil
- }
-
- // cpu,tag=foo value=1.0
- // cpu, tag=foo\= value=1.0
- if buf[i] == ' ' && buf[i-1] != '\\' {
- return fieldsState, i, nil
- }
- }
-}
-
-func insertionSort(l, r int, buf []byte, indices []int) {
- for i := l + 1; i < r; i++ {
- for j := i; j > l && less(buf, indices, j, j-1); j-- {
- indices[j], indices[j-1] = indices[j-1], indices[j]
- }
- }
-}
-
-func less(buf []byte, indices []int, i, j int) bool {
- // This grabs the tag names for i & j, it ignores the values
- _, a := scanTo(buf, indices[i], '=')
- _, b := scanTo(buf, indices[j], '=')
- return bytes.Compare(a, b) < 0
-}
-
-// scanFields scans buf, starting at i for the fields section of a point. It returns
-// the ending position and the byte slice of the fields within buf.
-func scanFields(buf []byte, i int) (int, []byte, error) {
- start := skipWhitespace(buf, i)
- i = start
- quoted := false
-
- // tracks how many '=' we've seen
- equals := 0
-
- // tracks how many commas we've seen
- commas := 0
-
- for {
- // reached the end of buf?
- if i >= len(buf) {
- break
- }
-
- // escaped characters?
- if buf[i] == '\\' && i+1 < len(buf) {
- i += 2
- continue
- }
-
- // If the value is quoted, scan until we get to the end quote
- // Only quote values in the field value since quotes are not significant
- // in the field key
- if buf[i] == '"' && equals > commas {
- quoted = !quoted
- i++
- continue
- }
-
- // If we see an =, ensure that there is at least on char before and after it
- if buf[i] == '=' && !quoted {
- equals++
-
- // check for "... =123" but allow "a\ =123"
- if buf[i-1] == ' ' && buf[i-2] != '\\' {
- return i, buf[start:i], fmt.Errorf("missing field key")
- }
-
- // check for "...a=123,=456" but allow "a=123,a\,=456"
- if buf[i-1] == ',' && buf[i-2] != '\\' {
- return i, buf[start:i], fmt.Errorf("missing field key")
- }
-
- // check for "... value="
- if i+1 >= len(buf) {
- return i, buf[start:i], fmt.Errorf("missing field value")
- }
-
- // check for "... value=,value2=..."
- if buf[i+1] == ',' || buf[i+1] == ' ' {
- return i, buf[start:i], fmt.Errorf("missing field value")
- }
-
- if isNumeric(buf[i+1]) || buf[i+1] == '-' || buf[i+1] == 'N' || buf[i+1] == 'n' {
- var err error
- i, err = scanNumber(buf, i+1)
- if err != nil {
- return i, buf[start:i], err
- }
- continue
- }
- // If next byte is not a double-quote, the value must be a boolean
- if buf[i+1] != '"' {
- var err error
- i, _, err = scanBoolean(buf, i+1)
- if err != nil {
- return i, buf[start:i], err
- }
- continue
- }
- }
-
- if buf[i] == ',' && !quoted {
- commas++
- }
-
- // reached end of block?
- if buf[i] == ' ' && !quoted {
- break
- }
- i++
- }
-
- if quoted {
- return i, buf[start:i], fmt.Errorf("unbalanced quotes")
- }
-
- // check that all field sections had key and values (e.g. prevent "a=1,b"
- if equals == 0 || commas != equals-1 {
- return i, buf[start:i], fmt.Errorf("invalid field format")
- }
-
- return i, buf[start:i], nil
-}
-
-// scanTime scans buf, starting at i for the time section of a point. It
-// returns the ending position and the byte slice of the timestamp within buf
-// and and error if the timestamp is not in the correct numeric format.
-func scanTime(buf []byte, i int) (int, []byte, error) {
- start := skipWhitespace(buf, i)
- i = start
-
- for {
- // reached the end of buf?
- if i >= len(buf) {
- break
- }
-
- // Reached end of block or trailing whitespace?
- if buf[i] == '\n' || buf[i] == ' ' {
- break
- }
-
- // Handle negative timestamps
- if i == start && buf[i] == '-' {
- i++
- continue
- }
-
- // Timestamps should be integers, make sure they are so we don't need
- // to actually parse the timestamp until needed.
- if buf[i] < '0' || buf[i] > '9' {
- return i, buf[start:i], fmt.Errorf("bad timestamp")
- }
- i++
- }
- return i, buf[start:i], nil
-}
-
-func isNumeric(b byte) bool {
- return (b >= '0' && b <= '9') || b == '.'
-}
-
-// scanNumber returns the end position within buf, start at i after
-// scanning over buf for an integer, or float. It returns an
-// error if a invalid number is scanned.
-func scanNumber(buf []byte, i int) (int, error) {
- start := i
- var isInt, isUnsigned bool
-
- // Is negative number?
- if i < len(buf) && buf[i] == '-' {
- i++
- // There must be more characters now, as just '-' is illegal.
- if i == len(buf) {
- return i, ErrInvalidNumber
- }
- }
-
- // how many decimal points we've see
- decimal := false
-
- // indicates the number is float in scientific notation
- scientific := false
-
- for {
- if i >= len(buf) {
- break
- }
-
- if buf[i] == ',' || buf[i] == ' ' {
- break
- }
-
- if buf[i] == 'i' && i > start && !(isInt || isUnsigned) {
- isInt = true
- i++
- continue
- } else if buf[i] == 'u' && i > start && !(isInt || isUnsigned) {
- isUnsigned = true
- i++
- continue
- }
-
- if buf[i] == '.' {
- // Can't have more than 1 decimal (e.g. 1.1.1 should fail)
- if decimal {
- return i, ErrInvalidNumber
- }
- decimal = true
- }
-
- // `e` is valid for floats but not as the first char
- if i > start && (buf[i] == 'e' || buf[i] == 'E') {
- scientific = true
- i++
- continue
- }
-
- // + and - are only valid at this point if they follow an e (scientific notation)
- if (buf[i] == '+' || buf[i] == '-') && (buf[i-1] == 'e' || buf[i-1] == 'E') {
- i++
- continue
- }
-
- // NaN is an unsupported value
- if i+2 < len(buf) && (buf[i] == 'N' || buf[i] == 'n') {
- return i, ErrInvalidNumber
- }
-
- if !isNumeric(buf[i]) {
- return i, ErrInvalidNumber
- }
- i++
- }
-
- if (isInt || isUnsigned) && (decimal || scientific) {
- return i, ErrInvalidNumber
- }
-
- numericDigits := i - start
- if isInt {
- numericDigits--
- }
- if decimal {
- numericDigits--
- }
- if buf[start] == '-' {
- numericDigits--
- }
-
- if numericDigits == 0 {
- return i, ErrInvalidNumber
- }
-
- // It's more common that numbers will be within min/max range for their type but we need to prevent
- // out or range numbers from being parsed successfully. This uses some simple heuristics to decide
- // if we should parse the number to the actual type. It does not do it all the time because it incurs
- // extra allocations and we end up converting the type again when writing points to disk.
- if isInt {
- // Make sure the last char is an 'i' for integers (e.g. 9i10 is not valid)
- if buf[i-1] != 'i' {
- return i, ErrInvalidNumber
- }
- // Parse the int to check bounds the number of digits could be larger than the max range
- // We subtract 1 from the index to remove the `i` from our tests
- if len(buf[start:i-1]) >= maxInt64Digits || len(buf[start:i-1]) >= minInt64Digits {
- if _, err := parseIntBytes(buf[start:i-1], 10, 64); err != nil {
- return i, fmt.Errorf("unable to parse integer %s: %s", buf[start:i-1], err)
- }
- }
- } else if isUnsigned {
- // Return an error if uint64 support has not been enabled.
- if !enableUint64Support {
- return i, ErrInvalidNumber
- }
- // Make sure the last char is a 'u' for unsigned
- if buf[i-1] != 'u' {
- return i, ErrInvalidNumber
- }
- // Make sure the first char is not a '-' for unsigned
- if buf[start] == '-' {
- return i, ErrInvalidNumber
- }
- // Parse the uint to check bounds the number of digits could be larger than the max range
- // We subtract 1 from the index to remove the `u` from our tests
- if len(buf[start:i-1]) >= maxUint64Digits {
- if _, err := parseUintBytes(buf[start:i-1], 10, 64); err != nil {
- return i, fmt.Errorf("unable to parse unsigned %s: %s", buf[start:i-1], err)
- }
- }
- } else {
- // Parse the float to check bounds if it's scientific or the number of digits could be larger than the max range
- if scientific || len(buf[start:i]) >= maxFloat64Digits || len(buf[start:i]) >= minFloat64Digits {
- if _, err := parseFloatBytes(buf[start:i], 10); err != nil {
- return i, fmt.Errorf("invalid float")
- }
- }
- }
-
- return i, nil
-}
-
-// scanBoolean returns the end position within buf, start at i after
-// scanning over buf for boolean. Valid values for a boolean are
-// t, T, true, TRUE, f, F, false, FALSE. It returns an error if a invalid boolean
-// is scanned.
-func scanBoolean(buf []byte, i int) (int, []byte, error) {
- start := i
-
- if i < len(buf) && (buf[i] != 't' && buf[i] != 'f' && buf[i] != 'T' && buf[i] != 'F') {
- return i, buf[start:i], fmt.Errorf("invalid boolean")
- }
-
- i++
- for {
- if i >= len(buf) {
- break
- }
-
- if buf[i] == ',' || buf[i] == ' ' {
- break
- }
- i++
- }
-
- // Single char bool (t, T, f, F) is ok
- if i-start == 1 {
- return i, buf[start:i], nil
- }
-
- // length must be 4 for true or TRUE
- if (buf[start] == 't' || buf[start] == 'T') && i-start != 4 {
- return i, buf[start:i], fmt.Errorf("invalid boolean")
- }
-
- // length must be 5 for false or FALSE
- if (buf[start] == 'f' || buf[start] == 'F') && i-start != 5 {
- return i, buf[start:i], fmt.Errorf("invalid boolean")
- }
-
- // Otherwise
- valid := false
- switch buf[start] {
- case 't':
- valid = bytes.Equal(buf[start:i], []byte("true"))
- case 'f':
- valid = bytes.Equal(buf[start:i], []byte("false"))
- case 'T':
- valid = bytes.Equal(buf[start:i], []byte("TRUE")) || bytes.Equal(buf[start:i], []byte("True"))
- case 'F':
- valid = bytes.Equal(buf[start:i], []byte("FALSE")) || bytes.Equal(buf[start:i], []byte("False"))
- }
-
- if !valid {
- return i, buf[start:i], fmt.Errorf("invalid boolean")
- }
-
- return i, buf[start:i], nil
-
-}
-
-// skipWhitespace returns the end position within buf, starting at i after
-// scanning over spaces in tags.
-func skipWhitespace(buf []byte, i int) int {
- for i < len(buf) {
- if buf[i] != ' ' && buf[i] != '\t' && buf[i] != 0 {
- break
- }
- i++
- }
- return i
-}
-
-// scanLine returns the end position in buf and the next line found within
-// buf.
-func scanLine(buf []byte, i int) (int, []byte) {
- start := i
- quoted := false
- fields := false
-
- // tracks how many '=' and commas we've seen
- // this duplicates some of the functionality in scanFields
- equals := 0
- commas := 0
- for {
- // reached the end of buf?
- if i >= len(buf) {
- break
- }
-
- // skip past escaped characters
- if buf[i] == '\\' && i+2 < len(buf) {
- i += 2
- continue
- }
-
- if buf[i] == ' ' {
- fields = true
- }
-
- // If we see a double quote, makes sure it is not escaped
- if fields {
- if !quoted && buf[i] == '=' {
- i++
- equals++
- continue
- } else if !quoted && buf[i] == ',' {
- i++
- commas++
- continue
- } else if buf[i] == '"' && equals > commas {
- i++
- quoted = !quoted
- continue
- }
- }
-
- if buf[i] == '\n' && !quoted {
- break
- }
-
- i++
- }
-
- return i, buf[start:i]
-}
-
-// scanTo returns the end position in buf and the next consecutive block
-// of bytes, starting from i and ending with stop byte, where stop byte
-// has not been escaped.
-//
-// If there are leading spaces, they are skipped.
-func scanTo(buf []byte, i int, stop byte) (int, []byte) {
- start := i
- for {
- // reached the end of buf?
- if i >= len(buf) {
- break
- }
-
- // Reached unescaped stop value?
- if buf[i] == stop && (i == 0 || buf[i-1] != '\\') {
- break
- }
- i++
- }
-
- return i, buf[start:i]
-}
-
-// scanTo returns the end position in buf and the next consecutive block
-// of bytes, starting from i and ending with stop byte. If there are leading
-// spaces, they are skipped.
-func scanToSpaceOr(buf []byte, i int, stop byte) (int, []byte) {
- start := i
- if buf[i] == stop || buf[i] == ' ' {
- return i, buf[start:i]
- }
-
- for {
- i++
- if buf[i-1] == '\\' {
- continue
- }
-
- // reached the end of buf?
- if i >= len(buf) {
- return i, buf[start:i]
- }
-
- // reached end of block?
- if buf[i] == stop || buf[i] == ' ' {
- return i, buf[start:i]
- }
- }
-}
-
-func scanTagValue(buf []byte, i int) (int, []byte) {
- start := i
- for {
- if i >= len(buf) {
- break
- }
-
- if buf[i] == ',' && buf[i-1] != '\\' {
- break
- }
- i++
- }
- if i > len(buf) {
- return i, nil
- }
- return i, buf[start:i]
-}
-
-func scanFieldValue(buf []byte, i int) (int, []byte) {
- start := i
- quoted := false
- for i < len(buf) {
- // Only escape char for a field value is a double-quote and backslash
- if buf[i] == '\\' && i+1 < len(buf) && (buf[i+1] == '"' || buf[i+1] == '\\') {
- i += 2
- continue
- }
-
- // Quoted value? (e.g. string)
- if buf[i] == '"' {
- i++
- quoted = !quoted
- continue
- }
-
- if buf[i] == ',' && !quoted {
- break
- }
- i++
- }
- return i, buf[start:i]
-}
-
-func EscapeMeasurement(in []byte) []byte {
- for b, esc := range measurementEscapeCodes {
- in = bytes.Replace(in, []byte{b}, esc, -1)
- }
- return in
-}
-
-func unescapeMeasurement(in []byte) []byte {
- for b, esc := range measurementEscapeCodes {
- in = bytes.Replace(in, esc, []byte{b}, -1)
- }
- return in
-}
-
-func escapeTag(in []byte) []byte {
- for b, esc := range tagEscapeCodes {
- if bytes.IndexByte(in, b) != -1 {
- in = bytes.Replace(in, []byte{b}, esc, -1)
- }
- }
- return in
-}
-
-func unescapeTag(in []byte) []byte {
- if bytes.IndexByte(in, '\\') == -1 {
- return in
- }
-
- for b, esc := range tagEscapeCodes {
- if bytes.IndexByte(in, b) != -1 {
- in = bytes.Replace(in, esc, []byte{b}, -1)
- }
- }
- return in
-}
-
-// escapeStringFieldReplacer replaces double quotes and backslashes
-// with the same character preceded by a backslash.
-// As of Go 1.7 this benchmarked better in allocations and CPU time
-// compared to iterating through a string byte-by-byte and appending to a new byte slice,
-// calling strings.Replace twice, and better than (*Regex).ReplaceAllString.
-var escapeStringFieldReplacer = strings.NewReplacer(`"`, `\"`, `\`, `\\`)
-
-// EscapeStringField returns a copy of in with any double quotes or
-// backslashes with escaped values.
-func EscapeStringField(in string) string {
- return escapeStringFieldReplacer.Replace(in)
-}
-
-// unescapeStringField returns a copy of in with any escaped double-quotes
-// or backslashes unescaped.
-func unescapeStringField(in string) string {
- if strings.IndexByte(in, '\\') == -1 {
- return in
- }
-
- var out []byte
- i := 0
- for {
- if i >= len(in) {
- break
- }
- // unescape backslashes
- if in[i] == '\\' && i+1 < len(in) && in[i+1] == '\\' {
- out = append(out, '\\')
- i += 2
- continue
- }
- // unescape double-quotes
- if in[i] == '\\' && i+1 < len(in) && in[i+1] == '"' {
- out = append(out, '"')
- i += 2
- continue
- }
- out = append(out, in[i])
- i++
-
- }
- return string(out)
-}
-
-// NewPoint returns a new point with the given measurement name, tags, fields and timestamp. If
-// an unsupported field value (NaN) or out of range time is passed, this function returns an error.
-func NewPoint(name string, tags Tags, fields Fields, t time.Time) (Point, error) {
- key, err := pointKey(name, tags, fields, t)
- if err != nil {
- return nil, err
- }
-
- return &point{
- key: key,
- time: t,
- fields: fields.MarshalBinary(),
- }, nil
-}
-
-// pointKey checks some basic requirements for valid points, and returns the
-// key, along with an possible error.
-func pointKey(measurement string, tags Tags, fields Fields, t time.Time) ([]byte, error) {
- if len(fields) == 0 {
- return nil, ErrPointMustHaveAField
- }
-
- if !t.IsZero() {
- if err := CheckTime(t); err != nil {
- return nil, err
- }
- }
-
- for key, value := range fields {
- switch value := value.(type) {
- case float64:
- // Ensure the caller validates and handles invalid field values
- if math.IsNaN(value) {
- return nil, fmt.Errorf("NaN is an unsupported value for field %s", key)
- }
- case float32:
- // Ensure the caller validates and handles invalid field values
- if math.IsNaN(float64(value)) {
- return nil, fmt.Errorf("NaN is an unsupported value for field %s", key)
- }
- }
- if len(key) == 0 {
- return nil, fmt.Errorf("all fields must have non-empty names")
- }
- }
-
- key := MakeKey([]byte(measurement), tags)
- for field := range fields {
- sz := seriesKeySize(key, []byte(field))
- if sz > MaxKeyLength {
- return nil, fmt.Errorf("max key length exceeded: %v > %v", sz, MaxKeyLength)
- }
- }
-
- return key, nil
-}
-
-func seriesKeySize(key, field []byte) int {
- // 4 is the length of the tsm1.fieldKeySeparator constant. It's inlined here to avoid a circular
- // dependency.
- return len(key) + 4 + len(field)
-}
-
-// NewPointFromBytes returns a new Point from a marshalled Point.
-func NewPointFromBytes(b []byte) (Point, error) {
- p := &point{}
- if err := p.UnmarshalBinary(b); err != nil {
- return nil, err
- }
-
- // This does some basic validation to ensure there are fields and they
- // can be unmarshalled as well.
- iter := p.FieldIterator()
- var hasField bool
- for iter.Next() {
- if len(iter.FieldKey()) == 0 {
- continue
- }
- hasField = true
- switch iter.Type() {
- case Float:
- _, err := iter.FloatValue()
- if err != nil {
- return nil, fmt.Errorf("unable to unmarshal field %s: %s", string(iter.FieldKey()), err)
- }
- case Integer:
- _, err := iter.IntegerValue()
- if err != nil {
- return nil, fmt.Errorf("unable to unmarshal field %s: %s", string(iter.FieldKey()), err)
- }
- case Unsigned:
- _, err := iter.UnsignedValue()
- if err != nil {
- return nil, fmt.Errorf("unable to unmarshal field %s: %s", string(iter.FieldKey()), err)
- }
- case String:
- // Skip since this won't return an error
- case Boolean:
- _, err := iter.BooleanValue()
- if err != nil {
- return nil, fmt.Errorf("unable to unmarshal field %s: %s", string(iter.FieldKey()), err)
- }
- }
- }
-
- if !hasField {
- return nil, ErrPointMustHaveAField
- }
-
- return p, nil
-}
-
-// MustNewPoint returns a new point with the given measurement name, tags, fields and timestamp. If
-// an unsupported field value (NaN) is passed, this function panics.
-func MustNewPoint(name string, tags Tags, fields Fields, time time.Time) Point {
- pt, err := NewPoint(name, tags, fields, time)
- if err != nil {
- panic(err.Error())
- }
- return pt
-}
-
-// Key returns the key (measurement joined with tags) of the point.
-func (p *point) Key() []byte {
- return p.key
-}
-
-func (p *point) name() []byte {
- _, name := scanTo(p.key, 0, ',')
- return name
-}
-
-func (p *point) Name() []byte {
- return escape.Unescape(p.name())
-}
-
-// SetName updates the measurement name for the point.
-func (p *point) SetName(name string) {
- p.cachedName = ""
- p.key = MakeKey([]byte(name), p.Tags())
-}
-
-// Time return the timestamp for the point.
-func (p *point) Time() time.Time {
- return p.time
-}
-
-// SetTime updates the timestamp for the point.
-func (p *point) SetTime(t time.Time) {
- p.time = t
-}
-
-// Round will round the timestamp of the point to the given duration.
-func (p *point) Round(d time.Duration) {
- p.time = p.time.Round(d)
-}
-
-// Tags returns the tag set for the point.
-func (p *point) Tags() Tags {
- if p.cachedTags != nil {
- return p.cachedTags
- }
- p.cachedTags = parseTags(p.key)
- return p.cachedTags
-}
-
-func (p *point) HasTag(tag []byte) bool {
- if len(p.key) == 0 {
- return false
- }
-
- var exists bool
- walkTags(p.key, func(key, value []byte) bool {
- if bytes.Equal(tag, key) {
- exists = true
- return false
- }
- return true
- })
-
- return exists
-}
-
-func walkTags(buf []byte, fn func(key, value []byte) bool) {
- if len(buf) == 0 {
- return
- }
-
- pos, name := scanTo(buf, 0, ',')
-
- // it's an empty key, so there are no tags
- if len(name) == 0 {
- return
- }
-
- hasEscape := bytes.IndexByte(buf, '\\') != -1
- i := pos + 1
- var key, value []byte
- for {
- if i >= len(buf) {
- break
- }
- i, key = scanTo(buf, i, '=')
- i, value = scanTagValue(buf, i+1)
-
- if len(value) == 0 {
- continue
- }
-
- if hasEscape {
- if !fn(unescapeTag(key), unescapeTag(value)) {
- return
- }
- } else {
- if !fn(key, value) {
- return
- }
- }
-
- i++
- }
-}
-
-// walkFields walks each field key and value via fn. If fn returns false, the iteration
-// is stopped. The values are the raw byte slices and not the converted types.
-func walkFields(buf []byte, fn func(key, value []byte) bool) {
- var i int
- var key, val []byte
- for len(buf) > 0 {
- i, key = scanTo(buf, 0, '=')
- buf = buf[i+1:]
- i, val = scanFieldValue(buf, 0)
- buf = buf[i:]
- if !fn(key, val) {
- break
- }
-
- // slice off comma
- if len(buf) > 0 {
- buf = buf[1:]
- }
- }
-}
-
-func parseTags(buf []byte) Tags {
- if len(buf) == 0 {
- return nil
- }
-
- tags := make(Tags, bytes.Count(buf, []byte(",")))
- p := 0
- walkTags(buf, func(key, value []byte) bool {
- tags[p].Key = key
- tags[p].Value = value
- p++
- return true
- })
- return tags
-}
-
-// MakeKey creates a key for a set of tags.
-func MakeKey(name []byte, tags Tags) []byte {
- // unescape the name and then re-escape it to avoid double escaping.
- // The key should always be stored in escaped form.
- return append(EscapeMeasurement(unescapeMeasurement(name)), tags.HashKey()...)
-}
-
-// SetTags replaces the tags for the point.
-func (p *point) SetTags(tags Tags) {
- p.key = MakeKey(p.Name(), tags)
- p.cachedTags = tags
-}
-
-// AddTag adds or replaces a tag value for a point.
-func (p *point) AddTag(key, value string) {
- tags := p.Tags()
- tags = append(tags, Tag{Key: []byte(key), Value: []byte(value)})
- sort.Sort(tags)
- p.cachedTags = tags
- p.key = MakeKey(p.Name(), tags)
-}
-
-// Fields returns the fields for the point.
-func (p *point) Fields() (Fields, error) {
- if p.cachedFields != nil {
- return p.cachedFields, nil
- }
- cf, err := p.unmarshalBinary()
- if err != nil {
- return nil, err
- }
- p.cachedFields = cf
- return p.cachedFields, nil
-}
-
-// SetPrecision will round a time to the specified precision.
-func (p *point) SetPrecision(precision string) {
- switch precision {
- case "n":
- case "u":
- p.SetTime(p.Time().Truncate(time.Microsecond))
- case "ms":
- p.SetTime(p.Time().Truncate(time.Millisecond))
- case "s":
- p.SetTime(p.Time().Truncate(time.Second))
- case "m":
- p.SetTime(p.Time().Truncate(time.Minute))
- case "h":
- p.SetTime(p.Time().Truncate(time.Hour))
- }
-}
-
-// String returns the string representation of the point.
-func (p *point) String() string {
- if p.Time().IsZero() {
- return string(p.Key()) + " " + string(p.fields)
- }
- return string(p.Key()) + " " + string(p.fields) + " " + strconv.FormatInt(p.UnixNano(), 10)
-}
-
-// AppendString appends the string representation of the point to buf.
-func (p *point) AppendString(buf []byte) []byte {
- buf = append(buf, p.key...)
- buf = append(buf, ' ')
- buf = append(buf, p.fields...)
-
- if !p.time.IsZero() {
- buf = append(buf, ' ')
- buf = strconv.AppendInt(buf, p.UnixNano(), 10)
- }
-
- return buf
-}
-
-// StringSize returns the length of the string that would be returned by String().
-func (p *point) StringSize() int {
- size := len(p.key) + len(p.fields) + 1
-
- if !p.time.IsZero() {
- digits := 1 // even "0" has one digit
- t := p.UnixNano()
- if t < 0 {
- // account for negative sign, then negate
- digits++
- t = -t
- }
- for t > 9 { // already accounted for one digit
- digits++
- t /= 10
- }
- size += digits + 1 // digits and a space
- }
-
- return size
-}
-
-// MarshalBinary returns a binary representation of the point.
-func (p *point) MarshalBinary() ([]byte, error) {
- if len(p.fields) == 0 {
- return nil, ErrPointMustHaveAField
- }
-
- tb, err := p.time.MarshalBinary()
- if err != nil {
- return nil, err
- }
-
- b := make([]byte, 8+len(p.key)+len(p.fields)+len(tb))
- i := 0
-
- binary.BigEndian.PutUint32(b[i:], uint32(len(p.key)))
- i += 4
-
- i += copy(b[i:], p.key)
-
- binary.BigEndian.PutUint32(b[i:i+4], uint32(len(p.fields)))
- i += 4
-
- i += copy(b[i:], p.fields)
-
- copy(b[i:], tb)
- return b, nil
-}
-
-// UnmarshalBinary decodes a binary representation of the point into a point struct.
-func (p *point) UnmarshalBinary(b []byte) error {
- var n int
-
- // Read key length.
- if len(b) < 4 {
- return io.ErrShortBuffer
- }
- n, b = int(binary.BigEndian.Uint32(b[:4])), b[4:]
-
- // Read key.
- if len(b) < n {
- return io.ErrShortBuffer
- }
- p.key, b = b[:n], b[n:]
-
- // Read fields length.
- if len(b) < 4 {
- return io.ErrShortBuffer
- }
- n, b = int(binary.BigEndian.Uint32(b[:4])), b[4:]
-
- // Read fields.
- if len(b) < n {
- return io.ErrShortBuffer
- }
- p.fields, b = b[:n], b[n:]
-
- // Read timestamp.
- if err := p.time.UnmarshalBinary(b); err != nil {
- return err
- }
- return nil
-}
-
-// PrecisionString returns a string representation of the point. If there
-// is a timestamp associated with the point then it will be specified in the
-// given unit.
-func (p *point) PrecisionString(precision string) string {
- if p.Time().IsZero() {
- return fmt.Sprintf("%s %s", p.Key(), string(p.fields))
- }
- return fmt.Sprintf("%s %s %d", p.Key(), string(p.fields),
- p.UnixNano()/GetPrecisionMultiplier(precision))
-}
-
-// RoundedString returns a string representation of the point. If there
-// is a timestamp associated with the point, then it will be rounded to the
-// given duration.
-func (p *point) RoundedString(d time.Duration) string {
- if p.Time().IsZero() {
- return fmt.Sprintf("%s %s", p.Key(), string(p.fields))
- }
- return fmt.Sprintf("%s %s %d", p.Key(), string(p.fields),
- p.time.Round(d).UnixNano())
-}
-
-func (p *point) unmarshalBinary() (Fields, error) {
- iter := p.FieldIterator()
- fields := make(Fields, 8)
- for iter.Next() {
- if len(iter.FieldKey()) == 0 {
- continue
- }
- switch iter.Type() {
- case Float:
- v, err := iter.FloatValue()
- if err != nil {
- return nil, fmt.Errorf("unable to unmarshal field %s: %s", string(iter.FieldKey()), err)
- }
- fields[string(iter.FieldKey())] = v
- case Integer:
- v, err := iter.IntegerValue()
- if err != nil {
- return nil, fmt.Errorf("unable to unmarshal field %s: %s", string(iter.FieldKey()), err)
- }
- fields[string(iter.FieldKey())] = v
- case Unsigned:
- v, err := iter.UnsignedValue()
- if err != nil {
- return nil, fmt.Errorf("unable to unmarshal field %s: %s", string(iter.FieldKey()), err)
- }
- fields[string(iter.FieldKey())] = v
- case String:
- fields[string(iter.FieldKey())] = iter.StringValue()
- case Boolean:
- v, err := iter.BooleanValue()
- if err != nil {
- return nil, fmt.Errorf("unable to unmarshal field %s: %s", string(iter.FieldKey()), err)
- }
- fields[string(iter.FieldKey())] = v
- }
- }
- return fields, nil
-}
-
-// HashID returns a non-cryptographic checksum of the point's key.
-func (p *point) HashID() uint64 {
- h := NewInlineFNV64a()
- h.Write(p.key)
- sum := h.Sum64()
- return sum
-}
-
-// UnixNano returns the timestamp of the point as nanoseconds since Unix epoch.
-func (p *point) UnixNano() int64 {
- return p.Time().UnixNano()
-}
-
-// Split will attempt to return multiple points with the same timestamp whose
-// string representations are no longer than size. Points with a single field or
-// a point without a timestamp may exceed the requested size.
-func (p *point) Split(size int) []Point {
- if p.time.IsZero() || p.StringSize() <= size {
- return []Point{p}
- }
-
- // key string, timestamp string, spaces
- size -= len(p.key) + len(strconv.FormatInt(p.time.UnixNano(), 10)) + 2
-
- var points []Point
- var start, cur int
-
- for cur < len(p.fields) {
- end, _ := scanTo(p.fields, cur, '=')
- end, _ = scanFieldValue(p.fields, end+1)
-
- if cur > start && end-start > size {
- points = append(points, &point{
- key: p.key,
- time: p.time,
- fields: p.fields[start : cur-1],
- })
- start = cur
- }
-
- cur = end + 1
- }
-
- points = append(points, &point{
- key: p.key,
- time: p.time,
- fields: p.fields[start:],
- })
-
- return points
-}
-
-// Tag represents a single key/value tag pair.
-type Tag struct {
- Key []byte
- Value []byte
-}
-
-// NewTag returns a new Tag.
-func NewTag(key, value []byte) Tag {
- return Tag{
- Key: key,
- Value: value,
- }
-}
-
-// Size returns the size of the key and value.
-func (t Tag) Size() int { return len(t.Key) + len(t.Value) }
-
-// Clone returns a shallow copy of Tag.
-//
-// Tags associated with a Point created by ParsePointsWithPrecision will hold references to the byte slice that was parsed.
-// Use Clone to create a Tag with new byte slices that do not refer to the argument to ParsePointsWithPrecision.
-func (t Tag) Clone() Tag {
- other := Tag{
- Key: make([]byte, len(t.Key)),
- Value: make([]byte, len(t.Value)),
- }
-
- copy(other.Key, t.Key)
- copy(other.Value, t.Value)
-
- return other
-}
-
-// String returns the string reprsentation of the tag.
-func (t *Tag) String() string {
- var buf bytes.Buffer
- buf.WriteByte('{')
- buf.WriteString(string(t.Key))
- buf.WriteByte(' ')
- buf.WriteString(string(t.Value))
- buf.WriteByte('}')
- return buf.String()
-}
-
-// Tags represents a sorted list of tags.
-type Tags []Tag
-
-// NewTags returns a new Tags from a map.
-func NewTags(m map[string]string) Tags {
- if len(m) == 0 {
- return nil
- }
- a := make(Tags, 0, len(m))
- for k, v := range m {
- a = append(a, NewTag([]byte(k), []byte(v)))
- }
- sort.Sort(a)
- return a
-}
-
-// Keys returns the list of keys for a tag set.
-func (a Tags) Keys() []string {
- if len(a) == 0 {
- return nil
- }
- keys := make([]string, len(a))
- for i, tag := range a {
- keys[i] = string(tag.Key)
- }
- return keys
-}
-
-// Values returns the list of values for a tag set.
-func (a Tags) Values() []string {
- if len(a) == 0 {
- return nil
- }
- values := make([]string, len(a))
- for i, tag := range a {
- values[i] = string(tag.Value)
- }
- return values
-}
-
-// String returns the string representation of the tags.
-func (a Tags) String() string {
- var buf bytes.Buffer
- buf.WriteByte('[')
- for i := range a {
- buf.WriteString(a[i].String())
- if i < len(a)-1 {
- buf.WriteByte(' ')
- }
- }
- buf.WriteByte(']')
- return buf.String()
-}
-
-// Size returns the number of bytes needed to store all tags. Note, this is
-// the number of bytes needed to store all keys and values and does not account
-// for data structures or delimiters for example.
-func (a Tags) Size() int {
- var total int
- for _, t := range a {
- total += t.Size()
- }
- return total
-}
-
-// Clone returns a copy of the slice where the elements are a result of calling `Clone` on the original elements
-//
-// Tags associated with a Point created by ParsePointsWithPrecision will hold references to the byte slice that was parsed.
-// Use Clone to create Tags with new byte slices that do not refer to the argument to ParsePointsWithPrecision.
-func (a Tags) Clone() Tags {
- if len(a) == 0 {
- return nil
- }
-
- others := make(Tags, len(a))
- for i := range a {
- others[i] = a[i].Clone()
- }
-
- return others
-}
-
-func (a Tags) Len() int { return len(a) }
-func (a Tags) Less(i, j int) bool { return bytes.Compare(a[i].Key, a[j].Key) == -1 }
-func (a Tags) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
-
-// Equal returns true if a equals other.
-func (a Tags) Equal(other Tags) bool {
- if len(a) != len(other) {
- return false
- }
- for i := range a {
- if !bytes.Equal(a[i].Key, other[i].Key) || !bytes.Equal(a[i].Value, other[i].Value) {
- return false
- }
- }
- return true
-}
-
-// CompareTags returns -1 if a < b, 1 if a > b, and 0 if a == b.
-func CompareTags(a, b Tags) int {
- // Compare each key & value until a mismatch.
- for i := 0; i < len(a) && i < len(b); i++ {
- if cmp := bytes.Compare(a[i].Key, b[i].Key); cmp != 0 {
- return cmp
- }
- if cmp := bytes.Compare(a[i].Value, b[i].Value); cmp != 0 {
- return cmp
- }
- }
-
- // If all tags are equal up to this point then return shorter tagset.
- if len(a) < len(b) {
- return -1
- } else if len(a) > len(b) {
- return 1
- }
-
- // All tags are equal.
- return 0
-}
-
-// Get returns the value for a key.
-func (a Tags) Get(key []byte) []byte {
- // OPTIMIZE: Use sort.Search if tagset is large.
-
- for _, t := range a {
- if bytes.Equal(t.Key, key) {
- return t.Value
- }
- }
- return nil
-}
-
-// GetString returns the string value for a string key.
-func (a Tags) GetString(key string) string {
- return string(a.Get([]byte(key)))
-}
-
-// Set sets the value for a key.
-func (a *Tags) Set(key, value []byte) {
- for i, t := range *a {
- if bytes.Equal(t.Key, key) {
- (*a)[i].Value = value
- return
- }
- }
- *a = append(*a, Tag{Key: key, Value: value})
- sort.Sort(*a)
-}
-
-// SetString sets the string value for a string key.
-func (a *Tags) SetString(key, value string) {
- a.Set([]byte(key), []byte(value))
-}
-
-// Delete removes a tag by key.
-func (a *Tags) Delete(key []byte) {
- for i, t := range *a {
- if bytes.Equal(t.Key, key) {
- copy((*a)[i:], (*a)[i+1:])
- (*a)[len(*a)-1] = Tag{}
- *a = (*a)[:len(*a)-1]
- return
- }
- }
-}
-
-// Map returns a map representation of the tags.
-func (a Tags) Map() map[string]string {
- m := make(map[string]string, len(a))
- for _, t := range a {
- m[string(t.Key)] = string(t.Value)
- }
- return m
-}
-
-// Merge merges the tags combining the two. If both define a tag with the
-// same key, the merged value overwrites the old value.
-// A new map is returned.
-func (a Tags) Merge(other map[string]string) Tags {
- merged := make(map[string]string, len(a)+len(other))
- for _, t := range a {
- merged[string(t.Key)] = string(t.Value)
- }
- for k, v := range other {
- merged[k] = v
- }
- return NewTags(merged)
-}
-
-// HashKey hashes all of a tag's keys.
-func (a Tags) HashKey() []byte {
- // Empty maps marshal to empty bytes.
- if len(a) == 0 {
- return nil
- }
-
- // Type invariant: Tags are sorted
-
- escaped := make(Tags, 0, len(a))
- sz := 0
- for _, t := range a {
- ek := escapeTag(t.Key)
- ev := escapeTag(t.Value)
-
- if len(ev) > 0 {
- escaped = append(escaped, Tag{Key: ek, Value: ev})
- sz += len(ek) + len(ev)
- }
- }
-
- sz += len(escaped) + (len(escaped) * 2) // separators
-
- // Generate marshaled bytes.
- b := make([]byte, sz)
- buf := b
- idx := 0
- for _, k := range escaped {
- buf[idx] = ','
- idx++
- copy(buf[idx:idx+len(k.Key)], k.Key)
- idx += len(k.Key)
- buf[idx] = '='
- idx++
- copy(buf[idx:idx+len(k.Value)], k.Value)
- idx += len(k.Value)
- }
- return b[:idx]
-}
-
-// CopyTags returns a shallow copy of tags.
-func CopyTags(a Tags) Tags {
- other := make(Tags, len(a))
- copy(other, a)
- return other
-}
-
-// DeepCopyTags returns a deep copy of tags.
-func DeepCopyTags(a Tags) Tags {
- // Calculate size of keys/values in bytes.
- var n int
- for _, t := range a {
- n += len(t.Key) + len(t.Value)
- }
-
- // Build single allocation for all key/values.
- buf := make([]byte, n)
-
- // Copy tags to new set.
- other := make(Tags, len(a))
- for i, t := range a {
- copy(buf, t.Key)
- other[i].Key, buf = buf[:len(t.Key)], buf[len(t.Key):]
-
- copy(buf, t.Value)
- other[i].Value, buf = buf[:len(t.Value)], buf[len(t.Value):]
- }
-
- return other
-}
-
-// Fields represents a mapping between a Point's field names and their
-// values.
-type Fields map[string]interface{}
-
-// FieldIterator retuns a FieldIterator that can be used to traverse the
-// fields of a point without constructing the in-memory map.
-func (p *point) FieldIterator() FieldIterator {
- p.Reset()
- return p
-}
-
-type fieldIterator struct {
- start, end int
- key, keybuf []byte
- valueBuf []byte
- fieldType FieldType
-}
-
-// Next indicates whether there any fields remaining.
-func (p *point) Next() bool {
- p.it.start = p.it.end
- if p.it.start >= len(p.fields) {
- return false
- }
-
- p.it.end, p.it.key = scanTo(p.fields, p.it.start, '=')
- if escape.IsEscaped(p.it.key) {
- p.it.keybuf = escape.AppendUnescaped(p.it.keybuf[:0], p.it.key)
- p.it.key = p.it.keybuf
- }
-
- p.it.end, p.it.valueBuf = scanFieldValue(p.fields, p.it.end+1)
- p.it.end++
-
- if len(p.it.valueBuf) == 0 {
- p.it.fieldType = Empty
- return true
- }
-
- c := p.it.valueBuf[0]
-
- if c == '"' {
- p.it.fieldType = String
- return true
- }
-
- if strings.IndexByte(`0123456789-.nNiIu`, c) >= 0 {
- if p.it.valueBuf[len(p.it.valueBuf)-1] == 'i' {
- p.it.fieldType = Integer
- p.it.valueBuf = p.it.valueBuf[:len(p.it.valueBuf)-1]
- } else if p.it.valueBuf[len(p.it.valueBuf)-1] == 'u' {
- p.it.fieldType = Unsigned
- p.it.valueBuf = p.it.valueBuf[:len(p.it.valueBuf)-1]
- } else {
- p.it.fieldType = Float
- }
- return true
- }
-
- // to keep the same behavior that currently exists, default to boolean
- p.it.fieldType = Boolean
- return true
-}
-
-// FieldKey returns the key of the current field.
-func (p *point) FieldKey() []byte {
- return p.it.key
-}
-
-// Type returns the FieldType of the current field.
-func (p *point) Type() FieldType {
- return p.it.fieldType
-}
-
-// StringValue returns the string value of the current field.
-func (p *point) StringValue() string {
- return unescapeStringField(string(p.it.valueBuf[1 : len(p.it.valueBuf)-1]))
-}
-
-// IntegerValue returns the integer value of the current field.
-func (p *point) IntegerValue() (int64, error) {
- n, err := parseIntBytes(p.it.valueBuf, 10, 64)
- if err != nil {
- return 0, fmt.Errorf("unable to parse integer value %q: %v", p.it.valueBuf, err)
- }
- return n, nil
-}
-
-// UnsignedValue returns the unsigned value of the current field.
-func (p *point) UnsignedValue() (uint64, error) {
- n, err := parseUintBytes(p.it.valueBuf, 10, 64)
- if err != nil {
- return 0, fmt.Errorf("unable to parse unsigned value %q: %v", p.it.valueBuf, err)
- }
- return n, nil
-}
-
-// BooleanValue returns the boolean value of the current field.
-func (p *point) BooleanValue() (bool, error) {
- b, err := parseBoolBytes(p.it.valueBuf)
- if err != nil {
- return false, fmt.Errorf("unable to parse bool value %q: %v", p.it.valueBuf, err)
- }
- return b, nil
-}
-
-// FloatValue returns the float value of the current field.
-func (p *point) FloatValue() (float64, error) {
- f, err := parseFloatBytes(p.it.valueBuf, 64)
- if err != nil {
- return 0, fmt.Errorf("unable to parse floating point value %q: %v", p.it.valueBuf, err)
- }
- return f, nil
-}
-
-// Reset resets the iterator to its initial state.
-func (p *point) Reset() {
- p.it.fieldType = Empty
- p.it.key = nil
- p.it.valueBuf = nil
- p.it.start = 0
- p.it.end = 0
-}
-
-// MarshalBinary encodes all the fields to their proper type and returns the binary
-// represenation
-// NOTE: uint64 is specifically not supported due to potential overflow when we decode
-// again later to an int64
-// NOTE2: uint is accepted, and may be 64 bits, and is for some reason accepted...
-func (p Fields) MarshalBinary() []byte {
- var b []byte
- keys := make([]string, 0, len(p))
-
- for k := range p {
- keys = append(keys, k)
- }
-
- // Not really necessary, can probably be removed.
- sort.Strings(keys)
-
- for i, k := range keys {
- if i > 0 {
- b = append(b, ',')
- }
- b = appendField(b, k, p[k])
- }
-
- return b
-}
-
-func appendField(b []byte, k string, v interface{}) []byte {
- b = append(b, []byte(escape.String(k))...)
- b = append(b, '=')
-
- // check popular types first
- switch v := v.(type) {
- case float64:
- b = strconv.AppendFloat(b, v, 'f', -1, 64)
- case int64:
- b = strconv.AppendInt(b, v, 10)
- b = append(b, 'i')
- case string:
- b = append(b, '"')
- b = append(b, []byte(EscapeStringField(v))...)
- b = append(b, '"')
- case bool:
- b = strconv.AppendBool(b, v)
- case int32:
- b = strconv.AppendInt(b, int64(v), 10)
- b = append(b, 'i')
- case int16:
- b = strconv.AppendInt(b, int64(v), 10)
- b = append(b, 'i')
- case int8:
- b = strconv.AppendInt(b, int64(v), 10)
- b = append(b, 'i')
- case int:
- b = strconv.AppendInt(b, int64(v), 10)
- b = append(b, 'i')
- case uint64:
- b = strconv.AppendUint(b, v, 10)
- b = append(b, 'u')
- case uint32:
- b = strconv.AppendInt(b, int64(v), 10)
- b = append(b, 'i')
- case uint16:
- b = strconv.AppendInt(b, int64(v), 10)
- b = append(b, 'i')
- case uint8:
- b = strconv.AppendInt(b, int64(v), 10)
- b = append(b, 'i')
- case uint:
- // TODO: 'uint' should be converted to writing as an unsigned integer,
- // but we cannot since that would break backwards compatibility.
- b = strconv.AppendInt(b, int64(v), 10)
- b = append(b, 'i')
- case float32:
- b = strconv.AppendFloat(b, float64(v), 'f', -1, 32)
- case []byte:
- b = append(b, v...)
- case nil:
- // skip
- default:
- // Can't determine the type, so convert to string
- b = append(b, '"')
- b = append(b, []byte(EscapeStringField(fmt.Sprintf("%v", v)))...)
- b = append(b, '"')
-
- }
-
- return b
-}
-
-type byteSlices [][]byte
-
-func (a byteSlices) Len() int { return len(a) }
-func (a byteSlices) Less(i, j int) bool { return bytes.Compare(a[i], a[j]) == -1 }
-func (a byteSlices) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
diff --git a/vendor/github.com/influxdata/influxdb/models/rows.go b/vendor/github.com/influxdata/influxdb/models/rows.go
deleted file mode 100644
index c087a4882d..0000000000
--- a/vendor/github.com/influxdata/influxdb/models/rows.go
+++ /dev/null
@@ -1,62 +0,0 @@
-package models
-
-import (
- "sort"
-)
-
-// Row represents a single row returned from the execution of a statement.
-type Row struct {
- Name string `json:"name,omitempty"`
- Tags map[string]string `json:"tags,omitempty"`
- Columns []string `json:"columns,omitempty"`
- Values [][]interface{} `json:"values,omitempty"`
- Partial bool `json:"partial,omitempty"`
-}
-
-// SameSeries returns true if r contains values for the same series as o.
-func (r *Row) SameSeries(o *Row) bool {
- return r.tagsHash() == o.tagsHash() && r.Name == o.Name
-}
-
-// tagsHash returns a hash of tag key/value pairs.
-func (r *Row) tagsHash() uint64 {
- h := NewInlineFNV64a()
- keys := r.tagsKeys()
- for _, k := range keys {
- h.Write([]byte(k))
- h.Write([]byte(r.Tags[k]))
- }
- return h.Sum64()
-}
-
-// tagKeys returns a sorted list of tag keys.
-func (r *Row) tagsKeys() []string {
- a := make([]string, 0, len(r.Tags))
- for k := range r.Tags {
- a = append(a, k)
- }
- sort.Strings(a)
- return a
-}
-
-// Rows represents a collection of rows. Rows implements sort.Interface.
-type Rows []*Row
-
-// Len implements sort.Interface.
-func (p Rows) Len() int { return len(p) }
-
-// Less implements sort.Interface.
-func (p Rows) Less(i, j int) bool {
- // Sort by name first.
- if p[i].Name != p[j].Name {
- return p[i].Name < p[j].Name
- }
-
- // Sort by tag set hash. Tags don't have a meaningful sort order so we
- // just compute a hash and sort by that instead. This allows the tests
- // to receive rows in a predictable order every time.
- return p[i].tagsHash() < p[j].tagsHash()
-}
-
-// Swap implements sort.Interface.
-func (p Rows) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
diff --git a/vendor/github.com/influxdata/influxdb/models/statistic.go b/vendor/github.com/influxdata/influxdb/models/statistic.go
deleted file mode 100644
index 553e9d09fb..0000000000
--- a/vendor/github.com/influxdata/influxdb/models/statistic.go
+++ /dev/null
@@ -1,42 +0,0 @@
-package models
-
-// Statistic is the representation of a statistic used by the monitoring service.
-type Statistic struct {
- Name string `json:"name"`
- Tags map[string]string `json:"tags"`
- Values map[string]interface{} `json:"values"`
-}
-
-// NewStatistic returns an initialized Statistic.
-func NewStatistic(name string) Statistic {
- return Statistic{
- Name: name,
- Tags: make(map[string]string),
- Values: make(map[string]interface{}),
- }
-}
-
-// StatisticTags is a map that can be merged with others without causing
-// mutations to either map.
-type StatisticTags map[string]string
-
-// Merge creates a new map containing the merged contents of tags and t.
-// If both tags and the receiver map contain the same key, the value in tags
-// is used in the resulting map.
-//
-// Merge always returns a usable map.
-func (t StatisticTags) Merge(tags map[string]string) map[string]string {
- // Add everything in tags to the result.
- out := make(map[string]string, len(tags))
- for k, v := range tags {
- out[k] = v
- }
-
- // Only add values from t that don't appear in tags.
- for k, v := range t {
- if _, ok := tags[k]; !ok {
- out[k] = v
- }
- }
- return out
-}
diff --git a/vendor/github.com/influxdata/influxdb/models/time.go b/vendor/github.com/influxdata/influxdb/models/time.go
deleted file mode 100644
index e98f2cb336..0000000000
--- a/vendor/github.com/influxdata/influxdb/models/time.go
+++ /dev/null
@@ -1,74 +0,0 @@
-package models
-
-// Helper time methods since parsing time can easily overflow and we only support a
-// specific time range.
-
-import (
- "fmt"
- "math"
- "time"
-)
-
-const (
- // MinNanoTime is the minumum time that can be represented.
- //
- // 1677-09-21 00:12:43.145224194 +0000 UTC
- //
- // The two lowest minimum integers are used as sentinel values. The
- // minimum value needs to be used as a value lower than any other value for
- // comparisons and another separate value is needed to act as a sentinel
- // default value that is unusable by the user, but usable internally.
- // Because these two values need to be used for a special purpose, we do
- // not allow users to write points at these two times.
- MinNanoTime = int64(math.MinInt64) + 2
-
- // MaxNanoTime is the maximum time that can be represented.
- //
- // 2262-04-11 23:47:16.854775806 +0000 UTC
- //
- // The highest time represented by a nanosecond needs to be used for an
- // exclusive range in the shard group, so the maximum time needs to be one
- // less than the possible maximum number of nanoseconds representable by an
- // int64 so that we don't lose a point at that one time.
- MaxNanoTime = int64(math.MaxInt64) - 1
-)
-
-var (
- minNanoTime = time.Unix(0, MinNanoTime).UTC()
- maxNanoTime = time.Unix(0, MaxNanoTime).UTC()
-
- // ErrTimeOutOfRange gets returned when time is out of the representable range using int64 nanoseconds since the epoch.
- ErrTimeOutOfRange = fmt.Errorf("time outside range %d - %d", MinNanoTime, MaxNanoTime)
-)
-
-// SafeCalcTime safely calculates the time given. Will return error if the time is outside the
-// supported range.
-func SafeCalcTime(timestamp int64, precision string) (time.Time, error) {
- mult := GetPrecisionMultiplier(precision)
- if t, ok := safeSignedMult(timestamp, mult); ok {
- tme := time.Unix(0, t).UTC()
- return tme, CheckTime(tme)
- }
-
- return time.Time{}, ErrTimeOutOfRange
-}
-
-// CheckTime checks that a time is within the safe range.
-func CheckTime(t time.Time) error {
- if t.Before(minNanoTime) || t.After(maxNanoTime) {
- return ErrTimeOutOfRange
- }
- return nil
-}
-
-// Perform the multiplication and check to make sure it didn't overflow.
-func safeSignedMult(a, b int64) (int64, bool) {
- if a == 0 || b == 0 || a == 1 || b == 1 {
- return a * b, true
- }
- if a == MinNanoTime || b == MaxNanoTime {
- return 0, false
- }
- c := a * b
- return c, c/b == a
-}
diff --git a/vendor/github.com/influxdata/influxdb/models/uint_support.go b/vendor/github.com/influxdata/influxdb/models/uint_support.go
deleted file mode 100644
index 18d1ca06e2..0000000000
--- a/vendor/github.com/influxdata/influxdb/models/uint_support.go
+++ /dev/null
@@ -1,7 +0,0 @@
-// +build uint uint64
-
-package models
-
-func init() {
- EnableUintSupport()
-}
diff --git a/vendor/github.com/influxdata/influxdb/pkg/escape/bytes.go b/vendor/github.com/influxdata/influxdb/pkg/escape/bytes.go
deleted file mode 100644
index f3b31f42d3..0000000000
--- a/vendor/github.com/influxdata/influxdb/pkg/escape/bytes.go
+++ /dev/null
@@ -1,115 +0,0 @@
-// Package escape contains utilities for escaping parts of InfluxQL
-// and InfluxDB line protocol.
-package escape // import "github.com/influxdata/influxdb/pkg/escape"
-
-import (
- "bytes"
- "strings"
-)
-
-// Codes is a map of bytes to be escaped.
-var Codes = map[byte][]byte{
- ',': []byte(`\,`),
- '"': []byte(`\"`),
- ' ': []byte(`\ `),
- '=': []byte(`\=`),
-}
-
-// Bytes escapes characters on the input slice, as defined by Codes.
-func Bytes(in []byte) []byte {
- for b, esc := range Codes {
- in = bytes.Replace(in, []byte{b}, esc, -1)
- }
- return in
-}
-
-const escapeChars = `," =`
-
-// IsEscaped returns whether b has any escaped characters,
-// i.e. whether b seems to have been processed by Bytes.
-func IsEscaped(b []byte) bool {
- for len(b) > 0 {
- i := bytes.IndexByte(b, '\\')
- if i < 0 {
- return false
- }
-
- if i+1 < len(b) && strings.IndexByte(escapeChars, b[i+1]) >= 0 {
- return true
- }
- b = b[i+1:]
- }
- return false
-}
-
-// AppendUnescaped appends the unescaped version of src to dst
-// and returns the resulting slice.
-func AppendUnescaped(dst, src []byte) []byte {
- var pos int
- for len(src) > 0 {
- next := bytes.IndexByte(src[pos:], '\\')
- if next < 0 || pos+next+1 >= len(src) {
- return append(dst, src...)
- }
-
- if pos+next+1 < len(src) && strings.IndexByte(escapeChars, src[pos+next+1]) >= 0 {
- if pos+next > 0 {
- dst = append(dst, src[:pos+next]...)
- }
- src = src[pos+next+1:]
- pos = 0
- } else {
- pos += next + 1
- }
- }
-
- return dst
-}
-
-// Unescape returns a new slice containing the unescaped version of in.
-func Unescape(in []byte) []byte {
- if len(in) == 0 {
- return nil
- }
-
- if bytes.IndexByte(in, '\\') == -1 {
- return in
- }
-
- i := 0
- inLen := len(in)
-
- // The output size will be no more than inLen. Preallocating the
- // capacity of the output is faster and uses less memory than
- // letting append() do its own (over)allocation.
- out := make([]byte, 0, inLen)
-
- for {
- if i >= inLen {
- break
- }
- if in[i] == '\\' && i+1 < inLen {
- switch in[i+1] {
- case ',':
- out = append(out, ',')
- i += 2
- continue
- case '"':
- out = append(out, '"')
- i += 2
- continue
- case ' ':
- out = append(out, ' ')
- i += 2
- continue
- case '=':
- out = append(out, '=')
- i += 2
- continue
- }
- }
- out = append(out, in[i])
- i += 1
- }
- return out
-}
diff --git a/vendor/github.com/influxdata/influxdb/pkg/escape/strings.go b/vendor/github.com/influxdata/influxdb/pkg/escape/strings.go
deleted file mode 100644
index db98033b0d..0000000000
--- a/vendor/github.com/influxdata/influxdb/pkg/escape/strings.go
+++ /dev/null
@@ -1,21 +0,0 @@
-package escape
-
-import "strings"
-
-var (
- escaper = strings.NewReplacer(`,`, `\,`, `"`, `\"`, ` `, `\ `, `=`, `\=`)
- unescaper = strings.NewReplacer(`\,`, `,`, `\"`, `"`, `\ `, ` `, `\=`, `=`)
-)
-
-// UnescapeString returns unescaped version of in.
-func UnescapeString(in string) string {
- if strings.IndexByte(in, '\\') == -1 {
- return in
- }
- return unescaper.Replace(in)
-}
-
-// String returns the escaped version of in.
-func String(in string) string {
- return escaper.Replace(in)
-}
diff --git a/vendor/github.com/jackpal/go-nat-pmp/LICENSE b/vendor/github.com/jackpal/go-nat-pmp/LICENSE
deleted file mode 100644
index 249514b0fb..0000000000
--- a/vendor/github.com/jackpal/go-nat-pmp/LICENSE
+++ /dev/null
@@ -1,13 +0,0 @@
- Copyright 2013 John Howard Palevich
-
- 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/vendor/github.com/jackpal/go-nat-pmp/README.md b/vendor/github.com/jackpal/go-nat-pmp/README.md
deleted file mode 100644
index 3ca687f0b7..0000000000
--- a/vendor/github.com/jackpal/go-nat-pmp/README.md
+++ /dev/null
@@ -1,52 +0,0 @@
-go-nat-pmp
-==========
-
-A Go language client for the NAT-PMP internet protocol for port mapping and discovering the external
-IP address of a firewall.
-
-NAT-PMP is supported by Apple brand routers and open source routers like Tomato and DD-WRT.
-
-See http://tools.ietf.org/html/draft-cheshire-nat-pmp-03
-
-
-[![Build Status](https://travis-ci.org/jackpal/go-nat-pmp.svg)](https://travis-ci.org/jackpal/go-nat-pmp)
-
-Get the package
----------------
-
- go get -u github.com/jackpal/go-nat-pmp
-
-Usage
------
-
- import (
- "github.com/jackpal/gateway"
- natpmp "github.com/jackpal/go-nat-pmp"
- )
-
- gatewayIP, err = gateway.DiscoverGateway()
- if err != nil {
- return
- }
-
- client := natpmp.NewClient(gatewayIP)
- response, err := client.GetExternalAddress()
- if err != nil {
- return
- }
- print("External IP address:", response.ExternalIPAddress)
-
-Clients
--------
-
-This library is used in the Taipei Torrent BitTorrent client http://github.com/jackpal/Taipei-Torrent
-
-Complete documentation
-----------------------
-
- http://godoc.org/github.com/jackpal/go-nat-pmp
-
-License
--------
-
-This project is licensed under the Apache License 2.0.
diff --git a/vendor/github.com/jackpal/go-nat-pmp/natpmp.go b/vendor/github.com/jackpal/go-nat-pmp/natpmp.go
deleted file mode 100644
index 5ca7680e41..0000000000
--- a/vendor/github.com/jackpal/go-nat-pmp/natpmp.go
+++ /dev/null
@@ -1,153 +0,0 @@
-package natpmp
-
-import (
- "fmt"
- "net"
- "time"
-)
-
-// Implement the NAT-PMP protocol, typically supported by Apple routers and open source
-// routers such as DD-WRT and Tomato.
-//
-// See http://tools.ietf.org/html/draft-cheshire-nat-pmp-03
-//
-// Usage:
-//
-// client := natpmp.NewClient(gatewayIP)
-// response, err := client.GetExternalAddress()
-
-// The recommended mapping lifetime for AddPortMapping
-const RECOMMENDED_MAPPING_LIFETIME_SECONDS = 3600
-
-// Interface used to make remote procedure calls.
-type caller interface {
- call(msg []byte, timeout time.Duration) (result []byte, err error)
-}
-
-// Client is a NAT-PMP protocol client.
-type Client struct {
- caller caller
- timeout time.Duration
-}
-
-// Create a NAT-PMP client for the NAT-PMP server at the gateway.
-// Uses default timeout which is around 128 seconds.
-func NewClient(gateway net.IP) (nat *Client) {
- return &Client{&network{gateway}, 0}
-}
-
-// Create a NAT-PMP client for the NAT-PMP server at the gateway, with a timeout.
-// Timeout defines the total amount of time we will keep retrying before giving up.
-func NewClientWithTimeout(gateway net.IP, timeout time.Duration) (nat *Client) {
- return &Client{&network{gateway}, timeout}
-}
-
-// Results of the NAT-PMP GetExternalAddress operation.
-type GetExternalAddressResult struct {
- SecondsSinceStartOfEpoc uint32
- ExternalIPAddress [4]byte
-}
-
-// Get the external address of the router.
-func (n *Client) GetExternalAddress() (result *GetExternalAddressResult, err error) {
- msg := make([]byte, 2)
- msg[0] = 0 // Version 0
- msg[1] = 0 // OP Code 0
- response, err := n.rpc(msg, 12)
- if err != nil {
- return
- }
- result = &GetExternalAddressResult{}
- result.SecondsSinceStartOfEpoc = readNetworkOrderUint32(response[4:8])
- copy(result.ExternalIPAddress[:], response[8:12])
- return
-}
-
-// Results of the NAT-PMP AddPortMapping operation
-type AddPortMappingResult struct {
- SecondsSinceStartOfEpoc uint32
- InternalPort uint16
- MappedExternalPort uint16
- PortMappingLifetimeInSeconds uint32
-}
-
-// Add (or delete) a port mapping. To delete a mapping, set the requestedExternalPort and lifetime to 0
-func (n *Client) AddPortMapping(protocol string, internalPort, requestedExternalPort int, lifetime int) (result *AddPortMappingResult, err error) {
- var opcode byte
- if protocol == "udp" {
- opcode = 1
- } else if protocol == "tcp" {
- opcode = 2
- } else {
- err = fmt.Errorf("unknown protocol %v", protocol)
- return
- }
- msg := make([]byte, 12)
- msg[0] = 0 // Version 0
- msg[1] = opcode
- writeNetworkOrderUint16(msg[4:6], uint16(internalPort))
- writeNetworkOrderUint16(msg[6:8], uint16(requestedExternalPort))
- writeNetworkOrderUint32(msg[8:12], uint32(lifetime))
- response, err := n.rpc(msg, 16)
- if err != nil {
- return
- }
- result = &AddPortMappingResult{}
- result.SecondsSinceStartOfEpoc = readNetworkOrderUint32(response[4:8])
- result.InternalPort = readNetworkOrderUint16(response[8:10])
- result.MappedExternalPort = readNetworkOrderUint16(response[10:12])
- result.PortMappingLifetimeInSeconds = readNetworkOrderUint32(response[12:16])
- return
-}
-
-func (n *Client) rpc(msg []byte, resultSize int) (result []byte, err error) {
- result, err = n.caller.call(msg, n.timeout)
- if err != nil {
- return
- }
- err = protocolChecks(msg, resultSize, result)
- return
-}
-
-func protocolChecks(msg []byte, resultSize int, result []byte) (err error) {
- if len(result) != resultSize {
- err = fmt.Errorf("unexpected result size %d, expected %d", len(result), resultSize)
- return
- }
- if result[0] != 0 {
- err = fmt.Errorf("unknown protocol version %d", result[0])
- return
- }
- expectedOp := msg[1] | 0x80
- if result[1] != expectedOp {
- err = fmt.Errorf("Unexpected opcode %d. Expected %d", result[1], expectedOp)
- return
- }
- resultCode := readNetworkOrderUint16(result[2:4])
- if resultCode != 0 {
- err = fmt.Errorf("Non-zero result code %d", resultCode)
- return
- }
- // If we got here the RPC is good.
- return
-}
-
-func writeNetworkOrderUint16(buf []byte, d uint16) {
- buf[0] = byte(d >> 8)
- buf[1] = byte(d)
-}
-
-func writeNetworkOrderUint32(buf []byte, d uint32) {
- buf[0] = byte(d >> 24)
- buf[1] = byte(d >> 16)
- buf[2] = byte(d >> 8)
- buf[3] = byte(d)
-}
-
-func readNetworkOrderUint16(buf []byte) uint16 {
- return (uint16(buf[0]) << 8) | uint16(buf[1])
-}
-
-func readNetworkOrderUint32(buf []byte) uint32 {
- return (uint32(buf[0]) << 24) | (uint32(buf[1]) << 16) | (uint32(buf[2]) << 8) | uint32(buf[3])
-}
diff --git a/vendor/github.com/jackpal/go-nat-pmp/network.go b/vendor/github.com/jackpal/go-nat-pmp/network.go
deleted file mode 100644
index c42b4fee9d..0000000000
--- a/vendor/github.com/jackpal/go-nat-pmp/network.go
+++ /dev/null
@@ -1,89 +0,0 @@
-package natpmp
-
-import (
- "fmt"
- "net"
- "time"
-)
-
-const nAT_PMP_PORT = 5351
-const nAT_TRIES = 9
-const nAT_INITIAL_MS = 250
-
-// A caller that implements the NAT-PMP RPC protocol.
-type network struct {
- gateway net.IP
-}
-
-func (n *network) call(msg []byte, timeout time.Duration) (result []byte, err error) {
- var server net.UDPAddr
- server.IP = n.gateway
- server.Port = nAT_PMP_PORT
- conn, err := net.DialUDP("udp", nil, &server)
- if err != nil {
- return
- }
- defer conn.Close()
-
- // 16 bytes is the maximum result size.
- result = make([]byte, 16)
-
- var finalTimeout time.Time
- if timeout != 0 {
- finalTimeout = time.Now().Add(timeout)
- }
-
- needNewDeadline := true
-
- var tries uint
- for tries = 0; (tries < nAT_TRIES && finalTimeout.IsZero()) || time.Now().Before(finalTimeout); {
- if needNewDeadline {
- nextDeadline := time.Now().Add((nAT_INITIAL_MS << tries) * time.Millisecond)
- err = conn.SetDeadline(minTime(nextDeadline, finalTimeout))
- if err != nil {
- return
- }
- needNewDeadline = false
- }
- _, err = conn.Write(msg)
- if err != nil {
- return
- }
- var bytesRead int
- var remoteAddr *net.UDPAddr
- bytesRead, remoteAddr, err = conn.ReadFromUDP(result)
- if err != nil {
- if err.(net.Error).Timeout() {
- tries++
- needNewDeadline = true
- continue
- }
- return
- }
- if !remoteAddr.IP.Equal(n.gateway) {
- // Ignore this packet.
- // Continue without increasing retransmission timeout or deadline.
- continue
- }
- // Trim result to actual number of bytes received
- if bytesRead < len(result) {
- result = result[:bytesRead]
- }
- return
- }
- err = fmt.Errorf("Timed out trying to contact gateway")
- return
-}
-
-func minTime(a, b time.Time) time.Time {
- if a.IsZero() {
- return b
- }
- if b.IsZero() {
- return a
- }
- if a.Before(b) {
- return a
- }
- return b
-}
diff --git a/vendor/github.com/jackpal/go-nat-pmp/recorder.go b/vendor/github.com/jackpal/go-nat-pmp/recorder.go
deleted file mode 100644
index 845703672b..0000000000
--- a/vendor/github.com/jackpal/go-nat-pmp/recorder.go
+++ /dev/null
@@ -1,19 +0,0 @@
-package natpmp
-
-import "time"
-
-type callObserver interface {
- observeCall(msg []byte, result []byte, err error)
-}
-
-// A caller that records the RPC call.
-type recorder struct {
- child caller
- observer callObserver
-}
-
-func (n *recorder) call(msg []byte, timeout time.Duration) (result []byte, err error) {
- result, err = n.child.call(msg, timeout)
- n.observer.observeCall(msg, result, err)
- return
-}
diff --git a/vendor/github.com/julienschmidt/httprouter/LICENSE b/vendor/github.com/julienschmidt/httprouter/LICENSE
deleted file mode 100644
index b829abc8a1..0000000000
--- a/vendor/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/vendor/github.com/julienschmidt/httprouter/README.md b/vendor/github.com/julienschmidt/httprouter/README.md
deleted file mode 100644
index 92885470b9..0000000000
--- a/vendor/github.com/julienschmidt/httprouter/README.md
+++ /dev/null
@@ -1,266 +0,0 @@
-# HttpRouter [![Build Status](https://travis-ci.org/julienschmidt/httprouter.svg?branch=master)](https://travis-ci.org/julienschmidt/httprouter) [![Coverage Status](https://coveralls.io/repos/github/julienschmidt/httprouter/badge.svg?branch=master)](https://coveralls.io/github/julienschmidt/httprouter?branch=master) [![GoDoc](https://godoc.org/github.com/julienschmidt/httprouter?status.svg)](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](https://golang.org/).
-
-In contrast to the [default mux](https://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`](https://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](https://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](https://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.
-
-**Perfect for APIs:** The router design encourages to build sensible, hierarchical RESTful APIs. Moreover it has builtin native support for [OPTIONS requests](http://zacstewart.com/2012/04/14/http-options-method.html) and `405 Method Not Allowed` replies.
-
-Of course you can also set **custom [`NotFound`](https://godoc.org/github.com/julienschmidt/httprouter#Router.NotFound) and [`MethodNotAllowed`](https://godoc.org/github.com/julienschmidt/httprouter#Router.MethodNotAllowed) handlers** and [**serve static files**](https://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*](https://en.wikipedia.org/wiki/Trie) (or just [*Radix tree*](https://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`](https://godoc.org/github.com/julienschmidt/httprouter#Router.Handler)s and [`http.HandlerFunc`](https://godoc.org/github.com/julienschmidt/httprouter#Router.HandlerFunc)s which allows them to be used as a [`httprouter.Handle`](https://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`](https://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`](https://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](https://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 Authentication (RFC 2617) for handles:
-
-```go
-package main
-
-import (
- "fmt"
- "log"
- "net/http"
-
- "github.com/julienschmidt/httprouter"
-)
-
-func BasicAuth(h httprouter.Handle, requiredUser, requiredPassword string) httprouter.Handle {
- return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
- // Get the Basic Authentication credentials
- user, password, hasAuth := r.BasicAuth()
-
- if hasAuth && user == requiredUser && password == requiredPassword {
- // Delegate request to the given handle
- h(w, r, ps)
- } else {
- // 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 := "gordon"
- pass := "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`](https://godoc.org/github.com/julienschmidt/httprouter#Router.HandleMethodNotAllowed) to `false` to avoid problems.**
-
-You can use another [`http.Handler`](https://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`](https://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"))
-```
-
-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/manyminds/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
-* [goMiddlewareChain](https://github.com/TobiEiss/goMiddlewareChain): An express.js-like-middleware-chain
-* [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
-* [httpway](https://github.com/corneldamian/httpway): Simple middleware extension with context for httprouter and a server with gracefully shutdown support
-* [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
-* [River](https://github.com/abiosoft/river): River is a simple and lightweight REST server
-* [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
-* [xmux](https://github.com/rs/xmux): xmux is a httprouter fork on top of xhandler (net/context aware)
diff --git a/vendor/github.com/julienschmidt/httprouter/path.go b/vendor/github.com/julienschmidt/httprouter/path.go
deleted file mode 100644
index 486134db37..0000000000
--- a/vendor/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/vendor/github.com/julienschmidt/httprouter/router.go b/vendor/github.com/julienschmidt/httprouter/router.go
deleted file mode 100644
index bb1733005b..0000000000
--- a/vendor/github.com/julienschmidt/httprouter/router.go
+++ /dev/null
@@ -1,411 +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
-
- // If enabled, the router automatically replies to OPTIONS requests.
- // Custom OPTIONS handlers take priority over automatic replies.
- HandleOPTIONS 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.
- // The "Allow" header with allowed request methods is set before the handler
- // is called.
- 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,
- HandleOPTIONS: 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
-}
-
-func (r *Router) allowed(path, reqMethod string) (allow string) {
- if path == "*" { // server-wide
- for method := range r.trees {
- if method == "OPTIONS" {
- continue
- }
-
- // add request method to list of allowed methods
- if len(allow) == 0 {
- allow = method
- } else {
- allow += ", " + method
- }
- }
- } else { // specific path
- for method := range r.trees {
- // Skip the requested method - we already tried this one
- if method == reqMethod || method == "OPTIONS" {
- continue
- }
-
- handle, _, _ := r.trees[method].getValue(path)
- if handle != nil {
- // add request method to list of allowed methods
- if len(allow) == 0 {
- allow = method
- } else {
- allow += ", " + method
- }
- }
- }
- }
- if len(allow) > 0 {
- allow += ", OPTIONS"
- }
- return
-}
-
-// 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)
- }
-
- path := req.URL.Path
-
- if root := r.trees[req.Method]; root != nil {
- 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
- }
- }
- }
- }
-
- if req.Method == "OPTIONS" {
- // Handle OPTIONS requests
- if r.HandleOPTIONS {
- if allow := r.allowed(path, req.Method); len(allow) > 0 {
- w.Header().Set("Allow", allow)
- return
- }
- }
- } else {
- // Handle 405
- if r.HandleMethodNotAllowed {
- if allow := r.allowed(path, req.Method); len(allow) > 0 {
- w.Header().Set("Allow", allow)
- 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/vendor/github.com/julienschmidt/httprouter/tree.go b/vendor/github.com/julienschmidt/httprouter/tree.go
deleted file mode 100644
index a8fa98b04f..0000000000
--- a/vendor/github.com/julienschmidt/httprouter/tree.go
+++ /dev/null
@@ -1,656 +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"
- "unicode/utf8"
-)
-
-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 = iota // default
- root
- param
- catchAll
-)
-
-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
- n.children[newPos-1], n.children[newPos] = n.children[newPos], n.children[newPos-1]
-
- 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,
- nType: static,
- 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
- (len(n.path) >= len(path) || path[len(n.path)] == '/') {
- continue walk
- } else {
- // Wildcard conflict
- var pathSeg string
- if n.nType == catchAll {
- pathSeg = path
- } else {
- pathSeg = strings.SplitN(path, "/", 2)[0]
- }
- prefix := fullPath[:strings.Index(fullPath, pathSeg)] + n.path
- panic("'" + pathSeg +
- "' in new path '" + fullPath +
- "' conflicts with existing wildcard '" + n.path +
- "' in existing prefix '" + prefix +
- "'")
- }
- }
-
- 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)
- n.nType = root
- }
-}
-
-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
- }
-
- if path == "/" && n.wildChild && n.nType != root {
- tsr = true
- 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) {
- return n.findCaseInsensitivePathRec(
- path,
- strings.ToLower(path),
- make([]byte, 0, len(path)+1), // preallocate enough memory for new path
- [4]byte{}, // empty rune buffer
- fixTrailingSlash,
- )
-}
-
-// shift bytes in array by n bytes left
-func shiftNRuneBytes(rb [4]byte, n int) [4]byte {
- switch n {
- case 0:
- return rb
- case 1:
- return [4]byte{rb[1], rb[2], rb[3], 0}
- case 2:
- return [4]byte{rb[2], rb[3]}
- case 3:
- return [4]byte{rb[3]}
- default:
- return [4]byte{}
- }
-}
-
-// recursive case-insensitive lookup function used by n.findCaseInsensitivePath
-func (n *node) findCaseInsensitivePathRec(path, loPath string, ciPath []byte, rb [4]byte, fixTrailingSlash bool) ([]byte, bool) {
- loNPath := strings.ToLower(n.path)
-
-walk: // outer loop for walking the tree
- for len(loPath) >= len(loNPath) && (len(loNPath) == 0 || loPath[1:len(loNPath)] == loNPath[1:]) {
- // add common path to result
- ciPath = append(ciPath, n.path...)
-
- if path = path[len(n.path):]; len(path) > 0 {
- loOld := loPath
- loPath = loPath[len(loNPath):]
-
- // 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 {
- // skip rune bytes already processed
- rb = shiftNRuneBytes(rb, len(loNPath))
-
- if rb[0] != 0 {
- // old rune not finished
- for i := 0; i < len(n.indices); i++ {
- if n.indices[i] == rb[0] {
- // continue with child node
- n = n.children[i]
- loNPath = strings.ToLower(n.path)
- continue walk
- }
- }
- } else {
- // process a new rune
- var rv rune
-
- // find rune start
- // runes are up to 4 byte long,
- // -4 would definitely be another rune
- var off int
- for max := min(len(loNPath), 3); off < max; off++ {
- if i := len(loNPath) - off; utf8.RuneStart(loOld[i]) {
- // read rune from cached lowercase path
- rv, _ = utf8.DecodeRuneInString(loOld[i:])
- break
- }
- }
-
- // calculate lowercase bytes of current rune
- utf8.EncodeRune(rb[:], rv)
- // skipp already processed bytes
- rb = shiftNRuneBytes(rb, off)
-
- for i := 0; i < len(n.indices); i++ {
- // lowercase matches
- if n.indices[i] == rb[0] {
- // must use a recursive approach since both the
- // uppercase byte and the lowercase byte might exist
- // as an index
- if out, found := n.children[i].findCaseInsensitivePathRec(
- path, loPath, ciPath, rb, fixTrailingSlash,
- ); found {
- return out, true
- }
- break
- }
- }
-
- // same for uppercase rune, if it differs
- if up := unicode.ToUpper(rv); up != rv {
- utf8.EncodeRune(rb[:], up)
- rb = shiftNRuneBytes(rb, off)
-
- for i := 0; i < len(n.indices); i++ {
- // uppercase matches
- if n.indices[i] == rb[0] {
- // continue with child node
- n = n.children[i]
- loNPath = strings.ToLower(n.path)
- continue walk
- }
- }
- }
- }
-
- // Nothing found. We can recommend to redirect to the same URL
- // without a trailing slash if a leaf exists for that path
- return ciPath, (fixTrailingSlash && path == "/" && n.handle != nil)
- }
-
- 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 {
- // continue with child node
- n = n.children[0]
- loNPath = strings.ToLower(n.path)
- loPath = loPath[k:]
- path = path[k:]
- continue
- }
-
- // ... but we can't
- if fixTrailingSlash && len(path) == k+1 {
- return ciPath, true
- }
- return ciPath, false
- }
-
- 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 ciPath, false
-
- 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 ciPath, false
- }
- }
- }
- return ciPath, false
- }
- }
-
- // Nothing found.
- // Try to fix the path by adding / removing a trailing slash
- if fixTrailingSlash {
- if path == "/" {
- return ciPath, true
- }
- if len(loPath)+1 == len(loNPath) && loNPath[len(loPath)] == '/' &&
- loPath[1:] == loNPath[1:len(loPath)] && n.handle != nil {
- return append(ciPath, n.path...), true
- }
- }
- return ciPath, false
-}
diff --git a/vendor/github.com/karalabe/usb/AUTHORS b/vendor/github.com/karalabe/usb/AUTHORS
deleted file mode 100644
index bae45b3ec2..0000000000
--- a/vendor/github.com/karalabe/usb/AUTHORS
+++ /dev/null
@@ -1,7 +0,0 @@
-Felix Lange
-Guillaume Ballet
-Jakob Weisblat
-Martin Holst Swende
-Mateusz Mikołajczyk
-Péter Szilágyi
-Rosen Penev
diff --git a/vendor/github.com/karalabe/usb/Dockerfile.alpine b/vendor/github.com/karalabe/usb/Dockerfile.alpine
deleted file mode 100644
index 342bdf79a7..0000000000
--- a/vendor/github.com/karalabe/usb/Dockerfile.alpine
+++ /dev/null
@@ -1,6 +0,0 @@
-FROM golang:alpine
-
-RUN apk add --no-cache git gcc musl-dev linux-headers
-
-ADD . $GOPATH/src/github.com/karalabe/usb
-RUN cd $GOPATH/src/github.com/karalabe/usb && go install
diff --git a/vendor/github.com/karalabe/usb/Dockerfile.ubuntu b/vendor/github.com/karalabe/usb/Dockerfile.ubuntu
deleted file mode 100644
index b861e497be..0000000000
--- a/vendor/github.com/karalabe/usb/Dockerfile.ubuntu
+++ /dev/null
@@ -1,4 +0,0 @@
-FROM golang:latest
-
-ADD . $GOPATH/src/github.com/karalabe/usb
-RUN cd $GOPATH/src/github.com/karalabe/usb && go install
diff --git a/vendor/github.com/karalabe/usb/LICENSE b/vendor/github.com/karalabe/usb/LICENSE
deleted file mode 100644
index 65c5ca88a6..0000000000
--- a/vendor/github.com/karalabe/usb/LICENSE
+++ /dev/null
@@ -1,165 +0,0 @@
- GNU LESSER GENERAL PUBLIC LICENSE
- Version 3, 29 June 2007
-
- Copyright (C) 2007 Free Software Foundation, Inc.
- Everyone is permitted to copy and distribute verbatim copies
- of this license document, but changing it is not allowed.
-
-
- This version of the GNU Lesser General Public License incorporates
-the terms and conditions of version 3 of the GNU General Public
-License, supplemented by the additional permissions listed below.
-
- 0. Additional Definitions.
-
- As used herein, "this License" refers to version 3 of the GNU Lesser
-General Public License, and the "GNU GPL" refers to version 3 of the GNU
-General Public License.
-
- "The Library" refers to a covered work governed by this License,
-other than an Application or a Combined Work as defined below.
-
- An "Application" is any work that makes use of an interface provided
-by the Library, but which is not otherwise based on the Library.
-Defining a subclass of a class defined by the Library is deemed a mode
-of using an interface provided by the Library.
-
- A "Combined Work" is a work produced by combining or linking an
-Application with the Library. The particular version of the Library
-with which the Combined Work was made is also called the "Linked
-Version".
-
- The "Minimal Corresponding Source" for a Combined Work means the
-Corresponding Source for the Combined Work, excluding any source code
-for portions of the Combined Work that, considered in isolation, are
-based on the Application, and not on the Linked Version.
-
- The "Corresponding Application Code" for a Combined Work means the
-object code and/or source code for the Application, including any data
-and utility programs needed for reproducing the Combined Work from the
-Application, but excluding the System Libraries of the Combined Work.
-
- 1. Exception to Section 3 of the GNU GPL.
-
- You may convey a covered work under sections 3 and 4 of this License
-without being bound by section 3 of the GNU GPL.
-
- 2. Conveying Modified Versions.
-
- If you modify a copy of the Library, and, in your modifications, a
-facility refers to a function or data to be supplied by an Application
-that uses the facility (other than as an argument passed when the
-facility is invoked), then you may convey a copy of the modified
-version:
-
- a) under this License, provided that you make a good faith effort to
- ensure that, in the event an Application does not supply the
- function or data, the facility still operates, and performs
- whatever part of its purpose remains meaningful, or
-
- b) under the GNU GPL, with none of the additional permissions of
- this License applicable to that copy.
-
- 3. Object Code Incorporating Material from Library Header Files.
-
- The object code form of an Application may incorporate material from
-a header file that is part of the Library. You may convey such object
-code under terms of your choice, provided that, if the incorporated
-material is not limited to numerical parameters, data structure
-layouts and accessors, or small macros, inline functions and templates
-(ten or fewer lines in length), you do both of the following:
-
- a) Give prominent notice with each copy of the object code that the
- Library is used in it and that the Library and its use are
- covered by this License.
-
- b) Accompany the object code with a copy of the GNU GPL and this license
- document.
-
- 4. Combined Works.
-
- You may convey a Combined Work under terms of your choice that,
-taken together, effectively do not restrict modification of the
-portions of the Library contained in the Combined Work and reverse
-engineering for debugging such modifications, if you also do each of
-the following:
-
- a) Give prominent notice with each copy of the Combined Work that
- the Library is used in it and that the Library and its use are
- covered by this License.
-
- b) Accompany the Combined Work with a copy of the GNU GPL and this license
- document.
-
- c) For a Combined Work that displays copyright notices during
- execution, include the copyright notice for the Library among
- these notices, as well as a reference directing the user to the
- copies of the GNU GPL and this license document.
-
- d) Do one of the following:
-
- 0) Convey the Minimal Corresponding Source under the terms of this
- License, and the Corresponding Application Code in a form
- suitable for, and under terms that permit, the user to
- recombine or relink the Application with a modified version of
- the Linked Version to produce a modified Combined Work, in the
- manner specified by section 6 of the GNU GPL for conveying
- Corresponding Source.
-
- 1) Use a suitable shared library mechanism for linking with the
- Library. A suitable mechanism is one that (a) uses at run time
- a copy of the Library already present on the user's computer
- system, and (b) will operate properly with a modified version
- of the Library that is interface-compatible with the Linked
- Version.
-
- e) Provide Installation Information, but only if you would otherwise
- be required to provide such information under section 6 of the
- GNU GPL, and only to the extent that such information is
- necessary to install and execute a modified version of the
- Combined Work produced by recombining or relinking the
- Application with a modified version of the Linked Version. (If
- you use option 4d0, the Installation Information must accompany
- the Minimal Corresponding Source and Corresponding Application
- Code. If you use option 4d1, you must provide the Installation
- Information in the manner specified by section 6 of the GNU GPL
- for conveying Corresponding Source.)
-
- 5. Combined Libraries.
-
- You may place library facilities that are a work based on the
-Library side by side in a single library together with other library
-facilities that are not Applications and are not covered by this
-License, and convey such a combined library under terms of your
-choice, if you do both of the following:
-
- a) Accompany the combined library with a copy of the same work based
- on the Library, uncombined with any other library facilities,
- conveyed under the terms of this License.
-
- b) Give prominent notice with the combined library that part of it
- is a work based on the Library, and explaining where to find the
- accompanying uncombined form of the same work.
-
- 6. Revised Versions of the GNU Lesser General Public License.
-
- The Free Software Foundation may publish revised and/or new versions
-of the GNU Lesser General Public License from time to time. Such new
-versions will be similar in spirit to the present version, but may
-differ in detail to address new problems or concerns.
-
- Each version is given a distinguishing version number. If the
-Library as you received it specifies that a certain numbered version
-of the GNU Lesser General Public License "or any later version"
-applies to it, you have the option of following the terms and
-conditions either of that published version or of any later version
-published by the Free Software Foundation. If the Library as you
-received it does not specify a version number of the GNU Lesser
-General Public License, you may choose any version of the GNU Lesser
-General Public License ever published by the Free Software Foundation.
-
- If the Library as you received it specifies that a proxy can decide
-whether future versions of the GNU Lesser General Public License shall
-apply, that proxy's public statement of acceptance of any version is
-permanent authorization for you to choose that version for the
-Library.
diff --git a/vendor/github.com/karalabe/usb/README.md b/vendor/github.com/karalabe/usb/README.md
deleted file mode 100644
index b6920f51a1..0000000000
--- a/vendor/github.com/karalabe/usb/README.md
+++ /dev/null
@@ -1,47 +0,0 @@
-[![Travis][travisimg]][travisurl]
-[![AppVeyor][appveyorimg]][appveyorurl]
-[![GoDoc][docimg]][docurl]
-
-[travisimg]: https://travis-ci.org/karalabe/usb.svg?branch=master
-[travisurl]: https://travis-ci.org/karalabe/usb
-[appveyorimg]: https://ci.appveyor.com/api/projects/status/u96eq262bj2itprh/branch/master?svg=true
-[appveyorurl]: https://ci.appveyor.com/project/karalabe/usb
-[docimg]: https://godoc.org/github.com/karalabe/usb?status.svg
-[docurl]: https://godoc.org/github.com/karalabe/usb
-
-# Yet another USB library for Go
-
-The `usb` package is a cross platform, fully self-contained library for accessing and communicating with USB devices **either via HID or low level interrupts**. The goal of the library was to create a simple way to find-, attach to- and read/write form USB devices.
-
-There are multiple already existing USB libraries:
-
- * The original `gousb` package [created by @kylelemons](https://github.com/kylelemons/gousb) and nowadays [maintained by @google](https://github.com/google/gousb) is a CGO wrapper around `libusb`. It is the most advanced USB library for Go out there.
- * Unfortunately, `gousb` requires the `libusb` C library to be installed both during build as well as during runtime on the host operating system. This breaks binary portability and also adds unnecessary hurdles on Windows.
- * Furthermore, whilst HID devices are supported by `libusb`, the OS on Macos and Windows explicitly takes over these devices, so only native system calls can be used on recent versions (i.e. you **cannot** use `libusb` for HID).
- * There is a fork of `gousb` [created by @karalabe](https://github.com/karalabe/gousb) that statically linked `libusb` during build, but with the lack of HID access, that work was abandoned.
- * For HID-only devices, a previous self-contained package was created at [`github.com/karalabe/hid`](https://github.com/karalabe/hid), which worked well for hardware wallet uses cases in [`go-ethereum`](https://github.com/ethereum/go-ethereum). It's a simple package that does it's thing well.
- * Unfortunately, `hid` is not capable of talking to generic USB devices. When multiple different devices are needed, eventually some will not support the HID spec (e.g. WebUSB). Pulling in both `hid` and `gousb` will break down due to both depending internally on different versions of `libusb` on Linux.
-
-This `usb` package is a proper integration of `hidapi` and `libusb` so that communication with HID devices is done via system calls, whereas communication with lower level USB devices is done via interrupts. All this detail is hidden away behind a tiny interface.
-
-The package supports Linux, macOS, Windows and FreeBSD. Exclude constraints are also specified for Android and iOS to allow smoother vendoring into cross platform projects.
-
-## Cross-compiling
-
-Using `go get`, the embedded C library is compiled into the binary format of your host OS. Cross compiling to a different platform or architecture entails disabling CGO by default in Go, causing device enumeration `hid.Enumerate()` to yield no results.
-
-To cross compile a functional version of this library, you'll need to enable CGO during cross compilation via `CGO_ENABLED=1` and you'll need to install and set a cross compilation enabled C toolkit via `CC=your-cross-gcc`.
-
-## Acknowledgements
-
-Although the `usb` package is an implementation from scratch, HID support was heavily inspired by the existing [`go.hid`](https://github.com/GeertJohan/go.hid) library, which seems abandoned since 2015; is incompatible with Go 1.6+; and has various external dependencies.
-
-Wide character support in the HID support is done via the [`gowchar`](https://github.com/orofarne/gowchar) library, unmaintained since 2013; non buildable with a modern Go release and failing `go vet` checks. As such, `gowchar` was also vendored in inline.
-
-Error handling for the `libusb` integration originates from the [`gousb`](https://github.com/google/gousb) library.
-
-## License
-
-This USB library is licensed under the [GNU Lesser General Public License v3.0](https://www.gnu.org/licenses/lgpl-3.0.en.html) (dictated by libusb).
-
-If you are only interested in Human Interface devices, a less restrictive package can be found at [`github.com/karalabe/hid`](https://github.com/karalabe/hid).
diff --git a/vendor/github.com/karalabe/usb/appveyor.yml b/vendor/github.com/karalabe/usb/appveyor.yml
deleted file mode 100644
index 73a9664ae7..0000000000
--- a/vendor/github.com/karalabe/usb/appveyor.yml
+++ /dev/null
@@ -1,35 +0,0 @@
-os: Visual Studio 2015
-
-# Clone directly into GOPATH.
-clone_folder: C:\gopath\src\github.com\karalabe\usb
-clone_depth: 1
-version: "{branch}.{build}"
-environment:
- global:
- GOPATH: C:\gopath
- CC: gcc.exe
- matrix:
- - GOARCH: amd64
- MSYS2_ARCH: x86_64
- MSYS2_BITS: 64
- MSYSTEM: MINGW64
- PATH: C:\msys64\mingw64\bin\;%PATH%
- - GOARCH: 386
- MSYS2_ARCH: i686
- MSYS2_BITS: 32
- MSYSTEM: MINGW32
- PATH: C:\msys64\mingw32\bin\;%PATH%
-
-install:
- - rmdir C:\go /s /q
- - appveyor DownloadFile https://storage.googleapis.com/golang/go1.12.9.windows-%GOARCH%.zip
- - 7z x go1.12.9.windows-%GOARCH%.zip -y -oC:\ > NUL
- - go version
- - gcc --version
-
-build_script:
- - go install ./...
- - go test -v ./...
- - set CGO_ENABLED=0
- - go install ./...
- - go test -v ./...
diff --git a/vendor/github.com/karalabe/usb/demo.go b/vendor/github.com/karalabe/usb/demo.go
deleted file mode 100644
index 229faaf5f8..0000000000
--- a/vendor/github.com/karalabe/usb/demo.go
+++ /dev/null
@@ -1,76 +0,0 @@
-// usb - Self contained USB and HID library for Go
-// Copyright 2019 The library Authors
-//
-// This library is free software: you can redistribute it and/or modify it under
-// the terms of the GNU Lesser General Public License as published by the Free
-// Software Foundation, either version 3 of the License, or (at your option) any
-// later version.
-//
-// The library is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
-// A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public License along
-// with the library. If not, see .
-
-// +build none
-
-package main
-
-import (
- "fmt"
- "strings"
-
- "github.com/karalabe/usb"
-)
-
-func main() {
- // Enumerate all the HID devices in alphabetical path order
- hids, err := usb.EnumerateHid(0, 0)
- if err != nil {
- panic(err)
- }
- for i := 0; i < len(hids); i++ {
- for j := i + 1; j < len(hids); j++ {
- if hids[i].Path > hids[j].Path {
- hids[i], hids[j] = hids[j], hids[i]
- }
- }
- }
- for i, hid := range hids {
- fmt.Println(strings.Repeat("-", 128))
- fmt.Printf("HID #%d\n", i)
- fmt.Printf(" OS Path: %s\n", hid.Path)
- fmt.Printf(" Vendor ID: %#04x\n", hid.VendorID)
- fmt.Printf(" Product ID: %#04x\n", hid.ProductID)
- fmt.Printf(" Release: %d\n", hid.Release)
- fmt.Printf(" Serial: %s\n", hid.Serial)
- fmt.Printf(" Manufacturer: %s\n", hid.Manufacturer)
- fmt.Printf(" Product: %s\n", hid.Product)
- fmt.Printf(" Usage Page: %d\n", hid.UsagePage)
- fmt.Printf(" Usage: %d\n", hid.Usage)
- fmt.Printf(" Interface: %d\n", hid.Interface)
- }
- fmt.Println(strings.Repeat("=", 128))
-
- // Enumerate all the non-HID devices in alphabetical path order
- raws, err := usb.EnumerateRaw(0, 0)
- if err != nil {
- panic(err)
- }
- for i := 0; i < len(raws); i++ {
- for j := i + 1; j < len(raws); j++ {
- if raws[i].Path > raws[j].Path {
- raws[i], raws[j] = raws[j], raws[i]
- }
- }
- }
- for i, raw := range raws {
- fmt.Printf("RAW #%d\n", i)
- fmt.Printf(" OS Path: %s\n", raw.Path)
- fmt.Printf(" Vendor ID: %#04x\n", raw.VendorID)
- fmt.Printf(" Product ID: %#04x\n", raw.ProductID)
- fmt.Printf(" Interface: %d\n", raw.Interface)
- fmt.Println(strings.Repeat("-", 128))
- }
-}
diff --git a/vendor/github.com/karalabe/usb/go.mod b/vendor/github.com/karalabe/usb/go.mod
deleted file mode 100644
index ef549d28f5..0000000000
--- a/vendor/github.com/karalabe/usb/go.mod
+++ /dev/null
@@ -1,3 +0,0 @@
-module github.com/karalabe/usb
-
-go 1.12
diff --git a/vendor/github.com/karalabe/usb/hid_disabled.go b/vendor/github.com/karalabe/usb/hid_disabled.go
deleted file mode 100644
index a85964bf35..0000000000
--- a/vendor/github.com/karalabe/usb/hid_disabled.go
+++ /dev/null
@@ -1,42 +0,0 @@
-// usb - Self contained USB and HID library for Go
-// Copyright 2017 The library Authors
-//
-// This library is free software: you can redistribute it and/or modify it under
-// the terms of the GNU Lesser General Public License as published by the Free
-// Software Foundation, either version 3 of the License, or (at your option) any
-// later version.
-//
-// The library is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
-// A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public License along
-// with the library. If not, see .
-
-// +build !freebsd,!linux,!darwin,!windows ios !cgo
-
-package usb
-
-// HidDevice is a live HID USB connected device handle. On platforms that this file
-// implements, the type lacks the actual HID device and all methods are noop.
-type HidDevice struct {
- DeviceInfo // Embed the infos for easier access
-}
-
-// Close releases the HID USB device handle. On platforms that this file implements,
-// the method is just a noop.
-func (dev *HidDevice) Close() error {
- return ErrUnsupportedPlatform
-}
-
-// Write sends an output report to a HID device. On platforms that this file
-// implements, the method just returns an error.
-func (dev *HidDevice) Write(b []byte) (int, error) {
- return 0, ErrUnsupportedPlatform
-}
-
-// Read retrieves an input report from a HID device. On platforms that this file
-// implements, the method just returns an error.
-func (dev *HidDevice) Read(b []byte) (int, error) {
- return 0, ErrUnsupportedPlatform
-}
diff --git a/vendor/github.com/karalabe/usb/hid_enabled.go b/vendor/github.com/karalabe/usb/hid_enabled.go
deleted file mode 100644
index c2b3720989..0000000000
--- a/vendor/github.com/karalabe/usb/hid_enabled.go
+++ /dev/null
@@ -1,187 +0,0 @@
-// usb - Self contained USB and HID library for Go
-// Copyright 2017 The library Authors
-//
-// This library is free software: you can redistribute it and/or modify it under
-// the terms of the GNU Lesser General Public License as published by the Free
-// Software Foundation, either version 3 of the License, or (at your option) any
-// later version.
-//
-// The library is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
-// A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public License along
-// with the library. If not, see .
-
-// +build freebsd,cgo linux,cgo darwin,!ios,cgo windows,cgo
-
-package usb
-
-/*
-#include
-#include "./hidapi/hidapi/hidapi.h"
-*/
-import "C"
-
-import (
- "errors"
- "runtime"
- "sync"
- "unsafe"
-)
-
-// enumerateHid returns a list of all the HID devices attached to the system which
-// match the vendor and product id:
-// - If the vendor id is set to 0 then any vendor matches.
-// - If the product id is set to 0 then any product matches.
-// - If the vendor and product id are both 0, all HID devices are returned.
-func enumerateHid(vendorID uint16, productID uint16) ([]DeviceInfo, error) {
- // Gather all device infos and ensure they are freed before returning
- head := C.hid_enumerate(C.ushort(vendorID), C.ushort(productID))
- if head == nil {
- return nil, nil
- }
- defer C.hid_free_enumeration(head)
-
- // Iterate the list and retrieve the device details
- var infos []DeviceInfo
- for ; head != nil; head = head.next {
- info := DeviceInfo{
- Path: C.GoString(head.path),
- VendorID: uint16(head.vendor_id),
- ProductID: uint16(head.product_id),
- Release: uint16(head.release_number),
- UsagePage: uint16(head.usage_page),
- Usage: uint16(head.usage),
- Interface: int(head.interface_number),
- }
- if head.serial_number != nil {
- info.Serial, _ = wcharTToString(head.serial_number)
- }
- if head.product_string != nil {
- info.Product, _ = wcharTToString(head.product_string)
- }
- if head.manufacturer_string != nil {
- info.Manufacturer, _ = wcharTToString(head.manufacturer_string)
- }
- infos = append(infos, info)
- }
- return infos, nil
-}
-
-// openHid connects to an HID device by its path name.
-func openHid(info DeviceInfo) (*hidDevice, error) {
- path := C.CString(info.Path)
- defer C.free(unsafe.Pointer(path))
-
- device := C.hid_open_path(path)
- if device == nil {
- return nil, errors.New("hidapi: failed to open device")
- }
- return &hidDevice{
- DeviceInfo: info,
- device: device,
- }, nil
-}
-
-// hidDevice is a live HID USB connected device handle.
-type hidDevice struct {
- DeviceInfo // Embed the infos for easier access
-
- device *C.hid_device // Low level HID device to communicate through
- lock sync.Mutex
-}
-
-// Close releases the HID USB device handle.
-func (dev *hidDevice) Close() error {
- dev.lock.Lock()
- defer dev.lock.Unlock()
-
- if dev.device != nil {
- C.hid_close(dev.device)
- dev.device = nil
- }
- return nil
-}
-
-// Write sends an output report to a HID device.
-//
-// Write will send the data on the first OUT endpoint, if one exists. If it does
-// not, it will send the data through the Control Endpoint (Endpoint 0).
-func (dev *hidDevice) Write(b []byte) (int, error) {
- // Abort if nothing to write
- if len(b) == 0 {
- return 0, nil
- }
- // Abort if device closed in between
- dev.lock.Lock()
- device := dev.device
- dev.lock.Unlock()
-
- if device == nil {
- return 0, ErrDeviceClosed
- }
- // Prepend a HID report ID on Windows, other OSes don't need it
- var report []byte
- if runtime.GOOS == "windows" {
- report = append([]byte{0x00}, b...)
- } else {
- report = b
- }
- // Execute the write operation
- written := int(C.hid_write(device, (*C.uchar)(&report[0]), C.size_t(len(report))))
- if written == -1 {
- // If the write failed, verify if closed or other error
- dev.lock.Lock()
- device = dev.device
- dev.lock.Unlock()
-
- if device == nil {
- return 0, ErrDeviceClosed
- }
- // Device not closed, some other error occurred
- message := C.hid_error(device)
- if message == nil {
- return 0, errors.New("hidapi: unknown failure")
- }
- failure, _ := wcharTToString(message)
- return 0, errors.New("hidapi: " + failure)
- }
- return written, nil
-}
-
-// Read retrieves an input report from a HID device.
-func (dev *hidDevice) Read(b []byte) (int, error) {
- // Aborth if nothing to read
- if len(b) == 0 {
- return 0, nil
- }
- // Abort if device closed in between
- dev.lock.Lock()
- device := dev.device
- dev.lock.Unlock()
-
- if device == nil {
- return 0, ErrDeviceClosed
- }
- // Execute the read operation
- read := int(C.hid_read(device, (*C.uchar)(&b[0]), C.size_t(len(b))))
- if read == -1 {
- // If the read failed, verify if closed or other error
- dev.lock.Lock()
- device = dev.device
- dev.lock.Unlock()
-
- if device == nil {
- return 0, ErrDeviceClosed
- }
- // Device not closed, some other error occurred
- message := C.hid_error(device)
- if message == nil {
- return 0, errors.New("hidapi: unknown failure")
- }
- failure, _ := wcharTToString(message)
- return 0, errors.New("hidapi: " + failure)
- }
- return read, nil
-}
diff --git a/vendor/github.com/karalabe/usb/hidapi/AUTHORS.txt b/vendor/github.com/karalabe/usb/hidapi/AUTHORS.txt
deleted file mode 100644
index 7acafd78c3..0000000000
--- a/vendor/github.com/karalabe/usb/hidapi/AUTHORS.txt
+++ /dev/null
@@ -1,16 +0,0 @@
-
-HIDAPI Authors:
-
-Alan Ott :
- Original Author and Maintainer
- Linux, Windows, and Mac implementations
-
-Ludovic Rousseau :
- Formatting for Doxygen documentation
- Bug fixes
- Correctness fixes
-
-
-For a comprehensive list of contributions, see the commit list at github:
- http://github.com/signal11/hidapi/commits/master
-
diff --git a/vendor/github.com/karalabe/usb/hidapi/LICENSE-bsd.txt b/vendor/github.com/karalabe/usb/hidapi/LICENSE-bsd.txt
deleted file mode 100644
index 538cdf95cf..0000000000
--- a/vendor/github.com/karalabe/usb/hidapi/LICENSE-bsd.txt
+++ /dev/null
@@ -1,26 +0,0 @@
-Copyright (c) 2010, Alan Ott, Signal 11 Software
-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 Signal 11 Software 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.
diff --git a/vendor/github.com/karalabe/usb/hidapi/LICENSE-gpl3.txt b/vendor/github.com/karalabe/usb/hidapi/LICENSE-gpl3.txt
deleted file mode 100644
index 94a9ed024d..0000000000
--- a/vendor/github.com/karalabe/usb/hidapi/LICENSE-gpl3.txt
+++ /dev/null
@@ -1,674 +0,0 @@
- GNU GENERAL PUBLIC LICENSE
- Version 3, 29 June 2007
-
- Copyright (C) 2007 Free Software Foundation, Inc.
- Everyone is permitted to copy and distribute verbatim copies
- of this license document, but changing it is not allowed.
-
- Preamble
-
- The GNU General Public License is a free, copyleft license for
-software and other kinds of works.
-
- The licenses for most software and other practical works are designed
-to take away your freedom to share and change the works. By contrast,
-the GNU General Public License is intended to guarantee your freedom to
-share and change all versions of a program--to make sure it remains free
-software for all its users. We, the Free Software Foundation, use the
-GNU General Public License for most of our software; it applies also to
-any other work released this way by its authors. You can apply it to
-your programs, too.
-
- When we speak of free software, we are referring to freedom, not
-price. Our General Public Licenses are designed to make sure that you
-have the freedom to distribute copies of free software (and charge for
-them if you wish), that you receive source code or can get it if you
-want it, that you can change the software or use pieces of it in new
-free programs, and that you know you can do these things.
-
- To protect your rights, we need to prevent others from denying you
-these rights or asking you to surrender the rights. Therefore, you have
-certain responsibilities if you distribute copies of the software, or if
-you modify it: responsibilities to respect the freedom of others.
-
- For example, if you distribute copies of such a program, whether
-gratis or for a fee, you must pass on to the recipients the same
-freedoms that you received. You must make sure that they, too, receive
-or can get the source code. And you must show them these terms so they
-know their rights.
-
- Developers that use the GNU GPL protect your rights with two steps:
-(1) assert copyright on the software, and (2) offer you this License
-giving you legal permission to copy, distribute and/or modify it.
-
- For the developers' and authors' protection, the GPL clearly explains
-that there is no warranty for this free software. For both users' and
-authors' sake, the GPL requires that modified versions be marked as
-changed, so that their problems will not be attributed erroneously to
-authors of previous versions.
-
- Some devices are designed to deny users access to install or run
-modified versions of the software inside them, although the manufacturer
-can do so. This is fundamentally incompatible with the aim of
-protecting users' freedom to change the software. The systematic
-pattern of such abuse occurs in the area of products for individuals to
-use, which is precisely where it is most unacceptable. Therefore, we
-have designed this version of the GPL to prohibit the practice for those
-products. If such problems arise substantially in other domains, we
-stand ready to extend this provision to those domains in future versions
-of the GPL, as needed to protect the freedom of users.
-
- Finally, every program is threatened constantly by software patents.
-States should not allow patents to restrict development and use of
-software on general-purpose computers, but in those that do, we wish to
-avoid the special danger that patents applied to a free program could
-make it effectively proprietary. To prevent this, the GPL assures that
-patents cannot be used to render the program non-free.
-
- The precise terms and conditions for copying, distribution and
-modification follow.
-
- TERMS AND CONDITIONS
-
- 0. Definitions.
-
- "This License" refers to version 3 of the GNU General Public License.
-
- "Copyright" also means copyright-like laws that apply to other kinds of
-works, such as semiconductor masks.
-
- "The Program" refers to any copyrightable work licensed under this
-License. Each licensee is addressed as "you". "Licensees" and
-"recipients" may be individuals or organizations.
-
- To "modify" a work means to copy from or adapt all or part of the work
-in a fashion requiring copyright permission, other than the making of an
-exact copy. The resulting work is called a "modified version" of the
-earlier work or a work "based on" the earlier work.
-
- A "covered work" means either the unmodified Program or a work based
-on the Program.
-
- To "propagate" a work means to do anything with it that, without
-permission, would make you directly or secondarily liable for
-infringement under applicable copyright law, except executing it on a
-computer or modifying a private copy. Propagation includes copying,
-distribution (with or without modification), making available to the
-public, and in some countries other activities as well.
-
- To "convey" a work means any kind of propagation that enables other
-parties to make or receive copies. Mere interaction with a user through
-a computer network, with no transfer of a copy, is not conveying.
-
- An interactive user interface displays "Appropriate Legal Notices"
-to the extent that it includes a convenient and prominently visible
-feature that (1) displays an appropriate copyright notice, and (2)
-tells the user that there is no warranty for the work (except to the
-extent that warranties are provided), that licensees may convey the
-work under this License, and how to view a copy of this License. If
-the interface presents a list of user commands or options, such as a
-menu, a prominent item in the list meets this criterion.
-
- 1. Source Code.
-
- The "source code" for a work means the preferred form of the work
-for making modifications to it. "Object code" means any non-source
-form of a work.
-
- A "Standard Interface" means an interface that either is an official
-standard defined by a recognized standards body, or, in the case of
-interfaces specified for a particular programming language, one that
-is widely used among developers working in that language.
-
- The "System Libraries" of an executable work include anything, other
-than the work as a whole, that (a) is included in the normal form of
-packaging a Major Component, but which is not part of that Major
-Component, and (b) serves only to enable use of the work with that
-Major Component, or to implement a Standard Interface for which an
-implementation is available to the public in source code form. A
-"Major Component", in this context, means a major essential component
-(kernel, window system, and so on) of the specific operating system
-(if any) on which the executable work runs, or a compiler used to
-produce the work, or an object code interpreter used to run it.
-
- The "Corresponding Source" for a work in object code form means all
-the source code needed to generate, install, and (for an executable
-work) run the object code and to modify the work, including scripts to
-control those activities. However, it does not include the work's
-System Libraries, or general-purpose tools or generally available free
-programs which are used unmodified in performing those activities but
-which are not part of the work. For example, Corresponding Source
-includes interface definition files associated with source files for
-the work, and the source code for shared libraries and dynamically
-linked subprograms that the work is specifically designed to require,
-such as by intimate data communication or control flow between those
-subprograms and other parts of the work.
-
- The Corresponding Source need not include anything that users
-can regenerate automatically from other parts of the Corresponding
-Source.
-
- The Corresponding Source for a work in source code form is that
-same work.
-
- 2. Basic Permissions.
-
- All rights granted under this License are granted for the term of
-copyright on the Program, and are irrevocable provided the stated
-conditions are met. This License explicitly affirms your unlimited
-permission to run the unmodified Program. The output from running a
-covered work is covered by this License only if the output, given its
-content, constitutes a covered work. This License acknowledges your
-rights of fair use or other equivalent, as provided by copyright law.
-
- You may make, run and propagate covered works that you do not
-convey, without conditions so long as your license otherwise remains
-in force. You may convey covered works to others for the sole purpose
-of having them make modifications exclusively for you, or provide you
-with facilities for running those works, provided that you comply with
-the terms of this License in conveying all material for which you do
-not control copyright. Those thus making or running the covered works
-for you must do so exclusively on your behalf, under your direction
-and control, on terms that prohibit them from making any copies of
-your copyrighted material outside their relationship with you.
-
- Conveying under any other circumstances is permitted solely under
-the conditions stated below. Sublicensing is not allowed; section 10
-makes it unnecessary.
-
- 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
-
- No covered work shall be deemed part of an effective technological
-measure under any applicable law fulfilling obligations under article
-11 of the WIPO copyright treaty adopted on 20 December 1996, or
-similar laws prohibiting or restricting circumvention of such
-measures.
-
- When you convey a covered work, you waive any legal power to forbid
-circumvention of technological measures to the extent such circumvention
-is effected by exercising rights under this License with respect to
-the covered work, and you disclaim any intention to limit operation or
-modification of the work as a means of enforcing, against the work's
-users, your or third parties' legal rights to forbid circumvention of
-technological measures.
-
- 4. Conveying Verbatim Copies.
-
- You may convey verbatim copies of the Program's source code as you
-receive it, in any medium, provided that you conspicuously and
-appropriately publish on each copy an appropriate copyright notice;
-keep intact all notices stating that this License and any
-non-permissive terms added in accord with section 7 apply to the code;
-keep intact all notices of the absence of any warranty; and give all
-recipients a copy of this License along with the Program.
-
- You may charge any price or no price for each copy that you convey,
-and you may offer support or warranty protection for a fee.
-
- 5. Conveying Modified Source Versions.
-
- You may convey a work based on the Program, or the modifications to
-produce it from the Program, in the form of source code under the
-terms of section 4, provided that you also meet all of these conditions:
-
- a) The work must carry prominent notices stating that you modified
- it, and giving a relevant date.
-
- b) The work must carry prominent notices stating that it is
- released under this License and any conditions added under section
- 7. This requirement modifies the requirement in section 4 to
- "keep intact all notices".
-
- c) You must license the entire work, as a whole, under this
- License to anyone who comes into possession of a copy. This
- License will therefore apply, along with any applicable section 7
- additional terms, to the whole of the work, and all its parts,
- regardless of how they are packaged. This License gives no
- permission to license the work in any other way, but it does not
- invalidate such permission if you have separately received it.
-
- d) If the work has interactive user interfaces, each must display
- Appropriate Legal Notices; however, if the Program has interactive
- interfaces that do not display Appropriate Legal Notices, your
- work need not make them do so.
-
- A compilation of a covered work with other separate and independent
-works, which are not by their nature extensions of the covered work,
-and which are not combined with it such as to form a larger program,
-in or on a volume of a storage or distribution medium, is called an
-"aggregate" if the compilation and its resulting copyright are not
-used to limit the access or legal rights of the compilation's users
-beyond what the individual works permit. Inclusion of a covered work
-in an aggregate does not cause this License to apply to the other
-parts of the aggregate.
-
- 6. Conveying Non-Source Forms.
-
- You may convey a covered work in object code form under the terms
-of sections 4 and 5, provided that you also convey the
-machine-readable Corresponding Source under the terms of this License,
-in one of these ways:
-
- a) Convey the object code in, or embodied in, a physical product
- (including a physical distribution medium), accompanied by the
- Corresponding Source fixed on a durable physical medium
- customarily used for software interchange.
-
- b) Convey the object code in, or embodied in, a physical product
- (including a physical distribution medium), accompanied by a
- written offer, valid for at least three years and valid for as
- long as you offer spare parts or customer support for that product
- model, to give anyone who possesses the object code either (1) a
- copy of the Corresponding Source for all the software in the
- product that is covered by this License, on a durable physical
- medium customarily used for software interchange, for a price no
- more than your reasonable cost of physically performing this
- conveying of source, or (2) access to copy the
- Corresponding Source from a network server at no charge.
-
- c) Convey individual copies of the object code with a copy of the
- written offer to provide the Corresponding Source. This
- alternative is allowed only occasionally and noncommercially, and
- only if you received the object code with such an offer, in accord
- with subsection 6b.
-
- d) Convey the object code by offering access from a designated
- place (gratis or for a charge), and offer equivalent access to the
- Corresponding Source in the same way through the same place at no
- further charge. You need not require recipients to copy the
- Corresponding Source along with the object code. If the place to
- copy the object code is a network server, the Corresponding Source
- may be on a different server (operated by you or a third party)
- that supports equivalent copying facilities, provided you maintain
- clear directions next to the object code saying where to find the
- Corresponding Source. Regardless of what server hosts the
- Corresponding Source, you remain obligated to ensure that it is
- available for as long as needed to satisfy these requirements.
-
- e) Convey the object code using peer-to-peer transmission, provided
- you inform other peers where the object code and Corresponding
- Source of the work are being offered to the general public at no
- charge under subsection 6d.
-
- A separable portion of the object code, whose source code is excluded
-from the Corresponding Source as a System Library, need not be
-included in conveying the object code work.
-
- A "User Product" is either (1) a "consumer product", which means any
-tangible personal property which is normally used for personal, family,
-or household purposes, or (2) anything designed or sold for incorporation
-into a dwelling. In determining whether a product is a consumer product,
-doubtful cases shall be resolved in favor of coverage. For a particular
-product received by a particular user, "normally used" refers to a
-typical or common use of that class of product, regardless of the status
-of the particular user or of the way in which the particular user
-actually uses, or expects or is expected to use, the product. A product
-is a consumer product regardless of whether the product has substantial
-commercial, industrial or non-consumer uses, unless such uses represent
-the only significant mode of use of the product.
-
- "Installation Information" for a User Product means any methods,
-procedures, authorization keys, or other information required to install
-and execute modified versions of a covered work in that User Product from
-a modified version of its Corresponding Source. The information must
-suffice to ensure that the continued functioning of the modified object
-code is in no case prevented or interfered with solely because
-modification has been made.
-
- If you convey an object code work under this section in, or with, or
-specifically for use in, a User Product, and the conveying occurs as
-part of a transaction in which the right of possession and use of the
-User Product is transferred to the recipient in perpetuity or for a
-fixed term (regardless of how the transaction is characterized), the
-Corresponding Source conveyed under this section must be accompanied
-by the Installation Information. But this requirement does not apply
-if neither you nor any third party retains the ability to install
-modified object code on the User Product (for example, the work has
-been installed in ROM).
-
- The requirement to provide Installation Information does not include a
-requirement to continue to provide support service, warranty, or updates
-for a work that has been modified or installed by the recipient, or for
-the User Product in which it has been modified or installed. Access to a
-network may be denied when the modification itself materially and
-adversely affects the operation of the network or violates the rules and
-protocols for communication across the network.
-
- Corresponding Source conveyed, and Installation Information provided,
-in accord with this section must be in a format that is publicly
-documented (and with an implementation available to the public in
-source code form), and must require no special password or key for
-unpacking, reading or copying.
-
- 7. Additional Terms.
-
- "Additional permissions" are terms that supplement the terms of this
-License by making exceptions from one or more of its conditions.
-Additional permissions that are applicable to the entire Program shall
-be treated as though they were included in this License, to the extent
-that they are valid under applicable law. If additional permissions
-apply only to part of the Program, that part may be used separately
-under those permissions, but the entire Program remains governed by
-this License without regard to the additional permissions.
-
- When you convey a copy of a covered work, you may at your option
-remove any additional permissions from that copy, or from any part of
-it. (Additional permissions may be written to require their own
-removal in certain cases when you modify the work.) You may place
-additional permissions on material, added by you to a covered work,
-for which you have or can give appropriate copyright permission.
-
- Notwithstanding any other provision of this License, for material you
-add to a covered work, you may (if authorized by the copyright holders of
-that material) supplement the terms of this License with terms:
-
- a) Disclaiming warranty or limiting liability differently from the
- terms of sections 15 and 16 of this License; or
-
- b) Requiring preservation of specified reasonable legal notices or
- author attributions in that material or in the Appropriate Legal
- Notices displayed by works containing it; or
-
- c) Prohibiting misrepresentation of the origin of that material, or
- requiring that modified versions of such material be marked in
- reasonable ways as different from the original version; or
-
- d) Limiting the use for publicity purposes of names of licensors or
- authors of the material; or
-
- e) Declining to grant rights under trademark law for use of some
- trade names, trademarks, or service marks; or
-
- f) Requiring indemnification of licensors and authors of that
- material by anyone who conveys the material (or modified versions of
- it) with contractual assumptions of liability to the recipient, for
- any liability that these contractual assumptions directly impose on
- those licensors and authors.
-
- All other non-permissive additional terms are considered "further
-restrictions" within the meaning of section 10. If the Program as you
-received it, or any part of it, contains a notice stating that it is
-governed by this License along with a term that is a further
-restriction, you may remove that term. If a license document contains
-a further restriction but permits relicensing or conveying under this
-License, you may add to a covered work material governed by the terms
-of that license document, provided that the further restriction does
-not survive such relicensing or conveying.
-
- If you add terms to a covered work in accord with this section, you
-must place, in the relevant source files, a statement of the
-additional terms that apply to those files, or a notice indicating
-where to find the applicable terms.
-
- Additional terms, permissive or non-permissive, may be stated in the
-form of a separately written license, or stated as exceptions;
-the above requirements apply either way.
-
- 8. Termination.
-
- You may not propagate or modify a covered work except as expressly
-provided under this License. Any attempt otherwise to propagate or
-modify it is void, and will automatically terminate your rights under
-this License (including any patent licenses granted under the third
-paragraph of section 11).
-
- However, if you cease all violation of this License, then your
-license from a particular copyright holder is reinstated (a)
-provisionally, unless and until the copyright holder explicitly and
-finally terminates your license, and (b) permanently, if the copyright
-holder fails to notify you of the violation by some reasonable means
-prior to 60 days after the cessation.
-
- Moreover, your license from a particular copyright holder is
-reinstated permanently if the copyright holder notifies you of the
-violation by some reasonable means, this is the first time you have
-received notice of violation of this License (for any work) from that
-copyright holder, and you cure the violation prior to 30 days after
-your receipt of the notice.
-
- Termination of your rights under this section does not terminate the
-licenses of parties who have received copies or rights from you under
-this License. If your rights have been terminated and not permanently
-reinstated, you do not qualify to receive new licenses for the same
-material under section 10.
-
- 9. Acceptance Not Required for Having Copies.
-
- You are not required to accept this License in order to receive or
-run a copy of the Program. Ancillary propagation of a covered work
-occurring solely as a consequence of using peer-to-peer transmission
-to receive a copy likewise does not require acceptance. However,
-nothing other than this License grants you permission to propagate or
-modify any covered work. These actions infringe copyright if you do
-not accept this License. Therefore, by modifying or propagating a
-covered work, you indicate your acceptance of this License to do so.
-
- 10. Automatic Licensing of Downstream Recipients.
-
- Each time you convey a covered work, the recipient automatically
-receives a license from the original licensors, to run, modify and
-propagate that work, subject to this License. You are not responsible
-for enforcing compliance by third parties with this License.
-
- An "entity transaction" is a transaction transferring control of an
-organization, or substantially all assets of one, or subdividing an
-organization, or merging organizations. If propagation of a covered
-work results from an entity transaction, each party to that
-transaction who receives a copy of the work also receives whatever
-licenses to the work the party's predecessor in interest had or could
-give under the previous paragraph, plus a right to possession of the
-Corresponding Source of the work from the predecessor in interest, if
-the predecessor has it or can get it with reasonable efforts.
-
- You may not impose any further restrictions on the exercise of the
-rights granted or affirmed under this License. For example, you may
-not impose a license fee, royalty, or other charge for exercise of
-rights granted under this License, and you may not initiate litigation
-(including a cross-claim or counterclaim in a lawsuit) alleging that
-any patent claim is infringed by making, using, selling, offering for
-sale, or importing the Program or any portion of it.
-
- 11. Patents.
-
- A "contributor" is a copyright holder who authorizes use under this
-License of the Program or a work on which the Program is based. The
-work thus licensed is called the contributor's "contributor version".
-
- A contributor's "essential patent claims" are all patent claims
-owned or controlled by the contributor, whether already acquired or
-hereafter acquired, that would be infringed by some manner, permitted
-by this License, of making, using, or selling its contributor version,
-but do not include claims that would be infringed only as a
-consequence of further modification of the contributor version. For
-purposes of this definition, "control" includes the right to grant
-patent sublicenses in a manner consistent with the requirements of
-this License.
-
- Each contributor grants you a non-exclusive, worldwide, royalty-free
-patent license under the contributor's essential patent claims, to
-make, use, sell, offer for sale, import and otherwise run, modify and
-propagate the contents of its contributor version.
-
- In the following three paragraphs, a "patent license" is any express
-agreement or commitment, however denominated, not to enforce a patent
-(such as an express permission to practice a patent or covenant not to
-sue for patent infringement). To "grant" such a patent license to a
-party means to make such an agreement or commitment not to enforce a
-patent against the party.
-
- If you convey a covered work, knowingly relying on a patent license,
-and the Corresponding Source of the work is not available for anyone
-to copy, free of charge and under the terms of this License, through a
-publicly available network server or other readily accessible means,
-then you must either (1) cause the Corresponding Source to be so
-available, or (2) arrange to deprive yourself of the benefit of the
-patent license for this particular work, or (3) arrange, in a manner
-consistent with the requirements of this License, to extend the patent
-license to downstream recipients. "Knowingly relying" means you have
-actual knowledge that, but for the patent license, your conveying the
-covered work in a country, or your recipient's use of the covered work
-in a country, would infringe one or more identifiable patents in that
-country that you have reason to believe are valid.
-
- If, pursuant to or in connection with a single transaction or
-arrangement, you convey, or propagate by procuring conveyance of, a
-covered work, and grant a patent license to some of the parties
-receiving the covered work authorizing them to use, propagate, modify
-or convey a specific copy of the covered work, then the patent license
-you grant is automatically extended to all recipients of the covered
-work and works based on it.
-
- A patent license is "discriminatory" if it does not include within
-the scope of its coverage, prohibits the exercise of, or is
-conditioned on the non-exercise of one or more of the rights that are
-specifically granted under this License. You may not convey a covered
-work if you are a party to an arrangement with a third party that is
-in the business of distributing software, under which you make payment
-to the third party based on the extent of your activity of conveying
-the work, and under which the third party grants, to any of the
-parties who would receive the covered work from you, a discriminatory
-patent license (a) in connection with copies of the covered work
-conveyed by you (or copies made from those copies), or (b) primarily
-for and in connection with specific products or compilations that
-contain the covered work, unless you entered into that arrangement,
-or that patent license was granted, prior to 28 March 2007.
-
- Nothing in this License shall be construed as excluding or limiting
-any implied license or other defenses to infringement that may
-otherwise be available to you under applicable patent law.
-
- 12. No Surrender of Others' Freedom.
-
- If conditions are imposed on you (whether by court order, agreement or
-otherwise) that contradict the conditions of this License, they do not
-excuse you from the conditions of this License. If you cannot convey a
-covered work so as to satisfy simultaneously your obligations under this
-License and any other pertinent obligations, then as a consequence you may
-not convey it at all. For example, if you agree to terms that obligate you
-to collect a royalty for further conveying from those to whom you convey
-the Program, the only way you could satisfy both those terms and this
-License would be to refrain entirely from conveying the Program.
-
- 13. Use with the GNU Affero General Public License.
-
- Notwithstanding any other provision of this License, you have
-permission to link or combine any covered work with a work licensed
-under version 3 of the GNU Affero General Public License into a single
-combined work, and to convey the resulting work. The terms of this
-License will continue to apply to the part which is the covered work,
-but the special requirements of the GNU Affero General Public License,
-section 13, concerning interaction through a network will apply to the
-combination as such.
-
- 14. Revised Versions of this License.
-
- The Free Software Foundation may publish revised and/or new versions of
-the GNU General Public License from time to time. Such new versions will
-be similar in spirit to the present version, but may differ in detail to
-address new problems or concerns.
-
- Each version is given a distinguishing version number. If the
-Program specifies that a certain numbered version of the GNU General
-Public License "or any later version" applies to it, you have the
-option of following the terms and conditions either of that numbered
-version or of any later version published by the Free Software
-Foundation. If the Program does not specify a version number of the
-GNU General Public License, you may choose any version ever published
-by the Free Software Foundation.
-
- If the Program specifies that a proxy can decide which future
-versions of the GNU General Public License can be used, that proxy's
-public statement of acceptance of a version permanently authorizes you
-to choose that version for the Program.
-
- Later license versions may give you additional or different
-permissions. However, no additional obligations are imposed on any
-author or copyright holder as a result of your choosing to follow a
-later version.
-
- 15. Disclaimer of Warranty.
-
- THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
-APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
-HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
-OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
-THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
-PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
-IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
-ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
-
- 16. Limitation of Liability.
-
- IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
-WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
-THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
-GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
-USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
-DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
-PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
-EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
-SUCH DAMAGES.
-
- 17. Interpretation of Sections 15 and 16.
-
- If the disclaimer of warranty and limitation of liability provided
-above cannot be given local legal effect according to their terms,
-reviewing courts shall apply local law that most closely approximates
-an absolute waiver of all civil liability in connection with the
-Program, unless a warranty or assumption of liability accompanies a
-copy of the Program in return for a fee.
-
- END OF TERMS AND CONDITIONS
-
- How to Apply These Terms to Your New Programs
-
- If you develop a new program, and you want it to be of the greatest
-possible use to the public, the best way to achieve this is to make it
-free software which everyone can redistribute and change under these terms.
-
- To do so, attach the following notices to the program. It is safest
-to attach them to the start of each source file to most effectively
-state the exclusion of warranty; and each file should have at least
-the "copyright" line and a pointer to where the full notice is found.
-
-
- Copyright (C)
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU General Public License for more details.
-
- You should have received a copy of the GNU General Public License
- along with this program. If not, see .
-
-Also add information on how to contact you by electronic and paper mail.
-
- If the program does terminal interaction, make it output a short
-notice like this when it starts in an interactive mode:
-
- Copyright (C)
- This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
- This is free software, and you are welcome to redistribute it
- under certain conditions; type `show c' for details.
-
-The hypothetical commands `show w' and `show c' should show the appropriate
-parts of the General Public License. Of course, your program's commands
-might be different; for a GUI interface, you would use an "about box".
-
- You should also get your employer (if you work as a programmer) or school,
-if any, to sign a "copyright disclaimer" for the program, if necessary.
-For more information on this, and how to apply and follow the GNU GPL, see
-.
-
- The GNU General Public License does not permit incorporating your program
-into proprietary programs. If your program is a subroutine library, you
-may consider it more useful to permit linking proprietary applications with
-the library. If this is what you want to do, use the GNU Lesser General
-Public License instead of this License. But first, please read
-.
diff --git a/vendor/github.com/karalabe/usb/hidapi/LICENSE-orig.txt b/vendor/github.com/karalabe/usb/hidapi/LICENSE-orig.txt
deleted file mode 100644
index e3f3380829..0000000000
--- a/vendor/github.com/karalabe/usb/hidapi/LICENSE-orig.txt
+++ /dev/null
@@ -1,9 +0,0 @@
- HIDAPI - Multi-Platform library for
- communication with HID devices.
-
- Copyright 2009, Alan Ott, Signal 11 Software.
- All Rights Reserved.
-
- This software may be used by anyone for any reason so
- long as the copyright notice in the source files
- remains intact.
diff --git a/vendor/github.com/karalabe/usb/hidapi/LICENSE.txt b/vendor/github.com/karalabe/usb/hidapi/LICENSE.txt
deleted file mode 100644
index e1676d4c42..0000000000
--- a/vendor/github.com/karalabe/usb/hidapi/LICENSE.txt
+++ /dev/null
@@ -1,13 +0,0 @@
-HIDAPI can be used under one of three licenses.
-
-1. The GNU General Public License, version 3.0, in LICENSE-gpl3.txt
-2. A BSD-Style License, in LICENSE-bsd.txt.
-3. The more liberal original HIDAPI license. LICENSE-orig.txt
-
-The license chosen is at the discretion of the user of HIDAPI. For example:
-1. An author of GPL software would likely use HIDAPI under the terms of the
-GPL.
-
-2. An author of commercial closed-source software would likely use HIDAPI
-under the terms of the BSD-style license or the original HIDAPI license.
-
diff --git a/vendor/github.com/karalabe/usb/hidapi/README.txt b/vendor/github.com/karalabe/usb/hidapi/README.txt
deleted file mode 100644
index f19dae4ab7..0000000000
--- a/vendor/github.com/karalabe/usb/hidapi/README.txt
+++ /dev/null
@@ -1,339 +0,0 @@
- HIDAPI library for Windows, Linux, FreeBSD and Mac OS X
- =========================================================
-
-About
-======
-
-HIDAPI is a multi-platform library which allows an application to interface
-with USB and Bluetooth HID-Class devices on Windows, Linux, FreeBSD, and Mac
-OS X. HIDAPI can be either built as a shared library (.so or .dll) or
-can be embedded directly into a target application by adding a single source
-file (per platform) and a single header.
-
-HIDAPI has four back-ends:
- * Windows (using hid.dll)
- * Linux/hidraw (using the Kernel's hidraw driver)
- * Linux/libusb (using libusb-1.0)
- * FreeBSD (using libusb-1.0)
- * Mac (using IOHidManager)
-
-On Linux, either the hidraw or the libusb back-end can be used. There are
-tradeoffs, and the functionality supported is slightly different.
-
-Linux/hidraw (linux/hid.c):
-This back-end uses the hidraw interface in the Linux kernel. While this
-back-end will support both USB and Bluetooth, it has some limitations on
-kernels prior to 2.6.39, including the inability to send or receive feature
-reports. In addition, it will only communicate with devices which have
-hidraw nodes associated with them. Keyboards, mice, and some other devices
-which are blacklisted from having hidraw nodes will not work. Fortunately,
-for nearly all the uses of hidraw, this is not a problem.
-
-Linux/FreeBSD/libusb (libusb/hid.c):
-This back-end uses libusb-1.0 to communicate directly to a USB device. This
-back-end will of course not work with Bluetooth devices.
-
-HIDAPI also comes with a Test GUI. The Test GUI is cross-platform and uses
-Fox Toolkit (http://www.fox-toolkit.org). It will build on every platform
-which HIDAPI supports. Since it relies on a 3rd party library, building it
-is optional but recommended because it is so useful when debugging hardware.
-
-What Does the API Look Like?
-=============================
-The API provides the the most commonly used HID functions including sending
-and receiving of input, output, and feature reports. The sample program,
-which communicates with a heavily hacked up version of the Microchip USB
-Generic HID sample looks like this (with error checking removed for
-simplicity):
-
-#ifdef WIN32
-#include
-#endif
-#include
-#include
-#include "hidapi.h"
-
-#define MAX_STR 255
-
-int main(int argc, char* argv[])
-{
- int res;
- unsigned char buf[65];
- wchar_t wstr[MAX_STR];
- hid_device *handle;
- int i;
-
- // Initialize the hidapi library
- res = hid_init();
-
- // Open the device using the VID, PID,
- // and optionally the Serial number.
- handle = hid_open(0x4d8, 0x3f, NULL);
-
- // Read the Manufacturer String
- res = hid_get_manufacturer_string(handle, wstr, MAX_STR);
- wprintf(L"Manufacturer String: %s\n", wstr);
-
- // Read the Product String
- res = hid_get_product_string(handle, wstr, MAX_STR);
- wprintf(L"Product String: %s\n", wstr);
-
- // Read the Serial Number String
- res = hid_get_serial_number_string(handle, wstr, MAX_STR);
- wprintf(L"Serial Number String: (%d) %s\n", wstr[0], wstr);
-
- // Read Indexed String 1
- res = hid_get_indexed_string(handle, 1, wstr, MAX_STR);
- wprintf(L"Indexed String 1: %s\n", wstr);
-
- // Toggle LED (cmd 0x80). The first byte is the report number (0x0).
- buf[0] = 0x0;
- buf[1] = 0x80;
- res = hid_write(handle, buf, 65);
-
- // Request state (cmd 0x81). The first byte is the report number (0x0).
- buf[0] = 0x0;
- buf[1] = 0x81;
- res = hid_write(handle, buf, 65);
-
- // Read requested state
- res = hid_read(handle, buf, 65);
-
- // Print out the returned buffer.
- for (i = 0; i < 4; i++)
- printf("buf[%d]: %d\n", i, buf[i]);
-
- // Finalize the hidapi library
- res = hid_exit();
-
- return 0;
-}
-
-If you have your own simple test programs which communicate with standard
-hardware development boards (such as those from Microchip, TI, Atmel,
-FreeScale and others), please consider sending me something like the above
-for inclusion into the HIDAPI source. This will help others who have the
-same hardware as you do.
-
-License
-========
-HIDAPI may be used by one of three licenses as outlined in LICENSE.txt.
-
-Download
-=========
-HIDAPI can be downloaded from github
- git clone git://github.com/signal11/hidapi.git
-
-Build Instructions
-===================
-
-This section is long. Don't be put off by this. It's not long because it's
-complicated to build HIDAPI; it's quite the opposite. This section is long
-because of the flexibility of HIDAPI and the large number of ways in which
-it can be built and used. You will likely pick a single build method.
-
-HIDAPI can be built in several different ways. If you elect to build a
-shared library, you will need to build it from the HIDAPI source
-distribution. If you choose instead to embed HIDAPI directly into your
-application, you can skip the building and look at the provided platform
-Makefiles for guidance. These platform Makefiles are located in linux/
-libusb/ mac/ and windows/ and are called Makefile-manual. In addition,
-Visual Studio projects are provided. Even if you're going to embed HIDAPI
-into your project, it is still beneficial to build the example programs.
-
-
-Prerequisites:
----------------
-
- Linux:
- -------
- On Linux, you will need to install development packages for libudev,
- libusb and optionally Fox-toolkit (for the test GUI). On
- Debian/Ubuntu systems these can be installed by running:
- sudo apt-get install libudev-dev libusb-1.0-0-dev libfox-1.6-dev
-
- If you downloaded the source directly from the git repository (using
- git clone), you'll need Autotools:
- sudo apt-get install autotools-dev autoconf automake libtool
-
- FreeBSD:
- ---------
- On FreeBSD you will need to install GNU make, libiconv, and
- optionally Fox-Toolkit (for the test GUI). This is done by running
- the following:
- pkg_add -r gmake libiconv fox16
-
- If you downloaded the source directly from the git repository (using
- git clone), you'll need Autotools:
- pkg_add -r autotools
-
- Mac:
- -----
- On Mac, you will need to install Fox-Toolkit if you wish to build
- the Test GUI. There are two ways to do this, and each has a slight
- complication. Which method you use depends on your use case.
-
- If you wish to build the Test GUI just for your own testing on your
- own computer, then the easiest method is to install Fox-Toolkit
- using ports:
- sudo port install fox
-
- If you wish to build the TestGUI app bundle to redistribute to
- others, you will need to install Fox-toolkit from source. This is
- because the version of fox that gets installed using ports uses the
- ports X11 libraries which are not compatible with the Apple X11
- libraries. If you install Fox with ports and then try to distribute
- your built app bundle, it will simply fail to run on other systems.
- To install Fox-Toolkit manually, download the source package from
- http://www.fox-toolkit.org, extract it, and run the following from
- within the extracted source:
- ./configure && make && make install
-
- Windows:
- ---------
- On Windows, if you want to build the test GUI, you will need to get
- the hidapi-externals.zip package from the download site. This
- contains pre-built binaries for Fox-toolkit. Extract
- hidapi-externals.zip just outside of hidapi, so that
- hidapi-externals and hidapi are on the same level, as shown:
-
- Parent_Folder
- |
- +hidapi
- +hidapi-externals
-
- Again, this step is not required if you do not wish to build the
- test GUI.
-
-
-Building HIDAPI into a shared library on Unix Platforms:
----------------------------------------------------------
-
-On Unix-like systems such as Linux, FreeBSD, Mac, and even Windows, using
-Mingw or Cygwin, the easiest way to build a standard system-installed shared
-library is to use the GNU Autotools build system. If you checked out the
-source from the git repository, run the following:
-
- ./bootstrap
- ./configure
- make
- make install <----- as root, or using sudo
-
-If you downloaded a source package (ie: if you did not run git clone), you
-can skip the ./bootstrap step.
-
-./configure can take several arguments which control the build. The two most
-likely to be used are:
- --enable-testgui
- Enable build of the Test GUI. This requires Fox toolkit to
- be installed. Instructions for installing Fox-Toolkit on
- each platform are in the Prerequisites section above.
-
- --prefix=/usr
- Specify where you want the output headers and libraries to
- be installed. The example above will put the headers in
- /usr/include and the binaries in /usr/lib. The default is to
- install into /usr/local which is fine on most systems.
-
-Building the manual way on Unix platforms:
--------------------------------------------
-
-Manual Makefiles are provided mostly to give the user and idea what it takes
-to build a program which embeds HIDAPI directly inside of it. These should
-really be used as examples only. If you want to build a system-wide shared
-library, use the Autotools method described above.
-
- To build HIDAPI using the manual makefiles, change to the directory
- of your platform and run make. For example, on Linux run:
- cd linux/
- make -f Makefile-manual
-
- To build the Test GUI using the manual makefiles:
- cd testgui/
- make -f Makefile-manual
-
-Building on Windows:
----------------------
-
-To build the HIDAPI DLL on Windows using Visual Studio, build the .sln file
-in the windows/ directory.
-
-To build the Test GUI on windows using Visual Studio, build the .sln file in
-the testgui/ directory.
-
-To build HIDAPI using MinGW or Cygwin using Autotools, use the instructions
-in the section titled "Building HIDAPI into a shared library on Unix
-Platforms" above. Note that building the Test GUI with MinGW or Cygwin will
-require the Windows procedure in the Prerequisites section above (ie:
-hidapi-externals.zip).
-
-To build HIDAPI using MinGW using the Manual Makefiles, see the section
-"Building the manual way on Unix platforms" above.
-
-HIDAPI can also be built using the Windows DDK (now also called the Windows
-Driver Kit or WDK). This method was originally required for the HIDAPI build
-but not anymore. However, some users still prefer this method. It is not as
-well supported anymore but should still work. Patches are welcome if it does
-not. To build using the DDK:
-
- 1. Install the Windows Driver Kit (WDK) from Microsoft.
- 2. From the Start menu, in the Windows Driver Kits folder, select Build
- Environments, then your operating system, then the x86 Free Build
- Environment (or one that is appropriate for your system).
- 3. From the console, change directory to the windows/ddk_build/ directory,
- which is part of the HIDAPI distribution.
- 4. Type build.
- 5. You can find the output files (DLL and LIB) in a subdirectory created
- by the build system which is appropriate for your environment. On
- Windows XP, this directory is objfre_wxp_x86/i386.
-
-Cross Compiling
-================
-
-This section talks about cross compiling HIDAPI for Linux using autotools.
-This is useful for using HIDAPI on embedded Linux targets. These
-instructions assume the most raw kind of embedded Linux build, where all
-prerequisites will need to be built first. This process will of course vary
-based on your embedded Linux build system if you are using one, such as
-OpenEmbedded or Buildroot.
-
-For the purpose of this section, it will be assumed that the following
-environment variables are exported.
-
- $ export STAGING=$HOME/out
- $ export HOST=arm-linux
-
-STAGING and HOST can be modified to suit your setup.
-
-Prerequisites
---------------
-
-Note that the build of libudev is the very basic configuration.
-
-Build Libusb. From the libusb source directory, run:
- ./configure --host=$HOST --prefix=$STAGING
- make
- make install
-
-Build libudev. From the libudev source directory, run:
- ./configure --disable-gudev --disable-introspection --disable-hwdb \
- --host=$HOST --prefix=$STAGING
- make
- make install
-
-Building HIDAPI
-----------------
-
-Build HIDAPI:
-
- PKG_CONFIG_DIR= \
- PKG_CONFIG_LIBDIR=$STAGING/lib/pkgconfig:$STAGING/share/pkgconfig \
- PKG_CONFIG_SYSROOT_DIR=$STAGING \
- ./configure --host=$HOST --prefix=$STAGING
-
-
-Signal 11 Software - 2010-04-11
- 2010-07-28
- 2011-09-10
- 2012-05-01
- 2012-07-03
diff --git a/vendor/github.com/karalabe/usb/hidapi/hidapi/hidapi.h b/vendor/github.com/karalabe/usb/hidapi/hidapi/hidapi.h
deleted file mode 100644
index 166f3509ab..0000000000
--- a/vendor/github.com/karalabe/usb/hidapi/hidapi/hidapi.h
+++ /dev/null
@@ -1,390 +0,0 @@
-/*******************************************************
- HIDAPI - Multi-Platform library for
- communication with HID devices.
-
- Alan Ott
- Signal 11 Software
-
- 8/22/2009
-
- Copyright 2009, All Rights Reserved.
-
- At the discretion of the user of this library,
- this software may be licensed under the terms of the
- GNU General Public License v3, a BSD-Style license, or the
- original HIDAPI license as outlined in the LICENSE.txt,
- LICENSE-gpl3.txt, LICENSE-bsd.txt, and LICENSE-orig.txt
- files located at the root of the source distribution.
- These files may also be found in the public source
- code repository located at:
- http://github.com/signal11/hidapi .
-********************************************************/
-
-/** @file
- * @defgroup API hidapi API
- */
-
-#ifndef HIDAPI_H__
-#define HIDAPI_H__
-
-#include
-
-#ifdef _WIN32
- #define HID_API_EXPORT __declspec(dllexport)
- #define HID_API_CALL
-#else
- #define HID_API_EXPORT /**< API export macro */
- #define HID_API_CALL /**< API call macro */
-#endif
-
-#define HID_API_EXPORT_CALL HID_API_EXPORT HID_API_CALL /**< API export and call macro*/
-
-#ifdef __cplusplus
-extern "C" {
-#endif
- struct hid_device_;
- typedef struct hid_device_ hid_device; /**< opaque hidapi structure */
-
- /** hidapi info structure */
- struct hid_device_info {
- /** Platform-specific device path */
- char *path;
- /** Device Vendor ID */
- unsigned short vendor_id;
- /** Device Product ID */
- unsigned short product_id;
- /** Serial Number */
- wchar_t *serial_number;
- /** Device Release Number in binary-coded decimal,
- also known as Device Version Number */
- unsigned short release_number;
- /** Manufacturer String */
- wchar_t *manufacturer_string;
- /** Product string */
- wchar_t *product_string;
- /** Usage Page for this Device/Interface
- (Windows/Mac only). */
- unsigned short usage_page;
- /** Usage for this Device/Interface
- (Windows/Mac only).*/
- unsigned short usage;
- /** The USB interface which this logical device
- represents. Valid on both Linux implementations
- in all cases, and valid on the Windows implementation
- only if the device contains more than one interface. */
- int interface_number;
-
- /** Pointer to the next device */
- struct hid_device_info *next;
- };
-
-
- /** @brief Initialize the HIDAPI library.
-
- This function initializes the HIDAPI library. Calling it is not
- strictly necessary, as it will be called automatically by
- hid_enumerate() and any of the hid_open_*() functions if it is
- needed. This function should be called at the beginning of
- execution however, if there is a chance of HIDAPI handles
- being opened by different threads simultaneously.
-
- @ingroup API
-
- @returns
- This function returns 0 on success and -1 on error.
- */
- int HID_API_EXPORT HID_API_CALL hid_init(void);
-
- /** @brief Finalize the HIDAPI library.
-
- This function frees all of the static data associated with
- HIDAPI. It should be called at the end of execution to avoid
- memory leaks.
-
- @ingroup API
-
- @returns
- This function returns 0 on success and -1 on error.
- */
- int HID_API_EXPORT HID_API_CALL hid_exit(void);
-
- /** @brief Enumerate the HID Devices.
-
- This function returns a linked list of all the HID devices
- attached to the system which match vendor_id and product_id.
- If @p vendor_id is set to 0 then any vendor matches.
- If @p product_id is set to 0 then any product matches.
- If @p vendor_id and @p product_id are both set to 0, then
- all HID devices will be returned.
-
- @ingroup API
- @param vendor_id The Vendor ID (VID) of the types of device
- to open.
- @param product_id The Product ID (PID) of the types of
- device to open.
-
- @returns
- This function returns a pointer to a linked list of type
- struct #hid_device, containing information about the HID devices
- attached to the system, or NULL in the case of failure. Free
- this linked list by calling hid_free_enumeration().
- */
- struct hid_device_info HID_API_EXPORT * HID_API_CALL hid_enumerate(unsigned short vendor_id, unsigned short product_id);
-
- /** @brief Free an enumeration Linked List
-
- This function frees a linked list created by hid_enumerate().
-
- @ingroup API
- @param devs Pointer to a list of struct_device returned from
- hid_enumerate().
- */
- void HID_API_EXPORT HID_API_CALL hid_free_enumeration(struct hid_device_info *devs);
-
- /** @brief Open a HID device using a Vendor ID (VID), Product ID
- (PID) and optionally a serial number.
-
- If @p serial_number is NULL, the first device with the
- specified VID and PID is opened.
-
- @ingroup API
- @param vendor_id The Vendor ID (VID) of the device to open.
- @param product_id The Product ID (PID) of the device to open.
- @param serial_number The Serial Number of the device to open
- (Optionally NULL).
-
- @returns
- This function returns a pointer to a #hid_device object on
- success or NULL on failure.
- */
- HID_API_EXPORT hid_device * HID_API_CALL hid_open(unsigned short vendor_id, unsigned short product_id, const wchar_t *serial_number);
-
- /** @brief Open a HID device by its path name.
-
- The path name be determined by calling hid_enumerate(), or a
- platform-specific path name can be used (eg: /dev/hidraw0 on
- Linux).
-
- @ingroup API
- @param path The path name of the device to open
-
- @returns
- This function returns a pointer to a #hid_device object on
- success or NULL on failure.
- */
- HID_API_EXPORT hid_device * HID_API_CALL hid_open_path(const char *path);
-
- /** @brief Write an Output report to a HID device.
-
- The first byte of @p data[] must contain the Report ID. For
- devices which only support a single report, this must be set
- to 0x0. The remaining bytes contain the report data. Since
- the Report ID is mandatory, calls to hid_write() will always
- contain one more byte than the report contains. For example,
- if a hid report is 16 bytes long, 17 bytes must be passed to
- hid_write(), the Report ID (or 0x0, for devices with a
- single report), followed by the report data (16 bytes). In
- this example, the length passed in would be 17.
-
- hid_write() will send the data on the first OUT endpoint, if
- one exists. If it does not, it will send the data through
- the Control Endpoint (Endpoint 0).
-
- @ingroup API
- @param device A device handle returned from hid_open().
- @param data The data to send, including the report number as
- the first byte.
- @param length The length in bytes of the data to send.
-
- @returns
- This function returns the actual number of bytes written and
- -1 on error.
- */
- int HID_API_EXPORT HID_API_CALL hid_write(hid_device *device, const unsigned char *data, size_t length);
-
- /** @brief Read an Input report from a HID device with timeout.
-
- Input reports are returned
- to the host through the INTERRUPT IN endpoint. The first byte will
- contain the Report number if the device uses numbered reports.
-
- @ingroup API
- @param device A device handle returned from hid_open().
- @param data A buffer to put the read data into.
- @param length The number of bytes to read. For devices with
- multiple reports, make sure to read an extra byte for
- the report number.
- @param milliseconds timeout in milliseconds or -1 for blocking wait.
-
- @returns
- This function returns the actual number of bytes read and
- -1 on error. If no packet was available to be read within
- the timeout period, this function returns 0.
- */
- int HID_API_EXPORT HID_API_CALL hid_read_timeout(hid_device *dev, unsigned char *data, size_t length, int milliseconds);
-
- /** @brief Read an Input report from a HID device.
-
- Input reports are returned
- to the host through the INTERRUPT IN endpoint. The first byte will
- contain the Report number if the device uses numbered reports.
-
- @ingroup API
- @param device A device handle returned from hid_open().
- @param data A buffer to put the read data into.
- @param length The number of bytes to read. For devices with
- multiple reports, make sure to read an extra byte for
- the report number.
-
- @returns
- This function returns the actual number of bytes read and
- -1 on error. If no packet was available to be read and
- the handle is in non-blocking mode, this function returns 0.
- */
- int HID_API_EXPORT HID_API_CALL hid_read(hid_device *device, unsigned char *data, size_t length);
-
- /** @brief Set the device handle to be non-blocking.
-
- In non-blocking mode calls to hid_read() will return
- immediately with a value of 0 if there is no data to be
- read. In blocking mode, hid_read() will wait (block) until
- there is data to read before returning.
-
- Nonblocking can be turned on and off at any time.
-
- @ingroup API
- @param device A device handle returned from hid_open().
- @param nonblock enable or not the nonblocking reads
- - 1 to enable nonblocking
- - 0 to disable nonblocking.
-
- @returns
- This function returns 0 on success and -1 on error.
- */
- int HID_API_EXPORT HID_API_CALL hid_set_nonblocking(hid_device *device, int nonblock);
-
- /** @brief Send a Feature report to the device.
-
- Feature reports are sent over the Control endpoint as a
- Set_Report transfer. The first byte of @p data[] must
- contain the Report ID. For devices which only support a
- single report, this must be set to 0x0. The remaining bytes
- contain the report data. Since the Report ID is mandatory,
- calls to hid_send_feature_report() will always contain one
- more byte than the report contains. For example, if a hid
- report is 16 bytes long, 17 bytes must be passed to
- hid_send_feature_report(): the Report ID (or 0x0, for
- devices which do not use numbered reports), followed by the
- report data (16 bytes). In this example, the length passed
- in would be 17.
-
- @ingroup API
- @param device A device handle returned from hid_open().
- @param data The data to send, including the report number as
- the first byte.
- @param length The length in bytes of the data to send, including
- the report number.
-
- @returns
- This function returns the actual number of bytes written and
- -1 on error.
- */
- int HID_API_EXPORT HID_API_CALL hid_send_feature_report(hid_device *device, const unsigned char *data, size_t length);
-
- /** @brief Get a feature report from a HID device.
-
- Set the first byte of @p data[] to the Report ID of the
- report to be read. Make sure to allow space for this
- extra byte in @p data[]. Upon return, the first byte will
- still contain the Report ID, and the report data will
- start in data[1].
-
- @ingroup API
- @param device A device handle returned from hid_open().
- @param data A buffer to put the read data into, including
- the Report ID. Set the first byte of @p data[] to the
- Report ID of the report to be read, or set it to zero
- if your device does not use numbered reports.
- @param length The number of bytes to read, including an
- extra byte for the report ID. The buffer can be longer
- than the actual report.
-
- @returns
- This function returns the number of bytes read plus
- one for the report ID (which is still in the first
- byte), or -1 on error.
- */
- int HID_API_EXPORT HID_API_CALL hid_get_feature_report(hid_device *device, unsigned char *data, size_t length);
-
- /** @brief Close a HID device.
-
- @ingroup API
- @param device A device handle returned from hid_open().
- */
- void HID_API_EXPORT HID_API_CALL hid_close(hid_device *device);
-
- /** @brief Get The Manufacturer String from a HID device.
-
- @ingroup API
- @param device A device handle returned from hid_open().
- @param string A wide string buffer to put the data into.
- @param maxlen The length of the buffer in multiples of wchar_t.
-
- @returns
- This function returns 0 on success and -1 on error.
- */
- int HID_API_EXPORT_CALL hid_get_manufacturer_string(hid_device *device, wchar_t *string, size_t maxlen);
-
- /** @brief Get The Product String from a HID device.
-
- @ingroup API
- @param device A device handle returned from hid_open().
- @param string A wide string buffer to put the data into.
- @param maxlen The length of the buffer in multiples of wchar_t.
-
- @returns
- This function returns 0 on success and -1 on error.
- */
- int HID_API_EXPORT_CALL hid_get_product_string(hid_device *device, wchar_t *string, size_t maxlen);
-
- /** @brief Get The Serial Number String from a HID device.
-
- @ingroup API
- @param device A device handle returned from hid_open().
- @param string A wide string buffer to put the data into.
- @param maxlen The length of the buffer in multiples of wchar_t.
-
- @returns
- This function returns 0 on success and -1 on error.
- */
- int HID_API_EXPORT_CALL hid_get_serial_number_string(hid_device *device, wchar_t *string, size_t maxlen);
-
- /** @brief Get a string from a HID device, based on its string index.
-
- @ingroup API
- @param device A device handle returned from hid_open().
- @param string_index The index of the string to get.
- @param string A wide string buffer to put the data into.
- @param maxlen The length of the buffer in multiples of wchar_t.
-
- @returns
- This function returns 0 on success and -1 on error.
- */
- int HID_API_EXPORT_CALL hid_get_indexed_string(hid_device *device, int string_index, wchar_t *string, size_t maxlen);
-
- /** @brief Get a string describing the last error which occurred.
-
- @ingroup API
- @param device A device handle returned from hid_open().
-
- @returns
- This function returns a string containing the last error
- which occurred or NULL if none has occurred.
- */
- HID_API_EXPORT const wchar_t* HID_API_CALL hid_error(hid_device *device);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif
diff --git a/vendor/github.com/karalabe/usb/hidapi/libusb/hid.c b/vendor/github.com/karalabe/usb/hidapi/libusb/hid.c
deleted file mode 100644
index 474dff41c1..0000000000
--- a/vendor/github.com/karalabe/usb/hidapi/libusb/hid.c
+++ /dev/null
@@ -1,1512 +0,0 @@
-/*******************************************************
- HIDAPI - Multi-Platform library for
- communication with HID devices.
-
- Alan Ott
- Signal 11 Software
-
- 8/22/2009
- Linux Version - 6/2/2010
- Libusb Version - 8/13/2010
- FreeBSD Version - 11/1/2011
-
- Copyright 2009, All Rights Reserved.
-
- At the discretion of the user of this library,
- this software may be licensed under the terms of the
- GNU General Public License v3, a BSD-Style license, or the
- original HIDAPI license as outlined in the LICENSE.txt,
- LICENSE-gpl3.txt, LICENSE-bsd.txt, and LICENSE-orig.txt
- files located at the root of the source distribution.
- These files may also be found in the public source
- code repository located at:
- http://github.com/signal11/hidapi .
-********************************************************/
-
-/* C */
-#include
-#include
-#include
-#include
-#include
-#include
-
-/* Unix */
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-
-/* GNU / LibUSB */
-#include
-#ifndef __ANDROID__
-#include
-#endif
-
-#include "hidapi.h"
-
-#ifdef __ANDROID__
-
-/* Barrier implementation because Android/Bionic don't have pthread_barrier.
- This implementation came from Brent Priddy and was posted on
- StackOverflow. It is used with his permission. */
-typedef int pthread_barrierattr_t;
-typedef struct pthread_barrier {
- pthread_mutex_t mutex;
- pthread_cond_t cond;
- int count;
- int trip_count;
-} pthread_barrier_t;
-
-static int pthread_barrier_init(pthread_barrier_t *barrier, const pthread_barrierattr_t *attr, unsigned int count)
-{
- if(count == 0) {
- errno = EINVAL;
- return -1;
- }
-
- if(pthread_mutex_init(&barrier->mutex, 0) < 0) {
- return -1;
- }
- if(pthread_cond_init(&barrier->cond, 0) < 0) {
- pthread_mutex_destroy(&barrier->mutex);
- return -1;
- }
- barrier->trip_count = count;
- barrier->count = 0;
-
- return 0;
-}
-
-static int pthread_barrier_destroy(pthread_barrier_t *barrier)
-{
- pthread_cond_destroy(&barrier->cond);
- pthread_mutex_destroy(&barrier->mutex);
- return 0;
-}
-
-static int pthread_barrier_wait(pthread_barrier_t *barrier)
-{
- pthread_mutex_lock(&barrier->mutex);
- ++(barrier->count);
- if(barrier->count >= barrier->trip_count)
- {
- barrier->count = 0;
- pthread_cond_broadcast(&barrier->cond);
- pthread_mutex_unlock(&barrier->mutex);
- return 1;
- }
- else
- {
- pthread_cond_wait(&barrier->cond, &(barrier->mutex));
- pthread_mutex_unlock(&barrier->mutex);
- return 0;
- }
-}
-
-#endif
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#ifdef DEBUG_PRINTF
-#define LOG(...) fprintf(stderr, __VA_ARGS__)
-#else
-#define LOG(...) do {} while (0)
-#endif
-
-#ifndef __FreeBSD__
-#define DETACH_KERNEL_DRIVER
-#endif
-
-/* Uncomment to enable the retrieval of Usage and Usage Page in
-hid_enumerate(). Warning, on platforms different from FreeBSD
-this is very invasive as it requires the detach
-and re-attach of the kernel driver. See comments inside hid_enumerate().
-libusb HIDAPI programs are encouraged to use the interface number
-instead to differentiate between interfaces on a composite HID device. */
-/*#define INVASIVE_GET_USAGE*/
-
-/* Linked List of input reports received from the device. */
-struct input_report {
- uint8_t *data;
- size_t len;
- struct input_report *next;
-};
-
-
-struct hid_device_ {
- /* Handle to the actual device. */
- libusb_device_handle *device_handle;
-
- /* Endpoint information */
- int input_endpoint;
- int output_endpoint;
- int input_ep_max_packet_size;
-
- /* The interface number of the HID */
- int interface;
-
- /* Indexes of Strings */
- int manufacturer_index;
- int product_index;
- int serial_index;
-
- /* Whether blocking reads are used */
- int blocking; /* boolean */
-
- /* Read thread objects */
- pthread_t thread;
- pthread_mutex_t mutex; /* Protects input_reports */
- pthread_cond_t condition;
- pthread_barrier_t barrier; /* Ensures correct startup sequence */
- int shutdown_thread;
- int cancelled;
- struct libusb_transfer *transfer;
-
- /* List of received input reports. */
- struct input_report *input_reports;
-};
-
-static libusb_context *usb_context = NULL;
-
-uint16_t get_usb_code_for_current_locale(void);
-static int return_data(hid_device *dev, unsigned char *data, size_t length);
-
-static hid_device *new_hid_device(void)
-{
- hid_device *dev = calloc(1, sizeof(hid_device));
- dev->blocking = 1;
-
- pthread_mutex_init(&dev->mutex, NULL);
- pthread_cond_init(&dev->condition, NULL);
- pthread_barrier_init(&dev->barrier, NULL, 2);
-
- return dev;
-}
-
-static void free_hid_device(hid_device *dev)
-{
- /* Clean up the thread objects */
- pthread_barrier_destroy(&dev->barrier);
- pthread_cond_destroy(&dev->condition);
- pthread_mutex_destroy(&dev->mutex);
-
- /* Free the device itself */
- free(dev);
-}
-
-#if 0
-/*TODO: Implement this funciton on hidapi/libusb.. */
-static void register_error(hid_device *device, const char *op)
-{
-
-}
-#endif
-
-#ifdef INVASIVE_GET_USAGE
-/* Get bytes from a HID Report Descriptor.
- Only call with a num_bytes of 0, 1, 2, or 4. */
-static uint32_t get_bytes(uint8_t *rpt, size_t len, size_t num_bytes, size_t cur)
-{
- /* Return if there aren't enough bytes. */
- if (cur + num_bytes >= len)
- return 0;
-
- if (num_bytes == 0)
- return 0;
- else if (num_bytes == 1) {
- return rpt[cur+1];
- }
- else if (num_bytes == 2) {
- return (rpt[cur+2] * 256 + rpt[cur+1]);
- }
- else if (num_bytes == 4) {
- return (rpt[cur+4] * 0x01000000 +
- rpt[cur+3] * 0x00010000 +
- rpt[cur+2] * 0x00000100 +
- rpt[cur+1] * 0x00000001);
- }
- else
- return 0;
-}
-
-/* Retrieves the device's Usage Page and Usage from the report
- descriptor. The algorithm is simple, as it just returns the first
- Usage and Usage Page that it finds in the descriptor.
- The return value is 0 on success and -1 on failure. */
-static int get_usage(uint8_t *report_descriptor, size_t size,
- unsigned short *usage_page, unsigned short *usage)
-{
- unsigned int i = 0;
- int size_code;
- int data_len, key_size;
- int usage_found = 0, usage_page_found = 0;
-
- while (i < size) {
- int key = report_descriptor[i];
- int key_cmd = key & 0xfc;
-
- //printf("key: %02hhx\n", key);
-
- if ((key & 0xf0) == 0xf0) {
- /* This is a Long Item. The next byte contains the
- length of the data section (value) for this key.
- See the HID specification, version 1.11, section
- 6.2.2.3, titled "Long Items." */
- if (i+1 < size)
- data_len = report_descriptor[i+1];
- else
- data_len = 0; /* malformed report */
- key_size = 3;
- }
- else {
- /* This is a Short Item. The bottom two bits of the
- key contain the size code for the data section
- (value) for this key. Refer to the HID
- specification, version 1.11, section 6.2.2.2,
- titled "Short Items." */
- size_code = key & 0x3;
- switch (size_code) {
- case 0:
- case 1:
- case 2:
- data_len = size_code;
- break;
- case 3:
- data_len = 4;
- break;
- default:
- /* Can't ever happen since size_code is & 0x3 */
- data_len = 0;
- break;
- };
- key_size = 1;
- }
-
- if (key_cmd == 0x4) {
- *usage_page = get_bytes(report_descriptor, size, data_len, i);
- usage_page_found = 1;
- //printf("Usage Page: %x\n", (uint32_t)*usage_page);
- }
- if (key_cmd == 0x8) {
- *usage = get_bytes(report_descriptor, size, data_len, i);
- usage_found = 1;
- //printf("Usage: %x\n", (uint32_t)*usage);
- }
-
- if (usage_page_found && usage_found)
- return 0; /* success */
-
- /* Skip over this key and it's associated data */
- i += data_len + key_size;
- }
-
- return -1; /* failure */
-}
-#endif /* INVASIVE_GET_USAGE */
-
-#if defined(__FreeBSD__) && __FreeBSD__ < 10
-/* The libusb version included in FreeBSD < 10 doesn't have this function. In
- mainline libusb, it's inlined in libusb.h. This function will bear a striking
- resemblance to that one, because there's about one way to code it.
-
- Note that the data parameter is Unicode in UTF-16LE encoding.
- Return value is the number of bytes in data, or LIBUSB_ERROR_*.
- */
-static inline int libusb_get_string_descriptor(libusb_device_handle *dev,
- uint8_t descriptor_index, uint16_t lang_id,
- unsigned char *data, int length)
-{
- return libusb_control_transfer(dev,
- LIBUSB_ENDPOINT_IN | 0x0, /* Endpoint 0 IN */
- LIBUSB_REQUEST_GET_DESCRIPTOR,
- (LIBUSB_DT_STRING << 8) | descriptor_index,
- lang_id, data, (uint16_t) length, 1000);
-}
-
-#endif
-
-
-/* Get the first language the device says it reports. This comes from
- USB string #0. */
-static uint16_t get_first_language(libusb_device_handle *dev)
-{
- uint16_t buf[32];
- int len;
-
- /* Get the string from libusb. */
- len = libusb_get_string_descriptor(dev,
- 0x0, /* String ID */
- 0x0, /* Language */
- (unsigned char*)buf,
- sizeof(buf));
- if (len < 4)
- return 0x0;
-
- return buf[1]; /* First two bytes are len and descriptor type. */
-}
-
-static int is_language_supported(libusb_device_handle *dev, uint16_t lang)
-{
- uint16_t buf[32];
- int len;
- int i;
-
- /* Get the string from libusb. */
- len = libusb_get_string_descriptor(dev,
- 0x0, /* String ID */
- 0x0, /* Language */
- (unsigned char*)buf,
- sizeof(buf));
- if (len < 4)
- return 0x0;
-
-
- len /= 2; /* language IDs are two-bytes each. */
- /* Start at index 1 because there are two bytes of protocol data. */
- for (i = 1; i < len; i++) {
- if (buf[i] == lang)
- return 1;
- }
-
- return 0;
-}
-
-
-/* This function returns a newly allocated wide string containing the USB
- device string numbered by the index. The returned string must be freed
- by using free(). */
-static wchar_t *get_usb_string(libusb_device_handle *dev, uint8_t idx)
-{
- char buf[512];
- int len;
- wchar_t *str = NULL;
-
-#ifndef __ANDROID__ /* we don't use iconv on Android */
- wchar_t wbuf[256];
- /* iconv variables */
- iconv_t ic;
- size_t inbytes;
- size_t outbytes;
- size_t res;
-#ifdef __FreeBSD__
- const char *inptr;
-#else
- char *inptr;
-#endif
- char *outptr;
-#endif
-
- /* Determine which language to use. */
- uint16_t lang;
- lang = get_usb_code_for_current_locale();
- if (!is_language_supported(dev, lang))
- lang = get_first_language(dev);
-
- /* Get the string from libusb. */
- len = libusb_get_string_descriptor(dev,
- idx,
- lang,
- (unsigned char*)buf,
- sizeof(buf));
- if (len < 0)
- return NULL;
-
-#ifdef __ANDROID__
-
- /* Bionic does not have iconv support nor wcsdup() function, so it
- has to be done manually. The following code will only work for
- code points that can be represented as a single UTF-16 character,
- and will incorrectly convert any code points which require more
- than one UTF-16 character.
-
- Skip over the first character (2-bytes). */
- len -= 2;
- str = malloc((len / 2 + 1) * sizeof(wchar_t));
- int i;
- for (i = 0; i < len / 2; i++) {
- str[i] = buf[i * 2 + 2] | (buf[i * 2 + 3] << 8);
- }
- str[len / 2] = 0x00000000;
-
-#else
-
- /* buf does not need to be explicitly NULL-terminated because
- it is only passed into iconv() which does not need it. */
-
- /* Initialize iconv. */
- ic = iconv_open("WCHAR_T", "UTF-16LE");
- if (ic == (iconv_t)-1) {
- LOG("iconv_open() failed\n");
- return NULL;
- }
-
- /* Convert to native wchar_t (UTF-32 on glibc/BSD systems).
- Skip the first character (2-bytes). */
- inptr = buf+2;
- inbytes = len-2;
- outptr = (char*) wbuf;
- outbytes = sizeof(wbuf);
- res = iconv(ic, &inptr, &inbytes, &outptr, &outbytes);
- if (res == (size_t)-1) {
- LOG("iconv() failed\n");
- goto err;
- }
-
- /* Write the terminating NULL. */
- wbuf[sizeof(wbuf)/sizeof(wbuf[0])-1] = 0x00000000;
- if (outbytes >= sizeof(wbuf[0]))
- *((wchar_t*)outptr) = 0x00000000;
-
- /* Allocate and copy the string. */
- str = wcsdup(wbuf);
-
-err:
- iconv_close(ic);
-
-#endif
-
- return str;
-}
-
-static char *make_path(libusb_device *dev, int interface_number)
-{
- char str[64];
- snprintf(str, sizeof(str), "%04x:%04x:%02x",
- libusb_get_bus_number(dev),
- libusb_get_device_address(dev),
- interface_number);
- str[sizeof(str)-1] = '\0';
-
- return strdup(str);
-}
-
-
-int HID_API_EXPORT hid_init(void)
-{
- if (!usb_context) {
- const char *locale;
-
- /* Init Libusb */
- if (libusb_init(&usb_context))
- return -1;
-
- /* Set the locale if it's not set. */
- locale = setlocale(LC_CTYPE, NULL);
- if (!locale)
- setlocale(LC_CTYPE, "");
- }
-
- return 0;
-}
-
-int HID_API_EXPORT hid_exit(void)
-{
- if (usb_context) {
- libusb_exit(usb_context);
- usb_context = NULL;
- }
-
- return 0;
-}
-
-struct hid_device_info HID_API_EXPORT *hid_enumerate(unsigned short vendor_id, unsigned short product_id)
-{
- libusb_device **devs;
- libusb_device *dev;
- libusb_device_handle *handle;
- ssize_t num_devs;
- int i = 0;
-
- struct hid_device_info *root = NULL; /* return object */
- struct hid_device_info *cur_dev = NULL;
-
- if(hid_init() < 0)
- return NULL;
-
- num_devs = libusb_get_device_list(usb_context, &devs);
- if (num_devs < 0)
- return NULL;
- while ((dev = devs[i++]) != NULL) {
- struct libusb_device_descriptor desc;
- struct libusb_config_descriptor *conf_desc = NULL;
- int j, k;
- int interface_num = 0;
-
- int res = libusb_get_device_descriptor(dev, &desc);
- unsigned short dev_vid = desc.idVendor;
- unsigned short dev_pid = desc.idProduct;
-
- res = libusb_get_active_config_descriptor(dev, &conf_desc);
- if (res < 0)
- libusb_get_config_descriptor(dev, 0, &conf_desc);
- if (conf_desc) {
- for (j = 0; j < conf_desc->bNumInterfaces; j++) {
- const struct libusb_interface *intf = &conf_desc->interface[j];
- for (k = 0; k < intf->num_altsetting; k++) {
- const struct libusb_interface_descriptor *intf_desc;
- intf_desc = &intf->altsetting[k];
- if (intf_desc->bInterfaceClass == LIBUSB_CLASS_HID) {
- interface_num = intf_desc->bInterfaceNumber;
-
- /* Check the VID/PID against the arguments */
- if ((vendor_id == 0x0 || vendor_id == dev_vid) &&
- (product_id == 0x0 || product_id == dev_pid)) {
- struct hid_device_info *tmp;
-
- /* VID/PID match. Create the record. */
- tmp = calloc(1, sizeof(struct hid_device_info));
- if (cur_dev) {
- cur_dev->next = tmp;
- }
- else {
- root = tmp;
- }
- cur_dev = tmp;
-
- /* Fill out the record */
- cur_dev->next = NULL;
- cur_dev->path = make_path(dev, interface_num);
-
- res = libusb_open(dev, &handle);
-
- if (res >= 0) {
- /* Serial Number */
- if (desc.iSerialNumber > 0)
- cur_dev->serial_number =
- get_usb_string(handle, desc.iSerialNumber);
-
- /* Manufacturer and Product strings */
- if (desc.iManufacturer > 0)
- cur_dev->manufacturer_string =
- get_usb_string(handle, desc.iManufacturer);
- if (desc.iProduct > 0)
- cur_dev->product_string =
- get_usb_string(handle, desc.iProduct);
-
-#ifdef INVASIVE_GET_USAGE
-{
- /*
- This section is removed because it is too
- invasive on the system. Getting a Usage Page
- and Usage requires parsing the HID Report
- descriptor. Getting a HID Report descriptor
- involves claiming the interface. Claiming the
- interface involves detaching the kernel driver.
- Detaching the kernel driver is hard on the system
- because it will unclaim interfaces (if another
- app has them claimed) and the re-attachment of
- the driver will sometimes change /dev entry names.
- It is for these reasons that this section is
- #if 0. For composite devices, use the interface
- field in the hid_device_info struct to distinguish
- between interfaces. */
- unsigned char data[256];
-#ifdef DETACH_KERNEL_DRIVER
- int detached = 0;
- /* Usage Page and Usage */
- res = libusb_kernel_driver_active(handle, interface_num);
- if (res == 1) {
- res = libusb_detach_kernel_driver(handle, interface_num);
- if (res < 0)
- LOG("Couldn't detach kernel driver, even though a kernel driver was attached.");
- else
- detached = 1;
- }
-#endif
- res = libusb_claim_interface(handle, interface_num);
- if (res >= 0) {
- /* Get the HID Report Descriptor. */
- res = libusb_control_transfer(handle, LIBUSB_ENDPOINT_IN|LIBUSB_RECIPIENT_INTERFACE, LIBUSB_REQUEST_GET_DESCRIPTOR, (LIBUSB_DT_REPORT << 8)|interface_num, 0, data, sizeof(data), 5000);
- if (res >= 0) {
- unsigned short page=0, usage=0;
- /* Parse the usage and usage page
- out of the report descriptor. */
- get_usage(data, res, &page, &usage);
- cur_dev->usage_page = page;
- cur_dev->usage = usage;
- }
- else
- LOG("libusb_control_transfer() for getting the HID report failed with %d\n", res);
-
- /* Release the interface */
- res = libusb_release_interface(handle, interface_num);
- if (res < 0)
- LOG("Can't release the interface.\n");
- }
- else
- LOG("Can't claim interface %d\n", res);
-#ifdef DETACH_KERNEL_DRIVER
- /* Re-attach kernel driver if necessary. */
- if (detached) {
- res = libusb_attach_kernel_driver(handle, interface_num);
- if (res < 0)
- LOG("Couldn't re-attach kernel driver.\n");
- }
-#endif
-}
-#endif /* INVASIVE_GET_USAGE */
-
- libusb_close(handle);
- }
- /* VID/PID */
- cur_dev->vendor_id = dev_vid;
- cur_dev->product_id = dev_pid;
-
- /* Release Number */
- cur_dev->release_number = desc.bcdDevice;
-
- /* Interface Number */
- cur_dev->interface_number = interface_num;
- }
- }
- } /* altsettings */
- } /* interfaces */
- libusb_free_config_descriptor(conf_desc);
- }
- }
-
- libusb_free_device_list(devs, 1);
-
- return root;
-}
-
-void HID_API_EXPORT hid_free_enumeration(struct hid_device_info *devs)
-{
- struct hid_device_info *d = devs;
- while (d) {
- struct hid_device_info *next = d->next;
- free(d->path);
- free(d->serial_number);
- free(d->manufacturer_string);
- free(d->product_string);
- free(d);
- d = next;
- }
-}
-
-hid_device * hid_open(unsigned short vendor_id, unsigned short product_id, const wchar_t *serial_number)
-{
- struct hid_device_info *devs, *cur_dev;
- const char *path_to_open = NULL;
- hid_device *handle = NULL;
-
- devs = hid_enumerate(vendor_id, product_id);
- cur_dev = devs;
- while (cur_dev) {
- if (cur_dev->vendor_id == vendor_id &&
- cur_dev->product_id == product_id) {
- if (serial_number) {
- if (cur_dev->serial_number &&
- wcscmp(serial_number, cur_dev->serial_number) == 0) {
- path_to_open = cur_dev->path;
- break;
- }
- }
- else {
- path_to_open = cur_dev->path;
- break;
- }
- }
- cur_dev = cur_dev->next;
- }
-
- if (path_to_open) {
- /* Open the device */
- handle = hid_open_path(path_to_open);
- }
-
- hid_free_enumeration(devs);
-
- return handle;
-}
-
-static void read_callback(struct libusb_transfer *transfer)
-{
- hid_device *dev = transfer->user_data;
- int res;
-
- if (transfer->status == LIBUSB_TRANSFER_COMPLETED) {
-
- struct input_report *rpt = malloc(sizeof(*rpt));
- rpt->data = malloc(transfer->actual_length);
- memcpy(rpt->data, transfer->buffer, transfer->actual_length);
- rpt->len = transfer->actual_length;
- rpt->next = NULL;
-
- pthread_mutex_lock(&dev->mutex);
-
- /* Attach the new report object to the end of the list. */
- if (dev->input_reports == NULL) {
- /* The list is empty. Put it at the root. */
- dev->input_reports = rpt;
- pthread_cond_signal(&dev->condition);
- }
- else {
- /* Find the end of the list and attach. */
- struct input_report *cur = dev->input_reports;
- int num_queued = 0;
- while (cur->next != NULL) {
- cur = cur->next;
- num_queued++;
- }
- cur->next = rpt;
-
- /* Pop one off if we've reached 30 in the queue. This
- way we don't grow forever if the user never reads
- anything from the device. */
- if (num_queued > 30) {
- return_data(dev, NULL, 0);
- }
- }
- pthread_mutex_unlock(&dev->mutex);
- }
- else if (transfer->status == LIBUSB_TRANSFER_CANCELLED) {
- dev->shutdown_thread = 1;
- dev->cancelled = 1;
- return;
- }
- else if (transfer->status == LIBUSB_TRANSFER_NO_DEVICE) {
- dev->shutdown_thread = 1;
- dev->cancelled = 1;
- return;
- }
- else if (transfer->status == LIBUSB_TRANSFER_TIMED_OUT) {
- //LOG("Timeout (normal)\n");
- }
- else {
- LOG("Unknown transfer code: %d\n", transfer->status);
- }
-
- /* Re-submit the transfer object. */
- res = libusb_submit_transfer(transfer);
- if (res != 0) {
- LOG("Unable to submit URB. libusb error code: %d\n", res);
- dev->shutdown_thread = 1;
- dev->cancelled = 1;
- }
-}
-
-
-static void *read_thread(void *param)
-{
- hid_device *dev = param;
- unsigned char *buf;
- const size_t length = dev->input_ep_max_packet_size;
-
- /* Set up the transfer object. */
- buf = malloc(length);
- dev->transfer = libusb_alloc_transfer(0);
- libusb_fill_interrupt_transfer(dev->transfer,
- dev->device_handle,
- dev->input_endpoint,
- buf,
- length,
- read_callback,
- dev,
- 5000/*timeout*/);
-
- /* Make the first submission. Further submissions are made
- from inside read_callback() */
- libusb_submit_transfer(dev->transfer);
-
- /* Notify the main thread that the read thread is up and running. */
- pthread_barrier_wait(&dev->barrier);
-
- /* Handle all the events. */
- while (!dev->shutdown_thread) {
- int res;
- res = libusb_handle_events(usb_context);
- if (res < 0) {
- /* There was an error. */
- LOG("read_thread(): libusb reports error # %d\n", res);
-
- /* Break out of this loop only on fatal error.*/
- if (res != LIBUSB_ERROR_BUSY &&
- res != LIBUSB_ERROR_TIMEOUT &&
- res != LIBUSB_ERROR_OVERFLOW &&
- res != LIBUSB_ERROR_INTERRUPTED) {
- break;
- }
- }
- }
-
- /* Cancel any transfer that may be pending. This call will fail
- if no transfers are pending, but that's OK. */
- libusb_cancel_transfer(dev->transfer);
-
- while (!dev->cancelled)
- libusb_handle_events_completed(usb_context, &dev->cancelled);
-
- /* Now that the read thread is stopping, Wake any threads which are
- waiting on data (in hid_read_timeout()). Do this under a mutex to
- make sure that a thread which is about to go to sleep waiting on
- the condition actually will go to sleep before the condition is
- signaled. */
- pthread_mutex_lock(&dev->mutex);
- pthread_cond_broadcast(&dev->condition);
- pthread_mutex_unlock(&dev->mutex);
-
- /* The dev->transfer->buffer and dev->transfer objects are cleaned up
- in hid_close(). They are not cleaned up here because this thread
- could end either due to a disconnect or due to a user
- call to hid_close(). In both cases the objects can be safely
- cleaned up after the call to pthread_join() (in hid_close()), but
- since hid_close() calls libusb_cancel_transfer(), on these objects,
- they can not be cleaned up here. */
-
- return NULL;
-}
-
-
-hid_device * HID_API_EXPORT hid_open_path(const char *path)
-{
- hid_device *dev = NULL;
-
- libusb_device **devs;
- libusb_device *usb_dev;
- int res;
- int d = 0;
- int good_open = 0;
-
- if(hid_init() < 0)
- return NULL;
-
- dev = new_hid_device();
-
- libusb_get_device_list(usb_context, &devs);
- while ((usb_dev = devs[d++]) != NULL) {
- struct libusb_device_descriptor desc;
- struct libusb_config_descriptor *conf_desc = NULL;
- int i,j,k;
- libusb_get_device_descriptor(usb_dev, &desc);
-
- if (libusb_get_active_config_descriptor(usb_dev, &conf_desc) < 0)
- continue;
- for (j = 0; j < conf_desc->bNumInterfaces; j++) {
- const struct libusb_interface *intf = &conf_desc->interface[j];
- for (k = 0; k < intf->num_altsetting; k++) {
- const struct libusb_interface_descriptor *intf_desc;
- intf_desc = &intf->altsetting[k];
- if (intf_desc->bInterfaceClass == LIBUSB_CLASS_HID) {
- char *dev_path = make_path(usb_dev, intf_desc->bInterfaceNumber);
- if (!strcmp(dev_path, path)) {
- /* Matched Paths. Open this device */
-
- /* OPEN HERE */
- res = libusb_open(usb_dev, &dev->device_handle);
- if (res < 0) {
- LOG("can't open device\n");
- free(dev_path);
- break;
- }
- good_open = 1;
-#ifdef DETACH_KERNEL_DRIVER
- /* Detach the kernel driver, but only if the
- device is managed by the kernel */
- if (libusb_kernel_driver_active(dev->device_handle, intf_desc->bInterfaceNumber) == 1) {
- res = libusb_detach_kernel_driver(dev->device_handle, intf_desc->bInterfaceNumber);
- if (res < 0) {
- libusb_close(dev->device_handle);
- LOG("Unable to detach Kernel Driver\n");
- free(dev_path);
- good_open = 0;
- break;
- }
- }
-#endif
- res = libusb_claim_interface(dev->device_handle, intf_desc->bInterfaceNumber);
- if (res < 0) {
- LOG("can't claim interface %d: %d\n", intf_desc->bInterfaceNumber, res);
- free(dev_path);
- libusb_close(dev->device_handle);
- good_open = 0;
- break;
- }
-
- /* Store off the string descriptor indexes */
- dev->manufacturer_index = desc.iManufacturer;
- dev->product_index = desc.iProduct;
- dev->serial_index = desc.iSerialNumber;
-
- /* Store off the interface number */
- dev->interface = intf_desc->bInterfaceNumber;
-
- /* Find the INPUT and OUTPUT endpoints. An
- OUTPUT endpoint is not required. */
- for (i = 0; i < intf_desc->bNumEndpoints; i++) {
- const struct libusb_endpoint_descriptor *ep
- = &intf_desc->endpoint[i];
-
- /* Determine the type and direction of this
- endpoint. */
- int is_interrupt =
- (ep->bmAttributes & LIBUSB_TRANSFER_TYPE_MASK)
- == LIBUSB_TRANSFER_TYPE_INTERRUPT;
- int is_output =
- (ep->bEndpointAddress & LIBUSB_ENDPOINT_DIR_MASK)
- == LIBUSB_ENDPOINT_OUT;
- int is_input =
- (ep->bEndpointAddress & LIBUSB_ENDPOINT_DIR_MASK)
- == LIBUSB_ENDPOINT_IN;
-
- /* Decide whether to use it for input or output. */
- if (dev->input_endpoint == 0 &&
- is_interrupt && is_input) {
- /* Use this endpoint for INPUT */
- dev->input_endpoint = ep->bEndpointAddress;
- dev->input_ep_max_packet_size = ep->wMaxPacketSize;
- }
- if (dev->output_endpoint == 0 &&
- is_interrupt && is_output) {
- /* Use this endpoint for OUTPUT */
- dev->output_endpoint = ep->bEndpointAddress;
- }
- }
-
- pthread_create(&dev->thread, NULL, read_thread, dev);
-
- /* Wait here for the read thread to be initialized. */
- pthread_barrier_wait(&dev->barrier);
-
- }
- free(dev_path);
- }
- }
- }
- libusb_free_config_descriptor(conf_desc);
-
- }
-
- libusb_free_device_list(devs, 1);
-
- /* If we have a good handle, return it. */
- if (good_open) {
- return dev;
- }
- else {
- /* Unable to open any devices. */
- free_hid_device(dev);
- return NULL;
- }
-}
-
-
-int HID_API_EXPORT hid_write(hid_device *dev, const unsigned char *data, size_t length)
-{
- int res;
- int report_number = data[0];
- int skipped_report_id = 0;
-
- if (report_number == 0x0) {
- data++;
- length--;
- skipped_report_id = 1;
- }
-
-
- if (dev->output_endpoint <= 0) {
- /* No interrupt out endpoint. Use the Control Endpoint */
- res = libusb_control_transfer(dev->device_handle,
- LIBUSB_REQUEST_TYPE_CLASS|LIBUSB_RECIPIENT_INTERFACE|LIBUSB_ENDPOINT_OUT,
- 0x09/*HID Set_Report*/,
- (2/*HID output*/ << 8) | report_number,
- dev->interface,
- (unsigned char *)data, length,
- 1000/*timeout millis*/);
-
- if (res < 0)
- return -1;
-
- if (skipped_report_id)
- length++;
-
- return length;
- }
- else {
- /* Use the interrupt out endpoint */
- int actual_length;
- res = libusb_interrupt_transfer(dev->device_handle,
- dev->output_endpoint,
- (unsigned char*)data,
- length,
- &actual_length, 1000);
-
- if (res < 0)
- return -1;
-
- if (skipped_report_id)
- actual_length++;
-
- return actual_length;
- }
-}
-
-/* Helper function, to simplify hid_read().
- This should be called with dev->mutex locked. */
-static int return_data(hid_device *dev, unsigned char *data, size_t length)
-{
- /* Copy the data out of the linked list item (rpt) into the
- return buffer (data), and delete the liked list item. */
- struct input_report *rpt = dev->input_reports;
- size_t len = (length < rpt->len)? length: rpt->len;
- if (len > 0)
- memcpy(data, rpt->data, len);
- dev->input_reports = rpt->next;
- free(rpt->data);
- free(rpt);
- return len;
-}
-
-static void cleanup_mutex(void *param)
-{
- hid_device *dev = param;
- pthread_mutex_unlock(&dev->mutex);
-}
-
-
-int HID_API_EXPORT hid_read_timeout(hid_device *dev, unsigned char *data, size_t length, int milliseconds)
-{
- int bytes_read = -1;
-
-#if 0
- int transferred;
- int res = libusb_interrupt_transfer(dev->device_handle, dev->input_endpoint, data, length, &transferred, 5000);
- LOG("transferred: %d\n", transferred);
- return transferred;
-#endif
-
- pthread_mutex_lock(&dev->mutex);
- pthread_cleanup_push(&cleanup_mutex, dev);
-
- /* There's an input report queued up. Return it. */
- if (dev->input_reports) {
- /* Return the first one */
- bytes_read = return_data(dev, data, length);
- goto ret;
- }
-
- if (dev->shutdown_thread) {
- /* This means the device has been disconnected.
- An error code of -1 should be returned. */
- bytes_read = -1;
- goto ret;
- }
-
- if (milliseconds == -1) {
- /* Blocking */
- while (!dev->input_reports && !dev->shutdown_thread) {
- pthread_cond_wait(&dev->condition, &dev->mutex);
- }
- if (dev->input_reports) {
- bytes_read = return_data(dev, data, length);
- }
- }
- else if (milliseconds > 0) {
- /* Non-blocking, but called with timeout. */
- int res;
- struct timespec ts;
- clock_gettime(CLOCK_REALTIME, &ts);
- ts.tv_sec += milliseconds / 1000;
- ts.tv_nsec += (milliseconds % 1000) * 1000000;
- if (ts.tv_nsec >= 1000000000L) {
- ts.tv_sec++;
- ts.tv_nsec -= 1000000000L;
- }
-
- while (!dev->input_reports && !dev->shutdown_thread) {
- res = pthread_cond_timedwait(&dev->condition, &dev->mutex, &ts);
- if (res == 0) {
- if (dev->input_reports) {
- bytes_read = return_data(dev, data, length);
- break;
- }
-
- /* If we're here, there was a spurious wake up
- or the read thread was shutdown. Run the
- loop again (ie: don't break). */
- }
- else if (res == ETIMEDOUT) {
- /* Timed out. */
- bytes_read = 0;
- break;
- }
- else {
- /* Error. */
- bytes_read = -1;
- break;
- }
- }
- }
- else {
- /* Purely non-blocking */
- bytes_read = 0;
- }
-
-ret:
- pthread_mutex_unlock(&dev->mutex);
- pthread_cleanup_pop(0);
-
- return bytes_read;
-}
-
-int HID_API_EXPORT hid_read(hid_device *dev, unsigned char *data, size_t length)
-{
- return hid_read_timeout(dev, data, length, dev->blocking ? -1 : 0);
-}
-
-int HID_API_EXPORT hid_set_nonblocking(hid_device *dev, int nonblock)
-{
- dev->blocking = !nonblock;
-
- return 0;
-}
-
-
-int HID_API_EXPORT hid_send_feature_report(hid_device *dev, const unsigned char *data, size_t length)
-{
- int res = -1;
- int skipped_report_id = 0;
- int report_number = data[0];
-
- if (report_number == 0x0) {
- data++;
- length--;
- skipped_report_id = 1;
- }
-
- res = libusb_control_transfer(dev->device_handle,
- LIBUSB_REQUEST_TYPE_CLASS|LIBUSB_RECIPIENT_INTERFACE|LIBUSB_ENDPOINT_OUT,
- 0x09/*HID set_report*/,
- (3/*HID feature*/ << 8) | report_number,
- dev->interface,
- (unsigned char *)data, length,
- 1000/*timeout millis*/);
-
- if (res < 0)
- return -1;
-
- /* Account for the report ID */
- if (skipped_report_id)
- length++;
-
- return length;
-}
-
-int HID_API_EXPORT hid_get_feature_report(hid_device *dev, unsigned char *data, size_t length)
-{
- int res = -1;
- int skipped_report_id = 0;
- int report_number = data[0];
-
- if (report_number == 0x0) {
- /* Offset the return buffer by 1, so that the report ID
- will remain in byte 0. */
- data++;
- length--;
- skipped_report_id = 1;
- }
- res = libusb_control_transfer(dev->device_handle,
- LIBUSB_REQUEST_TYPE_CLASS|LIBUSB_RECIPIENT_INTERFACE|LIBUSB_ENDPOINT_IN,
- 0x01/*HID get_report*/,
- (3/*HID feature*/ << 8) | report_number,
- dev->interface,
- (unsigned char *)data, length,
- 1000/*timeout millis*/);
-
- if (res < 0)
- return -1;
-
- if (skipped_report_id)
- res++;
-
- return res;
-}
-
-
-void HID_API_EXPORT hid_close(hid_device *dev)
-{
- if (!dev)
- return;
-
- /* Cause read_thread() to stop. */
- dev->shutdown_thread = 1;
- libusb_cancel_transfer(dev->transfer);
-
- /* Wait for read_thread() to end. */
- pthread_join(dev->thread, NULL);
-
- /* Clean up the Transfer objects allocated in read_thread(). */
- free(dev->transfer->buffer);
- libusb_free_transfer(dev->transfer);
-
- /* release the interface */
- libusb_release_interface(dev->device_handle, dev->interface);
-
- /* Close the handle */
- libusb_close(dev->device_handle);
-
- /* Clear out the queue of received reports. */
- pthread_mutex_lock(&dev->mutex);
- while (dev->input_reports) {
- return_data(dev, NULL, 0);
- }
- pthread_mutex_unlock(&dev->mutex);
-
- free_hid_device(dev);
-}
-
-
-int HID_API_EXPORT_CALL hid_get_manufacturer_string(hid_device *dev, wchar_t *string, size_t maxlen)
-{
- return hid_get_indexed_string(dev, dev->manufacturer_index, string, maxlen);
-}
-
-int HID_API_EXPORT_CALL hid_get_product_string(hid_device *dev, wchar_t *string, size_t maxlen)
-{
- return hid_get_indexed_string(dev, dev->product_index, string, maxlen);
-}
-
-int HID_API_EXPORT_CALL hid_get_serial_number_string(hid_device *dev, wchar_t *string, size_t maxlen)
-{
- return hid_get_indexed_string(dev, dev->serial_index, string, maxlen);
-}
-
-int HID_API_EXPORT_CALL hid_get_indexed_string(hid_device *dev, int string_index, wchar_t *string, size_t maxlen)
-{
- wchar_t *str;
-
- str = get_usb_string(dev->device_handle, string_index);
- if (str) {
- wcsncpy(string, str, maxlen);
- string[maxlen-1] = L'\0';
- free(str);
- return 0;
- }
- else
- return -1;
-}
-
-
-HID_API_EXPORT const wchar_t * HID_API_CALL hid_error(hid_device *dev)
-{
- return NULL;
-}
-
-
-struct lang_map_entry {
- const char *name;
- const char *string_code;
- uint16_t usb_code;
-};
-
-#define LANG(name,code,usb_code) { name, code, usb_code }
-static struct lang_map_entry lang_map[] = {
- LANG("Afrikaans", "af", 0x0436),
- LANG("Albanian", "sq", 0x041C),
- LANG("Arabic - United Arab Emirates", "ar_ae", 0x3801),
- LANG("Arabic - Bahrain", "ar_bh", 0x3C01),
- LANG("Arabic - Algeria", "ar_dz", 0x1401),
- LANG("Arabic - Egypt", "ar_eg", 0x0C01),
- LANG("Arabic - Iraq", "ar_iq", 0x0801),
- LANG("Arabic - Jordan", "ar_jo", 0x2C01),
- LANG("Arabic - Kuwait", "ar_kw", 0x3401),
- LANG("Arabic - Lebanon", "ar_lb", 0x3001),
- LANG("Arabic - Libya", "ar_ly", 0x1001),
- LANG("Arabic - Morocco", "ar_ma", 0x1801),
- LANG("Arabic - Oman", "ar_om", 0x2001),
- LANG("Arabic - Qatar", "ar_qa", 0x4001),
- LANG("Arabic - Saudi Arabia", "ar_sa", 0x0401),
- LANG("Arabic - Syria", "ar_sy", 0x2801),
- LANG("Arabic - Tunisia", "ar_tn", 0x1C01),
- LANG("Arabic - Yemen", "ar_ye", 0x2401),
- LANG("Armenian", "hy", 0x042B),
- LANG("Azeri - Latin", "az_az", 0x042C),
- LANG("Azeri - Cyrillic", "az_az", 0x082C),
- LANG("Basque", "eu", 0x042D),
- LANG("Belarusian", "be", 0x0423),
- LANG("Bulgarian", "bg", 0x0402),
- LANG("Catalan", "ca", 0x0403),
- LANG("Chinese - China", "zh_cn", 0x0804),
- LANG("Chinese - Hong Kong SAR", "zh_hk", 0x0C04),
- LANG("Chinese - Macau SAR", "zh_mo", 0x1404),
- LANG("Chinese - Singapore", "zh_sg", 0x1004),
- LANG("Chinese - Taiwan", "zh_tw", 0x0404),
- LANG("Croatian", "hr", 0x041A),
- LANG("Czech", "cs", 0x0405),
- LANG("Danish", "da", 0x0406),
- LANG("Dutch - Netherlands", "nl_nl", 0x0413),
- LANG("Dutch - Belgium", "nl_be", 0x0813),
- LANG("English - Australia", "en_au", 0x0C09),
- LANG("English - Belize", "en_bz", 0x2809),
- LANG("English - Canada", "en_ca", 0x1009),
- LANG("English - Caribbean", "en_cb", 0x2409),
- LANG("English - Ireland", "en_ie", 0x1809),
- LANG("English - Jamaica", "en_jm", 0x2009),
- LANG("English - New Zealand", "en_nz", 0x1409),
- LANG("English - Phillippines", "en_ph", 0x3409),
- LANG("English - Southern Africa", "en_za", 0x1C09),
- LANG("English - Trinidad", "en_tt", 0x2C09),
- LANG("English - Great Britain", "en_gb", 0x0809),
- LANG("English - United States", "en_us", 0x0409),
- LANG("Estonian", "et", 0x0425),
- LANG("Farsi", "fa", 0x0429),
- LANG("Finnish", "fi", 0x040B),
- LANG("Faroese", "fo", 0x0438),
- LANG("French - France", "fr_fr", 0x040C),
- LANG("French - Belgium", "fr_be", 0x080C),
- LANG("French - Canada", "fr_ca", 0x0C0C),
- LANG("French - Luxembourg", "fr_lu", 0x140C),
- LANG("French - Switzerland", "fr_ch", 0x100C),
- LANG("Gaelic - Ireland", "gd_ie", 0x083C),
- LANG("Gaelic - Scotland", "gd", 0x043C),
- LANG("German - Germany", "de_de", 0x0407),
- LANG("German - Austria", "de_at", 0x0C07),
- LANG("German - Liechtenstein", "de_li", 0x1407),
- LANG("German - Luxembourg", "de_lu", 0x1007),
- LANG("German - Switzerland", "de_ch", 0x0807),
- LANG("Greek", "el", 0x0408),
- LANG("Hebrew", "he", 0x040D),
- LANG("Hindi", "hi", 0x0439),
- LANG("Hungarian", "hu", 0x040E),
- LANG("Icelandic", "is", 0x040F),
- LANG("Indonesian", "id", 0x0421),
- LANG("Italian - Italy", "it_it", 0x0410),
- LANG("Italian - Switzerland", "it_ch", 0x0810),
- LANG("Japanese", "ja", 0x0411),
- LANG("Korean", "ko", 0x0412),
- LANG("Latvian", "lv", 0x0426),
- LANG("Lithuanian", "lt", 0x0427),
- LANG("F.Y.R.O. Macedonia", "mk", 0x042F),
- LANG("Malay - Malaysia", "ms_my", 0x043E),
- LANG("Malay – Brunei", "ms_bn", 0x083E),
- LANG("Maltese", "mt", 0x043A),
- LANG("Marathi", "mr", 0x044E),
- LANG("Norwegian - Bokml", "no_no", 0x0414),
- LANG("Norwegian - Nynorsk", "no_no", 0x0814),
- LANG("Polish", "pl", 0x0415),
- LANG("Portuguese - Portugal", "pt_pt", 0x0816),
- LANG("Portuguese - Brazil", "pt_br", 0x0416),
- LANG("Raeto-Romance", "rm", 0x0417),
- LANG("Romanian - Romania", "ro", 0x0418),
- LANG("Romanian - Republic of Moldova", "ro_mo", 0x0818),
- LANG("Russian", "ru", 0x0419),
- LANG("Russian - Republic of Moldova", "ru_mo", 0x0819),
- LANG("Sanskrit", "sa", 0x044F),
- LANG("Serbian - Cyrillic", "sr_sp", 0x0C1A),
- LANG("Serbian - Latin", "sr_sp", 0x081A),
- LANG("Setsuana", "tn", 0x0432),
- LANG("Slovenian", "sl", 0x0424),
- LANG("Slovak", "sk", 0x041B),
- LANG("Sorbian", "sb", 0x042E),
- LANG("Spanish - Spain (Traditional)", "es_es", 0x040A),
- LANG("Spanish - Argentina", "es_ar", 0x2C0A),
- LANG("Spanish - Bolivia", "es_bo", 0x400A),
- LANG("Spanish - Chile", "es_cl", 0x340A),
- LANG("Spanish - Colombia", "es_co", 0x240A),
- LANG("Spanish - Costa Rica", "es_cr", 0x140A),
- LANG("Spanish - Dominican Republic", "es_do", 0x1C0A),
- LANG("Spanish - Ecuador", "es_ec", 0x300A),
- LANG("Spanish - Guatemala", "es_gt", 0x100A),
- LANG("Spanish - Honduras", "es_hn", 0x480A),
- LANG("Spanish - Mexico", "es_mx", 0x080A),
- LANG("Spanish - Nicaragua", "es_ni", 0x4C0A),
- LANG("Spanish - Panama", "es_pa", 0x180A),
- LANG("Spanish - Peru", "es_pe", 0x280A),
- LANG("Spanish - Puerto Rico", "es_pr", 0x500A),
- LANG("Spanish - Paraguay", "es_py", 0x3C0A),
- LANG("Spanish - El Salvador", "es_sv", 0x440A),
- LANG("Spanish - Uruguay", "es_uy", 0x380A),
- LANG("Spanish - Venezuela", "es_ve", 0x200A),
- LANG("Southern Sotho", "st", 0x0430),
- LANG("Swahili", "sw", 0x0441),
- LANG("Swedish - Sweden", "sv_se", 0x041D),
- LANG("Swedish - Finland", "sv_fi", 0x081D),
- LANG("Tamil", "ta", 0x0449),
- LANG("Tatar", "tt", 0X0444),
- LANG("Thai", "th", 0x041E),
- LANG("Turkish", "tr", 0x041F),
- LANG("Tsonga", "ts", 0x0431),
- LANG("Ukrainian", "uk", 0x0422),
- LANG("Urdu", "ur", 0x0420),
- LANG("Uzbek - Cyrillic", "uz_uz", 0x0843),
- LANG("Uzbek – Latin", "uz_uz", 0x0443),
- LANG("Vietnamese", "vi", 0x042A),
- LANG("Xhosa", "xh", 0x0434),
- LANG("Yiddish", "yi", 0x043D),
- LANG("Zulu", "zu", 0x0435),
- LANG(NULL, NULL, 0x0),
-};
-
-uint16_t get_usb_code_for_current_locale(void)
-{
- char *locale;
- char search_string[64];
- char *ptr;
- struct lang_map_entry *lang;
-
- /* Get the current locale. */
- locale = setlocale(0, NULL);
- if (!locale)
- return 0x0;
-
- /* Make a copy of the current locale string. */
- strncpy(search_string, locale, sizeof(search_string));
- search_string[sizeof(search_string)-1] = '\0';
-
- /* Chop off the encoding part, and make it lower case. */
- ptr = search_string;
- while (*ptr) {
- *ptr = tolower(*ptr);
- if (*ptr == '.') {
- *ptr = '\0';
- break;
- }
- ptr++;
- }
-
- /* Find the entry which matches the string code of our locale. */
- lang = lang_map;
- while (lang->string_code) {
- if (!strcmp(lang->string_code, search_string)) {
- return lang->usb_code;
- }
- lang++;
- }
-
- /* There was no match. Find with just the language only. */
- /* Chop off the variant. Chop it off at the '_'. */
- ptr = search_string;
- while (*ptr) {
- *ptr = tolower(*ptr);
- if (*ptr == '_') {
- *ptr = '\0';
- break;
- }
- ptr++;
- }
-
-#if 0 /* TODO: Do we need this? */
- /* Find the entry which matches the string code of our language. */
- lang = lang_map;
- while (lang->string_code) {
- if (!strcmp(lang->string_code, search_string)) {
- return lang->usb_code;
- }
- lang++;
- }
-#endif
-
- /* Found nothing. */
- return 0x0;
-}
-
-#ifdef __cplusplus
-}
-#endif
diff --git a/vendor/github.com/karalabe/usb/hidapi/mac/hid.c b/vendor/github.com/karalabe/usb/hidapi/mac/hid.c
deleted file mode 100644
index e0756a1588..0000000000
--- a/vendor/github.com/karalabe/usb/hidapi/mac/hid.c
+++ /dev/null
@@ -1,1110 +0,0 @@
-/*******************************************************
- HIDAPI - Multi-Platform library for
- communication with HID devices.
-
- Alan Ott
- Signal 11 Software
-
- 2010-07-03
-
- Copyright 2010, All Rights Reserved.
-
- At the discretion of the user of this library,
- this software may be licensed under the terms of the
- GNU General Public License v3, a BSD-Style license, or the
- original HIDAPI license as outlined in the LICENSE.txt,
- LICENSE-gpl3.txt, LICENSE-bsd.txt, and LICENSE-orig.txt
- files located at the root of the source distribution.
- These files may also be found in the public source
- code repository located at:
- http://github.com/signal11/hidapi .
-********************************************************/
-
-/* See Apple Technical Note TN2187 for details on IOHidManager. */
-
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-#include
-
-#include "hidapi.h"
-
-/* Barrier implementation because Mac OSX doesn't have pthread_barrier.
- It also doesn't have clock_gettime(). So much for POSIX and SUSv2.
- This implementation came from Brent Priddy and was posted on
- StackOverflow. It is used with his permission. */
-typedef int pthread_barrierattr_t;
-typedef struct pthread_barrier {
- pthread_mutex_t mutex;
- pthread_cond_t cond;
- int count;
- int trip_count;
-} pthread_barrier_t;
-
-static int pthread_barrier_init(pthread_barrier_t *barrier, const pthread_barrierattr_t *attr, unsigned int count)
-{
- if(count == 0) {
- errno = EINVAL;
- return -1;
- }
-
- if(pthread_mutex_init(&barrier->mutex, 0) < 0) {
- return -1;
- }
- if(pthread_cond_init(&barrier->cond, 0) < 0) {
- pthread_mutex_destroy(&barrier->mutex);
- return -1;
- }
- barrier->trip_count = count;
- barrier->count = 0;
-
- return 0;
-}
-
-static int pthread_barrier_destroy(pthread_barrier_t *barrier)
-{
- pthread_cond_destroy(&barrier->cond);
- pthread_mutex_destroy(&barrier->mutex);
- return 0;
-}
-
-static int pthread_barrier_wait(pthread_barrier_t *barrier)
-{
- pthread_mutex_lock(&barrier->mutex);
- ++(barrier->count);
- if(barrier->count >= barrier->trip_count)
- {
- barrier->count = 0;
- pthread_cond_broadcast(&barrier->cond);
- pthread_mutex_unlock(&barrier->mutex);
- return 1;
- }
- else
- {
- pthread_cond_wait(&barrier->cond, &(barrier->mutex));
- pthread_mutex_unlock(&barrier->mutex);
- return 0;
- }
-}
-
-static int return_data(hid_device *dev, unsigned char *data, size_t length);
-
-/* Linked List of input reports received from the device. */
-struct input_report {
- uint8_t *data;
- size_t len;
- struct input_report *next;
-};
-
-struct hid_device_ {
- IOHIDDeviceRef device_handle;
- int blocking;
- int uses_numbered_reports;
- int disconnected;
- CFStringRef run_loop_mode;
- CFRunLoopRef run_loop;
- CFRunLoopSourceRef source;
- uint8_t *input_report_buf;
- CFIndex max_input_report_len;
- struct input_report *input_reports;
-
- pthread_t thread;
- pthread_mutex_t mutex; /* Protects input_reports */
- pthread_cond_t condition;
- pthread_barrier_t barrier; /* Ensures correct startup sequence */
- pthread_barrier_t shutdown_barrier; /* Ensures correct shutdown sequence */
- int shutdown_thread;
-};
-
-static hid_device *new_hid_device(void)
-{
- hid_device *dev = calloc(1, sizeof(hid_device));
- dev->device_handle = NULL;
- dev->blocking = 1;
- dev->uses_numbered_reports = 0;
- dev->disconnected = 0;
- dev->run_loop_mode = NULL;
- dev->run_loop = NULL;
- dev->source = NULL;
- dev->input_report_buf = NULL;
- dev->input_reports = NULL;
- dev->shutdown_thread = 0;
-
- /* Thread objects */
- pthread_mutex_init(&dev->mutex, NULL);
- pthread_cond_init(&dev->condition, NULL);
- pthread_barrier_init(&dev->barrier, NULL, 2);
- pthread_barrier_init(&dev->shutdown_barrier, NULL, 2);
-
- return dev;
-}
-
-static void free_hid_device(hid_device *dev)
-{
- if (!dev)
- return;
-
- /* Delete any input reports still left over. */
- struct input_report *rpt = dev->input_reports;
- while (rpt) {
- struct input_report *next = rpt->next;
- free(rpt->data);
- free(rpt);
- rpt = next;
- }
-
- /* Free the string and the report buffer. The check for NULL
- is necessary here as CFRelease() doesn't handle NULL like
- free() and others do. */
- if (dev->run_loop_mode)
- CFRelease(dev->run_loop_mode);
- if (dev->source)
- CFRelease(dev->source);
- free(dev->input_report_buf);
-
- /* Clean up the thread objects */
- pthread_barrier_destroy(&dev->shutdown_barrier);
- pthread_barrier_destroy(&dev->barrier);
- pthread_cond_destroy(&dev->condition);
- pthread_mutex_destroy(&dev->mutex);
-
- /* Free the structure itself. */
- free(dev);
-}
-
-static IOHIDManagerRef hid_mgr = 0x0;
-
-
-#if 0
-static void register_error(hid_device *device, const char *op)
-{
-
-}
-#endif
-
-
-static int32_t get_int_property(IOHIDDeviceRef device, CFStringRef key)
-{
- CFTypeRef ref;
- int32_t value;
-
- ref = IOHIDDeviceGetProperty(device, key);
- if (ref) {
- if (CFGetTypeID(ref) == CFNumberGetTypeID()) {
- CFNumberGetValue((CFNumberRef) ref, kCFNumberSInt32Type, &value);
- return value;
- }
- }
- return 0;
-}
-
-static unsigned short get_vendor_id(IOHIDDeviceRef device)
-{
- return get_int_property(device, CFSTR(kIOHIDVendorIDKey));
-}
-
-static unsigned short get_product_id(IOHIDDeviceRef device)
-{
- return get_int_property(device, CFSTR(kIOHIDProductIDKey));
-}
-
-static int32_t get_max_report_length(IOHIDDeviceRef device)
-{
- return get_int_property(device, CFSTR(kIOHIDMaxInputReportSizeKey));
-}
-
-static int get_string_property(IOHIDDeviceRef device, CFStringRef prop, wchar_t *buf, size_t len)
-{
- CFStringRef str;
-
- if (!len)
- return 0;
-
- str = IOHIDDeviceGetProperty(device, prop);
-
- buf[0] = 0;
-
- if (str) {
- CFIndex str_len = CFStringGetLength(str);
- CFRange range;
- CFIndex used_buf_len;
- CFIndex chars_copied;
-
- len --;
-
- range.location = 0;
- range.length = ((size_t)str_len > len)? len: (size_t)str_len;
- chars_copied = CFStringGetBytes(str,
- range,
- kCFStringEncodingUTF32LE,
- (char)'?',
- FALSE,
- (UInt8*)buf,
- len * sizeof(wchar_t),
- &used_buf_len);
-
- if (chars_copied == len)
- buf[len] = 0; /* len is decremented above */
- else
- buf[chars_copied] = 0;
-
- return 0;
- }
- else
- return -1;
-
-}
-
-static int get_serial_number(IOHIDDeviceRef device, wchar_t *buf, size_t len)
-{
- return get_string_property(device, CFSTR(kIOHIDSerialNumberKey), buf, len);
-}
-
-static int get_manufacturer_string(IOHIDDeviceRef device, wchar_t *buf, size_t len)
-{
- return get_string_property(device, CFSTR(kIOHIDManufacturerKey), buf, len);
-}
-
-static int get_product_string(IOHIDDeviceRef device, wchar_t *buf, size_t len)
-{
- return get_string_property(device, CFSTR(kIOHIDProductKey), buf, len);
-}
-
-
-/* Implementation of wcsdup() for Mac. */
-static wchar_t *dup_wcs(const wchar_t *s)
-{
- size_t len = wcslen(s);
- wchar_t *ret = malloc((len+1)*sizeof(wchar_t));
- wcscpy(ret, s);
-
- return ret;
-}
-
-/* hidapi_IOHIDDeviceGetService()
- *
- * Return the io_service_t corresponding to a given IOHIDDeviceRef, either by:
- * - on OS X 10.6 and above, calling IOHIDDeviceGetService()
- * - on OS X 10.5, extract it from the IOHIDDevice struct
- */
-static io_service_t hidapi_IOHIDDeviceGetService(IOHIDDeviceRef device)
-{
- static void *iokit_framework = NULL;
- static io_service_t (*dynamic_IOHIDDeviceGetService)(IOHIDDeviceRef device) = NULL;
-
- /* Use dlopen()/dlsym() to get a pointer to IOHIDDeviceGetService() if it exists.
- * If any of these steps fail, dynamic_IOHIDDeviceGetService will be left NULL
- * and the fallback method will be used.
- */
- if (iokit_framework == NULL) {
- iokit_framework = dlopen("/System/Library/IOKit.framework/IOKit", RTLD_LAZY);
-
- if (iokit_framework != NULL)
- dynamic_IOHIDDeviceGetService = dlsym(iokit_framework, "IOHIDDeviceGetService");
- }
-
- if (dynamic_IOHIDDeviceGetService != NULL) {
- /* Running on OS X 10.6 and above: IOHIDDeviceGetService() exists */
- return dynamic_IOHIDDeviceGetService(device);
- }
- else
- {
- /* Running on OS X 10.5: IOHIDDeviceGetService() doesn't exist.
- *
- * Be naughty and pull the service out of the IOHIDDevice.
- * IOHIDDevice is an opaque struct not exposed to applications, but its
- * layout is stable through all available versions of OS X.
- * Tested and working on OS X 10.5.8 i386, x86_64, and ppc.
- */
- struct IOHIDDevice_internal {
- /* The first field of the IOHIDDevice struct is a
- * CFRuntimeBase (which is a private CF struct).
- *
- * a, b, and c are the 3 fields that make up a CFRuntimeBase.
- * See http://opensource.apple.com/source/CF/CF-476.18/CFRuntime.h
- *
- * The second field of the IOHIDDevice is the io_service_t we're looking for.
- */
- uintptr_t a;
- uint8_t b[4];
-#if __LP64__
- uint32_t c;
-#endif
- io_service_t service;
- };
- struct IOHIDDevice_internal *tmp = (struct IOHIDDevice_internal *)device;
-
- return tmp->service;
- }
-}
-
-/* Initialize the IOHIDManager. Return 0 for success and -1 for failure. */
-static int init_hid_manager(void)
-{
- /* Initialize all the HID Manager Objects */
- hid_mgr = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDOptionsTypeNone);
- if (hid_mgr) {
- IOHIDManagerSetDeviceMatching(hid_mgr, NULL);
- IOHIDManagerScheduleWithRunLoop(hid_mgr, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);
- return 0;
- }
-
- return -1;
-}
-
-/* Initialize the IOHIDManager if necessary. This is the public function, and
- it is safe to call this function repeatedly. Return 0 for success and -1
- for failure. */
-int HID_API_EXPORT hid_init(void)
-{
- if (!hid_mgr) {
- return init_hid_manager();
- }
-
- /* Already initialized. */
- return 0;
-}
-
-int HID_API_EXPORT hid_exit(void)
-{
- if (hid_mgr) {
- /* Close the HID manager. */
- IOHIDManagerClose(hid_mgr, kIOHIDOptionsTypeNone);
- CFRelease(hid_mgr);
- hid_mgr = NULL;
- }
-
- return 0;
-}
-
-static void process_pending_events(void) {
- SInt32 res;
- do {
- res = CFRunLoopRunInMode(kCFRunLoopDefaultMode, 0.001, FALSE);
- } while(res != kCFRunLoopRunFinished && res != kCFRunLoopRunTimedOut);
-}
-
-struct hid_device_info HID_API_EXPORT *hid_enumerate(unsigned short vendor_id, unsigned short product_id)
-{
- struct hid_device_info *root = NULL; /* return object */
- struct hid_device_info *cur_dev = NULL;
- CFIndex num_devices;
- int i;
-
- /* Set up the HID Manager if it hasn't been done */
- if (hid_init() < 0)
- return NULL;
-
- /* give the IOHIDManager a chance to update itself */
- process_pending_events();
-
- /* Get a list of the Devices */
- IOHIDManagerSetDeviceMatching(hid_mgr, NULL);
- CFSetRef device_set = IOHIDManagerCopyDevices(hid_mgr);
-
- /* Convert the list into a C array so we can iterate easily. */
- num_devices = CFSetGetCount(device_set);
- IOHIDDeviceRef *device_array = calloc(num_devices, sizeof(IOHIDDeviceRef));
- CFSetGetValues(device_set, (const void **) device_array);
-
- /* Iterate over each device, making an entry for it. */
- for (i = 0; i < num_devices; i++) {
- unsigned short dev_vid;
- unsigned short dev_pid;
- #define BUF_LEN 256
- wchar_t buf[BUF_LEN];
-
- IOHIDDeviceRef dev = device_array[i];
-
- if (!dev) {
- continue;
- }
- dev_vid = get_vendor_id(dev);
- dev_pid = get_product_id(dev);
-
- /* Check the VID/PID against the arguments */
- if ((vendor_id == 0x0 || vendor_id == dev_vid) &&
- (product_id == 0x0 || product_id == dev_pid)) {
- struct hid_device_info *tmp;
- io_object_t iokit_dev;
- kern_return_t res;
- io_string_t path;
-
- /* VID/PID match. Create the record. */
- tmp = malloc(sizeof(struct hid_device_info));
- if (cur_dev) {
- cur_dev->next = tmp;
- }
- else {
- root = tmp;
- }
- cur_dev = tmp;
-
- /* Get the Usage Page and Usage for this device. */
- cur_dev->usage_page = get_int_property(dev, CFSTR(kIOHIDPrimaryUsagePageKey));
- cur_dev->usage = get_int_property(dev, CFSTR(kIOHIDPrimaryUsageKey));
-
- /* Fill out the record */
- cur_dev->next = NULL;
-
- /* Fill in the path (IOService plane) */
- iokit_dev = hidapi_IOHIDDeviceGetService(dev);
- res = IORegistryEntryGetPath(iokit_dev, kIOServicePlane, path);
- if (res == KERN_SUCCESS)
- cur_dev->path = strdup(path);
- else
- cur_dev->path = strdup("");
-
- /* Serial Number */
- get_serial_number(dev, buf, BUF_LEN);
- cur_dev->serial_number = dup_wcs(buf);
-
- /* Manufacturer and Product strings */
- get_manufacturer_string(dev, buf, BUF_LEN);
- cur_dev->manufacturer_string = dup_wcs(buf);
- get_product_string(dev, buf, BUF_LEN);
- cur_dev->product_string = dup_wcs(buf);
-
- /* VID/PID */
- cur_dev->vendor_id = dev_vid;
- cur_dev->product_id = dev_pid;
-
- /* Release Number */
- cur_dev->release_number = get_int_property(dev, CFSTR(kIOHIDVersionNumberKey));
-
- /* Interface Number (Unsupported on Mac)*/
- cur_dev->interface_number = -1;
- }
- }
-
- free(device_array);
- CFRelease(device_set);
-
- return root;
-}
-
-void HID_API_EXPORT hid_free_enumeration(struct hid_device_info *devs)
-{
- /* This function is identical to the Linux version. Platform independent. */
- struct hid_device_info *d = devs;
- while (d) {
- struct hid_device_info *next = d->next;
- free(d->path);
- free(d->serial_number);
- free(d->manufacturer_string);
- free(d->product_string);
- free(d);
- d = next;
- }
-}
-
-hid_device * HID_API_EXPORT hid_open(unsigned short vendor_id, unsigned short product_id, const wchar_t *serial_number)
-{
- /* This function is identical to the Linux version. Platform independent. */
- struct hid_device_info *devs, *cur_dev;
- const char *path_to_open = NULL;
- hid_device * handle = NULL;
-
- devs = hid_enumerate(vendor_id, product_id);
- cur_dev = devs;
- while (cur_dev) {
- if (cur_dev->vendor_id == vendor_id &&
- cur_dev->product_id == product_id) {
- if (serial_number) {
- if (wcscmp(serial_number, cur_dev->serial_number) == 0) {
- path_to_open = cur_dev->path;
- break;
- }
- }
- else {
- path_to_open = cur_dev->path;
- break;
- }
- }
- cur_dev = cur_dev->next;
- }
-
- if (path_to_open) {
- /* Open the device */
- handle = hid_open_path(path_to_open);
- }
-
- hid_free_enumeration(devs);
-
- return handle;
-}
-
-static void hid_device_removal_callback(void *context, IOReturn result,
- void *sender)
-{
- /* Stop the Run Loop for this device. */
- hid_device *d = context;
-
- d->disconnected = 1;
- CFRunLoopStop(d->run_loop);
-}
-
-/* The Run Loop calls this function for each input report received.
- This function puts the data into a linked list to be picked up by
- hid_read(). */
-static void hid_report_callback(void *context, IOReturn result, void *sender,
- IOHIDReportType report_type, uint32_t report_id,
- uint8_t *report, CFIndex report_length)
-{
- struct input_report *rpt;
- hid_device *dev = context;
-
- /* Make a new Input Report object */
- rpt = calloc(1, sizeof(struct input_report));
- rpt->data = calloc(1, report_length);
- memcpy(rpt->data, report, report_length);
- rpt->len = report_length;
- rpt->next = NULL;
-
- /* Lock this section */
- pthread_mutex_lock(&dev->mutex);
-
- /* Attach the new report object to the end of the list. */
- if (dev->input_reports == NULL) {
- /* The list is empty. Put it at the root. */
- dev->input_reports = rpt;
- }
- else {
- /* Find the end of the list and attach. */
- struct input_report *cur = dev->input_reports;
- int num_queued = 0;
- while (cur->next != NULL) {
- cur = cur->next;
- num_queued++;
- }
- cur->next = rpt;
-
- /* Pop one off if we've reached 30 in the queue. This
- way we don't grow forever if the user never reads
- anything from the device. */
- if (num_queued > 30) {
- return_data(dev, NULL, 0);
- }
- }
-
- /* Signal a waiting thread that there is data. */
- pthread_cond_signal(&dev->condition);
-
- /* Unlock */
- pthread_mutex_unlock(&dev->mutex);
-
-}
-
-/* This gets called when the read_thread's run loop gets signaled by
- hid_close(), and serves to stop the read_thread's run loop. */
-static void perform_signal_callback(void *context)
-{
- hid_device *dev = context;
- CFRunLoopStop(dev->run_loop); /*TODO: CFRunLoopGetCurrent()*/
-}
-
-static void *read_thread(void *param)
-{
- hid_device *dev = param;
- SInt32 code;
-
- /* Move the device's run loop to this thread. */
- IOHIDDeviceScheduleWithRunLoop(dev->device_handle, CFRunLoopGetCurrent(), dev->run_loop_mode);
-
- /* Create the RunLoopSource which is used to signal the
- event loop to stop when hid_close() is called. */
- CFRunLoopSourceContext ctx;
- memset(&ctx, 0, sizeof(ctx));
- ctx.version = 0;
- ctx.info = dev;
- ctx.perform = &perform_signal_callback;
- dev->source = CFRunLoopSourceCreate(kCFAllocatorDefault, 0/*order*/, &ctx);
- CFRunLoopAddSource(CFRunLoopGetCurrent(), dev->source, dev->run_loop_mode);
-
- /* Store off the Run Loop so it can be stopped from hid_close()
- and on device disconnection. */
- dev->run_loop = CFRunLoopGetCurrent();
-
- /* Notify the main thread that the read thread is up and running. */
- pthread_barrier_wait(&dev->barrier);
-
- /* Run the Event Loop. CFRunLoopRunInMode() will dispatch HID input
- reports into the hid_report_callback(). */
- while (!dev->shutdown_thread && !dev->disconnected) {
- code = CFRunLoopRunInMode(dev->run_loop_mode, 1000/*sec*/, FALSE);
- /* Return if the device has been disconnected */
- if (code == kCFRunLoopRunFinished) {
- dev->disconnected = 1;
- break;
- }
-
-
- /* Break if The Run Loop returns Finished or Stopped. */
- if (code != kCFRunLoopRunTimedOut &&
- code != kCFRunLoopRunHandledSource) {
- /* There was some kind of error. Setting
- shutdown seems to make sense, but
- there may be something else more appropriate */
- dev->shutdown_thread = 1;
- break;
- }
- }
-
- /* Now that the read thread is stopping, Wake any threads which are
- waiting on data (in hid_read_timeout()). Do this under a mutex to
- make sure that a thread which is about to go to sleep waiting on
- the condition actually will go to sleep before the condition is
- signaled. */
- pthread_mutex_lock(&dev->mutex);
- pthread_cond_broadcast(&dev->condition);
- pthread_mutex_unlock(&dev->mutex);
-
- /* Wait here until hid_close() is called and makes it past
- the call to CFRunLoopWakeUp(). This thread still needs to
- be valid when that function is called on the other thread. */
- pthread_barrier_wait(&dev->shutdown_barrier);
-
- return NULL;
-}
-
-/* hid_open_path()
- *
- * path must be a valid path to an IOHIDDevice in the IOService plane
- * Example: "IOService:/AppleACPIPlatformExpert/PCI0@0/AppleACPIPCI/EHC1@1D,7/AppleUSBEHCI/PLAYSTATION(R)3 Controller@fd120000/IOUSBInterface@0/IOUSBHIDDriver"
- */
-hid_device * HID_API_EXPORT hid_open_path(const char *path)
-{
- hid_device *dev = NULL;
- io_registry_entry_t entry = MACH_PORT_NULL;
-
- dev = new_hid_device();
-
- /* Set up the HID Manager if it hasn't been done */
- if (hid_init() < 0)
- return NULL;
-
- /* Get the IORegistry entry for the given path */
- entry = IORegistryEntryFromPath(kIOMasterPortDefault, path);
- if (entry == MACH_PORT_NULL) {
- /* Path wasn't valid (maybe device was removed?) */
- goto return_error;
- }
-
- /* Create an IOHIDDevice for the entry */
- dev->device_handle = IOHIDDeviceCreate(kCFAllocatorDefault, entry);
- if (dev->device_handle == NULL) {
- /* Error creating the HID device */
- goto return_error;
- }
-
- /* Open the IOHIDDevice */
- IOReturn ret = IOHIDDeviceOpen(dev->device_handle, kIOHIDOptionsTypeSeizeDevice);
- if (ret == kIOReturnSuccess) {
- char str[32];
-
- /* Create the buffers for receiving data */
- dev->max_input_report_len = (CFIndex) get_max_report_length(dev->device_handle);
- dev->input_report_buf = calloc(dev->max_input_report_len, sizeof(uint8_t));
-
- /* Create the Run Loop Mode for this device.
- printing the reference seems to work. */
- sprintf(str, "HIDAPI_%p", dev->device_handle);
- dev->run_loop_mode =
- CFStringCreateWithCString(NULL, str, kCFStringEncodingASCII);
-
- /* Attach the device to a Run Loop */
- IOHIDDeviceRegisterInputReportCallback(
- dev->device_handle, dev->input_report_buf, dev->max_input_report_len,
- &hid_report_callback, dev);
- IOHIDDeviceRegisterRemovalCallback(dev->device_handle, hid_device_removal_callback, dev);
-
- /* Start the read thread */
- pthread_create(&dev->thread, NULL, read_thread, dev);
-
- /* Wait here for the read thread to be initialized. */
- pthread_barrier_wait(&dev->barrier);
-
- IOObjectRelease(entry);
- return dev;
- }
- else {
- goto return_error;
- }
-
-return_error:
- if (dev->device_handle != NULL)
- CFRelease(dev->device_handle);
-
- if (entry != MACH_PORT_NULL)
- IOObjectRelease(entry);
-
- free_hid_device(dev);
- return NULL;
-}
-
-static int set_report(hid_device *dev, IOHIDReportType type, const unsigned char *data, size_t length)
-{
- const unsigned char *data_to_send;
- size_t length_to_send;
- IOReturn res;
-
- /* Return if the device has been disconnected. */
- if (dev->disconnected)
- return -1;
-
- if (data[0] == 0x0) {
- /* Not using numbered Reports.
- Don't send the report number. */
- data_to_send = data+1;
- length_to_send = length-1;
- }
- else {
- /* Using numbered Reports.
- Send the Report Number */
- data_to_send = data;
- length_to_send = length;
- }
-
- if (!dev->disconnected) {
- res = IOHIDDeviceSetReport(dev->device_handle,
- type,
- data[0], /* Report ID*/
- data_to_send, length_to_send);
-
- if (res == kIOReturnSuccess) {
- return length;
- }
- else
- return -1;
- }
-
- return -1;
-}
-
-int HID_API_EXPORT hid_write(hid_device *dev, const unsigned char *data, size_t length)
-{
- return set_report(dev, kIOHIDReportTypeOutput, data, length);
-}
-
-/* Helper function, so that this isn't duplicated in hid_read(). */
-static int return_data(hid_device *dev, unsigned char *data, size_t length)
-{
- /* Copy the data out of the linked list item (rpt) into the
- return buffer (data), and delete the liked list item. */
- struct input_report *rpt = dev->input_reports;
- size_t len = (length < rpt->len)? length: rpt->len;
- memcpy(data, rpt->data, len);
- dev->input_reports = rpt->next;
- free(rpt->data);
- free(rpt);
- return len;
-}
-
-static int cond_wait(const hid_device *dev, pthread_cond_t *cond, pthread_mutex_t *mutex)
-{
- while (!dev->input_reports) {
- int res = pthread_cond_wait(cond, mutex);
- if (res != 0)
- return res;
-
- /* A res of 0 means we may have been signaled or it may
- be a spurious wakeup. Check to see that there's acutally
- data in the queue before returning, and if not, go back
- to sleep. See the pthread_cond_timedwait() man page for
- details. */
-
- if (dev->shutdown_thread || dev->disconnected)
- return -1;
- }
-
- return 0;
-}
-
-static int cond_timedwait(const hid_device *dev, pthread_cond_t *cond, pthread_mutex_t *mutex, const struct timespec *abstime)
-{
- while (!dev->input_reports) {
- int res = pthread_cond_timedwait(cond, mutex, abstime);
- if (res != 0)
- return res;
-
- /* A res of 0 means we may have been signaled or it may
- be a spurious wakeup. Check to see that there's acutally
- data in the queue before returning, and if not, go back
- to sleep. See the pthread_cond_timedwait() man page for
- details. */
-
- if (dev->shutdown_thread || dev->disconnected)
- return -1;
- }
-
- return 0;
-
-}
-
-int HID_API_EXPORT hid_read_timeout(hid_device *dev, unsigned char *data, size_t length, int milliseconds)
-{
- int bytes_read = -1;
-
- /* Lock the access to the report list. */
- pthread_mutex_lock(&dev->mutex);
-
- /* There's an input report queued up. Return it. */
- if (dev->input_reports) {
- /* Return the first one */
- bytes_read = return_data(dev, data, length);
- goto ret;
- }
-
- /* Return if the device has been disconnected. */
- if (dev->disconnected) {
- bytes_read = -1;
- goto ret;
- }
-
- if (dev->shutdown_thread) {
- /* This means the device has been closed (or there
- has been an error. An error code of -1 should
- be returned. */
- bytes_read = -1;
- goto ret;
- }
-
- /* There is no data. Go to sleep and wait for data. */
-
- if (milliseconds == -1) {
- /* Blocking */
- int res;
- res = cond_wait(dev, &dev->condition, &dev->mutex);
- if (res == 0)
- bytes_read = return_data(dev, data, length);
- else {
- /* There was an error, or a device disconnection. */
- bytes_read = -1;
- }
- }
- else if (milliseconds > 0) {
- /* Non-blocking, but called with timeout. */
- int res;
- struct timespec ts;
- struct timeval tv;
- gettimeofday(&tv, NULL);
- TIMEVAL_TO_TIMESPEC(&tv, &ts);
- ts.tv_sec += milliseconds / 1000;
- ts.tv_nsec += (milliseconds % 1000) * 1000000;
- if (ts.tv_nsec >= 1000000000L) {
- ts.tv_sec++;
- ts.tv_nsec -= 1000000000L;
- }
-
- res = cond_timedwait(dev, &dev->condition, &dev->mutex, &ts);
- if (res == 0)
- bytes_read = return_data(dev, data, length);
- else if (res == ETIMEDOUT)
- bytes_read = 0;
- else
- bytes_read = -1;
- }
- else {
- /* Purely non-blocking */
- bytes_read = 0;
- }
-
-ret:
- /* Unlock */
- pthread_mutex_unlock(&dev->mutex);
- return bytes_read;
-}
-
-int HID_API_EXPORT hid_read(hid_device *dev, unsigned char *data, size_t length)
-{
- return hid_read_timeout(dev, data, length, (dev->blocking)? -1: 0);
-}
-
-int HID_API_EXPORT hid_set_nonblocking(hid_device *dev, int nonblock)
-{
- /* All Nonblocking operation is handled by the library. */
- dev->blocking = !nonblock;
-
- return 0;
-}
-
-int HID_API_EXPORT hid_send_feature_report(hid_device *dev, const unsigned char *data, size_t length)
-{
- return set_report(dev, kIOHIDReportTypeFeature, data, length);
-}
-
-int HID_API_EXPORT hid_get_feature_report(hid_device *dev, unsigned char *data, size_t length)
-{
- CFIndex len = length;
- IOReturn res;
-
- /* Return if the device has been unplugged. */
- if (dev->disconnected)
- return -1;
-
- res = IOHIDDeviceGetReport(dev->device_handle,
- kIOHIDReportTypeFeature,
- data[0], /* Report ID */
- data, &len);
- if (res == kIOReturnSuccess)
- return len;
- else
- return -1;
-}
-
-
-void HID_API_EXPORT hid_close(hid_device *dev)
-{
- if (!dev)
- return;
-
- /* Disconnect the report callback before close. */
- if (!dev->disconnected) {
- IOHIDDeviceRegisterInputReportCallback(
- dev->device_handle, dev->input_report_buf, dev->max_input_report_len,
- NULL, dev);
- IOHIDDeviceRegisterRemovalCallback(dev->device_handle, NULL, dev);
- IOHIDDeviceUnscheduleFromRunLoop(dev->device_handle, dev->run_loop, dev->run_loop_mode);
- IOHIDDeviceScheduleWithRunLoop(dev->device_handle, CFRunLoopGetMain(), kCFRunLoopDefaultMode);
- }
-
- /* Cause read_thread() to stop. */
- dev->shutdown_thread = 1;
-
- /* Wake up the run thread's event loop so that the thread can exit. */
- CFRunLoopSourceSignal(dev->source);
- CFRunLoopWakeUp(dev->run_loop);
-
- /* Notify the read thread that it can shut down now. */
- pthread_barrier_wait(&dev->shutdown_barrier);
-
- /* Wait for read_thread() to end. */
- pthread_join(dev->thread, NULL);
-
- /* Close the OS handle to the device, but only if it's not
- been unplugged. If it's been unplugged, then calling
- IOHIDDeviceClose() will crash. */
- if (!dev->disconnected) {
- IOHIDDeviceClose(dev->device_handle, kIOHIDOptionsTypeSeizeDevice);
- }
-
- /* Clear out the queue of received reports. */
- pthread_mutex_lock(&dev->mutex);
- while (dev->input_reports) {
- return_data(dev, NULL, 0);
- }
- pthread_mutex_unlock(&dev->mutex);
- CFRelease(dev->device_handle);
-
- free_hid_device(dev);
-}
-
-int HID_API_EXPORT_CALL hid_get_manufacturer_string(hid_device *dev, wchar_t *string, size_t maxlen)
-{
- return get_manufacturer_string(dev->device_handle, string, maxlen);
-}
-
-int HID_API_EXPORT_CALL hid_get_product_string(hid_device *dev, wchar_t *string, size_t maxlen)
-{
- return get_product_string(dev->device_handle, string, maxlen);
-}
-
-int HID_API_EXPORT_CALL hid_get_serial_number_string(hid_device *dev, wchar_t *string, size_t maxlen)
-{
- return get_serial_number(dev->device_handle, string, maxlen);
-}
-
-int HID_API_EXPORT_CALL hid_get_indexed_string(hid_device *dev, int string_index, wchar_t *string, size_t maxlen)
-{
- /* TODO: */
-
- return 0;
-}
-
-
-HID_API_EXPORT const wchar_t * HID_API_CALL hid_error(hid_device *dev)
-{
- /* TODO: */
-
- return NULL;
-}
-
-
-
-
-
-
-
-#if 0
-static int32_t get_location_id(IOHIDDeviceRef device)
-{
- return get_int_property(device, CFSTR(kIOHIDLocationIDKey));
-}
-
-static int32_t get_usage(IOHIDDeviceRef device)
-{
- int32_t res;
- res = get_int_property(device, CFSTR(kIOHIDDeviceUsageKey));
- if (!res)
- res = get_int_property(device, CFSTR(kIOHIDPrimaryUsageKey));
- return res;
-}
-
-static int32_t get_usage_page(IOHIDDeviceRef device)
-{
- int32_t res;
- res = get_int_property(device, CFSTR(kIOHIDDeviceUsagePageKey));
- if (!res)
- res = get_int_property(device, CFSTR(kIOHIDPrimaryUsagePageKey));
- return res;
-}
-
-static int get_transport(IOHIDDeviceRef device, wchar_t *buf, size_t len)
-{
- return get_string_property(device, CFSTR(kIOHIDTransportKey), buf, len);
-}
-
-
-int main(void)
-{
- IOHIDManagerRef mgr;
- int i;
-
- mgr = IOHIDManagerCreate(kCFAllocatorDefault, kIOHIDOptionsTypeNone);
- IOHIDManagerSetDeviceMatching(mgr, NULL);
- IOHIDManagerOpen(mgr, kIOHIDOptionsTypeNone);
-
- CFSetRef device_set = IOHIDManagerCopyDevices(mgr);
-
- CFIndex num_devices = CFSetGetCount(device_set);
- IOHIDDeviceRef *device_array = calloc(num_devices, sizeof(IOHIDDeviceRef));
- CFSetGetValues(device_set, (const void **) device_array);
-
- for (i = 0; i < num_devices; i++) {
- IOHIDDeviceRef dev = device_array[i];
- printf("Device: %p\n", dev);
- printf(" %04hx %04hx\n", get_vendor_id(dev), get_product_id(dev));
-
- wchar_t serial[256], buf[256];
- char cbuf[256];
- get_serial_number(dev, serial, 256);
-
-
- printf(" Serial: %ls\n", serial);
- printf(" Loc: %ld\n", get_location_id(dev));
- get_transport(dev, buf, 256);
- printf(" Trans: %ls\n", buf);
- make_path(dev, cbuf, 256);
- printf(" Path: %s\n", cbuf);
-
- }
-
- return 0;
-}
-#endif
diff --git a/vendor/github.com/karalabe/usb/hidapi/windows/hid.c b/vendor/github.com/karalabe/usb/hidapi/windows/hid.c
deleted file mode 100644
index 60da64608c..0000000000
--- a/vendor/github.com/karalabe/usb/hidapi/windows/hid.c
+++ /dev/null
@@ -1,946 +0,0 @@
-/*******************************************************
- HIDAPI - Multi-Platform library for
- communication with HID devices.
-
- Alan Ott
- Signal 11 Software
-
- 8/22/2009
-
- Copyright 2009, All Rights Reserved.
-
- At the discretion of the user of this library,
- this software may be licensed under the terms of the
- GNU General Public License v3, a BSD-Style license, or the
- original HIDAPI license as outlined in the LICENSE.txt,
- LICENSE-gpl3.txt, LICENSE-bsd.txt, and LICENSE-orig.txt
- files located at the root of the source distribution.
- These files may also be found in the public source
- code repository located at:
- http://github.com/signal11/hidapi .
-********************************************************/
-
-#include
-
-#ifndef _NTDEF_
-typedef LONG NTSTATUS;
-#endif
-
-#ifdef __MINGW32__
-#include
-#include
-#endif
-
-#ifdef __CYGWIN__
-#include
-#define _wcsdup wcsdup
-#endif
-
-/* The maximum number of characters that can be passed into the
- HidD_Get*String() functions without it failing.*/
-#define MAX_STRING_WCHARS 0xFFF
-
-/*#define HIDAPI_USE_DDK*/
-
-#ifdef __cplusplus
-extern "C" {
-#endif
- #include
- #include
- #ifdef HIDAPI_USE_DDK
- #include
- #endif
-
- /* Copied from inc/ddk/hidclass.h, part of the Windows DDK. */
- #define HID_OUT_CTL_CODE(id) \
- CTL_CODE(FILE_DEVICE_KEYBOARD, (id), METHOD_OUT_DIRECT, FILE_ANY_ACCESS)
- #define IOCTL_HID_GET_FEATURE HID_OUT_CTL_CODE(100)
-
-#ifdef __cplusplus
-} /* extern "C" */
-#endif
-
-#include
-#include
-
-
-#include "hidapi.h"
-
-#undef MIN
-#define MIN(x,y) ((x) < (y)? (x): (y))
-
-#ifdef _MSC_VER
- /* Thanks Microsoft, but I know how to use strncpy(). */
- #pragma warning(disable:4996)
-#endif
-
-#pragma GCC diagnostic ignored "-Wstringop-overflow"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#ifndef HIDAPI_USE_DDK
- /* Since we're not building with the DDK, and the HID header
- files aren't part of the SDK, we have to define all this
- stuff here. In lookup_functions(), the function pointers
- defined below are set. */
- typedef struct _HIDD_ATTRIBUTES{
- ULONG Size;
- USHORT VendorID;
- USHORT ProductID;
- USHORT VersionNumber;
- } HIDD_ATTRIBUTES, *PHIDD_ATTRIBUTES;
-
- typedef USHORT USAGE;
- typedef struct _HIDP_CAPS {
- USAGE Usage;
- USAGE UsagePage;
- USHORT InputReportByteLength;
- USHORT OutputReportByteLength;
- USHORT FeatureReportByteLength;
- USHORT Reserved[17];
- USHORT fields_not_used_by_hidapi[10];
- } HIDP_CAPS, *PHIDP_CAPS;
- typedef void* PHIDP_PREPARSED_DATA;
- #define HIDP_STATUS_SUCCESS 0x110000
-
- typedef BOOLEAN (__stdcall *HidD_GetAttributes_)(HANDLE device, PHIDD_ATTRIBUTES attrib);
- typedef BOOLEAN (__stdcall *HidD_GetSerialNumberString_)(HANDLE device, PVOID buffer, ULONG buffer_len);
- typedef BOOLEAN (__stdcall *HidD_GetManufacturerString_)(HANDLE handle, PVOID buffer, ULONG buffer_len);
- typedef BOOLEAN (__stdcall *HidD_GetProductString_)(HANDLE handle, PVOID buffer, ULONG buffer_len);
- typedef BOOLEAN (__stdcall *HidD_SetFeature_)(HANDLE handle, PVOID data, ULONG length);
- typedef BOOLEAN (__stdcall *HidD_GetFeature_)(HANDLE handle, PVOID data, ULONG length);
- typedef BOOLEAN (__stdcall *HidD_GetIndexedString_)(HANDLE handle, ULONG string_index, PVOID buffer, ULONG buffer_len);
- typedef BOOLEAN (__stdcall *HidD_GetPreparsedData_)(HANDLE handle, PHIDP_PREPARSED_DATA *preparsed_data);
- typedef BOOLEAN (__stdcall *HidD_FreePreparsedData_)(PHIDP_PREPARSED_DATA preparsed_data);
- typedef NTSTATUS (__stdcall *HidP_GetCaps_)(PHIDP_PREPARSED_DATA preparsed_data, HIDP_CAPS *caps);
- typedef BOOLEAN (__stdcall *HidD_SetNumInputBuffers_)(HANDLE handle, ULONG number_buffers);
-
- static HidD_GetAttributes_ HidD_GetAttributes;
- static HidD_GetSerialNumberString_ HidD_GetSerialNumberString;
- static HidD_GetManufacturerString_ HidD_GetManufacturerString;
- static HidD_GetProductString_ HidD_GetProductString;
- static HidD_SetFeature_ HidD_SetFeature;
- static HidD_GetFeature_ HidD_GetFeature;
- static HidD_GetIndexedString_ HidD_GetIndexedString;
- static HidD_GetPreparsedData_ HidD_GetPreparsedData;
- static HidD_FreePreparsedData_ HidD_FreePreparsedData;
- static HidP_GetCaps_ HidP_GetCaps;
- static HidD_SetNumInputBuffers_ HidD_SetNumInputBuffers;
-
- static HMODULE lib_handle = NULL;
- static BOOLEAN initialized = FALSE;
-#endif /* HIDAPI_USE_DDK */
-
-struct hid_device_ {
- HANDLE device_handle;
- BOOL blocking;
- USHORT output_report_length;
- size_t input_report_length;
- void *last_error_str;
- DWORD last_error_num;
- BOOL read_pending;
- char *read_buf;
- OVERLAPPED ol;
-};
-
-static hid_device *new_hid_device()
-{
- hid_device *dev = (hid_device*) calloc(1, sizeof(hid_device));
- dev->device_handle = INVALID_HANDLE_VALUE;
- dev->blocking = TRUE;
- dev->output_report_length = 0;
- dev->input_report_length = 0;
- dev->last_error_str = NULL;
- dev->last_error_num = 0;
- dev->read_pending = FALSE;
- dev->read_buf = NULL;
- memset(&dev->ol, 0, sizeof(dev->ol));
- dev->ol.hEvent = CreateEvent(NULL, FALSE, FALSE /*initial state f=nonsignaled*/, NULL);
-
- return dev;
-}
-
-static void free_hid_device(hid_device *dev)
-{
- CloseHandle(dev->ol.hEvent);
- CloseHandle(dev->device_handle);
- LocalFree(dev->last_error_str);
- free(dev->read_buf);
- free(dev);
-}
-
-static void register_error(hid_device *device, const char *op)
-{
- WCHAR *ptr, *msg;
-
- FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
- FORMAT_MESSAGE_FROM_SYSTEM |
- FORMAT_MESSAGE_IGNORE_INSERTS,
- NULL,
- GetLastError(),
- MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
- (LPVOID)&msg, 0/*sz*/,
- NULL);
-
- /* Get rid of the CR and LF that FormatMessage() sticks at the
- end of the message. Thanks Microsoft! */
- ptr = msg;
- while (*ptr) {
- if (*ptr == '\r') {
- *ptr = 0x0000;
- break;
- }
- ptr++;
- }
-
- /* Store the message off in the Device entry so that
- the hid_error() function can pick it up. */
- LocalFree(device->last_error_str);
- device->last_error_str = msg;
-}
-
-#ifndef HIDAPI_USE_DDK
-static int lookup_functions()
-{
- lib_handle = LoadLibraryA("hid.dll");
- if (lib_handle) {
-#define RESOLVE(x) x = (x##_)GetProcAddress(lib_handle, #x); if (!x) return -1;
- RESOLVE(HidD_GetAttributes);
- RESOLVE(HidD_GetSerialNumberString);
- RESOLVE(HidD_GetManufacturerString);
- RESOLVE(HidD_GetProductString);
- RESOLVE(HidD_SetFeature);
- RESOLVE(HidD_GetFeature);
- RESOLVE(HidD_GetIndexedString);
- RESOLVE(HidD_GetPreparsedData);
- RESOLVE(HidD_FreePreparsedData);
- RESOLVE(HidP_GetCaps);
- RESOLVE(HidD_SetNumInputBuffers);
-#undef RESOLVE
- }
- else
- return -1;
-
- return 0;
-}
-#endif
-
-static HANDLE open_device(const char *path, BOOL enumerate)
-{
- HANDLE handle;
- DWORD desired_access = (enumerate)? 0: (GENERIC_WRITE | GENERIC_READ);
- DWORD share_mode = FILE_SHARE_READ|FILE_SHARE_WRITE;
-
- handle = CreateFileA(path,
- desired_access,
- share_mode,
- NULL,
- OPEN_EXISTING,
- FILE_FLAG_OVERLAPPED,/*FILE_ATTRIBUTE_NORMAL,*/
- 0);
-
- return handle;
-}
-
-int HID_API_EXPORT hid_init(void)
-{
-#ifndef HIDAPI_USE_DDK
- if (!initialized) {
- if (lookup_functions() < 0) {
- hid_exit();
- return -1;
- }
- initialized = TRUE;
- }
-#endif
- return 0;
-}
-
-int HID_API_EXPORT hid_exit(void)
-{
-#ifndef HIDAPI_USE_DDK
- if (lib_handle)
- FreeLibrary(lib_handle);
- lib_handle = NULL;
- initialized = FALSE;
-#endif
- return 0;
-}
-
-struct hid_device_info HID_API_EXPORT * HID_API_CALL hid_enumerate(unsigned short vendor_id, unsigned short product_id)
-{
- BOOL res;
- struct hid_device_info *root = NULL; /* return object */
- struct hid_device_info *cur_dev = NULL;
-
- /* Windows objects for interacting with the driver. */
- GUID InterfaceClassGuid = {0x4d1e55b2, 0xf16f, 0x11cf, {0x88, 0xcb, 0x00, 0x11, 0x11, 0x00, 0x00, 0x30} };
- SP_DEVINFO_DATA devinfo_data;
- SP_DEVICE_INTERFACE_DATA device_interface_data;
- SP_DEVICE_INTERFACE_DETAIL_DATA_A *device_interface_detail_data = NULL;
- HDEVINFO device_info_set = INVALID_HANDLE_VALUE;
- int device_index = 0;
- int i;
-
- if (hid_init() < 0)
- return NULL;
-
- /* Initialize the Windows objects. */
- memset(&devinfo_data, 0x0, sizeof(devinfo_data));
- devinfo_data.cbSize = sizeof(SP_DEVINFO_DATA);
- device_interface_data.cbSize = sizeof(SP_DEVICE_INTERFACE_DATA);
-
- /* Get information for all the devices belonging to the HID class. */
- device_info_set = SetupDiGetClassDevsA(&InterfaceClassGuid, NULL, NULL, DIGCF_PRESENT | DIGCF_DEVICEINTERFACE);
-
- /* Iterate over each device in the HID class, looking for the right one. */
-
- for (;;) {
- HANDLE write_handle = INVALID_HANDLE_VALUE;
- DWORD required_size = 0;
- HIDD_ATTRIBUTES attrib;
-
- res = SetupDiEnumDeviceInterfaces(device_info_set,
- NULL,
- &InterfaceClassGuid,
- device_index,
- &device_interface_data);
-
- if (!res) {
- /* A return of FALSE from this function means that
- there are no more devices. */
- break;
- }
-
- /* Call with 0-sized detail size, and let the function
- tell us how long the detail struct needs to be. The
- size is put in &required_size. */
- res = SetupDiGetDeviceInterfaceDetailA(device_info_set,
- &device_interface_data,
- NULL,
- 0,
- &required_size,
- NULL);
-
- /* Allocate a long enough structure for device_interface_detail_data. */
- device_interface_detail_data = (SP_DEVICE_INTERFACE_DETAIL_DATA_A*) malloc(required_size);
- device_interface_detail_data->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA_A);
-
- /* Get the detailed data for this device. The detail data gives us
- the device path for this device, which is then passed into
- CreateFile() to get a handle to the device. */
- res = SetupDiGetDeviceInterfaceDetailA(device_info_set,
- &device_interface_data,
- device_interface_detail_data,
- required_size,
- NULL,
- NULL);
-
- if (!res) {
- /* register_error(dev, "Unable to call SetupDiGetDeviceInterfaceDetail");
- Continue to the next device. */
- goto cont;
- }
-
- /* Make sure this device is of Setup Class "HIDClass" and has a
- driver bound to it. */
- for (i = 0; ; i++) {
- char driver_name[256];
-
- /* Populate devinfo_data. This function will return failure
- when there are no more interfaces left. */
- res = SetupDiEnumDeviceInfo(device_info_set, i, &devinfo_data);
- if (!res)
- goto cont;
-
- res = SetupDiGetDeviceRegistryPropertyA(device_info_set, &devinfo_data,
- SPDRP_CLASS, NULL, (PBYTE)driver_name, sizeof(driver_name), NULL);
- if (!res)
- goto cont;
-
- if (strcmp(driver_name, "HIDClass") == 0) {
- /* See if there's a driver bound. */
- res = SetupDiGetDeviceRegistryPropertyA(device_info_set, &devinfo_data,
- SPDRP_DRIVER, NULL, (PBYTE)driver_name, sizeof(driver_name), NULL);
- if (res)
- break;
- }
- }
-
- //wprintf(L"HandleName: %s\n", device_interface_detail_data->DevicePath);
-
- /* Open a handle to the device */
- write_handle = open_device(device_interface_detail_data->DevicePath, TRUE);
-
- /* Check validity of write_handle. */
- if (write_handle == INVALID_HANDLE_VALUE) {
- /* Unable to open the device. */
- //register_error(dev, "CreateFile");
- goto cont_close;
- }
-
-
- /* Get the Vendor ID and Product ID for this device. */
- attrib.Size = sizeof(HIDD_ATTRIBUTES);
- HidD_GetAttributes(write_handle, &attrib);
- //wprintf(L"Product/Vendor: %x %x\n", attrib.ProductID, attrib.VendorID);
-
- /* Check the VID/PID to see if we should add this
- device to the enumeration list. */
- if ((vendor_id == 0x0 || attrib.VendorID == vendor_id) &&
- (product_id == 0x0 || attrib.ProductID == product_id)) {
-
- #define WSTR_LEN 512
- const char *str;
- struct hid_device_info *tmp;
- PHIDP_PREPARSED_DATA pp_data = NULL;
- HIDP_CAPS caps;
- BOOLEAN res;
- NTSTATUS nt_res;
- wchar_t wstr[WSTR_LEN]; /* TODO: Determine Size */
- size_t len;
-
- /* VID/PID match. Create the record. */
- tmp = (struct hid_device_info*) calloc(1, sizeof(struct hid_device_info));
- if (cur_dev) {
- cur_dev->next = tmp;
- }
- else {
- root = tmp;
- }
- cur_dev = tmp;
-
- /* Get the Usage Page and Usage for this device. */
- res = HidD_GetPreparsedData(write_handle, &pp_data);
- if (res) {
- nt_res = HidP_GetCaps(pp_data, &caps);
- if (nt_res == HIDP_STATUS_SUCCESS) {
- cur_dev->usage_page = caps.UsagePage;
- cur_dev->usage = caps.Usage;
- }
-
- HidD_FreePreparsedData(pp_data);
- }
-
- /* Fill out the record */
- cur_dev->next = NULL;
- str = device_interface_detail_data->DevicePath;
- if (str) {
- len = strlen(str);
- cur_dev->path = (char*) calloc(len+1, sizeof(char));
- strncpy(cur_dev->path, str, len+1);
- cur_dev->path[len] = '\0';
- }
- else
- cur_dev->path = NULL;
-
- /* Serial Number */
- res = HidD_GetSerialNumberString(write_handle, wstr, sizeof(wstr));
- wstr[WSTR_LEN-1] = 0x0000;
- if (res) {
- cur_dev->serial_number = _wcsdup(wstr);
- }
-
- /* Manufacturer String */
- res = HidD_GetManufacturerString(write_handle, wstr, sizeof(wstr));
- wstr[WSTR_LEN-1] = 0x0000;
- if (res) {
- cur_dev->manufacturer_string = _wcsdup(wstr);
- }
-
- /* Product String */
- res = HidD_GetProductString(write_handle, wstr, sizeof(wstr));
- wstr[WSTR_LEN-1] = 0x0000;
- if (res) {
- cur_dev->product_string = _wcsdup(wstr);
- }
-
- /* VID/PID */
- cur_dev->vendor_id = attrib.VendorID;
- cur_dev->product_id = attrib.ProductID;
-
- /* Release Number */
- cur_dev->release_number = attrib.VersionNumber;
-
- /* Interface Number. It can sometimes be parsed out of the path
- on Windows if a device has multiple interfaces. See
- http://msdn.microsoft.com/en-us/windows/hardware/gg487473 or
- search for "Hardware IDs for HID Devices" at MSDN. If it's not
- in the path, it's set to -1. */
- cur_dev->interface_number = -1;
- if (cur_dev->path) {
- char *interface_component = strstr(cur_dev->path, "&mi_");
- if (interface_component) {
- char *hex_str = interface_component + 4;
- char *endptr = NULL;
- cur_dev->interface_number = strtol(hex_str, &endptr, 16);
- if (endptr == hex_str) {
- /* The parsing failed. Set interface_number to -1. */
- cur_dev->interface_number = -1;
- }
- }
- }
- }
-
-cont_close:
- CloseHandle(write_handle);
-cont:
- /* We no longer need the detail data. It can be freed */
- free(device_interface_detail_data);
-
- device_index++;
-
- }
-
- /* Close the device information handle. */
- SetupDiDestroyDeviceInfoList(device_info_set);
-
- return root;
-
-}
-
-void HID_API_EXPORT HID_API_CALL hid_free_enumeration(struct hid_device_info *devs)
-{
- /* TODO: Merge this with the Linux version. This function is platform-independent. */
- struct hid_device_info *d = devs;
- while (d) {
- struct hid_device_info *next = d->next;
- free(d->path);
- free(d->serial_number);
- free(d->manufacturer_string);
- free(d->product_string);
- free(d);
- d = next;
- }
-}
-
-
-HID_API_EXPORT hid_device * HID_API_CALL hid_open(unsigned short vendor_id, unsigned short product_id, const wchar_t *serial_number)
-{
- /* TODO: Merge this functions with the Linux version. This function should be platform independent. */
- struct hid_device_info *devs, *cur_dev;
- const char *path_to_open = NULL;
- hid_device *handle = NULL;
-
- devs = hid_enumerate(vendor_id, product_id);
- cur_dev = devs;
- while (cur_dev) {
- if (cur_dev->vendor_id == vendor_id &&
- cur_dev->product_id == product_id) {
- if (serial_number) {
- if (wcscmp(serial_number, cur_dev->serial_number) == 0) {
- path_to_open = cur_dev->path;
- break;
- }
- }
- else {
- path_to_open = cur_dev->path;
- break;
- }
- }
- cur_dev = cur_dev->next;
- }
-
- if (path_to_open) {
- /* Open the device */
- handle = hid_open_path(path_to_open);
- }
-
- hid_free_enumeration(devs);
-
- return handle;
-}
-
-HID_API_EXPORT hid_device * HID_API_CALL hid_open_path(const char *path)
-{
- hid_device *dev;
- HIDP_CAPS caps;
- PHIDP_PREPARSED_DATA pp_data = NULL;
- BOOLEAN res;
- NTSTATUS nt_res;
-
- if (hid_init() < 0) {
- return NULL;
- }
-
- dev = new_hid_device();
-
- /* Open a handle to the device */
- dev->device_handle = open_device(path, FALSE);
-
- /* Check validity of write_handle. */
- if (dev->device_handle == INVALID_HANDLE_VALUE) {
- /* Unable to open the device. */
- register_error(dev, "CreateFile");
- goto err;
- }
-
- /* Set the Input Report buffer size to 64 reports. */
- res = HidD_SetNumInputBuffers(dev->device_handle, 64);
- if (!res) {
- register_error(dev, "HidD_SetNumInputBuffers");
- goto err;
- }
-
- /* Get the Input Report length for the device. */
- res = HidD_GetPreparsedData(dev->device_handle, &pp_data);
- if (!res) {
- register_error(dev, "HidD_GetPreparsedData");
- goto err;
- }
- nt_res = HidP_GetCaps(pp_data, &caps);
- if (nt_res != HIDP_STATUS_SUCCESS) {
- register_error(dev, "HidP_GetCaps");
- goto err_pp_data;
- }
- dev->output_report_length = caps.OutputReportByteLength;
- dev->input_report_length = caps.InputReportByteLength;
- HidD_FreePreparsedData(pp_data);
-
- dev->read_buf = (char*) malloc(dev->input_report_length);
-
- return dev;
-
-err_pp_data:
- HidD_FreePreparsedData(pp_data);
-err:
- free_hid_device(dev);
- return NULL;
-}
-
-int HID_API_EXPORT HID_API_CALL hid_write(hid_device *dev, const unsigned char *data, size_t length)
-{
- DWORD bytes_written;
- BOOL res;
-
- OVERLAPPED ol;
- unsigned char *buf;
- memset(&ol, 0, sizeof(ol));
-
- /* Make sure the right number of bytes are passed to WriteFile. Windows
- expects the number of bytes which are in the _longest_ report (plus
- one for the report number) bytes even if the data is a report
- which is shorter than that. Windows gives us this value in
- caps.OutputReportByteLength. If a user passes in fewer bytes than this,
- create a temporary buffer which is the proper size. */
- if (length >= dev->output_report_length) {
- /* The user passed the right number of bytes. Use the buffer as-is. */
- buf = (unsigned char *) data;
- } else {
- /* Create a temporary buffer and copy the user's data
- into it, padding the rest with zeros. */
- buf = (unsigned char *) malloc(dev->output_report_length);
- memcpy(buf, data, length);
- memset(buf + length, 0, dev->output_report_length - length);
- length = dev->output_report_length;
- }
-
- res = WriteFile(dev->device_handle, buf, length, NULL, &ol);
-
- if (!res) {
- if (GetLastError() != ERROR_IO_PENDING) {
- /* WriteFile() failed. Return error. */
- register_error(dev, "WriteFile");
- bytes_written = -1;
- goto end_of_function;
- }
- }
-
- /* Wait here until the write is done. This makes
- hid_write() synchronous. */
- res = GetOverlappedResult(dev->device_handle, &ol, &bytes_written, TRUE/*wait*/);
- if (!res) {
- /* The Write operation failed. */
- register_error(dev, "WriteFile");
- bytes_written = -1;
- goto end_of_function;
- }
-
-end_of_function:
- if (buf != data)
- free(buf);
-
- return bytes_written;
-}
-
-
-int HID_API_EXPORT HID_API_CALL hid_read_timeout(hid_device *dev, unsigned char *data, size_t length, int milliseconds)
-{
- DWORD bytes_read = 0;
- size_t copy_len = 0;
- BOOL res;
-
- /* Copy the handle for convenience. */
- HANDLE ev = dev->ol.hEvent;
-
- if (!dev->read_pending) {
- /* Start an Overlapped I/O read. */
- dev->read_pending = TRUE;
- memset(dev->read_buf, 0, dev->input_report_length);
- ResetEvent(ev);
- res = ReadFile(dev->device_handle, dev->read_buf, dev->input_report_length, &bytes_read, &dev->ol);
-
- if (!res) {
- if (GetLastError() != ERROR_IO_PENDING) {
- /* ReadFile() has failed.
- Clean up and return error. */
- CancelIo(dev->device_handle);
- dev->read_pending = FALSE;
- goto end_of_function;
- }
- }
- }
-
- if (milliseconds >= 0) {
- /* See if there is any data yet. */
- res = WaitForSingleObject(ev, milliseconds);
- if (res != WAIT_OBJECT_0) {
- /* There was no data this time. Return zero bytes available,
- but leave the Overlapped I/O running. */
- return 0;
- }
- }
-
- /* Either WaitForSingleObject() told us that ReadFile has completed, or
- we are in non-blocking mode. Get the number of bytes read. The actual
- data has been copied to the data[] array which was passed to ReadFile(). */
- res = GetOverlappedResult(dev->device_handle, &dev->ol, &bytes_read, TRUE/*wait*/);
-
- /* Set pending back to false, even if GetOverlappedResult() returned error. */
- dev->read_pending = FALSE;
-
- if (res && bytes_read > 0) {
- if (dev->read_buf[0] == 0x0) {
- /* If report numbers aren't being used, but Windows sticks a report
- number (0x0) on the beginning of the report anyway. To make this
- work like the other platforms, and to make it work more like the
- HID spec, we'll skip over this byte. */
- bytes_read--;
- copy_len = length > bytes_read ? bytes_read : length;
- memcpy(data, dev->read_buf+1, copy_len);
- }
- else {
- /* Copy the whole buffer, report number and all. */
- copy_len = length > bytes_read ? bytes_read : length;
- memcpy(data, dev->read_buf, copy_len);
- }
- }
-
-end_of_function:
- if (!res) {
- register_error(dev, "GetOverlappedResult");
- return -1;
- }
-
- return copy_len;
-}
-
-int HID_API_EXPORT HID_API_CALL hid_read(hid_device *dev, unsigned char *data, size_t length)
-{
- return hid_read_timeout(dev, data, length, (dev->blocking)? -1: 0);
-}
-
-int HID_API_EXPORT HID_API_CALL hid_set_nonblocking(hid_device *dev, int nonblock)
-{
- dev->blocking = !nonblock;
- return 0; /* Success */
-}
-
-int HID_API_EXPORT HID_API_CALL hid_send_feature_report(hid_device *dev, const unsigned char *data, size_t length)
-{
- BOOL res = HidD_SetFeature(dev->device_handle, (PVOID)data, length);
- if (!res) {
- register_error(dev, "HidD_SetFeature");
- return -1;
- }
-
- return length;
-}
-
-
-int HID_API_EXPORT HID_API_CALL hid_get_feature_report(hid_device *dev, unsigned char *data, size_t length)
-{
- BOOL res;
-#if 0
- res = HidD_GetFeature(dev->device_handle, data, length);
- if (!res) {
- register_error(dev, "HidD_GetFeature");
- return -1;
- }
- return 0; /* HidD_GetFeature() doesn't give us an actual length, unfortunately */
-#else
- DWORD bytes_returned;
-
- OVERLAPPED ol;
- memset(&ol, 0, sizeof(ol));
-
- res = DeviceIoControl(dev->device_handle,
- IOCTL_HID_GET_FEATURE,
- data, length,
- data, length,
- &bytes_returned, &ol);
-
- if (!res) {
- if (GetLastError() != ERROR_IO_PENDING) {
- /* DeviceIoControl() failed. Return error. */
- register_error(dev, "Send Feature Report DeviceIoControl");
- return -1;
- }
- }
-
- /* Wait here until the write is done. This makes
- hid_get_feature_report() synchronous. */
- res = GetOverlappedResult(dev->device_handle, &ol, &bytes_returned, TRUE/*wait*/);
- if (!res) {
- /* The operation failed. */
- register_error(dev, "Send Feature Report GetOverLappedResult");
- return -1;
- }
-
- /* bytes_returned does not include the first byte which contains the
- report ID. The data buffer actually contains one more byte than
- bytes_returned. */
- bytes_returned++;
-
- return bytes_returned;
-#endif
-}
-
-void HID_API_EXPORT HID_API_CALL hid_close(hid_device *dev)
-{
- if (!dev)
- return;
- CancelIo(dev->device_handle);
- free_hid_device(dev);
-}
-
-int HID_API_EXPORT_CALL HID_API_CALL hid_get_manufacturer_string(hid_device *dev, wchar_t *string, size_t maxlen)
-{
- BOOL res;
-
- res = HidD_GetManufacturerString(dev->device_handle, string, sizeof(wchar_t) * MIN(maxlen, MAX_STRING_WCHARS));
- if (!res) {
- register_error(dev, "HidD_GetManufacturerString");
- return -1;
- }
-
- return 0;
-}
-
-int HID_API_EXPORT_CALL HID_API_CALL hid_get_product_string(hid_device *dev, wchar_t *string, size_t maxlen)
-{
- BOOL res;
-
- res = HidD_GetProductString(dev->device_handle, string, sizeof(wchar_t) * MIN(maxlen, MAX_STRING_WCHARS));
- if (!res) {
- register_error(dev, "HidD_GetProductString");
- return -1;
- }
-
- return 0;
-}
-
-int HID_API_EXPORT_CALL HID_API_CALL hid_get_serial_number_string(hid_device *dev, wchar_t *string, size_t maxlen)
-{
- BOOL res;
-
- res = HidD_GetSerialNumberString(dev->device_handle, string, sizeof(wchar_t) * MIN(maxlen, MAX_STRING_WCHARS));
- if (!res) {
- register_error(dev, "HidD_GetSerialNumberString");
- return -1;
- }
-
- return 0;
-}
-
-int HID_API_EXPORT_CALL HID_API_CALL hid_get_indexed_string(hid_device *dev, int string_index, wchar_t *string, size_t maxlen)
-{
- BOOL res;
-
- res = HidD_GetIndexedString(dev->device_handle, string_index, string, sizeof(wchar_t) * MIN(maxlen, MAX_STRING_WCHARS));
- if (!res) {
- register_error(dev, "HidD_GetIndexedString");
- return -1;
- }
-
- return 0;
-}
-
-
-HID_API_EXPORT const wchar_t * HID_API_CALL hid_error(hid_device *dev)
-{
- return (wchar_t*)dev->last_error_str;
-}
-
-
-/*#define PICPGM*/
-/*#define S11*/
-#define P32
-#ifdef S11
- unsigned short VendorID = 0xa0a0;
- unsigned short ProductID = 0x0001;
-#endif
-
-#ifdef P32
- unsigned short VendorID = 0x04d8;
- unsigned short ProductID = 0x3f;
-#endif
-
-
-#ifdef PICPGM
- unsigned short VendorID = 0x04d8;
- unsigned short ProductID = 0x0033;
-#endif
-
-
-#if 0
-int __cdecl main(int argc, char* argv[])
-{
- int res;
- unsigned char buf[65];
-
- UNREFERENCED_PARAMETER(argc);
- UNREFERENCED_PARAMETER(argv);
-
- /* Set up the command buffer. */
- memset(buf,0x00,sizeof(buf));
- buf[0] = 0;
- buf[1] = 0x81;
-
-
- /* Open the device. */
- int handle = open(VendorID, ProductID, L"12345");
- if (handle < 0)
- printf("unable to open device\n");
-
-
- /* Toggle LED (cmd 0x80) */
- buf[1] = 0x80;
- res = write(handle, buf, 65);
- if (res < 0)
- printf("Unable to write()\n");
-
- /* Request state (cmd 0x81) */
- buf[1] = 0x81;
- write(handle, buf, 65);
- if (res < 0)
- printf("Unable to write() (2)\n");
-
- /* Read requested state */
- read(handle, buf, 65);
- if (res < 0)
- printf("Unable to read()\n");
-
- /* Print out the returned buffer. */
- for (int i = 0; i < 4; i++)
- printf("buf[%d]: %d\n", i, buf[i]);
-
- return 0;
-}
-#endif
-
-#ifdef __cplusplus
-} /* extern "C" */
-#endif
diff --git a/vendor/github.com/karalabe/usb/libs.go b/vendor/github.com/karalabe/usb/libs.go
deleted file mode 100644
index 6446acee9e..0000000000
--- a/vendor/github.com/karalabe/usb/libs.go
+++ /dev/null
@@ -1,74 +0,0 @@
-// usb - Self contained USB and HID library for Go
-// Copyright 2019 The library Authors
-//
-// This library is free software: you can redistribute it and/or modify it under
-// the terms of the GNU Lesser General Public License as published by the Free
-// Software Foundation, either version 3 of the License, or (at your option) any
-// later version.
-//
-// The library is distributed in the hope that it will be useful, but WITHOUT ANY
-// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
-// A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
-//
-// You should have received a copy of the GNU Lesser General Public License along
-// with the library. If not, see .
-
-// +build freebsd,cgo linux,cgo darwin,!ios,cgo windows,cgo
-
-package usb
-
-/*
-#cgo CFLAGS: -I./hidapi/hidapi
-#cgo CFLAGS: -I./libusb/libusb
-#cgo CFLAGS: -DDEFAULT_VISIBILITY=""
-#cgo CFLAGS: -DPOLL_NFDS_TYPE=int
-
-#cgo linux CFLAGS: -DOS_LINUX -D_GNU_SOURCE -DHAVE_SYS_TIME_H
-#cgo linux,!android LDFLAGS: -lrt
-#cgo darwin CFLAGS: -DOS_DARWIN -DHAVE_SYS_TIME_H
-#cgo darwin LDFLAGS: -framework CoreFoundation -framework IOKit -lobjc
-#cgo windows CFLAGS: -DOS_WINDOWS
-#cgo windows LDFLAGS: -lsetupapi
-#cgo freebsd CFLAGS: -DOS_FREEBSD
-#cgo freebsd LDFLAGS: -lusb
-#cgo openbsd CFLAGS: -DOS_OPENBSD
-
-#if defined(OS_LINUX) || defined(OS_DARWIN) || defined(DOS_FREEBSD) || defined(OS_OPENBSD)
- #include
- #include "os/threads_posix.c"
- #include "os/poll_posix.c"
-#elif defined(OS_WINDOWS)
- #include "os/poll_windows.c"
- #include "os/threads_windows.c"
-#endif
-
-#ifdef OS_LINUX
- #include "os/linux_usbfs.c"
- #include "os/linux_netlink.c"
- #include "hidapi/libusb/hid.c"
-#elif OS_DARWIN
- #include "os/darwin_usb.c"
- #include "hidapi/mac/hid.c"
-#elif OS_WINDOWS
- #include "os/windows_nt_common.c"
- #include "os/windows_usbdk.c"
- #include "os/windows_winusb.c"
- #include "hidapi/windows/hid.c"
-#elif OS_FREEBSD
- #include
- #include "hidapi/libusb/hid.c"
-#elif DOS_OPENBSD
- #include "os/openbsd_usb.c"
- #include "hidapi/libusb/hid.c"
-#endif
-
-#ifndef OS_FREEBSD
- #include "core.c"
- #include "descriptor.c"
- #include "hotplug.c"
- #include "io.c"
- #include "strerror.c"
- #include "sync.c"
-#endif
-*/
-import "C"
diff --git a/vendor/github.com/karalabe/usb/libusb/AUTHORS b/vendor/github.com/karalabe/usb/libusb/AUTHORS
deleted file mode 100644
index e90ad9bb2a..0000000000
--- a/vendor/github.com/karalabe/usb/libusb/AUTHORS
+++ /dev/null
@@ -1,119 +0,0 @@
-Copyright © 2001 Johannes Erdfelt
-Copyright © 2007-2009 Daniel Drake
-Copyright © 2010-2012 Peter Stuge
-Copyright © 2008-2016 Nathan Hjelm
-Copyright © 2009-2013 Pete Batard
-Copyright © 2009-2013 Ludovic Rousseau
-Copyright © 2010-2012 Michael Plante
-Copyright © 2011-2013 Hans de Goede