repo
stringlengths
5
67
sha
stringlengths
40
40
path
stringlengths
4
234
url
stringlengths
85
339
language
stringclasses
6 values
split
stringclasses
3 values
doc
stringlengths
3
51.2k
sign
stringlengths
5
8.01k
problem
stringlengths
13
51.2k
output
stringlengths
0
3.87M
golang/lint
959b441ac422379a43da2230f62be024250818b0
golint/import.go
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/golint/import.go#L86-L97
go
train
// matchPattern(pattern)(name) reports whether // name matches pattern. Pattern is a limited glob // pattern in which '...' means 'any string' and there // is no other special syntax.
func matchPattern(pattern string) func(name string) bool
// matchPattern(pattern)(name) reports whether // name matches pattern. Pattern is a limited glob // pattern in which '...' means 'any string' and there // is no other special syntax. func matchPattern(pattern string) func(name string) bool
{ re := regexp.QuoteMeta(pattern) re = strings.Replace(re, `\.\.\.`, `.*`, -1) // Special case: foo/... matches foo too. if strings.HasSuffix(re, `/.*`) { re = re[:len(re)-len(`/.*`)] + `(/.*)?` } reg := regexp.MustCompile(`^` + re + `$`) return func(name string) bool { return reg.MatchString(name) } }
golang/lint
959b441ac422379a43da2230f62be024250818b0
golint/import.go
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/golint/import.go#L101-L113
go
train
// hasPathPrefix reports whether the path s begins with the // elements in prefix.
func hasPathPrefix(s, prefix string) bool
// hasPathPrefix reports whether the path s begins with the // elements in prefix. func hasPathPrefix(s, prefix string) bool
{ switch { default: return false case len(s) == len(prefix): return s == prefix case len(s) > len(prefix): if prefix != "" && prefix[len(prefix)-1] == '/' { return strings.HasPrefix(s, prefix) } return s[len(prefix)] == '/' && s[:len(prefix)] == prefix } }
golang/lint
959b441ac422379a43da2230f62be024250818b0
golint/import.go
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/golint/import.go#L118-L128
go
train
// treeCanMatchPattern(pattern)(name) reports whether // name or children of name can possibly match pattern. // Pattern is the same limited glob accepted by matchPattern.
func treeCanMatchPattern(pattern string) func(name string) bool
// treeCanMatchPattern(pattern)(name) reports whether // name or children of name can possibly match pattern. // Pattern is the same limited glob accepted by matchPattern. func treeCanMatchPattern(pattern string) func(name string) bool
{ wildCard := false if i := strings.Index(pattern, "..."); i >= 0 { wildCard = true pattern = pattern[:i] } return func(name string) bool { return len(name) <= len(pattern) && hasPathPrefix(pattern, name) || wildCard && strings.HasPrefix(name, pattern) } }
golang/lint
959b441ac422379a43da2230f62be024250818b0
golint/import.go
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/golint/import.go#L134-L140
go
train
// allPackages returns all the packages that can be found // under the $GOPATH directories and $GOROOT matching pattern. // The pattern is either "all" (all packages), "std" (standard packages) // or a path including "...".
func allPackages(pattern string) []string
// allPackages returns all the packages that can be found // under the $GOPATH directories and $GOROOT matching pattern. // The pattern is either "all" (all packages), "std" (standard packages) // or a path including "...". func allPackages(pattern string) []string
{ pkgs := matchPackages(pattern) if len(pkgs) == 0 { fmt.Fprintf(os.Stderr, "warning: %q matched no packages\n", pattern) } return pkgs }
golang/lint
959b441ac422379a43da2230f62be024250818b0
golint/import.go
https://github.com/golang/lint/blob/959b441ac422379a43da2230f62be024250818b0/golint/import.go#L245-L251
go
train
// allPackagesInFS is like allPackages but is passed a pattern // beginning ./ or ../, meaning it should scan the tree rooted // at the given directory. There are ... in the pattern too.
func allPackagesInFS(pattern string) []string
// allPackagesInFS is like allPackages but is passed a pattern // beginning ./ or ../, meaning it should scan the tree rooted // at the given directory. There are ... in the pattern too. func allPackagesInFS(pattern string) []string
{ pkgs := matchPackagesInFS(pattern) if len(pkgs) == 0 { fmt.Fprintf(os.Stderr, "warning: %q matched no packages\n", pattern) } return pkgs }
hashicorp/go-plugin
5692942914bbdbc03558fde936b1f0bc2af365be
grpc_client.go
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/grpc_client.go#L47-L68
go
train
// newGRPCClient creates a new GRPCClient. The Client argument is expected // to be successfully started already with a lock held.
func newGRPCClient(doneCtx context.Context, c *Client) (*GRPCClient, error)
// newGRPCClient creates a new GRPCClient. The Client argument is expected // to be successfully started already with a lock held. func newGRPCClient(doneCtx context.Context, c *Client) (*GRPCClient, error)
{ conn, err := dialGRPCConn(c.config.TLSConfig, c.dialer) if err != nil { return nil, err } // Start the broker. brokerGRPCClient := newGRPCBrokerClient(conn) broker := newGRPCBroker(brokerGRPCClient, c.config.TLSConfig) go broker.Run() go brokerGRPCClient.StartStream() cl := &GRPCClient{ Conn: co...
hashicorp/go-plugin
5692942914bbdbc03558fde936b1f0bc2af365be
grpc_client.go
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/grpc_client.go#L82-L86
go
train
// ClientProtocol impl.
func (c *GRPCClient) Close() error
// ClientProtocol impl. func (c *GRPCClient) Close() error
{ c.broker.Close() c.controller.Shutdown(c.doneCtx, &plugin.Empty{}) return c.Conn.Close() }
hashicorp/go-plugin
5692942914bbdbc03558fde936b1f0bc2af365be
grpc_client.go
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/grpc_client.go#L89-L101
go
train
// ClientProtocol impl.
func (c *GRPCClient) Dispense(name string) (interface{}, error)
// ClientProtocol impl. func (c *GRPCClient) Dispense(name string) (interface{}, error)
{ raw, ok := c.Plugins[name] if !ok { return nil, fmt.Errorf("unknown plugin type: %s", name) } p, ok := raw.(GRPCPlugin) if !ok { return nil, fmt.Errorf("plugin %q doesn't support gRPC", name) } return p.GRPCClient(c.doneCtx, c.broker, c.Conn) }
hashicorp/go-plugin
5692942914bbdbc03558fde936b1f0bc2af365be
grpc_client.go
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/grpc_client.go#L104-L111
go
train
// ClientProtocol impl.
func (c *GRPCClient) Ping() error
// ClientProtocol impl. func (c *GRPCClient) Ping() error
{ client := grpc_health_v1.NewHealthClient(c.Conn) _, err := client.Check(context.Background(), &grpc_health_v1.HealthCheckRequest{ Service: GRPCServiceName, }) return err }
hashicorp/go-plugin
5692942914bbdbc03558fde936b1f0bc2af365be
server_mux.go
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/server_mux.go#L16-L31
go
train
// ServeMux is like Serve, but serves multiple types of plugins determined // by the argument given on the command-line. // // This command doesn't return until the plugin is done being executed. Any // errors are logged or output to stderr.
func ServeMux(m ServeMuxMap)
// ServeMux is like Serve, but serves multiple types of plugins determined // by the argument given on the command-line. // // This command doesn't return until the plugin is done being executed. Any // errors are logged or output to stderr. func ServeMux(m ServeMuxMap)
{ if len(os.Args) != 2 { fmt.Fprintf(os.Stderr, "Invoked improperly. This is an internal command that shouldn't\n"+ "be manually invoked.\n") os.Exit(1) } opts, ok := m[os.Args[1]] if !ok { fmt.Fprintf(os.Stderr, "Unknown plugin: %s\n", os.Args[1]) os.Exit(1) } Serve(opts) }
hashicorp/go-plugin
5692942914bbdbc03558fde936b1f0bc2af365be
grpc_broker.go
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/grpc_broker.go#L63-L98
go
train
// StartStream implements the GRPCBrokerServer interface and will block until // the quit channel is closed or the context reports Done. The stream will pass // connection information to/from the client.
func (s *gRPCBrokerServer) StartStream(stream plugin.GRPCBroker_StartStreamServer) error
// StartStream implements the GRPCBrokerServer interface and will block until // the quit channel is closed or the context reports Done. The stream will pass // connection information to/from the client. func (s *gRPCBrokerServer) StartStream(stream plugin.GRPCBroker_StartStreamServer) error
{ doneCh := stream.Context().Done() defer s.Close() // Proccess send stream go func() { for { select { case <-doneCh: return case <-s.quit: return case se := <-s.send: err := stream.Send(se.i) se.ch <- err } } }() // Process receive stream for { i, err := stream.Recv() i...
hashicorp/go-plugin
5692942914bbdbc03558fde936b1f0bc2af365be
grpc_broker.go
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/grpc_broker.go#L120-L127
go
train
// Recv is used by the GRPCBroker to pass connection information that has been // sent from the client from the stream to the broker.
func (s *gRPCBrokerServer) Recv() (*plugin.ConnInfo, error)
// Recv is used by the GRPCBroker to pass connection information that has been // sent from the client from the stream to the broker. func (s *gRPCBrokerServer) Recv() (*plugin.ConnInfo, error)
{ select { case <-s.quit: return nil, errors.New("broker closed") case i := <-s.recv: return i, nil } }
hashicorp/go-plugin
5692942914bbdbc03558fde936b1f0bc2af365be
grpc_broker.go
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/grpc_broker.go#L168-L208
go
train
// StartStream implements the GRPCBrokerClient interface and will block until // the quit channel is closed or the context reports Done. The stream will pass // connection information to/from the plugin.
func (s *gRPCBrokerClientImpl) StartStream() error
// StartStream implements the GRPCBrokerClient interface and will block until // the quit channel is closed or the context reports Done. The stream will pass // connection information to/from the plugin. func (s *gRPCBrokerClientImpl) StartStream() error
{ ctx, cancelFunc := context.WithCancel(context.Background()) defer cancelFunc() defer s.Close() stream, err := s.client.StartStream(ctx) if err != nil { return err } doneCh := stream.Context().Done() go func() { for { select { case <-doneCh: return case <-s.quit: return case se := <-...
hashicorp/go-plugin
5692942914bbdbc03558fde936b1f0bc2af365be
grpc_broker.go
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/grpc_broker.go#L212-L226
go
train
// Send is used by the GRPCBroker to pass connection information into the stream // to the plugin.
func (s *gRPCBrokerClientImpl) Send(i *plugin.ConnInfo) error
// Send is used by the GRPCBroker to pass connection information into the stream // to the plugin. func (s *gRPCBrokerClientImpl) Send(i *plugin.ConnInfo) error
{ ch := make(chan error) defer close(ch) select { case <-s.quit: return errors.New("broker closed") case s.send <- &sendErr{ i: i, ch: ch, }: } return <-ch }
hashicorp/go-plugin
5692942914bbdbc03558fde936b1f0bc2af365be
grpc_broker.go
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/grpc_broker.go#L287-L303
go
train
// Accept accepts a connection by ID. // // This should not be called multiple times with the same ID at one time.
func (b *GRPCBroker) Accept(id uint32) (net.Listener, error)
// Accept accepts a connection by ID. // // This should not be called multiple times with the same ID at one time. func (b *GRPCBroker) Accept(id uint32) (net.Listener, error)
{ listener, err := serverListener() if err != nil { return nil, err } err = b.streamer.Send(&plugin.ConnInfo{ ServiceId: id, Network: listener.Addr().Network(), Address: listener.Addr().String(), }) if err != nil { return nil, err } return listener, nil }
hashicorp/go-plugin
5692942914bbdbc03558fde936b1f0bc2af365be
grpc_broker.go
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/grpc_broker.go#L312-L355
go
train
// AcceptAndServe is used to accept a specific stream ID and immediately // serve a gRPC server on that stream ID. This is used to easily serve // complex arguments. Each AcceptAndServe call opens a new listener socket and // sends the connection info down the stream to the dialer. Since a new // connection is opened e...
func (b *GRPCBroker) AcceptAndServe(id uint32, s func([]grpc.ServerOption) *grpc.Server)
// AcceptAndServe is used to accept a specific stream ID and immediately // serve a gRPC server on that stream ID. This is used to easily serve // complex arguments. Each AcceptAndServe call opens a new listener socket and // sends the connection info down the stream to the dialer. Since a new // connection is opened e...
{ listener, err := b.Accept(id) if err != nil { log.Printf("[ERR] plugin: plugin acceptAndServe error: %s", err) return } defer listener.Close() var opts []grpc.ServerOption if b.tls != nil { opts = []grpc.ServerOption{grpc.Creds(credentials.NewTLS(b.tls))} } server := s(opts) // Here we use a run gr...
hashicorp/go-plugin
5692942914bbdbc03558fde936b1f0bc2af365be
grpc_broker.go
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/grpc_broker.go#L358-L364
go
train
// Close closes the stream and all servers.
func (b *GRPCBroker) Close() error
// Close closes the stream and all servers. func (b *GRPCBroker) Close() error
{ b.streamer.Close() b.o.Do(func() { close(b.doneCh) }) return nil }
hashicorp/go-plugin
5692942914bbdbc03558fde936b1f0bc2af365be
grpc_broker.go
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/grpc_broker.go#L367-L393
go
train
// Dial opens a connection by ID.
func (b *GRPCBroker) Dial(id uint32) (conn *grpc.ClientConn, err error)
// Dial opens a connection by ID. func (b *GRPCBroker) Dial(id uint32) (conn *grpc.ClientConn, err error)
{ var c *plugin.ConnInfo // Open the stream p := b.getStream(id) select { case c = <-p.ch: close(p.doneCh) case <-time.After(5 * time.Second): return nil, fmt.Errorf("timeout waiting for connection info") } var addr net.Addr switch c.Network { case "tcp": addr, err = net.ResolveTCPAddr("tcp", c.Addre...
hashicorp/go-plugin
5692942914bbdbc03558fde936b1f0bc2af365be
grpc_broker.go
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/grpc_broker.go#L409-L426
go
train
// Run starts the brokering and should be executed in a goroutine, since it // blocks forever, or until the session closes. // // Uses of GRPCBroker never need to call this. It is called internally by // the plugin host/client.
func (m *GRPCBroker) Run()
// Run starts the brokering and should be executed in a goroutine, since it // blocks forever, or until the session closes. // // Uses of GRPCBroker never need to call this. It is called internally by // the plugin host/client. func (m *GRPCBroker) Run()
{ for { stream, err := m.streamer.Recv() if err != nil { // Once we receive an error, just exit break } // Initialize the waiter p := m.getStream(stream.ServiceId) select { case p.ch <- stream: default: } go m.timeoutWait(stream.ServiceId, p) } }
hashicorp/go-plugin
5692942914bbdbc03558fde936b1f0bc2af365be
log_entry.go
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/log_entry.go#L24-L32
go
train
// flattenKVPairs is used to flatten KVPair slice into []interface{} // for hclog consumption.
func flattenKVPairs(kvs []*logEntryKV) []interface{}
// flattenKVPairs is used to flatten KVPair slice into []interface{} // for hclog consumption. func flattenKVPairs(kvs []*logEntryKV) []interface{}
{ var result []interface{} for _, kv := range kvs { result = append(result, kv.Key) result = append(result, kv.Value) } return result }
hashicorp/go-plugin
5692942914bbdbc03558fde936b1f0bc2af365be
log_entry.go
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/log_entry.go#L35-L73
go
train
// parseJSON handles parsing JSON output
func parseJSON(input []byte) (*logEntry, error)
// parseJSON handles parsing JSON output func parseJSON(input []byte) (*logEntry, error)
{ var raw map[string]interface{} entry := &logEntry{} err := json.Unmarshal(input, &raw) if err != nil { return nil, err } // Parse hclog-specific objects if v, ok := raw["@message"]; ok { entry.Message = v.(string) delete(raw, "@message") } if v, ok := raw["@level"]; ok { entry.Level = v.(string) ...
hashicorp/go-plugin
5692942914bbdbc03558fde936b1f0bc2af365be
discover.go
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/discover.go#L16-L28
go
train
// Discover discovers plugins that are in a given directory. // // The directory doesn't need to be absolute. For example, "." will work fine. // // This currently assumes any file matching the glob is a plugin. // In the future this may be smarter about checking that a file is // executable and so on. // // TODO: test
func Discover(glob, dir string) ([]string, error)
// Discover discovers plugins that are in a given directory. // // The directory doesn't need to be absolute. For example, "." will work fine. // // This currently assumes any file matching the glob is a plugin. // In the future this may be smarter about checking that a file is // executable and so on. // // TODO: test...
{ var err error // Make the directory absolute if it isn't already if !filepath.IsAbs(dir) { dir, err = filepath.Abs(dir) if err != nil { return nil, err } } return filepath.Glob(filepath.Join(dir, glob)) }
hashicorp/go-plugin
5692942914bbdbc03558fde936b1f0bc2af365be
client.go
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/client.go#L233-L256
go
train
// Check takes the filepath to an executable and returns true if the checksum of // the file matches the checksum provided in the SecureConfig.
func (s *SecureConfig) Check(filePath string) (bool, error)
// Check takes the filepath to an executable and returns true if the checksum of // the file matches the checksum provided in the SecureConfig. func (s *SecureConfig) Check(filePath string) (bool, error)
{ if len(s.Checksum) == 0 { return false, ErrSecureConfigNoChecksum } if s.Hash == nil { return false, ErrSecureConfigNoHash } file, err := os.Open(filePath) if err != nil { return false, err } defer file.Close() _, err = io.Copy(s.Hash, file) if err != nil { return false, err } sum := s.Hash.S...
hashicorp/go-plugin
5692942914bbdbc03558fde936b1f0bc2af365be
client.go
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/client.go#L263-L282
go
train
// This makes sure all the managed subprocesses are killed and properly // logged. This should be called before the parent process running the // plugins exits. // // This must only be called _once_.
func CleanupClients()
// This makes sure all the managed subprocesses are killed and properly // logged. This should be called before the parent process running the // plugins exits. // // This must only be called _once_. func CleanupClients()
{ // Set the killed to true so that we don't get unexpected panics atomic.StoreUint32(&Killed, 1) // Kill all the managed clients in parallel and use a WaitGroup // to wait for them all to finish up. var wg sync.WaitGroup managedClientsLock.Lock() for _, client := range managedClients { wg.Add(1) go func(...
hashicorp/go-plugin
5692942914bbdbc03558fde936b1f0bc2af365be
client.go
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/client.go#L291-L335
go
train
// Creates a new plugin client which manages the lifecycle of an external // plugin and gets the address for the RPC connection. // // The client must be cleaned up at some point by calling Kill(). If // the client is a managed client (created with NewManagedClient) you // can just call CleanupClients at the end of you...
func NewClient(config *ClientConfig) (c *Client)
// Creates a new plugin client which manages the lifecycle of an external // plugin and gets the address for the RPC connection. // // The client must be cleaned up at some point by calling Kill(). If // the client is a managed client (created with NewManagedClient) you // can just call CleanupClients at the end of you...
{ if config.MinPort == 0 && config.MaxPort == 0 { config.MinPort = 10000 config.MaxPort = 25000 } if config.StartTimeout == 0 { config.StartTimeout = 1 * time.Minute } if config.Stderr == nil { config.Stderr = ioutil.Discard } if config.SyncStdout == nil { config.SyncStdout = ioutil.Discard } if ...
hashicorp/go-plugin
5692942914bbdbc03558fde936b1f0bc2af365be
client.go
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/client.go#L340-L370
go
train
// Client returns the protocol client for this connection. // // Subsequent calls to this will return the same client.
func (c *Client) Client() (ClientProtocol, error)
// Client returns the protocol client for this connection. // // Subsequent calls to this will return the same client. func (c *Client) Client() (ClientProtocol, error)
{ _, err := c.Start() if err != nil { return nil, err } c.l.Lock() defer c.l.Unlock() if c.client != nil { return c.client, nil } switch c.protocol { case ProtocolNetRPC: c.client, err = newRPCClient(c) case ProtocolGRPC: c.client, err = newGRPCClient(c.doneCtx, c) default: return nil, fmt.Er...
hashicorp/go-plugin
5692942914bbdbc03558fde936b1f0bc2af365be
client.go
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/client.go#L381-L385
go
train
// killed is used in tests to check if a process failed to exit gracefully, and // needed to be killed.
func (c *Client) killed() bool
// killed is used in tests to check if a process failed to exit gracefully, and // needed to be killed. func (c *Client) killed() bool
{ c.l.Lock() defer c.l.Unlock() return c.processKilled }
hashicorp/go-plugin
5692942914bbdbc03558fde936b1f0bc2af365be
client.go
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/client.go#L393-L460
go
train
// End the executing subprocess (if it is running) and perform any cleanup // tasks necessary such as capturing any remaining logs and so on. // // This method blocks until the process successfully exits. // // This method can safely be called multiple times.
func (c *Client) Kill()
// End the executing subprocess (if it is running) and perform any cleanup // tasks necessary such as capturing any remaining logs and so on. // // This method blocks until the process successfully exits. // // This method can safely be called multiple times. func (c *Client) Kill()
{ // Grab a lock to read some private fields. c.l.Lock() process := c.process addr := c.address c.l.Unlock() // If there is no process, there is nothing to kill. if process == nil { return } defer func() { // Wait for the all client goroutines to finish. c.clientWaitGroup.Wait() // Make sure there ...
hashicorp/go-plugin
5692942914bbdbc03558fde936b1f0bc2af365be
client.go
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/client.go#L468-L755
go
train
// Starts the underlying subprocess, communicating with it to negotiate // a port for RPC connections, and returning the address to connect via RPC. // // This method is safe to call multiple times. Subsequent calls have no effect. // Once a client has been started once, it cannot be started again, even if // it was ki...
func (c *Client) Start() (addr net.Addr, err error)
// Starts the underlying subprocess, communicating with it to negotiate // a port for RPC connections, and returning the address to connect via RPC. // // This method is safe to call multiple times. Subsequent calls have no effect. // Once a client has been started once, it cannot be started again, even if // it was ki...
{ c.l.Lock() defer c.l.Unlock() if c.address != nil { return c.address, nil } // If one of cmd or reattach isn't set, then it is an error. We wrap // this in a {} for scoping reasons, and hopeful that the escape // analysis will pop the stack here. { cmdSet := c.config.Cmd != nil attachSet := c.config....
hashicorp/go-plugin
5692942914bbdbc03558fde936b1f0bc2af365be
client.go
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/client.go#L759-L776
go
train
// loadServerCert is used by AutoMTLS to read an x.509 cert returned by the // server, and load it as the RootCA for the client TLSConfig.
func (c *Client) loadServerCert(cert string) error
// loadServerCert is used by AutoMTLS to read an x.509 cert returned by the // server, and load it as the RootCA for the client TLSConfig. func (c *Client) loadServerCert(cert string) error
{ certPool := x509.NewCertPool() asn1, err := base64.RawStdEncoding.DecodeString(cert) if err != nil { return err } x509Cert, err := x509.ParseCertificate([]byte(asn1)) if err != nil { return err } certPool.AddCert(x509Cert) c.config.TLSConfig.RootCAs = certPool return nil }
hashicorp/go-plugin
5692942914bbdbc03558fde936b1f0bc2af365be
client.go
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/client.go#L834-L856
go
train
// checkProtoVersion returns the negotiated version and PluginSet. // This returns an error if the server returned an incompatible protocol // version, or an invalid handshake response.
func (c *Client) checkProtoVersion(protoVersion string) (int, PluginSet, error)
// checkProtoVersion returns the negotiated version and PluginSet. // This returns an error if the server returned an incompatible protocol // version, or an invalid handshake response. func (c *Client) checkProtoVersion(protoVersion string) (int, PluginSet, error)
{ serverVersion, err := strconv.Atoi(protoVersion) if err != nil { return 0, nil, fmt.Errorf("Error parsing protocol version %q: %s", protoVersion, err) } // record these for the error message var clientVersions []int // all versions, including the legacy ProtocolVersion have been added to // the versions s...
hashicorp/go-plugin
5692942914bbdbc03558fde936b1f0bc2af365be
client.go
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/client.go#L864-L886
go
train
// ReattachConfig returns the information that must be provided to NewClient // to reattach to the plugin process that this client started. This is // useful for plugins that detach from their parent process. // // If this returns nil then the process hasn't been started yet. Please // call Start or Client before calli...
func (c *Client) ReattachConfig() *ReattachConfig
// ReattachConfig returns the information that must be provided to NewClient // to reattach to the plugin process that this client started. This is // useful for plugins that detach from their parent process. // // If this returns nil then the process hasn't been started yet. Please // call Start or Client before calli...
{ c.l.Lock() defer c.l.Unlock() if c.address == nil { return nil } if c.config.Cmd != nil && c.config.Cmd.Process == nil { return nil } // If we connected via reattach, just return the information as-is if c.config.Reattach != nil { return c.config.Reattach } return &ReattachConfig{ Protocol: c.p...
hashicorp/go-plugin
5692942914bbdbc03558fde936b1f0bc2af365be
client.go
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/client.go#L893-L900
go
train
// Protocol returns the protocol of server on the remote end. This will // start the plugin process if it isn't already started. Errors from // starting the plugin are surpressed and ProtocolInvalid is returned. It // is recommended you call Start explicitly before calling Protocol to ensure // no errors occur.
func (c *Client) Protocol() Protocol
// Protocol returns the protocol of server on the remote end. This will // start the plugin process if it isn't already started. Errors from // starting the plugin are surpressed and ProtocolInvalid is returned. It // is recommended you call Start explicitly before calling Protocol to ensure // no errors occur. func (c...
{ _, err := c.Start() if err != nil { return ProtocolInvalid } return c.protocol }
hashicorp/go-plugin
5692942914bbdbc03558fde936b1f0bc2af365be
client.go
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/client.go#L920-L933
go
train
// dialer is compatible with grpc.WithDialer and creates the connection // to the plugin.
func (c *Client) dialer(_ string, timeout time.Duration) (net.Conn, error)
// dialer is compatible with grpc.WithDialer and creates the connection // to the plugin. func (c *Client) dialer(_ string, timeout time.Duration) (net.Conn, error)
{ conn, err := netAddrDialer(c.address)("", timeout) if err != nil { return nil, err } // If we have a TLS config we wrap our connection. We only do this // for net/rpc since gRPC uses its own mechanism for TLS. if c.protocol == ProtocolNetRPC && c.config.TLSConfig != nil { conn = tls.Client(conn, c.config....
hashicorp/go-plugin
5692942914bbdbc03558fde936b1f0bc2af365be
mtls.go
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/mtls.go#L17-L73
go
train
// generateCert generates a temporary certificate for plugin authentication. The // certificate and private key are returns in PEM format.
func generateCert() (cert []byte, privateKey []byte, err error)
// generateCert generates a temporary certificate for plugin authentication. The // certificate and private key are returns in PEM format. func generateCert() (cert []byte, privateKey []byte, err error)
{ key, err := ecdsa.GenerateKey(elliptic.P521(), rand.Reader) if err != nil { return nil, nil, err } serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128) sn, err := rand.Int(rand.Reader, serialNumberLimit) if err != nil { return nil, nil, err } host := "localhost" template := &x509.Certificate{ ...
hashicorp/go-plugin
5692942914bbdbc03558fde936b1f0bc2af365be
process_windows.go
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/process_windows.go#L17-L29
go
train
// _pidAlive tests whether a process is alive or not
func _pidAlive(pid int) bool
// _pidAlive tests whether a process is alive or not func _pidAlive(pid int) bool
{ h, err := syscall.OpenProcess(processDesiredAccess, false, uint32(pid)) if err != nil { return false } var ec uint32 if e := syscall.GetExitCodeProcess(h, &ec); e != nil { return false } return ec == exit_STILL_ACTIVE }
hashicorp/go-plugin
5692942914bbdbc03558fde936b1f0bc2af365be
grpc_server.go
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/grpc_server.go#L62-L101
go
train
// ServerProtocol impl.
func (s *GRPCServer) Init() error
// ServerProtocol impl. func (s *GRPCServer) Init() error
{ // Create our server var opts []grpc.ServerOption if s.TLS != nil { opts = append(opts, grpc.Creds(credentials.NewTLS(s.TLS))) } s.server = s.Server(opts) // Register the health service healthCheck := health.NewServer() healthCheck.SetServingStatus( GRPCServiceName, grpc_health_v1.HealthCheckResponse_SE...
hashicorp/go-plugin
5692942914bbdbc03558fde936b1f0bc2af365be
grpc_server.go
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/grpc_server.go#L114-L127
go
train
// Config is the GRPCServerConfig encoded as JSON then base64.
func (s *GRPCServer) Config() string
// Config is the GRPCServerConfig encoded as JSON then base64. func (s *GRPCServer) Config() string
{ // Create a buffer that will contain our final contents var buf bytes.Buffer // Wrap the base64 encoding with JSON encoding. if err := json.NewEncoder(&buf).Encode(s.config); err != nil { // We panic since ths shouldn't happen under any scenario. We // carefully control the structure being encoded here and ...
hashicorp/go-plugin
5692942914bbdbc03558fde936b1f0bc2af365be
rpc_client.go
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/rpc_client.go#L25-L57
go
train
// newRPCClient creates a new RPCClient. The Client argument is expected // to be successfully started already with a lock held.
func newRPCClient(c *Client) (*RPCClient, error)
// newRPCClient creates a new RPCClient. The Client argument is expected // to be successfully started already with a lock held. func newRPCClient(c *Client) (*RPCClient, error)
{ // Connect to the client conn, err := net.Dial(c.address.Network(), c.address.String()) if err != nil { return nil, err } if tcpConn, ok := conn.(*net.TCPConn); ok { // Make sure to set keep alive so that the connection doesn't die tcpConn.SetKeepAlive(true) } if c.config.TLSConfig != nil { conn = tl...
hashicorp/go-plugin
5692942914bbdbc03558fde936b1f0bc2af365be
rpc_client.go
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/rpc_client.go#L61-L98
go
train
// NewRPCClient creates a client from an already-open connection-like value. // Dial is typically used instead.
func NewRPCClient(conn io.ReadWriteCloser, plugins map[string]Plugin) (*RPCClient, error)
// NewRPCClient creates a client from an already-open connection-like value. // Dial is typically used instead. func NewRPCClient(conn io.ReadWriteCloser, plugins map[string]Plugin) (*RPCClient, error)
{ // Create the yamux client so we can multiplex mux, err := yamux.Client(conn, nil) if err != nil { conn.Close() return nil, err } // Connect to the control stream. control, err := mux.Open() if err != nil { mux.Close() return nil, err } // Connect stdout, stderr streams stdstream := make([]net.Co...
hashicorp/go-plugin
5692942914bbdbc03558fde936b1f0bc2af365be
rpc_client.go
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/rpc_client.go#L107-L111
go
train
// SyncStreams should be called to enable syncing of stdout, // stderr with the plugin. // // This will return immediately and the syncing will continue to happen // in the background. You do not need to launch this in a goroutine itself. // // This should never be called multiple times.
func (c *RPCClient) SyncStreams(stdout io.Writer, stderr io.Writer) error
// SyncStreams should be called to enable syncing of stdout, // stderr with the plugin. // // This will return immediately and the syncing will continue to happen // in the background. You do not need to launch this in a goroutine itself. // // This should never be called multiple times. func (c *RPCClient) SyncStreams...
{ go copyStream("stdout", stdout, c.stdout) go copyStream("stderr", stderr, c.stderr) return nil }
hashicorp/go-plugin
5692942914bbdbc03558fde936b1f0bc2af365be
rpc_client.go
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/rpc_client.go#L115-L140
go
train
// Close closes the connection. The client is no longer usable after this // is called.
func (c *RPCClient) Close() error
// Close closes the connection. The client is no longer usable after this // is called. func (c *RPCClient) Close() error
{ // Call the control channel and ask it to gracefully exit. If this // errors, then we save it so that we always return an error but we // want to try to close the other channels anyways. var empty struct{} returnErr := c.control.Call("Control.Quit", true, &empty) // Close the other streams we have if err := ...
hashicorp/go-plugin
5692942914bbdbc03558fde936b1f0bc2af365be
rpc_client.go
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/rpc_client.go#L167-L170
go
train
// Ping pings the connection to ensure it is still alive. // // The error from the RPC call is returned exactly if you want to inspect // it for further error analysis. Any error returned from here would indicate // that the connection to the plugin is not healthy.
func (c *RPCClient) Ping() error
// Ping pings the connection to ensure it is still alive. // // The error from the RPC call is returned exactly if you want to inspect // it for further error analysis. Any error returned from here would indicate // that the connection to the plugin is not healthy. func (c *RPCClient) Ping() error
{ var empty struct{} return c.control.Call("Control.Ping", true, &empty) }
hashicorp/go-plugin
5692942914bbdbc03558fde936b1f0bc2af365be
rpc_server.go
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/rpc_server.go#L44-L54
go
train
// ServerProtocol impl.
func (s *RPCServer) Serve(lis net.Listener)
// ServerProtocol impl. func (s *RPCServer) Serve(lis net.Listener)
{ for { conn, err := lis.Accept() if err != nil { log.Printf("[ERR] plugin: plugin server: %s", err) return } go s.ServeConn(conn) } }
hashicorp/go-plugin
5692942914bbdbc03558fde936b1f0bc2af365be
rpc_server.go
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/rpc_server.go#L59-L109
go
train
// ServeConn runs a single connection. // // ServeConn blocks, serving the connection until the client hangs up.
func (s *RPCServer) ServeConn(conn io.ReadWriteCloser)
// ServeConn runs a single connection. // // ServeConn blocks, serving the connection until the client hangs up. func (s *RPCServer) ServeConn(conn io.ReadWriteCloser)
{ // First create the yamux server to wrap this connection mux, err := yamux.Server(conn, nil) if err != nil { conn.Close() log.Printf("[ERR] plugin: error creating yamux server: %s", err) return } // Accept the control connection control, err := mux.Accept() if err != nil { mux.Close() if err != io....
hashicorp/go-plugin
5692942914bbdbc03558fde936b1f0bc2af365be
rpc_server.go
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/rpc_server.go#L114-L122
go
train
// done is called internally by the control server to trigger the // doneCh to close which is listened to by the main process to cleanly // exit.
func (s *RPCServer) done()
// done is called internally by the control server to trigger the // doneCh to close which is listened to by the main process to cleanly // exit. func (s *RPCServer) done()
{ s.lock.Lock() defer s.lock.Unlock() if s.DoneCh != nil { close(s.DoneCh) s.DoneCh = nil } }
hashicorp/go-plugin
5692942914bbdbc03558fde936b1f0bc2af365be
server.go
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/server.go#L93-L167
go
train
// protocolVersion determines the protocol version and plugin set to be used by // the server. In the event that there is no suitable version, the last version // in the config is returned leaving the client to report the incompatibility.
func protocolVersion(opts *ServeConfig) (int, Protocol, PluginSet)
// protocolVersion determines the protocol version and plugin set to be used by // the server. In the event that there is no suitable version, the last version // in the config is returned leaving the client to report the incompatibility. func protocolVersion(opts *ServeConfig) (int, Protocol, PluginSet)
{ protoVersion := int(opts.ProtocolVersion) pluginSet := opts.Plugins protoType := ProtocolNetRPC // Check if the client sent a list of acceptable versions var clientVersions []int if vs := os.Getenv("PLUGIN_PROTOCOL_VERSIONS"); vs != "" { for _, s := range strings.Split(vs, ",") { v, err := strconv.Atoi(s)...
hashicorp/go-plugin
5692942914bbdbc03558fde936b1f0bc2af365be
server.go
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/server.go#L175-L355
go
train
// Serve serves the plugins given by ServeConfig. // // Serve doesn't return until the plugin is done being executed. Any // errors will be outputted to os.Stderr. // // This is the method that plugins should call in their main() functions.
func Serve(opts *ServeConfig)
// Serve serves the plugins given by ServeConfig. // // Serve doesn't return until the plugin is done being executed. Any // errors will be outputted to os.Stderr. // // This is the method that plugins should call in their main() functions. func Serve(opts *ServeConfig)
{ // Validate the handshake config if opts.MagicCookieKey == "" || opts.MagicCookieValue == "" { fmt.Fprintf(os.Stderr, "Misconfigured ServeConfig given to serve this plugin: no magic cookie\n"+ "key or value was set. Please notify the plugin author and report\n"+ "this as a bug.\n") os.Exit(1) } /...
hashicorp/go-plugin
5692942914bbdbc03558fde936b1f0bc2af365be
process_posix.go
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/process_posix.go#L12-L19
go
train
// _pidAlive tests whether a process is alive or not by sending it Signal 0, // since Go otherwise has no way to test this.
func _pidAlive(pid int) bool
// _pidAlive tests whether a process is alive or not by sending it Signal 0, // since Go otherwise has no way to test this. func _pidAlive(pid int) bool
{ proc, err := os.FindProcess(pid) if err == nil { err = proc.Signal(syscall.Signal(0)) } return err == nil }
hashicorp/go-plugin
5692942914bbdbc03558fde936b1f0bc2af365be
mux_broker.go
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/mux_broker.go#L80-L88
go
train
// AcceptAndServe is used to accept a specific stream ID and immediately // serve an RPC server on that stream ID. This is used to easily serve // complex arguments. // // The served interface is always registered to the "Plugin" name.
func (m *MuxBroker) AcceptAndServe(id uint32, v interface{})
// AcceptAndServe is used to accept a specific stream ID and immediately // serve an RPC server on that stream ID. This is used to easily serve // complex arguments. // // The served interface is always registered to the "Plugin" name. func (m *MuxBroker) AcceptAndServe(id uint32, v interface{})
{ conn, err := m.Accept(id) if err != nil { log.Printf("[ERR] plugin: plugin acceptAndServe error: %s", err) return } serve(conn, "Plugin", v) }
hashicorp/go-plugin
5692942914bbdbc03558fde936b1f0bc2af365be
process.go
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/process.go#L13-L24
go
train
// pidWait blocks for a process to exit.
func pidWait(pid int) error
// pidWait blocks for a process to exit. func pidWait(pid int) error
{ ticker := time.NewTicker(1 * time.Second) defer ticker.Stop() for range ticker.C { if !pidAlive(pid) { break } } return nil }
hashicorp/go-plugin
5692942914bbdbc03558fde936b1f0bc2af365be
grpc_controller.go
https://github.com/hashicorp/go-plugin/blob/5692942914bbdbc03558fde936b1f0bc2af365be/grpc_controller.go#L17-L23
go
train
// Shutdown stops the grpc server. It first will attempt a graceful stop, then a // full stop on the server.
func (s *grpcControllerServer) Shutdown(ctx context.Context, _ *plugin.Empty) (*plugin.Empty, error)
// Shutdown stops the grpc server. It first will attempt a graceful stop, then a // full stop on the server. func (s *grpcControllerServer) Shutdown(ctx context.Context, _ *plugin.Empty) (*plugin.Empty, error)
{ resp := &plugin.Empty{} // TODO: figure out why GracefullStop doesn't work. s.server.Stop() return resp, nil }
nareix/joy4
3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02
av/av.go
https://github.com/nareix/joy4/blob/3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02/av/av.go#L70-L77
go
train
// Check if this sample format is in planar.
func (self SampleFormat) IsPlanar() bool
// Check if this sample format is in planar. func (self SampleFormat) IsPlanar() bool
{ switch self { case S16P, S32P, FLTP, DBLP: return true default: return false } }
nareix/joy4
3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02
av/av.go
https://github.com/nareix/joy4/blob/3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02/av/av.go#L157-L160
go
train
// Make a new audio codec type.
func MakeAudioCodecType(base uint32) (c CodecType)
// Make a new audio codec type. func MakeAudioCodecType(base uint32) (c CodecType)
{ c = CodecType(base)<<codecTypeOtherBits | CodecType(codecTypeAudioBit) return }
nareix/joy4
3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02
av/av.go
https://github.com/nareix/joy4/blob/3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02/av/av.go#L252-L263
go
train
// Check this audio frame has same format as other audio frame.
func (self AudioFrame) HasSameFormat(other AudioFrame) bool
// Check this audio frame has same format as other audio frame. func (self AudioFrame) HasSameFormat(other AudioFrame) bool
{ if self.SampleRate != other.SampleRate { return false } if self.ChannelLayout != other.ChannelLayout { return false } if self.SampleFormat != other.SampleFormat { return false } return true }
nareix/joy4
3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02
av/av.go
https://github.com/nareix/joy4/blob/3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02/av/av.go#L266-L278
go
train
// Split sample audio sample from this frame.
func (self AudioFrame) Slice(start int, end int) (out AudioFrame)
// Split sample audio sample from this frame. func (self AudioFrame) Slice(start int, end int) (out AudioFrame)
{ if start > end { panic(fmt.Sprintf("av: AudioFrame split failed start=%d end=%d invalid", start, end)) } out = self out.Data = append([][]byte(nil), out.Data...) out.SampleCount = end - start size := self.SampleFormat.BytesPerSample() for i := range out.Data { out.Data[i] = out.Data[i][start*size : end*si...
nareix/joy4
3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02
av/av.go
https://github.com/nareix/joy4/blob/3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02/av/av.go#L281-L289
go
train
// Concat two audio frames.
func (self AudioFrame) Concat(in AudioFrame) (out AudioFrame)
// Concat two audio frames. func (self AudioFrame) Concat(in AudioFrame) (out AudioFrame)
{ out = self out.Data = append([][]byte(nil), out.Data...) out.SampleCount += in.SampleCount for i := range out.Data { out.Data[i] = append(out.Data[i], in.Data[i]...) } return }
nareix/joy4
3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02
examples/rtmp_publish/main.go
https://github.com/nareix/joy4/blob/3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02/examples/rtmp_publish/main.go#L16-L26
go
train
// as same as: ffmpeg -re -i projectindex.flv -c copy -f flv rtmp://localhost:1936/app/publish
func main()
// as same as: ffmpeg -re -i projectindex.flv -c copy -f flv rtmp://localhost:1936/app/publish func main()
{ file, _ := avutil.Open("projectindex.flv") conn, _ := rtmp.Dial("rtmp://localhost:1936/app/publish") // conn, _ := avutil.Create("rtmp://localhost:1936/app/publish") demuxer := &pktque.FilterDemuxer{Demuxer: file, Filter: &pktque.Walltime{}} avutil.CopyFile(conn, demuxer) file.Close() conn.Close() }
nareix/joy4
3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02
av/transcode/transcode.go
https://github.com/nareix/joy4/blob/3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02/av/transcode/transcode.go#L114-L124
go
train
// Do the transcode. // // In audio transcoding one Packet may transcode into many Packets // packet time will be adjusted automatically.
func (self *Transcoder) Do(pkt av.Packet) (out []av.Packet, err error)
// Do the transcode. // // In audio transcoding one Packet may transcode into many Packets // packet time will be adjusted automatically. func (self *Transcoder) Do(pkt av.Packet) (out []av.Packet, err error)
{ stream := self.streams[pkt.Idx] if stream.aenc != nil && stream.adec != nil { if out, err = stream.audioDecodeAndEncode(pkt); err != nil { return } } else { out = append(out, pkt) } return }
nareix/joy4
3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02
av/transcode/transcode.go
https://github.com/nareix/joy4/blob/3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02/av/transcode/transcode.go#L127-L132
go
train
// Get CodecDatas after transcoding.
func (self *Transcoder) Streams() (streams []av.CodecData, err error)
// Get CodecDatas after transcoding. func (self *Transcoder) Streams() (streams []av.CodecData, err error)
{ for _, stream := range self.streams { streams = append(streams, stream.codec) } return }
nareix/joy4
3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02
av/transcode/transcode.go
https://github.com/nareix/joy4/blob/3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02/av/transcode/transcode.go#L135-L148
go
train
// Close transcoder, close related encoder and decoders.
func (self *Transcoder) Close() (err error)
// Close transcoder, close related encoder and decoders. func (self *Transcoder) Close() (err error)
{ for _, stream := range self.streams { if stream.aenc != nil { stream.aenc.Close() stream.aenc = nil } if stream.adec != nil { stream.adec.Close() stream.adec = nil } } self.streams = nil return }
nareix/joy4
3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02
format/mp4/mp4io/mp4io.go
https://github.com/nareix/joy4/blob/3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02/format/mp4/mp4io/mp4io.go#L278-L293
go
train
// Version(4) // ESDesc( // MP4ESDescrTag // ESID(2) // ESFlags(1) // DecConfigDesc( // MP4DecConfigDescrTag // objectId streamType bufSize avgBitrate // DecSpecificDesc( // MP4DecSpecificDescrTag // decConfig // ) // ) // ?Desc(lenDescHdr+1) // )
func (self ElemStreamDesc) Marshal(b []byte) (n int)
// Version(4) // ESDesc( // MP4ESDescrTag // ESID(2) // ESFlags(1) // DecConfigDesc( // MP4DecConfigDescrTag // objectId streamType bufSize avgBitrate // DecSpecificDesc( // MP4DecSpecificDescrTag // decConfig // ) // ) // ?Desc(lenDescHdr+1) // ) func (self ElemStreamDesc) Marsh...
{ pio.PutU32BE(b[4:], uint32(ESDS)) n += 8 pio.PutU32BE(b[n:], 0) // Version n += 4 datalen := self.Len() n += self.fillESDescHdr(b[n:], datalen-n-self.lenESDescHdr()) n += self.fillDecConfigDescHdr(b[n:], datalen-n-self.lenDescHdr()-1) copy(b[n:], self.DecConfig) n += len(self.DecConfig) n += self.fillDescH...
nareix/joy4
3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02
av/pubsub/queue.go
https://github.com/nareix/joy4/blob/3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02/av/pubsub/queue.go#L72-L80
go
train
// After Close() called, all QueueCursor's ReadPacket will return io.EOF.
func (self *Queue) Close() (err error)
// After Close() called, all QueueCursor's ReadPacket will return io.EOF. func (self *Queue) Close() (err error)
{ self.lock.Lock() self.closed = true self.cond.Broadcast() self.lock.Unlock() return }
nareix/joy4
3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02
av/pubsub/queue.go
https://github.com/nareix/joy4/blob/3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02/av/pubsub/queue.go#L83-L106
go
train
// Put packet into buffer, old packets will be discared.
func (self *Queue) WritePacket(pkt av.Packet) (err error)
// Put packet into buffer, old packets will be discared. func (self *Queue) WritePacket(pkt av.Packet) (err error)
{ self.lock.Lock() self.buf.Push(pkt) if pkt.Idx == int8(self.videoidx) && pkt.IsKeyFrame { self.curgopcount++ } for self.curgopcount >= self.maxgopcount && self.buf.Count > 1 { pkt := self.buf.Pop() if pkt.Idx == int8(self.videoidx) && pkt.IsKeyFrame { self.curgopcount-- } if self.curgopcount < se...
nareix/joy4
3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02
av/pubsub/queue.go
https://github.com/nareix/joy4/blob/3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02/av/pubsub/queue.go#L131-L137
go
train
// Create cursor position at oldest buffered packet.
func (self *Queue) Oldest() *QueueCursor
// Create cursor position at oldest buffered packet. func (self *Queue) Oldest() *QueueCursor
{ cursor := self.newCursor() cursor.init = func(buf *pktque.Buf, videoidx int) pktque.BufPos { return buf.Head } return cursor }
nareix/joy4
3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02
av/pubsub/queue.go
https://github.com/nareix/joy4/blob/3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02/av/pubsub/queue.go#L140-L156
go
train
// Create cursor position at specific time in buffered packets.
func (self *Queue) DelayedTime(dur time.Duration) *QueueCursor
// Create cursor position at specific time in buffered packets. func (self *Queue) DelayedTime(dur time.Duration) *QueueCursor
{ cursor := self.newCursor() cursor.init = func(buf *pktque.Buf, videoidx int) pktque.BufPos { i := buf.Tail - 1 if buf.IsValidPos(i) { end := buf.Get(i) for buf.IsValidPos(i) { if end.Time-buf.Get(i).Time > dur { break } i-- } } return i } return cursor }
nareix/joy4
3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02
av/pubsub/queue.go
https://github.com/nareix/joy4/blob/3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02/av/pubsub/queue.go#L159-L174
go
train
// Create cursor position at specific delayed GOP count in buffered packets.
func (self *Queue) DelayedGopCount(n int) *QueueCursor
// Create cursor position at specific delayed GOP count in buffered packets. func (self *Queue) DelayedGopCount(n int) *QueueCursor
{ cursor := self.newCursor() cursor.init = func(buf *pktque.Buf, videoidx int) pktque.BufPos { i := buf.Tail - 1 if videoidx != -1 { for gop := 0; buf.IsValidPos(i) && gop < n; i-- { pkt := buf.Get(i) if pkt.Idx == int8(self.videoidx) && pkt.IsKeyFrame { gop++ } } } return i } return...
nareix/joy4
3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02
av/pubsub/queue.go
https://github.com/nareix/joy4/blob/3ddbc8f9d4316ab2bbec2bc9ee98127862e3af02/av/pubsub/queue.go#L191-L217
go
train
// ReadPacket will not consume packets in Queue, it's just a cursor.
func (self *QueueCursor) ReadPacket() (pkt av.Packet, err error)
// ReadPacket will not consume packets in Queue, it's just a cursor. func (self *QueueCursor) ReadPacket() (pkt av.Packet, err error)
{ self.que.cond.L.Lock() buf := self.que.buf if !self.gotpos { self.pos = self.init(buf, self.que.videoidx) self.gotpos = true } for { if self.pos.LT(buf.Head) { self.pos = buf.Head } else if self.pos.GT(buf.Tail) { self.pos = buf.Tail } if buf.IsValidPos(self.pos) { pkt = buf.Get(self.pos) ...
go-martini/martini
22fa46961aabd2665cf3f1343b146d20028f5071
martini.go
https://github.com/go-martini/martini/blob/22fa46961aabd2665cf3f1343b146d20028f5071/martini.go#L38-L43
go
train
// New creates a bare bones Martini instance. Use this method if you want to have full control over the middleware that is used.
func New() *Martini
// New creates a bare bones Martini instance. Use this method if you want to have full control over the middleware that is used. func New() *Martini
{ m := &Martini{Injector: inject.New(), action: func() {}, logger: log.New(os.Stdout, "[martini] ", 0)} m.Map(m.logger) m.Map(defaultReturnHandler()) return m }
go-martini/martini
22fa46961aabd2665cf3f1343b146d20028f5071
martini.go
https://github.com/go-martini/martini/blob/22fa46961aabd2665cf3f1343b146d20028f5071/martini.go#L55-L58
go
train
// Action sets the handler that will be called after all the middleware has been invoked. This is set to martini.Router in a martini.Classic().
func (m *Martini) Action(handler Handler)
// Action sets the handler that will be called after all the middleware has been invoked. This is set to martini.Router in a martini.Classic(). func (m *Martini) Action(handler Handler)
{ validateHandler(handler) m.action = handler }
go-martini/martini
22fa46961aabd2665cf3f1343b146d20028f5071
martini.go
https://github.com/go-martini/martini/blob/22fa46961aabd2665cf3f1343b146d20028f5071/martini.go#L61-L64
go
train
// Logger sets the logger
func (m *Martini) Logger(logger *log.Logger)
// Logger sets the logger func (m *Martini) Logger(logger *log.Logger)
{ m.logger = logger m.Map(m.logger) }
go-martini/martini
22fa46961aabd2665cf3f1343b146d20028f5071
martini.go
https://github.com/go-martini/martini/blob/22fa46961aabd2665cf3f1343b146d20028f5071/martini.go#L67-L71
go
train
// Use adds a middleware Handler to the stack. Will panic if the handler is not a callable func. Middleware Handlers are invoked in the order that they are added.
func (m *Martini) Use(handler Handler)
// Use adds a middleware Handler to the stack. Will panic if the handler is not a callable func. Middleware Handlers are invoked in the order that they are added. func (m *Martini) Use(handler Handler)
{ validateHandler(handler) m.handlers = append(m.handlers, handler) }
go-martini/martini
22fa46961aabd2665cf3f1343b146d20028f5071
martini.go
https://github.com/go-martini/martini/blob/22fa46961aabd2665cf3f1343b146d20028f5071/martini.go#L74-L76
go
train
// ServeHTTP is the HTTP Entry point for a Martini instance. Useful if you want to control your own HTTP server.
func (m *Martini) ServeHTTP(res http.ResponseWriter, req *http.Request)
// ServeHTTP is the HTTP Entry point for a Martini instance. Useful if you want to control your own HTTP server. func (m *Martini) ServeHTTP(res http.ResponseWriter, req *http.Request)
{ m.createContext(res, req).run() }
go-martini/martini
22fa46961aabd2665cf3f1343b146d20028f5071
martini.go
https://github.com/go-martini/martini/blob/22fa46961aabd2665cf3f1343b146d20028f5071/martini.go#L79-L87
go
train
// Run the http server on a given host and port.
func (m *Martini) RunOnAddr(addr string)
// Run the http server on a given host and port. func (m *Martini) RunOnAddr(addr string)
{ // TODO: Should probably be implemented using a new instance of http.Server in place of // calling http.ListenAndServer directly, so that it could be stored in the martini struct for later use. // This would also allow to improve testing when a custom host and port are passed. logger := m.Injector.Get(reflect.T...
go-martini/martini
22fa46961aabd2665cf3f1343b146d20028f5071
martini.go
https://github.com/go-martini/martini/blob/22fa46961aabd2665cf3f1343b146d20028f5071/martini.go#L90-L99
go
train
// Run the http server. Listening on os.GetEnv("PORT") or 3000 by default.
func (m *Martini) Run()
// Run the http server. Listening on os.GetEnv("PORT") or 3000 by default. func (m *Martini) Run()
{ port := os.Getenv("PORT") if len(port) == 0 { port = "3000" } host := os.Getenv("HOST") m.RunOnAddr(host + ":" + port) }
go-martini/martini
22fa46961aabd2665cf3f1343b146d20028f5071
martini.go
https://github.com/go-martini/martini/blob/22fa46961aabd2665cf3f1343b146d20028f5071/martini.go#L118-L127
go
train
// Classic creates a classic Martini with some basic default middleware - martini.Logger, martini.Recovery and martini.Static. // Classic also maps martini.Routes as a service.
func Classic() *ClassicMartini
// Classic creates a classic Martini with some basic default middleware - martini.Logger, martini.Recovery and martini.Static. // Classic also maps martini.Routes as a service. func Classic() *ClassicMartini
{ r := NewRouter() m := New() m.Use(Logger()) m.Use(Recovery()) m.Use(Static("public")) m.MapTo(r, (*Routes)(nil)) m.Action(r.Handle) return &ClassicMartini{m, r} }
go-martini/martini
22fa46961aabd2665cf3f1343b146d20028f5071
response_writer.go
https://github.com/go-martini/martini/blob/22fa46961aabd2665cf3f1343b146d20028f5071/response_writer.go#L32-L38
go
train
// NewResponseWriter creates a ResponseWriter that wraps an http.ResponseWriter
func NewResponseWriter(rw http.ResponseWriter) ResponseWriter
// NewResponseWriter creates a ResponseWriter that wraps an http.ResponseWriter func NewResponseWriter(rw http.ResponseWriter) ResponseWriter
{ newRw := responseWriter{rw, 0, 0, nil} if cn, ok := rw.(http.CloseNotifier); ok { return &closeNotifyResponseWriter{newRw, cn} } return &newRw }
go-martini/martini
22fa46961aabd2665cf3f1343b146d20028f5071
router.go
https://github.com/go-martini/martini/blob/22fa46961aabd2665cf3f1343b146d20028f5071/router.go#L68-L70
go
train
// NewRouter creates a new Router instance. // If you aren't using ClassicMartini, then you can add Routes as a // service with: // // m := martini.New() // r := martini.NewRouter() // m.MapTo(r, (*martini.Routes)(nil)) // // If you are using ClassicMartini, then this is done for you.
func NewRouter() Router
// NewRouter creates a new Router instance. // If you aren't using ClassicMartini, then you can add Routes as a // service with: // // m := martini.New() // r := martini.NewRouter() // m.MapTo(r, (*martini.Routes)(nil)) // // If you are using ClassicMartini, then this is done for you. func NewRouter() Router
{ return &router{notFounds: []Handler{http.NotFound}, groups: make([]group, 0)} }
go-martini/martini
22fa46961aabd2665cf3f1343b146d20028f5071
router.go
https://github.com/go-martini/martini/blob/22fa46961aabd2665cf3f1343b146d20028f5071/router.go#L291-L309
go
train
// URLWith returns the url pattern replacing the parameters for its values
func (r *route) URLWith(args []string) string
// URLWith returns the url pattern replacing the parameters for its values func (r *route) URLWith(args []string) string
{ if len(args) > 0 { argCount := len(args) i := 0 url := urlReg.ReplaceAllStringFunc(r.pattern, func(m string) string { var val interface{} if i < argCount { val = args[i] } else { val = m } i += 1 return fmt.Sprintf(`%v`, val) }) return url } return r.pattern }
go-martini/martini
22fa46961aabd2665cf3f1343b146d20028f5071
router.go
https://github.com/go-martini/martini/blob/22fa46961aabd2665cf3f1343b146d20028f5071/router.go#L338-L360
go
train
// URLFor returns the url for the given route name.
func (r *router) URLFor(name string, params ...interface{}) string
// URLFor returns the url for the given route name. func (r *router) URLFor(name string, params ...interface{}) string
{ route := r.findRoute(name) if route == nil { panic("route not found") } var args []string for _, param := range params { switch v := param.(type) { case int: args = append(args, strconv.FormatInt(int64(v), 10)) case string: args = append(args, v) default: if v != nil { panic("Arguments ...
go-martini/martini
22fa46961aabd2665cf3f1343b146d20028f5071
router.go
https://github.com/go-martini/martini/blob/22fa46961aabd2665cf3f1343b146d20028f5071/router.go#L383-L392
go
train
// MethodsFor returns all methods available for path
func (r *router) MethodsFor(path string) []string
// MethodsFor returns all methods available for path func (r *router) MethodsFor(path string) []string
{ methods := []string{} for _, route := range r.getRoutes() { matches := route.regex.FindStringSubmatch(path) if len(matches) > 0 && matches[0] == path && !hasMethod(methods, route.method) { methods = append(methods, route.method) } } return methods }
go-martini/martini
22fa46961aabd2665cf3f1343b146d20028f5071
logger.go
https://github.com/go-martini/martini/blob/22fa46961aabd2665cf3f1343b146d20028f5071/logger.go#L10-L29
go
train
// Logger returns a middleware handler that logs the request as it goes in and the response as it goes out.
func Logger() Handler
// Logger returns a middleware handler that logs the request as it goes in and the response as it goes out. func Logger() Handler
{ return func(res http.ResponseWriter, req *http.Request, c Context, log *log.Logger) { start := time.Now() addr := req.Header.Get("X-Real-IP") if addr == "" { addr = req.Header.Get("X-Forwarded-For") if addr == "" { addr = req.RemoteAddr } } log.Printf("Started %s %s for %s", req.Method, req...
buger/jsonparser
bf1c66bbce23153d89b23f8960071a680dbef54b
escape.go
https://github.com/buger/jsonparser/blob/bf1c66bbce23153d89b23f8960071a680dbef54b/escape.go#L39-L53
go
train
// decodeSingleUnicodeEscape decodes a single \uXXXX escape sequence. The prefix \u is assumed to be present and // is not checked. // In JSON, these escapes can either come alone or as part of "UTF16 surrogate pairs" that must be handled together. // This function only handles one; decodeUnicodeEscape handles this mor...
func decodeSingleUnicodeEscape(in []byte) (rune, bool)
// decodeSingleUnicodeEscape decodes a single \uXXXX escape sequence. The prefix \u is assumed to be present and // is not checked. // In JSON, these escapes can either come alone or as part of "UTF16 surrogate pairs" that must be handled together. // This function only handles one; decodeUnicodeEscape handles this mor...
{ // We need at least 6 characters total if len(in) < 6 { return utf8.RuneError, false } // Convert hex to decimal h1, h2, h3, h4 := h2I(in[2]), h2I(in[3]), h2I(in[4]), h2I(in[5]) if h1 == badHex || h2 == badHex || h3 == badHex || h4 == badHex { return utf8.RuneError, false } // Compose the hex digits r...
buger/jsonparser
bf1c66bbce23153d89b23f8960071a680dbef54b
escape.go
https://github.com/buger/jsonparser/blob/bf1c66bbce23153d89b23f8960071a680dbef54b/escape.go#L96-L121
go
train
// unescapeToUTF8 unescapes the single escape sequence starting at 'in' into 'out' and returns // how many characters were consumed from 'in' and emitted into 'out'. // If a valid escape sequence does not appear as a prefix of 'in', (-1, -1) to signal the error.
func unescapeToUTF8(in, out []byte) (inLen int, outLen int)
// unescapeToUTF8 unescapes the single escape sequence starting at 'in' into 'out' and returns // how many characters were consumed from 'in' and emitted into 'out'. // If a valid escape sequence does not appear as a prefix of 'in', (-1, -1) to signal the error. func unescapeToUTF8(in, out []byte) (inLen int, outLen in...
{ if len(in) < 2 || in[0] != '\\' { // Invalid escape due to insufficient characters for any escape or no initial backslash return -1, -1 } // https://tools.ietf.org/html/rfc7159#section-7 switch e := in[1]; e { case '"', '\\', '/', 'b', 'f', 'n', 'r', 't': // Valid basic 2-character escapes (use lookup ta...
buger/jsonparser
bf1c66bbce23153d89b23f8960071a680dbef54b
escape.go
https://github.com/buger/jsonparser/blob/bf1c66bbce23153d89b23f8960071a680dbef54b/escape.go#L130-L173
go
train
// unescape unescapes the string contained in 'in' and returns it as a slice. // If 'in' contains no escaped characters: // Returns 'in'. // Else, if 'out' is of sufficient capacity (guaranteed if cap(out) >= len(in)): // 'out' is used to build the unescaped string and is returned with no extra allocation // Else: ...
func Unescape(in, out []byte) ([]byte, error)
// unescape unescapes the string contained in 'in' and returns it as a slice. // If 'in' contains no escaped characters: // Returns 'in'. // Else, if 'out' is of sufficient capacity (guaranteed if cap(out) >= len(in)): // 'out' is used to build the unescaped string and is returned with no extra allocation // Else: ...
{ firstBackslash := bytes.IndexByte(in, '\\') if firstBackslash == -1 { return in, nil } // Get a buffer of sufficient size (allocate if needed) if cap(out) < len(in) { out = make([]byte, len(in)) } else { out = out[0:len(in)] } // Copy the first sequence of unescaped bytes to the output and obtain a b...
buger/jsonparser
bf1c66bbce23153d89b23f8960071a680dbef54b
bytes.go
https://github.com/buger/jsonparser/blob/bf1c66bbce23153d89b23f8960071a680dbef54b/bytes.go#L11-L47
go
train
// About 2x faster then strconv.ParseInt because it only supports base 10, which is enough for JSON
func parseInt(bytes []byte) (v int64, ok bool, overflow bool)
// About 2x faster then strconv.ParseInt because it only supports base 10, which is enough for JSON func parseInt(bytes []byte) (v int64, ok bool, overflow bool)
{ if len(bytes) == 0 { return 0, false, false } var neg bool = false if bytes[0] == '-' { neg = true bytes = bytes[1:] } var b int64 = 0 for _, c := range bytes { if c >= '0' && c <= '9' { b = (10 * v) + int64(c-'0') } else { return 0, false, false } if overflow = (b < v); overflow { br...
buger/jsonparser
bf1c66bbce23153d89b23f8960071a680dbef54b
parser.go
https://github.com/buger/jsonparser/blob/bf1c66bbce23153d89b23f8960071a680dbef54b/parser.go#L137-L148
go
train
// Find position of last character which is not whitespace
func lastToken(data []byte) int
// Find position of last character which is not whitespace func lastToken(data []byte) int
{ for i := len(data) - 1; i >= 0; i-- { switch data[i] { case ' ', '\n', '\r', '\t': continue default: return i } } return -1 }
buger/jsonparser
bf1c66bbce23153d89b23f8960071a680dbef54b
parser.go
https://github.com/buger/jsonparser/blob/bf1c66bbce23153d89b23f8960071a680dbef54b/parser.go#L152-L178
go
train
// Tries to find the end of string // Support if string contains escaped quote symbols.
func stringEnd(data []byte) (int, bool)
// Tries to find the end of string // Support if string contains escaped quote symbols. func stringEnd(data []byte) (int, bool)
{ escaped := false for i, c := range data { if c == '"' { if !escaped { return i + 1, false } else { j := i - 1 for { if j < 0 || data[j] != '\\' { return i + 1, true // even number of backslashes } j-- if j < 0 || data[j] != '\\' { break // odd number of backslash...
buger/jsonparser
bf1c66bbce23153d89b23f8960071a680dbef54b
parser.go
https://github.com/buger/jsonparser/blob/bf1c66bbce23153d89b23f8960071a680dbef54b/parser.go#L182-L209
go
train
// Find end of the data structure, array or object. // For array openSym and closeSym will be '[' and ']', for object '{' and '}'
func blockEnd(data []byte, openSym byte, closeSym byte) int
// Find end of the data structure, array or object. // For array openSym and closeSym will be '[' and ']', for object '{' and '}' func blockEnd(data []byte, openSym byte, closeSym byte) int
{ level := 0 i := 0 ln := len(data) for i < ln { switch data[i] { case '"': // If inside string, skip it se, _ := stringEnd(data[i+1:]) if se == -1 { return -1 } i += se case openSym: // If open symbol, increase level level++ case closeSym: // If close symbol, increase level level-- ...
buger/jsonparser
bf1c66bbce23153d89b23f8960071a680dbef54b
parser.go
https://github.com/buger/jsonparser/blob/bf1c66bbce23153d89b23f8960071a680dbef54b/parser.go#L638-L709
go
train
/* Del - Receives existing data structure, path to delete. Returns: `data` - return modified data */
func Delete(data []byte, keys ...string) []byte
/* Del - Receives existing data structure, path to delete. Returns: `data` - return modified data */ func Delete(data []byte, keys ...string) []byte
{ lk := len(keys) if lk == 0 { return data[:0] } array := false if len(keys[lk-1]) > 0 && string(keys[lk-1][0]) == "[" { array = true } var startOffset, keyOffset int endOffset := len(data) var err error if !array { if len(keys) > 1 { _, _, startOffset, endOffset, err = internalGet(data, keys[:lk-...
buger/jsonparser
bf1c66bbce23153d89b23f8960071a680dbef54b
parser.go
https://github.com/buger/jsonparser/blob/bf1c66bbce23153d89b23f8960071a680dbef54b/parser.go#L720-L789
go
train
/* Set - Receives existing data structure, path to set, and data to set at that key. Returns: `value` - modified byte array `err` - On any parsing error */
func Set(data []byte, setValue []byte, keys ...string) (value []byte, err error)
/* Set - Receives existing data structure, path to set, and data to set at that key. Returns: `value` - modified byte array `err` - On any parsing error */ func Set(data []byte, setValue []byte, keys ...string) (value []byte, err error)
{ // ensure keys are set if len(keys) == 0 { return nil, KeyPathNotFoundError } _, _, startOffset, endOffset, err := internalGet(data, keys...) if err != nil { if err != KeyPathNotFoundError { // problem parsing the data return nil, err } // full path doesnt exist // does any subpath exist? var...
buger/jsonparser
bf1c66bbce23153d89b23f8960071a680dbef54b
parser.go
https://github.com/buger/jsonparser/blob/bf1c66bbce23153d89b23f8960071a680dbef54b/parser.go#L869-L872
go
train
/* Get - Receives data structure, and key path to extract value from. Returns: `value` - Pointer to original data structure containing key value, or just empty slice if nothing found or error `dataType` - Can be: `NotExist`, `String`, `Number`, `Object`, `Array`, `Boolean` or `Null` `offset` - Offset from provided ...
func Get(data []byte, keys ...string) (value []byte, dataType ValueType, offset int, err error)
/* Get - Receives data structure, and key path to extract value from. Returns: `value` - Pointer to original data structure containing key value, or just empty slice if nothing found or error `dataType` - Can be: `NotExist`, `String`, `Number`, `Object`, `Array`, `Boolean` or `Null` `offset` - Offset from provided ...
{ a, b, _, d, e := internalGet(data, keys...) return a, b, d, e }
buger/jsonparser
bf1c66bbce23153d89b23f8960071a680dbef54b
parser.go
https://github.com/buger/jsonparser/blob/bf1c66bbce23153d89b23f8960071a680dbef54b/parser.go#L902-L979
go
train
// ArrayEach is used when iterating arrays, accepts a callback function with the same return arguments as `Get`.
func ArrayEach(data []byte, cb func(value []byte, dataType ValueType, offset int, err error), keys ...string) (offset int, err error)
// ArrayEach is used when iterating arrays, accepts a callback function with the same return arguments as `Get`. func ArrayEach(data []byte, cb func(value []byte, dataType ValueType, offset int, err error), keys ...string) (offset int, err error)
{ if len(data) == 0 { return -1, MalformedObjectError } offset = 1 if len(keys) > 0 { if offset = searchKeys(data, keys...); offset == -1 { return offset, KeyPathNotFoundError } // Go to closest value nO := nextToken(data[offset:]) if nO == -1 { return offset, MalformedJsonError } offset ...
buger/jsonparser
bf1c66bbce23153d89b23f8960071a680dbef54b
parser.go
https://github.com/buger/jsonparser/blob/bf1c66bbce23153d89b23f8960071a680dbef54b/parser.go#L982-L1086
go
train
// ObjectEach iterates over the key-value pairs of a JSON object, invoking a given callback for each such entry
func ObjectEach(data []byte, callback func(key []byte, value []byte, dataType ValueType, offset int) error, keys ...string) (err error)
// ObjectEach iterates over the key-value pairs of a JSON object, invoking a given callback for each such entry func ObjectEach(data []byte, callback func(key []byte, value []byte, dataType ValueType, offset int) error, keys ...string) (err error)
{ var stackbuf [unescapeStackBufSize]byte // stack-allocated array for allocation-free unescaping of small strings offset := 0 // Descend to the desired key, if requested if len(keys) > 0 { if off := searchKeys(data, keys...); off == -1 { return KeyPathNotFoundError } else { offset = off } } // Val...
buger/jsonparser
bf1c66bbce23153d89b23f8960071a680dbef54b
parser.go
https://github.com/buger/jsonparser/blob/bf1c66bbce23153d89b23f8960071a680dbef54b/parser.go#L1089-L1097
go
train
// GetUnsafeString returns the value retrieved by `Get`, use creates string without memory allocation by mapping string to slice memory. It does not handle escape symbols.
func GetUnsafeString(data []byte, keys ...string) (val string, err error)
// GetUnsafeString returns the value retrieved by `Get`, use creates string without memory allocation by mapping string to slice memory. It does not handle escape symbols. func GetUnsafeString(data []byte, keys ...string) (val string, err error)
{ v, _, _, e := Get(data, keys...) if e != nil { return "", e } return bytesToString(&v), nil }
buger/jsonparser
bf1c66bbce23153d89b23f8960071a680dbef54b
parser.go
https://github.com/buger/jsonparser/blob/bf1c66bbce23153d89b23f8960071a680dbef54b/parser.go#L1101-L1118
go
train
// GetString returns the value retrieved by `Get`, cast to a string if possible, trying to properly handle escape and utf8 symbols // If key data type do not match, it will return an error.
func GetString(data []byte, keys ...string) (val string, err error)
// GetString returns the value retrieved by `Get`, cast to a string if possible, trying to properly handle escape and utf8 symbols // If key data type do not match, it will return an error. func GetString(data []byte, keys ...string) (val string, err error)
{ v, t, _, e := Get(data, keys...) if e != nil { return "", e } if t != String { return "", fmt.Errorf("Value is not a string: %s", string(v)) } // If no escapes return raw conten if bytes.IndexByte(v, '\\') == -1 { return string(v), nil } return ParseString(v) }
buger/jsonparser
bf1c66bbce23153d89b23f8960071a680dbef54b
parser.go
https://github.com/buger/jsonparser/blob/bf1c66bbce23153d89b23f8960071a680dbef54b/parser.go#L1123-L1135
go
train
// GetFloat returns the value retrieved by `Get`, cast to a float64 if possible. // The offset is the same as in `Get`. // If key data type do not match, it will return an error.
func GetFloat(data []byte, keys ...string) (val float64, err error)
// GetFloat returns the value retrieved by `Get`, cast to a float64 if possible. // The offset is the same as in `Get`. // If key data type do not match, it will return an error. func GetFloat(data []byte, keys ...string) (val float64, err error)
{ v, t, _, e := Get(data, keys...) if e != nil { return 0, e } if t != Number { return 0, fmt.Errorf("Value is not a number: %s", string(v)) } return ParseFloat(v) }
buger/jsonparser
bf1c66bbce23153d89b23f8960071a680dbef54b
parser.go
https://github.com/buger/jsonparser/blob/bf1c66bbce23153d89b23f8960071a680dbef54b/parser.go#L1139-L1151
go
train
// GetInt returns the value retrieved by `Get`, cast to a int64 if possible. // If key data type do not match, it will return an error.
func GetInt(data []byte, keys ...string) (val int64, err error)
// GetInt returns the value retrieved by `Get`, cast to a int64 if possible. // If key data type do not match, it will return an error. func GetInt(data []byte, keys ...string) (val int64, err error)
{ v, t, _, e := Get(data, keys...) if e != nil { return 0, e } if t != Number { return 0, fmt.Errorf("Value is not a number: %s", string(v)) } return ParseInt(v) }
buger/jsonparser
bf1c66bbce23153d89b23f8960071a680dbef54b
parser.go
https://github.com/buger/jsonparser/blob/bf1c66bbce23153d89b23f8960071a680dbef54b/parser.go#L1156-L1168
go
train
// GetBoolean returns the value retrieved by `Get`, cast to a bool if possible. // The offset is the same as in `Get`. // If key data type do not match, it will return error.
func GetBoolean(data []byte, keys ...string) (val bool, err error)
// GetBoolean returns the value retrieved by `Get`, cast to a bool if possible. // The offset is the same as in `Get`. // If key data type do not match, it will return error. func GetBoolean(data []byte, keys ...string) (val bool, err error)
{ v, t, _, e := Get(data, keys...) if e != nil { return false, e } if t != Boolean { return false, fmt.Errorf("Value is not a boolean: %s", string(v)) } return ParseBoolean(v) }
buger/jsonparser
bf1c66bbce23153d89b23f8960071a680dbef54b
parser.go
https://github.com/buger/jsonparser/blob/bf1c66bbce23153d89b23f8960071a680dbef54b/parser.go#L1171-L1180
go
train
// ParseBoolean parses a Boolean ValueType into a Go bool (not particularly useful, but here for completeness)
func ParseBoolean(b []byte) (bool, error)
// ParseBoolean parses a Boolean ValueType into a Go bool (not particularly useful, but here for completeness) func ParseBoolean(b []byte) (bool, error)
{ switch { case bytes.Equal(b, trueLiteral): return true, nil case bytes.Equal(b, falseLiteral): return false, nil default: return false, MalformedValueError } }