repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
sequence
docstring
stringlengths
6
2.61k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
85
252
partition
stringclasses
1 value
libp2p/go-libp2p
options.go
Routing
func Routing(rt config.RoutingC) Option { return func(cfg *Config) error { if cfg.Routing != nil { return fmt.Errorf("cannot specify multiple routing options") } cfg.Routing = rt return nil } }
go
func Routing(rt config.RoutingC) Option { return func(cfg *Config) error { if cfg.Routing != nil { return fmt.Errorf("cannot specify multiple routing options") } cfg.Routing = rt return nil } }
[ "func", "Routing", "(", "rt", "config", ".", "RoutingC", ")", "Option", "{", "return", "func", "(", "cfg", "*", "Config", ")", "error", "{", "if", "cfg", ".", "Routing", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "cfg", ".", "Routing", "=", "rt", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// Routing will configure libp2p to use routing.
[ "Routing", "will", "configure", "libp2p", "to", "use", "routing", "." ]
bd0f8953cf5cb16e1f9d0a420ad20ebc08ffd344
https://github.com/libp2p/go-libp2p/blob/bd0f8953cf5cb16e1f9d0a420ad20ebc08ffd344/options.go#L288-L296
train
libp2p/go-libp2p
p2p/host/basic/natmgr.go
sync
func (nmgr *natManager) sync() { nat := nmgr.NAT() if nat == nil { // Nothing to do. return } nmgr.proc.Go(func(_ goprocess.Process) { nmgr.syncMu.Lock() defer nmgr.syncMu.Unlock() ports := map[string]map[int]bool{ "tcp": map[int]bool{}, "udp": map[int]bool{}, } for _, maddr := range nmgr.net.ListenAddresses() { // Strip the IP maIP, rest := ma.SplitFirst(maddr) if maIP == nil || rest == nil { continue } switch maIP.Protocol().Code { case ma.P_IP6, ma.P_IP4: default: continue } // Only bother if we're listening on a // unicast/unspecified IP. ip := net.IP(maIP.RawValue()) if !(ip.IsGlobalUnicast() || ip.IsUnspecified()) { continue } // Extract the port/protocol proto, _ := ma.SplitFirst(rest) if proto == nil { continue } var protocol string switch proto.Protocol().Code { case ma.P_TCP: protocol = "tcp" case ma.P_UDP: protocol = "udp" default: continue } port, err := strconv.ParseUint(proto.Value(), 10, 16) if err != nil { // bug in multiaddr panic(err) } ports[protocol][int(port)] = false } var wg sync.WaitGroup defer wg.Wait() // Close old mappings for _, m := range nat.Mappings() { mappedPort := m.InternalPort() if _, ok := ports[m.Protocol()][mappedPort]; !ok { // No longer need this mapping. wg.Add(1) go func(m inat.Mapping) { defer wg.Done() m.Close() }(m) } else { // already mapped ports[m.Protocol()][mappedPort] = true } } // Create new mappings. for proto, pports := range ports { for port, mapped := range pports { if mapped { continue } wg.Add(1) go func(proto string, port int) { defer wg.Done() _, err := nat.NewMapping(proto, port) if err != nil { log.Errorf("failed to port-map %s port %d: %s", proto, port, err) } }(proto, port) } } }) }
go
func (nmgr *natManager) sync() { nat := nmgr.NAT() if nat == nil { // Nothing to do. return } nmgr.proc.Go(func(_ goprocess.Process) { nmgr.syncMu.Lock() defer nmgr.syncMu.Unlock() ports := map[string]map[int]bool{ "tcp": map[int]bool{}, "udp": map[int]bool{}, } for _, maddr := range nmgr.net.ListenAddresses() { // Strip the IP maIP, rest := ma.SplitFirst(maddr) if maIP == nil || rest == nil { continue } switch maIP.Protocol().Code { case ma.P_IP6, ma.P_IP4: default: continue } // Only bother if we're listening on a // unicast/unspecified IP. ip := net.IP(maIP.RawValue()) if !(ip.IsGlobalUnicast() || ip.IsUnspecified()) { continue } // Extract the port/protocol proto, _ := ma.SplitFirst(rest) if proto == nil { continue } var protocol string switch proto.Protocol().Code { case ma.P_TCP: protocol = "tcp" case ma.P_UDP: protocol = "udp" default: continue } port, err := strconv.ParseUint(proto.Value(), 10, 16) if err != nil { // bug in multiaddr panic(err) } ports[protocol][int(port)] = false } var wg sync.WaitGroup defer wg.Wait() // Close old mappings for _, m := range nat.Mappings() { mappedPort := m.InternalPort() if _, ok := ports[m.Protocol()][mappedPort]; !ok { // No longer need this mapping. wg.Add(1) go func(m inat.Mapping) { defer wg.Done() m.Close() }(m) } else { // already mapped ports[m.Protocol()][mappedPort] = true } } // Create new mappings. for proto, pports := range ports { for port, mapped := range pports { if mapped { continue } wg.Add(1) go func(proto string, port int) { defer wg.Done() _, err := nat.NewMapping(proto, port) if err != nil { log.Errorf("failed to port-map %s port %d: %s", proto, port, err) } }(proto, port) } } }) }
[ "func", "(", "nmgr", "*", "natManager", ")", "sync", "(", ")", "{", "nat", ":=", "nmgr", ".", "NAT", "(", ")", "\n", "if", "nat", "==", "nil", "{", "// Nothing to do.", "return", "\n", "}", "\n\n", "nmgr", ".", "proc", ".", "Go", "(", "func", "(", "_", "goprocess", ".", "Process", ")", "{", "nmgr", ".", "syncMu", ".", "Lock", "(", ")", "\n", "defer", "nmgr", ".", "syncMu", ".", "Unlock", "(", ")", "\n\n", "ports", ":=", "map", "[", "string", "]", "map", "[", "int", "]", "bool", "{", "\"", "\"", ":", "map", "[", "int", "]", "bool", "{", "}", ",", "\"", "\"", ":", "map", "[", "int", "]", "bool", "{", "}", ",", "}", "\n", "for", "_", ",", "maddr", ":=", "range", "nmgr", ".", "net", ".", "ListenAddresses", "(", ")", "{", "// Strip the IP", "maIP", ",", "rest", ":=", "ma", ".", "SplitFirst", "(", "maddr", ")", "\n", "if", "maIP", "==", "nil", "||", "rest", "==", "nil", "{", "continue", "\n", "}", "\n\n", "switch", "maIP", ".", "Protocol", "(", ")", ".", "Code", "{", "case", "ma", ".", "P_IP6", ",", "ma", ".", "P_IP4", ":", "default", ":", "continue", "\n", "}", "\n\n", "// Only bother if we're listening on a", "// unicast/unspecified IP.", "ip", ":=", "net", ".", "IP", "(", "maIP", ".", "RawValue", "(", ")", ")", "\n", "if", "!", "(", "ip", ".", "IsGlobalUnicast", "(", ")", "||", "ip", ".", "IsUnspecified", "(", ")", ")", "{", "continue", "\n", "}", "\n\n", "// Extract the port/protocol", "proto", ",", "_", ":=", "ma", ".", "SplitFirst", "(", "rest", ")", "\n", "if", "proto", "==", "nil", "{", "continue", "\n", "}", "\n\n", "var", "protocol", "string", "\n", "switch", "proto", ".", "Protocol", "(", ")", ".", "Code", "{", "case", "ma", ".", "P_TCP", ":", "protocol", "=", "\"", "\"", "\n", "case", "ma", ".", "P_UDP", ":", "protocol", "=", "\"", "\"", "\n", "default", ":", "continue", "\n", "}", "\n\n", "port", ",", "err", ":=", "strconv", ".", "ParseUint", "(", "proto", ".", "Value", "(", ")", ",", "10", ",", "16", ")", "\n", "if", "err", "!=", "nil", "{", "// bug in multiaddr", "panic", "(", "err", ")", "\n", "}", "\n", "ports", "[", "protocol", "]", "[", "int", "(", "port", ")", "]", "=", "false", "\n", "}", "\n\n", "var", "wg", "sync", ".", "WaitGroup", "\n", "defer", "wg", ".", "Wait", "(", ")", "\n\n", "// Close old mappings", "for", "_", ",", "m", ":=", "range", "nat", ".", "Mappings", "(", ")", "{", "mappedPort", ":=", "m", ".", "InternalPort", "(", ")", "\n", "if", "_", ",", "ok", ":=", "ports", "[", "m", ".", "Protocol", "(", ")", "]", "[", "mappedPort", "]", ";", "!", "ok", "{", "// No longer need this mapping.", "wg", ".", "Add", "(", "1", ")", "\n", "go", "func", "(", "m", "inat", ".", "Mapping", ")", "{", "defer", "wg", ".", "Done", "(", ")", "\n", "m", ".", "Close", "(", ")", "\n", "}", "(", "m", ")", "\n", "}", "else", "{", "// already mapped", "ports", "[", "m", ".", "Protocol", "(", ")", "]", "[", "mappedPort", "]", "=", "true", "\n", "}", "\n", "}", "\n\n", "// Create new mappings.", "for", "proto", ",", "pports", ":=", "range", "ports", "{", "for", "port", ",", "mapped", ":=", "range", "pports", "{", "if", "mapped", "{", "continue", "\n", "}", "\n", "wg", ".", "Add", "(", "1", ")", "\n", "go", "func", "(", "proto", "string", ",", "port", "int", ")", "{", "defer", "wg", ".", "Done", "(", ")", "\n", "_", ",", "err", ":=", "nat", ".", "NewMapping", "(", "proto", ",", "port", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "Errorf", "(", "\"", "\"", ",", "proto", ",", "port", ",", "err", ")", "\n", "}", "\n", "}", "(", "proto", ",", "port", ")", "\n", "}", "\n", "}", "\n", "}", ")", "\n", "}" ]
// syncs the current NAT mappings, removing any outdated mappings and adding any // new mappings.
[ "syncs", "the", "current", "NAT", "mappings", "removing", "any", "outdated", "mappings", "and", "adding", "any", "new", "mappings", "." ]
bd0f8953cf5cb16e1f9d0a420ad20ebc08ffd344
https://github.com/libp2p/go-libp2p/blob/bd0f8953cf5cb16e1f9d0a420ad20ebc08ffd344/p2p/host/basic/natmgr.go#L120-L215
train
libp2p/go-libp2p
p2p/host/relay/addrsplosion.go
cleanupAddressSet
func cleanupAddressSet(addrs []ma.Multiaddr) []ma.Multiaddr { var public, private []ma.Multiaddr for _, a := range addrs { if isRelayAddr(a) { continue } if manet.IsPublicAddr(a) || isDNSAddr(a) { public = append(public, a) continue } // discard unroutable addrs if manet.IsPrivateAddr(a) { private = append(private, a) } } if !hasAddrsplosion(public) { return public } return sanitizeAddrsplodedSet(public, private) }
go
func cleanupAddressSet(addrs []ma.Multiaddr) []ma.Multiaddr { var public, private []ma.Multiaddr for _, a := range addrs { if isRelayAddr(a) { continue } if manet.IsPublicAddr(a) || isDNSAddr(a) { public = append(public, a) continue } // discard unroutable addrs if manet.IsPrivateAddr(a) { private = append(private, a) } } if !hasAddrsplosion(public) { return public } return sanitizeAddrsplodedSet(public, private) }
[ "func", "cleanupAddressSet", "(", "addrs", "[", "]", "ma", ".", "Multiaddr", ")", "[", "]", "ma", ".", "Multiaddr", "{", "var", "public", ",", "private", "[", "]", "ma", ".", "Multiaddr", "\n\n", "for", "_", ",", "a", ":=", "range", "addrs", "{", "if", "isRelayAddr", "(", "a", ")", "{", "continue", "\n", "}", "\n\n", "if", "manet", ".", "IsPublicAddr", "(", "a", ")", "||", "isDNSAddr", "(", "a", ")", "{", "public", "=", "append", "(", "public", ",", "a", ")", "\n", "continue", "\n", "}", "\n\n", "// discard unroutable addrs", "if", "manet", ".", "IsPrivateAddr", "(", "a", ")", "{", "private", "=", "append", "(", "private", ",", "a", ")", "\n", "}", "\n", "}", "\n\n", "if", "!", "hasAddrsplosion", "(", "public", ")", "{", "return", "public", "\n", "}", "\n\n", "return", "sanitizeAddrsplodedSet", "(", "public", ",", "private", ")", "\n", "}" ]
// This function cleans up a relay's address set to remove private addresses and curtail // addrsplosion.
[ "This", "function", "cleans", "up", "a", "relay", "s", "address", "set", "to", "remove", "private", "addresses", "and", "curtail", "addrsplosion", "." ]
bd0f8953cf5cb16e1f9d0a420ad20ebc08ffd344
https://github.com/libp2p/go-libp2p/blob/bd0f8953cf5cb16e1f9d0a420ad20ebc08ffd344/p2p/host/relay/addrsplosion.go#L14-L38
train
libp2p/go-libp2p
p2p/host/relay/addrsplosion.go
hasAddrsplosion
func hasAddrsplosion(addrs []ma.Multiaddr) bool { aset := make(map[string]int) for _, a := range addrs { key, port := addrKeyAndPort(a) xport, ok := aset[key] if ok && port != xport { return true } aset[key] = port } return false }
go
func hasAddrsplosion(addrs []ma.Multiaddr) bool { aset := make(map[string]int) for _, a := range addrs { key, port := addrKeyAndPort(a) xport, ok := aset[key] if ok && port != xport { return true } aset[key] = port } return false }
[ "func", "hasAddrsplosion", "(", "addrs", "[", "]", "ma", ".", "Multiaddr", ")", "bool", "{", "aset", ":=", "make", "(", "map", "[", "string", "]", "int", ")", "\n\n", "for", "_", ",", "a", ":=", "range", "addrs", "{", "key", ",", "port", ":=", "addrKeyAndPort", "(", "a", ")", "\n", "xport", ",", "ok", ":=", "aset", "[", "key", "]", "\n", "if", "ok", "&&", "port", "!=", "xport", "{", "return", "true", "\n", "}", "\n", "aset", "[", "key", "]", "=", "port", "\n", "}", "\n\n", "return", "false", "\n", "}" ]
// we have addrsplosion if for some protocol we advertise multiple ports on // the same base address.
[ "we", "have", "addrsplosion", "if", "for", "some", "protocol", "we", "advertise", "multiple", "ports", "on", "the", "same", "base", "address", "." ]
bd0f8953cf5cb16e1f9d0a420ad20ebc08ffd344
https://github.com/libp2p/go-libp2p/blob/bd0f8953cf5cb16e1f9d0a420ad20ebc08ffd344/p2p/host/relay/addrsplosion.go#L68-L81
train
libp2p/go-libp2p
p2p/net/mock/mock_stream.go
Write
func (s *stream) Write(p []byte) (n int, err error) { l := s.conn.link delay := l.GetLatency() + l.RateLimit(len(p)) t := time.Now().Add(delay) // Copy it. cpy := make([]byte, len(p)) copy(cpy, p) select { case <-s.closed: // bail out if we're closing. return 0, s.writeErr case s.toDeliver <- &transportObject{msg: cpy, arrivalTime: t}: } return len(p), nil }
go
func (s *stream) Write(p []byte) (n int, err error) { l := s.conn.link delay := l.GetLatency() + l.RateLimit(len(p)) t := time.Now().Add(delay) // Copy it. cpy := make([]byte, len(p)) copy(cpy, p) select { case <-s.closed: // bail out if we're closing. return 0, s.writeErr case s.toDeliver <- &transportObject{msg: cpy, arrivalTime: t}: } return len(p), nil }
[ "func", "(", "s", "*", "stream", ")", "Write", "(", "p", "[", "]", "byte", ")", "(", "n", "int", ",", "err", "error", ")", "{", "l", ":=", "s", ".", "conn", ".", "link", "\n", "delay", ":=", "l", ".", "GetLatency", "(", ")", "+", "l", ".", "RateLimit", "(", "len", "(", "p", ")", ")", "\n", "t", ":=", "time", ".", "Now", "(", ")", ".", "Add", "(", "delay", ")", "\n\n", "// Copy it.", "cpy", ":=", "make", "(", "[", "]", "byte", ",", "len", "(", "p", ")", ")", "\n", "copy", "(", "cpy", ",", "p", ")", "\n\n", "select", "{", "case", "<-", "s", ".", "closed", ":", "// bail out if we're closing.", "return", "0", ",", "s", ".", "writeErr", "\n", "case", "s", ".", "toDeliver", "<-", "&", "transportObject", "{", "msg", ":", "cpy", ",", "arrivalTime", ":", "t", "}", ":", "}", "\n", "return", "len", "(", "p", ")", ",", "nil", "\n", "}" ]
// How to handle errors with writes?
[ "How", "to", "handle", "errors", "with", "writes?" ]
bd0f8953cf5cb16e1f9d0a420ad20ebc08ffd344
https://github.com/libp2p/go-libp2p/blob/bd0f8953cf5cb16e1f9d0a420ad20ebc08ffd344/p2p/net/mock/mock_stream.go#L56-L71
train
libp2p/go-libp2p
p2p/net/mock/mock_stream.go
transport
func (s *stream) transport() { defer s.teardown() bufsize := 256 buf := new(bytes.Buffer) timer := time.NewTimer(0) if !timer.Stop() { select { case <-timer.C: default: } } // cleanup defer timer.Stop() // writeBuf writes the contents of buf through to the s.Writer. // done only when arrival time makes sense. drainBuf := func() error { if buf.Len() > 0 { _, err := s.write.Write(buf.Bytes()) if err != nil { return err } buf.Reset() } return nil } // deliverOrWait is a helper func that processes // an incoming packet. it waits until the arrival time, // and then writes things out. deliverOrWait := func(o *transportObject) error { buffered := len(o.msg) + buf.Len() // Yes, we can end up extending a timer multiple times if we // keep on making small writes but that shouldn't be too much of an // issue. Fixing that would be painful. if !timer.Stop() { // FIXME: So, we *shouldn't* need to do this but we hang // here if we don't... Go bug? select { case <-timer.C: default: } } delay := o.arrivalTime.Sub(time.Now()) if delay >= 0 { timer.Reset(delay) } else { timer.Reset(0) } if buffered >= bufsize { select { case <-timer.C: case <-s.reset: select { case s.reset <- struct{}{}: default: } return ErrReset } if err := drainBuf(); err != nil { return err } // write this message. _, err := s.write.Write(o.msg) if err != nil { return err } } else { buf.Write(o.msg) } return nil } for { // Reset takes precedent. select { case <-s.reset: s.writeErr = ErrReset return default: } select { case <-s.reset: s.writeErr = ErrReset return case <-s.close: if err := drainBuf(); err != nil { s.resetWith(err) return } s.writeErr = s.write.Close() if s.writeErr == nil { s.writeErr = ErrClosed } return case o := <-s.toDeliver: if err := deliverOrWait(o); err != nil { s.resetWith(err) return } case <-timer.C: // ok, due to write it out. if err := drainBuf(); err != nil { s.resetWith(err) return } } } }
go
func (s *stream) transport() { defer s.teardown() bufsize := 256 buf := new(bytes.Buffer) timer := time.NewTimer(0) if !timer.Stop() { select { case <-timer.C: default: } } // cleanup defer timer.Stop() // writeBuf writes the contents of buf through to the s.Writer. // done only when arrival time makes sense. drainBuf := func() error { if buf.Len() > 0 { _, err := s.write.Write(buf.Bytes()) if err != nil { return err } buf.Reset() } return nil } // deliverOrWait is a helper func that processes // an incoming packet. it waits until the arrival time, // and then writes things out. deliverOrWait := func(o *transportObject) error { buffered := len(o.msg) + buf.Len() // Yes, we can end up extending a timer multiple times if we // keep on making small writes but that shouldn't be too much of an // issue. Fixing that would be painful. if !timer.Stop() { // FIXME: So, we *shouldn't* need to do this but we hang // here if we don't... Go bug? select { case <-timer.C: default: } } delay := o.arrivalTime.Sub(time.Now()) if delay >= 0 { timer.Reset(delay) } else { timer.Reset(0) } if buffered >= bufsize { select { case <-timer.C: case <-s.reset: select { case s.reset <- struct{}{}: default: } return ErrReset } if err := drainBuf(); err != nil { return err } // write this message. _, err := s.write.Write(o.msg) if err != nil { return err } } else { buf.Write(o.msg) } return nil } for { // Reset takes precedent. select { case <-s.reset: s.writeErr = ErrReset return default: } select { case <-s.reset: s.writeErr = ErrReset return case <-s.close: if err := drainBuf(); err != nil { s.resetWith(err) return } s.writeErr = s.write.Close() if s.writeErr == nil { s.writeErr = ErrClosed } return case o := <-s.toDeliver: if err := deliverOrWait(o); err != nil { s.resetWith(err) return } case <-timer.C: // ok, due to write it out. if err := drainBuf(); err != nil { s.resetWith(err) return } } } }
[ "func", "(", "s", "*", "stream", ")", "transport", "(", ")", "{", "defer", "s", ".", "teardown", "(", ")", "\n\n", "bufsize", ":=", "256", "\n", "buf", ":=", "new", "(", "bytes", ".", "Buffer", ")", "\n", "timer", ":=", "time", ".", "NewTimer", "(", "0", ")", "\n", "if", "!", "timer", ".", "Stop", "(", ")", "{", "select", "{", "case", "<-", "timer", ".", "C", ":", "default", ":", "}", "\n", "}", "\n\n", "// cleanup", "defer", "timer", ".", "Stop", "(", ")", "\n\n", "// writeBuf writes the contents of buf through to the s.Writer.", "// done only when arrival time makes sense.", "drainBuf", ":=", "func", "(", ")", "error", "{", "if", "buf", ".", "Len", "(", ")", ">", "0", "{", "_", ",", "err", ":=", "s", ".", "write", ".", "Write", "(", "buf", ".", "Bytes", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "buf", ".", "Reset", "(", ")", "\n", "}", "\n", "return", "nil", "\n", "}", "\n\n", "// deliverOrWait is a helper func that processes", "// an incoming packet. it waits until the arrival time,", "// and then writes things out.", "deliverOrWait", ":=", "func", "(", "o", "*", "transportObject", ")", "error", "{", "buffered", ":=", "len", "(", "o", ".", "msg", ")", "+", "buf", ".", "Len", "(", ")", "\n\n", "// Yes, we can end up extending a timer multiple times if we", "// keep on making small writes but that shouldn't be too much of an", "// issue. Fixing that would be painful.", "if", "!", "timer", ".", "Stop", "(", ")", "{", "// FIXME: So, we *shouldn't* need to do this but we hang", "// here if we don't... Go bug?", "select", "{", "case", "<-", "timer", ".", "C", ":", "default", ":", "}", "\n", "}", "\n", "delay", ":=", "o", ".", "arrivalTime", ".", "Sub", "(", "time", ".", "Now", "(", ")", ")", "\n", "if", "delay", ">=", "0", "{", "timer", ".", "Reset", "(", "delay", ")", "\n", "}", "else", "{", "timer", ".", "Reset", "(", "0", ")", "\n", "}", "\n\n", "if", "buffered", ">=", "bufsize", "{", "select", "{", "case", "<-", "timer", ".", "C", ":", "case", "<-", "s", ".", "reset", ":", "select", "{", "case", "s", ".", "reset", "<-", "struct", "{", "}", "{", "}", ":", "default", ":", "}", "\n", "return", "ErrReset", "\n", "}", "\n", "if", "err", ":=", "drainBuf", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "// write this message.", "_", ",", "err", ":=", "s", ".", "write", ".", "Write", "(", "o", ".", "msg", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "else", "{", "buf", ".", "Write", "(", "o", ".", "msg", ")", "\n", "}", "\n", "return", "nil", "\n", "}", "\n\n", "for", "{", "// Reset takes precedent.", "select", "{", "case", "<-", "s", ".", "reset", ":", "s", ".", "writeErr", "=", "ErrReset", "\n", "return", "\n", "default", ":", "}", "\n\n", "select", "{", "case", "<-", "s", ".", "reset", ":", "s", ".", "writeErr", "=", "ErrReset", "\n", "return", "\n", "case", "<-", "s", ".", "close", ":", "if", "err", ":=", "drainBuf", "(", ")", ";", "err", "!=", "nil", "{", "s", ".", "resetWith", "(", "err", ")", "\n", "return", "\n", "}", "\n", "s", ".", "writeErr", "=", "s", ".", "write", ".", "Close", "(", ")", "\n", "if", "s", ".", "writeErr", "==", "nil", "{", "s", ".", "writeErr", "=", "ErrClosed", "\n", "}", "\n", "return", "\n", "case", "o", ":=", "<-", "s", ".", "toDeliver", ":", "if", "err", ":=", "deliverOrWait", "(", "o", ")", ";", "err", "!=", "nil", "{", "s", ".", "resetWith", "(", "err", ")", "\n", "return", "\n", "}", "\n", "case", "<-", "timer", ".", "C", ":", "// ok, due to write it out.", "if", "err", ":=", "drainBuf", "(", ")", ";", "err", "!=", "nil", "{", "s", ".", "resetWith", "(", "err", ")", "\n", "return", "\n", "}", "\n", "}", "\n", "}", "\n", "}" ]
// transport will grab message arrival times, wait until that time, and // then write the message out when it is scheduled to arrive
[ "transport", "will", "grab", "message", "arrival", "times", "wait", "until", "that", "time", "and", "then", "write", "the", "message", "out", "when", "it", "is", "scheduled", "to", "arrive" ]
bd0f8953cf5cb16e1f9d0a420ad20ebc08ffd344
https://github.com/libp2p/go-libp2p/blob/bd0f8953cf5cb16e1f9d0a420ad20ebc08ffd344/p2p/net/mock/mock_stream.go#L148-L260
train
libp2p/go-libp2p
p2p/host/relay/autorelay.go
usingRelay
func (ar *AutoRelay) usingRelay(p peer.ID) bool { ar.mx.Lock() defer ar.mx.Unlock() _, ok := ar.relays[p] return ok }
go
func (ar *AutoRelay) usingRelay(p peer.ID) bool { ar.mx.Lock() defer ar.mx.Unlock() _, ok := ar.relays[p] return ok }
[ "func", "(", "ar", "*", "AutoRelay", ")", "usingRelay", "(", "p", "peer", ".", "ID", ")", "bool", "{", "ar", ".", "mx", ".", "Lock", "(", ")", "\n", "defer", "ar", ".", "mx", ".", "Unlock", "(", ")", "\n", "_", ",", "ok", ":=", "ar", ".", "relays", "[", "p", "]", "\n", "return", "ok", "\n", "}" ]
// usingRelay returns if we're currently using the given relay.
[ "usingRelay", "returns", "if", "we", "re", "currently", "using", "the", "given", "relay", "." ]
bd0f8953cf5cb16e1f9d0a420ad20ebc08ffd344
https://github.com/libp2p/go-libp2p/blob/bd0f8953cf5cb16e1f9d0a420ad20ebc08ffd344/p2p/host/relay/autorelay.go#L182-L187
train
libp2p/go-libp2p
p2p/host/relay/autorelay.go
tryRelay
func (ar *AutoRelay) tryRelay(ctx context.Context, pi pstore.PeerInfo) bool { if ar.usingRelay(pi.ID) { return false } if !ar.connect(ctx, pi) { return false } ar.mx.Lock() defer ar.mx.Unlock() // make sure we're still connected. if ar.host.Network().Connectedness(pi.ID) != inet.Connected { return false } ar.relays[pi.ID] = struct{}{} return true }
go
func (ar *AutoRelay) tryRelay(ctx context.Context, pi pstore.PeerInfo) bool { if ar.usingRelay(pi.ID) { return false } if !ar.connect(ctx, pi) { return false } ar.mx.Lock() defer ar.mx.Unlock() // make sure we're still connected. if ar.host.Network().Connectedness(pi.ID) != inet.Connected { return false } ar.relays[pi.ID] = struct{}{} return true }
[ "func", "(", "ar", "*", "AutoRelay", ")", "tryRelay", "(", "ctx", "context", ".", "Context", ",", "pi", "pstore", ".", "PeerInfo", ")", "bool", "{", "if", "ar", ".", "usingRelay", "(", "pi", ".", "ID", ")", "{", "return", "false", "\n", "}", "\n\n", "if", "!", "ar", ".", "connect", "(", "ctx", ",", "pi", ")", "{", "return", "false", "\n", "}", "\n\n", "ar", ".", "mx", ".", "Lock", "(", ")", "\n", "defer", "ar", ".", "mx", ".", "Unlock", "(", ")", "\n\n", "// make sure we're still connected.", "if", "ar", ".", "host", ".", "Network", "(", ")", ".", "Connectedness", "(", "pi", ".", "ID", ")", "!=", "inet", ".", "Connected", "{", "return", "false", "\n", "}", "\n", "ar", ".", "relays", "[", "pi", ".", "ID", "]", "=", "struct", "{", "}", "{", "}", "\n\n", "return", "true", "\n", "}" ]
// addRelay adds the given relay to our set of relays. // returns true when we add a new relay
[ "addRelay", "adds", "the", "given", "relay", "to", "our", "set", "of", "relays", ".", "returns", "true", "when", "we", "add", "a", "new", "relay" ]
bd0f8953cf5cb16e1f9d0a420ad20ebc08ffd344
https://github.com/libp2p/go-libp2p/blob/bd0f8953cf5cb16e1f9d0a420ad20ebc08ffd344/p2p/host/relay/autorelay.go#L191-L210
train
name5566/leaf
console/command.go
Register
func Register(name string, help string, f interface{}, server *chanrpc.Server) { for _, c := range commands { if c.name() == name { log.Fatal("command %v is already registered", name) } } server.Register(name, f) c := new(ExternalCommand) c._name = name c._help = help c.server = server commands = append(commands, c) }
go
func Register(name string, help string, f interface{}, server *chanrpc.Server) { for _, c := range commands { if c.name() == name { log.Fatal("command %v is already registered", name) } } server.Register(name, f) c := new(ExternalCommand) c._name = name c._help = help c.server = server commands = append(commands, c) }
[ "func", "Register", "(", "name", "string", ",", "help", "string", ",", "f", "interface", "{", "}", ",", "server", "*", "chanrpc", ".", "Server", ")", "{", "for", "_", ",", "c", ":=", "range", "commands", "{", "if", "c", ".", "name", "(", ")", "==", "name", "{", "log", ".", "Fatal", "(", "\"", "\"", ",", "name", ")", "\n", "}", "\n", "}", "\n\n", "server", ".", "Register", "(", "name", ",", "f", ")", "\n\n", "c", ":=", "new", "(", "ExternalCommand", ")", "\n", "c", ".", "_name", "=", "name", "\n", "c", ".", "_help", "=", "help", "\n", "c", ".", "server", "=", "server", "\n", "commands", "=", "append", "(", "commands", ",", "c", ")", "\n", "}" ]
// you must call the function before calling console.Init // goroutine not safe
[ "you", "must", "call", "the", "function", "before", "calling", "console", ".", "Init", "goroutine", "not", "safe" ]
1364c176dfbdff8df210496098265c2962fe922d
https://github.com/name5566/leaf/blob/1364c176dfbdff8df210496098265c2962fe922d/console/command.go#L63-L77
train
name5566/leaf
chanrpc/chanrpc.go
Register
func (s *Server) Register(id interface{}, f interface{}) { switch f.(type) { case func([]interface{}): case func([]interface{}) interface{}: case func([]interface{}) []interface{}: default: panic(fmt.Sprintf("function id %v: definition of function is invalid", id)) } if _, ok := s.functions[id]; ok { panic(fmt.Sprintf("function id %v: already registered", id)) } s.functions[id] = f }
go
func (s *Server) Register(id interface{}, f interface{}) { switch f.(type) { case func([]interface{}): case func([]interface{}) interface{}: case func([]interface{}) []interface{}: default: panic(fmt.Sprintf("function id %v: definition of function is invalid", id)) } if _, ok := s.functions[id]; ok { panic(fmt.Sprintf("function id %v: already registered", id)) } s.functions[id] = f }
[ "func", "(", "s", "*", "Server", ")", "Register", "(", "id", "interface", "{", "}", ",", "f", "interface", "{", "}", ")", "{", "switch", "f", ".", "(", "type", ")", "{", "case", "func", "(", "[", "]", "interface", "{", "}", ")", ":", "case", "func", "(", "[", "]", "interface", "{", "}", ")", "interface", "{", "}", ":", "case", "func", "(", "[", "]", "interface", "{", "}", ")", "[", "]", "interface", "{", "}", ":", "default", ":", "panic", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "id", ")", ")", "\n", "}", "\n\n", "if", "_", ",", "ok", ":=", "s", ".", "functions", "[", "id", "]", ";", "ok", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "id", ")", ")", "\n", "}", "\n\n", "s", ".", "functions", "[", "id", "]", "=", "f", "\n", "}" ]
// you must call the function before calling Open and Go
[ "you", "must", "call", "the", "function", "before", "calling", "Open", "and", "Go" ]
1364c176dfbdff8df210496098265c2962fe922d
https://github.com/name5566/leaf/blob/1364c176dfbdff8df210496098265c2962fe922d/chanrpc/chanrpc.go#L67-L81
train
name5566/leaf
network/ws_conn.go
ReadMsg
func (wsConn *WSConn) ReadMsg() ([]byte, error) { _, b, err := wsConn.conn.ReadMessage() return b, err }
go
func (wsConn *WSConn) ReadMsg() ([]byte, error) { _, b, err := wsConn.conn.ReadMessage() return b, err }
[ "func", "(", "wsConn", "*", "WSConn", ")", "ReadMsg", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "_", ",", "b", ",", "err", ":=", "wsConn", ".", "conn", ".", "ReadMessage", "(", ")", "\n", "return", "b", ",", "err", "\n", "}" ]
// goroutine not safe
[ "goroutine", "not", "safe" ]
1364c176dfbdff8df210496098265c2962fe922d
https://github.com/name5566/leaf/blob/1364c176dfbdff8df210496098265c2962fe922d/network/ws_conn.go#L95-L98
train
name5566/leaf
network/ws_conn.go
WriteMsg
func (wsConn *WSConn) WriteMsg(args ...[]byte) error { wsConn.Lock() defer wsConn.Unlock() if wsConn.closeFlag { return nil } // get len var msgLen uint32 for i := 0; i < len(args); i++ { msgLen += uint32(len(args[i])) } // check len if msgLen > wsConn.maxMsgLen { return errors.New("message too long") } else if msgLen < 1 { return errors.New("message too short") } // don't copy if len(args) == 1 { wsConn.doWrite(args[0]) return nil } // merge the args msg := make([]byte, msgLen) l := 0 for i := 0; i < len(args); i++ { copy(msg[l:], args[i]) l += len(args[i]) } wsConn.doWrite(msg) return nil }
go
func (wsConn *WSConn) WriteMsg(args ...[]byte) error { wsConn.Lock() defer wsConn.Unlock() if wsConn.closeFlag { return nil } // get len var msgLen uint32 for i := 0; i < len(args); i++ { msgLen += uint32(len(args[i])) } // check len if msgLen > wsConn.maxMsgLen { return errors.New("message too long") } else if msgLen < 1 { return errors.New("message too short") } // don't copy if len(args) == 1 { wsConn.doWrite(args[0]) return nil } // merge the args msg := make([]byte, msgLen) l := 0 for i := 0; i < len(args); i++ { copy(msg[l:], args[i]) l += len(args[i]) } wsConn.doWrite(msg) return nil }
[ "func", "(", "wsConn", "*", "WSConn", ")", "WriteMsg", "(", "args", "...", "[", "]", "byte", ")", "error", "{", "wsConn", ".", "Lock", "(", ")", "\n", "defer", "wsConn", ".", "Unlock", "(", ")", "\n", "if", "wsConn", ".", "closeFlag", "{", "return", "nil", "\n", "}", "\n\n", "// get len", "var", "msgLen", "uint32", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "args", ")", ";", "i", "++", "{", "msgLen", "+=", "uint32", "(", "len", "(", "args", "[", "i", "]", ")", ")", "\n", "}", "\n\n", "// check len", "if", "msgLen", ">", "wsConn", ".", "maxMsgLen", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "else", "if", "msgLen", "<", "1", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// don't copy", "if", "len", "(", "args", ")", "==", "1", "{", "wsConn", ".", "doWrite", "(", "args", "[", "0", "]", ")", "\n", "return", "nil", "\n", "}", "\n\n", "// merge the args", "msg", ":=", "make", "(", "[", "]", "byte", ",", "msgLen", ")", "\n", "l", ":=", "0", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "args", ")", ";", "i", "++", "{", "copy", "(", "msg", "[", "l", ":", "]", ",", "args", "[", "i", "]", ")", "\n", "l", "+=", "len", "(", "args", "[", "i", "]", ")", "\n", "}", "\n\n", "wsConn", ".", "doWrite", "(", "msg", ")", "\n\n", "return", "nil", "\n", "}" ]
// args must not be modified by the others goroutines
[ "args", "must", "not", "be", "modified", "by", "the", "others", "goroutines" ]
1364c176dfbdff8df210496098265c2962fe922d
https://github.com/name5566/leaf/blob/1364c176dfbdff8df210496098265c2962fe922d/network/ws_conn.go#L101-L138
train
name5566/leaf
network/tcp_conn.go
Write
func (tcpConn *TCPConn) Write(b []byte) { tcpConn.Lock() defer tcpConn.Unlock() if tcpConn.closeFlag || b == nil { return } tcpConn.doWrite(b) }
go
func (tcpConn *TCPConn) Write(b []byte) { tcpConn.Lock() defer tcpConn.Unlock() if tcpConn.closeFlag || b == nil { return } tcpConn.doWrite(b) }
[ "func", "(", "tcpConn", "*", "TCPConn", ")", "Write", "(", "b", "[", "]", "byte", ")", "{", "tcpConn", ".", "Lock", "(", ")", "\n", "defer", "tcpConn", ".", "Unlock", "(", ")", "\n", "if", "tcpConn", ".", "closeFlag", "||", "b", "==", "nil", "{", "return", "\n", "}", "\n\n", "tcpConn", ".", "doWrite", "(", "b", ")", "\n", "}" ]
// b must not be modified by the others goroutines
[ "b", "must", "not", "be", "modified", "by", "the", "others", "goroutines" ]
1364c176dfbdff8df210496098265c2962fe922d
https://github.com/name5566/leaf/blob/1364c176dfbdff8df210496098265c2962fe922d/network/tcp_conn.go#L85-L93
train
name5566/leaf
network/tcp_msg.go
SetMsgLen
func (p *MsgParser) SetMsgLen(lenMsgLen int, minMsgLen uint32, maxMsgLen uint32) { if lenMsgLen == 1 || lenMsgLen == 2 || lenMsgLen == 4 { p.lenMsgLen = lenMsgLen } if minMsgLen != 0 { p.minMsgLen = minMsgLen } if maxMsgLen != 0 { p.maxMsgLen = maxMsgLen } var max uint32 switch p.lenMsgLen { case 1: max = math.MaxUint8 case 2: max = math.MaxUint16 case 4: max = math.MaxUint32 } if p.minMsgLen > max { p.minMsgLen = max } if p.maxMsgLen > max { p.maxMsgLen = max } }
go
func (p *MsgParser) SetMsgLen(lenMsgLen int, minMsgLen uint32, maxMsgLen uint32) { if lenMsgLen == 1 || lenMsgLen == 2 || lenMsgLen == 4 { p.lenMsgLen = lenMsgLen } if minMsgLen != 0 { p.minMsgLen = minMsgLen } if maxMsgLen != 0 { p.maxMsgLen = maxMsgLen } var max uint32 switch p.lenMsgLen { case 1: max = math.MaxUint8 case 2: max = math.MaxUint16 case 4: max = math.MaxUint32 } if p.minMsgLen > max { p.minMsgLen = max } if p.maxMsgLen > max { p.maxMsgLen = max } }
[ "func", "(", "p", "*", "MsgParser", ")", "SetMsgLen", "(", "lenMsgLen", "int", ",", "minMsgLen", "uint32", ",", "maxMsgLen", "uint32", ")", "{", "if", "lenMsgLen", "==", "1", "||", "lenMsgLen", "==", "2", "||", "lenMsgLen", "==", "4", "{", "p", ".", "lenMsgLen", "=", "lenMsgLen", "\n", "}", "\n", "if", "minMsgLen", "!=", "0", "{", "p", ".", "minMsgLen", "=", "minMsgLen", "\n", "}", "\n", "if", "maxMsgLen", "!=", "0", "{", "p", ".", "maxMsgLen", "=", "maxMsgLen", "\n", "}", "\n\n", "var", "max", "uint32", "\n", "switch", "p", ".", "lenMsgLen", "{", "case", "1", ":", "max", "=", "math", ".", "MaxUint8", "\n", "case", "2", ":", "max", "=", "math", ".", "MaxUint16", "\n", "case", "4", ":", "max", "=", "math", ".", "MaxUint32", "\n", "}", "\n", "if", "p", ".", "minMsgLen", ">", "max", "{", "p", ".", "minMsgLen", "=", "max", "\n", "}", "\n", "if", "p", ".", "maxMsgLen", ">", "max", "{", "p", ".", "maxMsgLen", "=", "max", "\n", "}", "\n", "}" ]
// It's dangerous to call the method on reading or writing
[ "It", "s", "dangerous", "to", "call", "the", "method", "on", "reading", "or", "writing" ]
1364c176dfbdff8df210496098265c2962fe922d
https://github.com/name5566/leaf/blob/1364c176dfbdff8df210496098265c2962fe922d/network/tcp_msg.go#L31-L57
train
name5566/leaf
log/log.go
Close
func (logger *Logger) Close() { if logger.baseFile != nil { logger.baseFile.Close() } logger.baseLogger = nil logger.baseFile = nil }
go
func (logger *Logger) Close() { if logger.baseFile != nil { logger.baseFile.Close() } logger.baseLogger = nil logger.baseFile = nil }
[ "func", "(", "logger", "*", "Logger", ")", "Close", "(", ")", "{", "if", "logger", ".", "baseFile", "!=", "nil", "{", "logger", ".", "baseFile", ".", "Close", "(", ")", "\n", "}", "\n\n", "logger", ".", "baseLogger", "=", "nil", "\n", "logger", ".", "baseFile", "=", "nil", "\n", "}" ]
// It's dangerous to call the method on logging
[ "It", "s", "dangerous", "to", "call", "the", "method", "on", "logging" ]
1364c176dfbdff8df210496098265c2962fe922d
https://github.com/name5566/leaf/blob/1364c176dfbdff8df210496098265c2962fe922d/log/log.go#L85-L92
train
json-iterator/go
iter_array.go
ReadArrayCB
func (iter *Iterator) ReadArrayCB(callback func(*Iterator) bool) (ret bool) { c := iter.nextToken() if c == '[' { c = iter.nextToken() if c != ']' { iter.unreadByte() if !callback(iter) { return false } c = iter.nextToken() for c == ',' { if !callback(iter) { return false } c = iter.nextToken() } if c != ']' { iter.ReportError("ReadArrayCB", "expect ] in the end, but found "+string([]byte{c})) return false } return true } return true } if c == 'n' { iter.skipThreeBytes('u', 'l', 'l') return true // null } iter.ReportError("ReadArrayCB", "expect [ or n, but found "+string([]byte{c})) return false }
go
func (iter *Iterator) ReadArrayCB(callback func(*Iterator) bool) (ret bool) { c := iter.nextToken() if c == '[' { c = iter.nextToken() if c != ']' { iter.unreadByte() if !callback(iter) { return false } c = iter.nextToken() for c == ',' { if !callback(iter) { return false } c = iter.nextToken() } if c != ']' { iter.ReportError("ReadArrayCB", "expect ] in the end, but found "+string([]byte{c})) return false } return true } return true } if c == 'n' { iter.skipThreeBytes('u', 'l', 'l') return true // null } iter.ReportError("ReadArrayCB", "expect [ or n, but found "+string([]byte{c})) return false }
[ "func", "(", "iter", "*", "Iterator", ")", "ReadArrayCB", "(", "callback", "func", "(", "*", "Iterator", ")", "bool", ")", "(", "ret", "bool", ")", "{", "c", ":=", "iter", ".", "nextToken", "(", ")", "\n", "if", "c", "==", "'['", "{", "c", "=", "iter", ".", "nextToken", "(", ")", "\n", "if", "c", "!=", "']'", "{", "iter", ".", "unreadByte", "(", ")", "\n", "if", "!", "callback", "(", "iter", ")", "{", "return", "false", "\n", "}", "\n", "c", "=", "iter", ".", "nextToken", "(", ")", "\n", "for", "c", "==", "','", "{", "if", "!", "callback", "(", "iter", ")", "{", "return", "false", "\n", "}", "\n", "c", "=", "iter", ".", "nextToken", "(", ")", "\n", "}", "\n", "if", "c", "!=", "']'", "{", "iter", ".", "ReportError", "(", "\"", "\"", ",", "\"", "\"", "+", "string", "(", "[", "]", "byte", "{", "c", "}", ")", ")", "\n", "return", "false", "\n", "}", "\n", "return", "true", "\n", "}", "\n", "return", "true", "\n", "}", "\n", "if", "c", "==", "'n'", "{", "iter", ".", "skipThreeBytes", "(", "'u'", ",", "'l'", ",", "'l'", ")", "\n", "return", "true", "// null", "\n", "}", "\n", "iter", ".", "ReportError", "(", "\"", "\"", ",", "\"", "\"", "+", "string", "(", "[", "]", "byte", "{", "c", "}", ")", ")", "\n", "return", "false", "\n", "}" ]
// ReadArrayCB read array with callback
[ "ReadArrayCB", "read", "array", "with", "callback" ]
0ff49de124c6f76f8494e194af75bde0f1a49a29
https://github.com/json-iterator/go/blob/0ff49de124c6f76f8494e194af75bde0f1a49a29/iter_array.go#L28-L58
train
json-iterator/go
iter.go
NewIterator
func NewIterator(cfg API) *Iterator { return &Iterator{ cfg: cfg.(*frozenConfig), reader: nil, buf: nil, head: 0, tail: 0, } }
go
func NewIterator(cfg API) *Iterator { return &Iterator{ cfg: cfg.(*frozenConfig), reader: nil, buf: nil, head: 0, tail: 0, } }
[ "func", "NewIterator", "(", "cfg", "API", ")", "*", "Iterator", "{", "return", "&", "Iterator", "{", "cfg", ":", "cfg", ".", "(", "*", "frozenConfig", ")", ",", "reader", ":", "nil", ",", "buf", ":", "nil", ",", "head", ":", "0", ",", "tail", ":", "0", ",", "}", "\n", "}" ]
// NewIterator creates an empty Iterator instance
[ "NewIterator", "creates", "an", "empty", "Iterator", "instance" ]
0ff49de124c6f76f8494e194af75bde0f1a49a29
https://github.com/json-iterator/go/blob/0ff49de124c6f76f8494e194af75bde0f1a49a29/iter.go#L84-L92
train
json-iterator/go
iter.go
Parse
func Parse(cfg API, reader io.Reader, bufSize int) *Iterator { return &Iterator{ cfg: cfg.(*frozenConfig), reader: reader, buf: make([]byte, bufSize), head: 0, tail: 0, } }
go
func Parse(cfg API, reader io.Reader, bufSize int) *Iterator { return &Iterator{ cfg: cfg.(*frozenConfig), reader: reader, buf: make([]byte, bufSize), head: 0, tail: 0, } }
[ "func", "Parse", "(", "cfg", "API", ",", "reader", "io", ".", "Reader", ",", "bufSize", "int", ")", "*", "Iterator", "{", "return", "&", "Iterator", "{", "cfg", ":", "cfg", ".", "(", "*", "frozenConfig", ")", ",", "reader", ":", "reader", ",", "buf", ":", "make", "(", "[", "]", "byte", ",", "bufSize", ")", ",", "head", ":", "0", ",", "tail", ":", "0", ",", "}", "\n", "}" ]
// Parse creates an Iterator instance from io.Reader
[ "Parse", "creates", "an", "Iterator", "instance", "from", "io", ".", "Reader" ]
0ff49de124c6f76f8494e194af75bde0f1a49a29
https://github.com/json-iterator/go/blob/0ff49de124c6f76f8494e194af75bde0f1a49a29/iter.go#L95-L103
train
json-iterator/go
iter.go
ParseBytes
func ParseBytes(cfg API, input []byte) *Iterator { return &Iterator{ cfg: cfg.(*frozenConfig), reader: nil, buf: input, head: 0, tail: len(input), } }
go
func ParseBytes(cfg API, input []byte) *Iterator { return &Iterator{ cfg: cfg.(*frozenConfig), reader: nil, buf: input, head: 0, tail: len(input), } }
[ "func", "ParseBytes", "(", "cfg", "API", ",", "input", "[", "]", "byte", ")", "*", "Iterator", "{", "return", "&", "Iterator", "{", "cfg", ":", "cfg", ".", "(", "*", "frozenConfig", ")", ",", "reader", ":", "nil", ",", "buf", ":", "input", ",", "head", ":", "0", ",", "tail", ":", "len", "(", "input", ")", ",", "}", "\n", "}" ]
// ParseBytes creates an Iterator instance from byte array
[ "ParseBytes", "creates", "an", "Iterator", "instance", "from", "byte", "array" ]
0ff49de124c6f76f8494e194af75bde0f1a49a29
https://github.com/json-iterator/go/blob/0ff49de124c6f76f8494e194af75bde0f1a49a29/iter.go#L106-L114
train
json-iterator/go
iter.go
ParseString
func ParseString(cfg API, input string) *Iterator { return ParseBytes(cfg, []byte(input)) }
go
func ParseString(cfg API, input string) *Iterator { return ParseBytes(cfg, []byte(input)) }
[ "func", "ParseString", "(", "cfg", "API", ",", "input", "string", ")", "*", "Iterator", "{", "return", "ParseBytes", "(", "cfg", ",", "[", "]", "byte", "(", "input", ")", ")", "\n", "}" ]
// ParseString creates an Iterator instance from string
[ "ParseString", "creates", "an", "Iterator", "instance", "from", "string" ]
0ff49de124c6f76f8494e194af75bde0f1a49a29
https://github.com/json-iterator/go/blob/0ff49de124c6f76f8494e194af75bde0f1a49a29/iter.go#L117-L119
train
json-iterator/go
iter.go
Reset
func (iter *Iterator) Reset(reader io.Reader) *Iterator { iter.reader = reader iter.head = 0 iter.tail = 0 return iter }
go
func (iter *Iterator) Reset(reader io.Reader) *Iterator { iter.reader = reader iter.head = 0 iter.tail = 0 return iter }
[ "func", "(", "iter", "*", "Iterator", ")", "Reset", "(", "reader", "io", ".", "Reader", ")", "*", "Iterator", "{", "iter", ".", "reader", "=", "reader", "\n", "iter", ".", "head", "=", "0", "\n", "iter", ".", "tail", "=", "0", "\n", "return", "iter", "\n", "}" ]
// Reset reuse iterator instance by specifying another reader
[ "Reset", "reuse", "iterator", "instance", "by", "specifying", "another", "reader" ]
0ff49de124c6f76f8494e194af75bde0f1a49a29
https://github.com/json-iterator/go/blob/0ff49de124c6f76f8494e194af75bde0f1a49a29/iter.go#L127-L132
train
json-iterator/go
iter.go
ResetBytes
func (iter *Iterator) ResetBytes(input []byte) *Iterator { iter.reader = nil iter.buf = input iter.head = 0 iter.tail = len(input) return iter }
go
func (iter *Iterator) ResetBytes(input []byte) *Iterator { iter.reader = nil iter.buf = input iter.head = 0 iter.tail = len(input) return iter }
[ "func", "(", "iter", "*", "Iterator", ")", "ResetBytes", "(", "input", "[", "]", "byte", ")", "*", "Iterator", "{", "iter", ".", "reader", "=", "nil", "\n", "iter", ".", "buf", "=", "input", "\n", "iter", ".", "head", "=", "0", "\n", "iter", ".", "tail", "=", "len", "(", "input", ")", "\n", "return", "iter", "\n", "}" ]
// ResetBytes reuse iterator instance by specifying another byte array as input
[ "ResetBytes", "reuse", "iterator", "instance", "by", "specifying", "another", "byte", "array", "as", "input" ]
0ff49de124c6f76f8494e194af75bde0f1a49a29
https://github.com/json-iterator/go/blob/0ff49de124c6f76f8494e194af75bde0f1a49a29/iter.go#L135-L141
train
json-iterator/go
iter.go
WhatIsNext
func (iter *Iterator) WhatIsNext() ValueType { valueType := valueTypes[iter.nextToken()] iter.unreadByte() return valueType }
go
func (iter *Iterator) WhatIsNext() ValueType { valueType := valueTypes[iter.nextToken()] iter.unreadByte() return valueType }
[ "func", "(", "iter", "*", "Iterator", ")", "WhatIsNext", "(", ")", "ValueType", "{", "valueType", ":=", "valueTypes", "[", "iter", ".", "nextToken", "(", ")", "]", "\n", "iter", ".", "unreadByte", "(", ")", "\n", "return", "valueType", "\n", "}" ]
// WhatIsNext gets ValueType of relatively next json element
[ "WhatIsNext", "gets", "ValueType", "of", "relatively", "next", "json", "element" ]
0ff49de124c6f76f8494e194af75bde0f1a49a29
https://github.com/json-iterator/go/blob/0ff49de124c6f76f8494e194af75bde0f1a49a29/iter.go#L144-L148
train
json-iterator/go
iter.go
ReportError
func (iter *Iterator) ReportError(operation string, msg string) { if iter.Error != nil { if iter.Error != io.EOF { return } } peekStart := iter.head - 10 if peekStart < 0 { peekStart = 0 } peekEnd := iter.head + 10 if peekEnd > iter.tail { peekEnd = iter.tail } parsing := string(iter.buf[peekStart:peekEnd]) contextStart := iter.head - 50 if contextStart < 0 { contextStart = 0 } contextEnd := iter.head + 50 if contextEnd > iter.tail { contextEnd = iter.tail } context := string(iter.buf[contextStart:contextEnd]) iter.Error = fmt.Errorf("%s: %s, error found in #%v byte of ...|%s|..., bigger context ...|%s|...", operation, msg, iter.head-peekStart, parsing, context) }
go
func (iter *Iterator) ReportError(operation string, msg string) { if iter.Error != nil { if iter.Error != io.EOF { return } } peekStart := iter.head - 10 if peekStart < 0 { peekStart = 0 } peekEnd := iter.head + 10 if peekEnd > iter.tail { peekEnd = iter.tail } parsing := string(iter.buf[peekStart:peekEnd]) contextStart := iter.head - 50 if contextStart < 0 { contextStart = 0 } contextEnd := iter.head + 50 if contextEnd > iter.tail { contextEnd = iter.tail } context := string(iter.buf[contextStart:contextEnd]) iter.Error = fmt.Errorf("%s: %s, error found in #%v byte of ...|%s|..., bigger context ...|%s|...", operation, msg, iter.head-peekStart, parsing, context) }
[ "func", "(", "iter", "*", "Iterator", ")", "ReportError", "(", "operation", "string", ",", "msg", "string", ")", "{", "if", "iter", ".", "Error", "!=", "nil", "{", "if", "iter", ".", "Error", "!=", "io", ".", "EOF", "{", "return", "\n", "}", "\n", "}", "\n", "peekStart", ":=", "iter", ".", "head", "-", "10", "\n", "if", "peekStart", "<", "0", "{", "peekStart", "=", "0", "\n", "}", "\n", "peekEnd", ":=", "iter", ".", "head", "+", "10", "\n", "if", "peekEnd", ">", "iter", ".", "tail", "{", "peekEnd", "=", "iter", ".", "tail", "\n", "}", "\n", "parsing", ":=", "string", "(", "iter", ".", "buf", "[", "peekStart", ":", "peekEnd", "]", ")", "\n", "contextStart", ":=", "iter", ".", "head", "-", "50", "\n", "if", "contextStart", "<", "0", "{", "contextStart", "=", "0", "\n", "}", "\n", "contextEnd", ":=", "iter", ".", "head", "+", "50", "\n", "if", "contextEnd", ">", "iter", ".", "tail", "{", "contextEnd", "=", "iter", ".", "tail", "\n", "}", "\n", "context", ":=", "string", "(", "iter", ".", "buf", "[", "contextStart", ":", "contextEnd", "]", ")", "\n", "iter", ".", "Error", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "operation", ",", "msg", ",", "iter", ".", "head", "-", "peekStart", ",", "parsing", ",", "context", ")", "\n", "}" ]
// ReportError record a error in iterator instance with current position.
[ "ReportError", "record", "a", "error", "in", "iterator", "instance", "with", "current", "position", "." ]
0ff49de124c6f76f8494e194af75bde0f1a49a29
https://github.com/json-iterator/go/blob/0ff49de124c6f76f8494e194af75bde0f1a49a29/iter.go#L194-L220
train
json-iterator/go
iter.go
CurrentBuffer
func (iter *Iterator) CurrentBuffer() string { peekStart := iter.head - 10 if peekStart < 0 { peekStart = 0 } return fmt.Sprintf("parsing #%v byte, around ...|%s|..., whole buffer ...|%s|...", iter.head, string(iter.buf[peekStart:iter.head]), string(iter.buf[0:iter.tail])) }
go
func (iter *Iterator) CurrentBuffer() string { peekStart := iter.head - 10 if peekStart < 0 { peekStart = 0 } return fmt.Sprintf("parsing #%v byte, around ...|%s|..., whole buffer ...|%s|...", iter.head, string(iter.buf[peekStart:iter.head]), string(iter.buf[0:iter.tail])) }
[ "func", "(", "iter", "*", "Iterator", ")", "CurrentBuffer", "(", ")", "string", "{", "peekStart", ":=", "iter", ".", "head", "-", "10", "\n", "if", "peekStart", "<", "0", "{", "peekStart", "=", "0", "\n", "}", "\n", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "iter", ".", "head", ",", "string", "(", "iter", ".", "buf", "[", "peekStart", ":", "iter", ".", "head", "]", ")", ",", "string", "(", "iter", ".", "buf", "[", "0", ":", "iter", ".", "tail", "]", ")", ")", "\n", "}" ]
// CurrentBuffer gets current buffer as string for debugging purpose
[ "CurrentBuffer", "gets", "current", "buffer", "as", "string", "for", "debugging", "purpose" ]
0ff49de124c6f76f8494e194af75bde0f1a49a29
https://github.com/json-iterator/go/blob/0ff49de124c6f76f8494e194af75bde0f1a49a29/iter.go#L223-L230
train
json-iterator/go
extra/naming_strategy.go
SetNamingStrategy
func SetNamingStrategy(translate func(string) string) { jsoniter.RegisterExtension(&namingStrategyExtension{jsoniter.DummyExtension{}, translate}) }
go
func SetNamingStrategy(translate func(string) string) { jsoniter.RegisterExtension(&namingStrategyExtension{jsoniter.DummyExtension{}, translate}) }
[ "func", "SetNamingStrategy", "(", "translate", "func", "(", "string", ")", "string", ")", "{", "jsoniter", ".", "RegisterExtension", "(", "&", "namingStrategyExtension", "{", "jsoniter", ".", "DummyExtension", "{", "}", ",", "translate", "}", ")", "\n", "}" ]
// SetNamingStrategy rename struct fields uniformly
[ "SetNamingStrategy", "rename", "struct", "fields", "uniformly" ]
0ff49de124c6f76f8494e194af75bde0f1a49a29
https://github.com/json-iterator/go/blob/0ff49de124c6f76f8494e194af75bde0f1a49a29/extra/naming_strategy.go#L10-L12
train
json-iterator/go
extra/naming_strategy.go
LowerCaseWithUnderscores
func LowerCaseWithUnderscores(name string) string { newName := []rune{} for i, c := range name { if i == 0 { newName = append(newName, unicode.ToLower(c)) } else { if unicode.IsUpper(c) { newName = append(newName, '_') newName = append(newName, unicode.ToLower(c)) } else { newName = append(newName, c) } } } return string(newName) }
go
func LowerCaseWithUnderscores(name string) string { newName := []rune{} for i, c := range name { if i == 0 { newName = append(newName, unicode.ToLower(c)) } else { if unicode.IsUpper(c) { newName = append(newName, '_') newName = append(newName, unicode.ToLower(c)) } else { newName = append(newName, c) } } } return string(newName) }
[ "func", "LowerCaseWithUnderscores", "(", "name", "string", ")", "string", "{", "newName", ":=", "[", "]", "rune", "{", "}", "\n", "for", "i", ",", "c", ":=", "range", "name", "{", "if", "i", "==", "0", "{", "newName", "=", "append", "(", "newName", ",", "unicode", ".", "ToLower", "(", "c", ")", ")", "\n", "}", "else", "{", "if", "unicode", ".", "IsUpper", "(", "c", ")", "{", "newName", "=", "append", "(", "newName", ",", "'_'", ")", "\n", "newName", "=", "append", "(", "newName", ",", "unicode", ".", "ToLower", "(", "c", ")", ")", "\n", "}", "else", "{", "newName", "=", "append", "(", "newName", ",", "c", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "string", "(", "newName", ")", "\n", "}" ]
// LowerCaseWithUnderscores one strategy to SetNamingStrategy for. It will change HelloWorld to hello_world.
[ "LowerCaseWithUnderscores", "one", "strategy", "to", "SetNamingStrategy", "for", ".", "It", "will", "change", "HelloWorld", "to", "hello_world", "." ]
0ff49de124c6f76f8494e194af75bde0f1a49a29
https://github.com/json-iterator/go/blob/0ff49de124c6f76f8494e194af75bde0f1a49a29/extra/naming_strategy.go#L37-L52
train
json-iterator/go
config.go
Froze
func (cfg Config) Froze() API { api := &frozenConfig{ sortMapKeys: cfg.SortMapKeys, indentionStep: cfg.IndentionStep, objectFieldMustBeSimpleString: cfg.ObjectFieldMustBeSimpleString, onlyTaggedField: cfg.OnlyTaggedField, disallowUnknownFields: cfg.DisallowUnknownFields, caseSensitive: cfg.CaseSensitive, } api.streamPool = &sync.Pool{ New: func() interface{} { return NewStream(api, nil, 512) }, } api.iteratorPool = &sync.Pool{ New: func() interface{} { return NewIterator(api) }, } api.initCache() encoderExtension := EncoderExtension{} decoderExtension := DecoderExtension{} if cfg.MarshalFloatWith6Digits { api.marshalFloatWith6Digits(encoderExtension) } if cfg.EscapeHTML { api.escapeHTML(encoderExtension) } if cfg.UseNumber { api.useNumber(decoderExtension) } if cfg.ValidateJsonRawMessage { api.validateJsonRawMessage(encoderExtension) } api.encoderExtension = encoderExtension api.decoderExtension = decoderExtension api.configBeforeFrozen = cfg return api }
go
func (cfg Config) Froze() API { api := &frozenConfig{ sortMapKeys: cfg.SortMapKeys, indentionStep: cfg.IndentionStep, objectFieldMustBeSimpleString: cfg.ObjectFieldMustBeSimpleString, onlyTaggedField: cfg.OnlyTaggedField, disallowUnknownFields: cfg.DisallowUnknownFields, caseSensitive: cfg.CaseSensitive, } api.streamPool = &sync.Pool{ New: func() interface{} { return NewStream(api, nil, 512) }, } api.iteratorPool = &sync.Pool{ New: func() interface{} { return NewIterator(api) }, } api.initCache() encoderExtension := EncoderExtension{} decoderExtension := DecoderExtension{} if cfg.MarshalFloatWith6Digits { api.marshalFloatWith6Digits(encoderExtension) } if cfg.EscapeHTML { api.escapeHTML(encoderExtension) } if cfg.UseNumber { api.useNumber(decoderExtension) } if cfg.ValidateJsonRawMessage { api.validateJsonRawMessage(encoderExtension) } api.encoderExtension = encoderExtension api.decoderExtension = decoderExtension api.configBeforeFrozen = cfg return api }
[ "func", "(", "cfg", "Config", ")", "Froze", "(", ")", "API", "{", "api", ":=", "&", "frozenConfig", "{", "sortMapKeys", ":", "cfg", ".", "SortMapKeys", ",", "indentionStep", ":", "cfg", ".", "IndentionStep", ",", "objectFieldMustBeSimpleString", ":", "cfg", ".", "ObjectFieldMustBeSimpleString", ",", "onlyTaggedField", ":", "cfg", ".", "OnlyTaggedField", ",", "disallowUnknownFields", ":", "cfg", ".", "DisallowUnknownFields", ",", "caseSensitive", ":", "cfg", ".", "CaseSensitive", ",", "}", "\n", "api", ".", "streamPool", "=", "&", "sync", ".", "Pool", "{", "New", ":", "func", "(", ")", "interface", "{", "}", "{", "return", "NewStream", "(", "api", ",", "nil", ",", "512", ")", "\n", "}", ",", "}", "\n", "api", ".", "iteratorPool", "=", "&", "sync", ".", "Pool", "{", "New", ":", "func", "(", ")", "interface", "{", "}", "{", "return", "NewIterator", "(", "api", ")", "\n", "}", ",", "}", "\n", "api", ".", "initCache", "(", ")", "\n", "encoderExtension", ":=", "EncoderExtension", "{", "}", "\n", "decoderExtension", ":=", "DecoderExtension", "{", "}", "\n", "if", "cfg", ".", "MarshalFloatWith6Digits", "{", "api", ".", "marshalFloatWith6Digits", "(", "encoderExtension", ")", "\n", "}", "\n", "if", "cfg", ".", "EscapeHTML", "{", "api", ".", "escapeHTML", "(", "encoderExtension", ")", "\n", "}", "\n", "if", "cfg", ".", "UseNumber", "{", "api", ".", "useNumber", "(", "decoderExtension", ")", "\n", "}", "\n", "if", "cfg", ".", "ValidateJsonRawMessage", "{", "api", ".", "validateJsonRawMessage", "(", "encoderExtension", ")", "\n", "}", "\n", "api", ".", "encoderExtension", "=", "encoderExtension", "\n", "api", ".", "decoderExtension", "=", "decoderExtension", "\n", "api", ".", "configBeforeFrozen", "=", "cfg", "\n", "return", "api", "\n", "}" ]
// Froze forge API from config
[ "Froze", "forge", "API", "from", "config" ]
0ff49de124c6f76f8494e194af75bde0f1a49a29
https://github.com/json-iterator/go/blob/0ff49de124c6f76f8494e194af75bde0f1a49a29/config.go#L129-L167
train
json-iterator/go
stream_int.go
WriteUint8
func (stream *Stream) WriteUint8(val uint8) { stream.buf = writeFirstBuf(stream.buf, digits[val]) }
go
func (stream *Stream) WriteUint8(val uint8) { stream.buf = writeFirstBuf(stream.buf, digits[val]) }
[ "func", "(", "stream", "*", "Stream", ")", "WriteUint8", "(", "val", "uint8", ")", "{", "stream", ".", "buf", "=", "writeFirstBuf", "(", "stream", ".", "buf", ",", "digits", "[", "val", "]", ")", "\n", "}" ]
// WriteUint8 write uint8 to stream
[ "WriteUint8", "write", "uint8", "to", "stream" ]
0ff49de124c6f76f8494e194af75bde0f1a49a29
https://github.com/json-iterator/go/blob/0ff49de124c6f76f8494e194af75bde0f1a49a29/stream_int.go#L33-L35
train
json-iterator/go
stream_int.go
WriteInt8
func (stream *Stream) WriteInt8(nval int8) { var val uint8 if nval < 0 { val = uint8(-nval) stream.buf = append(stream.buf, '-') } else { val = uint8(nval) } stream.buf = writeFirstBuf(stream.buf, digits[val]) }
go
func (stream *Stream) WriteInt8(nval int8) { var val uint8 if nval < 0 { val = uint8(-nval) stream.buf = append(stream.buf, '-') } else { val = uint8(nval) } stream.buf = writeFirstBuf(stream.buf, digits[val]) }
[ "func", "(", "stream", "*", "Stream", ")", "WriteInt8", "(", "nval", "int8", ")", "{", "var", "val", "uint8", "\n", "if", "nval", "<", "0", "{", "val", "=", "uint8", "(", "-", "nval", ")", "\n", "stream", ".", "buf", "=", "append", "(", "stream", ".", "buf", ",", "'-'", ")", "\n", "}", "else", "{", "val", "=", "uint8", "(", "nval", ")", "\n", "}", "\n", "stream", ".", "buf", "=", "writeFirstBuf", "(", "stream", ".", "buf", ",", "digits", "[", "val", "]", ")", "\n", "}" ]
// WriteInt8 write int8 to stream
[ "WriteInt8", "write", "int8", "to", "stream" ]
0ff49de124c6f76f8494e194af75bde0f1a49a29
https://github.com/json-iterator/go/blob/0ff49de124c6f76f8494e194af75bde0f1a49a29/stream_int.go#L38-L47
train
json-iterator/go
stream_int.go
WriteUint16
func (stream *Stream) WriteUint16(val uint16) { q1 := val / 1000 if q1 == 0 { stream.buf = writeFirstBuf(stream.buf, digits[val]) return } r1 := val - q1*1000 stream.buf = writeFirstBuf(stream.buf, digits[q1]) stream.buf = writeBuf(stream.buf, digits[r1]) return }
go
func (stream *Stream) WriteUint16(val uint16) { q1 := val / 1000 if q1 == 0 { stream.buf = writeFirstBuf(stream.buf, digits[val]) return } r1 := val - q1*1000 stream.buf = writeFirstBuf(stream.buf, digits[q1]) stream.buf = writeBuf(stream.buf, digits[r1]) return }
[ "func", "(", "stream", "*", "Stream", ")", "WriteUint16", "(", "val", "uint16", ")", "{", "q1", ":=", "val", "/", "1000", "\n", "if", "q1", "==", "0", "{", "stream", ".", "buf", "=", "writeFirstBuf", "(", "stream", ".", "buf", ",", "digits", "[", "val", "]", ")", "\n", "return", "\n", "}", "\n", "r1", ":=", "val", "-", "q1", "*", "1000", "\n", "stream", ".", "buf", "=", "writeFirstBuf", "(", "stream", ".", "buf", ",", "digits", "[", "q1", "]", ")", "\n", "stream", ".", "buf", "=", "writeBuf", "(", "stream", ".", "buf", ",", "digits", "[", "r1", "]", ")", "\n", "return", "\n", "}" ]
// WriteUint16 write uint16 to stream
[ "WriteUint16", "write", "uint16", "to", "stream" ]
0ff49de124c6f76f8494e194af75bde0f1a49a29
https://github.com/json-iterator/go/blob/0ff49de124c6f76f8494e194af75bde0f1a49a29/stream_int.go#L50-L60
train
json-iterator/go
stream_int.go
WriteInt16
func (stream *Stream) WriteInt16(nval int16) { var val uint16 if nval < 0 { val = uint16(-nval) stream.buf = append(stream.buf, '-') } else { val = uint16(nval) } stream.WriteUint16(val) }
go
func (stream *Stream) WriteInt16(nval int16) { var val uint16 if nval < 0 { val = uint16(-nval) stream.buf = append(stream.buf, '-') } else { val = uint16(nval) } stream.WriteUint16(val) }
[ "func", "(", "stream", "*", "Stream", ")", "WriteInt16", "(", "nval", "int16", ")", "{", "var", "val", "uint16", "\n", "if", "nval", "<", "0", "{", "val", "=", "uint16", "(", "-", "nval", ")", "\n", "stream", ".", "buf", "=", "append", "(", "stream", ".", "buf", ",", "'-'", ")", "\n", "}", "else", "{", "val", "=", "uint16", "(", "nval", ")", "\n", "}", "\n", "stream", ".", "WriteUint16", "(", "val", ")", "\n", "}" ]
// WriteInt16 write int16 to stream
[ "WriteInt16", "write", "int16", "to", "stream" ]
0ff49de124c6f76f8494e194af75bde0f1a49a29
https://github.com/json-iterator/go/blob/0ff49de124c6f76f8494e194af75bde0f1a49a29/stream_int.go#L63-L72
train
json-iterator/go
stream_int.go
WriteUint32
func (stream *Stream) WriteUint32(val uint32) { q1 := val / 1000 if q1 == 0 { stream.buf = writeFirstBuf(stream.buf, digits[val]) return } r1 := val - q1*1000 q2 := q1 / 1000 if q2 == 0 { stream.buf = writeFirstBuf(stream.buf, digits[q1]) stream.buf = writeBuf(stream.buf, digits[r1]) return } r2 := q1 - q2*1000 q3 := q2 / 1000 if q3 == 0 { stream.buf = writeFirstBuf(stream.buf, digits[q2]) } else { r3 := q2 - q3*1000 stream.buf = append(stream.buf, byte(q3+'0')) stream.buf = writeBuf(stream.buf, digits[r3]) } stream.buf = writeBuf(stream.buf, digits[r2]) stream.buf = writeBuf(stream.buf, digits[r1]) }
go
func (stream *Stream) WriteUint32(val uint32) { q1 := val / 1000 if q1 == 0 { stream.buf = writeFirstBuf(stream.buf, digits[val]) return } r1 := val - q1*1000 q2 := q1 / 1000 if q2 == 0 { stream.buf = writeFirstBuf(stream.buf, digits[q1]) stream.buf = writeBuf(stream.buf, digits[r1]) return } r2 := q1 - q2*1000 q3 := q2 / 1000 if q3 == 0 { stream.buf = writeFirstBuf(stream.buf, digits[q2]) } else { r3 := q2 - q3*1000 stream.buf = append(stream.buf, byte(q3+'0')) stream.buf = writeBuf(stream.buf, digits[r3]) } stream.buf = writeBuf(stream.buf, digits[r2]) stream.buf = writeBuf(stream.buf, digits[r1]) }
[ "func", "(", "stream", "*", "Stream", ")", "WriteUint32", "(", "val", "uint32", ")", "{", "q1", ":=", "val", "/", "1000", "\n", "if", "q1", "==", "0", "{", "stream", ".", "buf", "=", "writeFirstBuf", "(", "stream", ".", "buf", ",", "digits", "[", "val", "]", ")", "\n", "return", "\n", "}", "\n", "r1", ":=", "val", "-", "q1", "*", "1000", "\n", "q2", ":=", "q1", "/", "1000", "\n", "if", "q2", "==", "0", "{", "stream", ".", "buf", "=", "writeFirstBuf", "(", "stream", ".", "buf", ",", "digits", "[", "q1", "]", ")", "\n", "stream", ".", "buf", "=", "writeBuf", "(", "stream", ".", "buf", ",", "digits", "[", "r1", "]", ")", "\n", "return", "\n", "}", "\n", "r2", ":=", "q1", "-", "q2", "*", "1000", "\n", "q3", ":=", "q2", "/", "1000", "\n", "if", "q3", "==", "0", "{", "stream", ".", "buf", "=", "writeFirstBuf", "(", "stream", ".", "buf", ",", "digits", "[", "q2", "]", ")", "\n", "}", "else", "{", "r3", ":=", "q2", "-", "q3", "*", "1000", "\n", "stream", ".", "buf", "=", "append", "(", "stream", ".", "buf", ",", "byte", "(", "q3", "+", "'0'", ")", ")", "\n", "stream", ".", "buf", "=", "writeBuf", "(", "stream", ".", "buf", ",", "digits", "[", "r3", "]", ")", "\n", "}", "\n", "stream", ".", "buf", "=", "writeBuf", "(", "stream", ".", "buf", ",", "digits", "[", "r2", "]", ")", "\n", "stream", ".", "buf", "=", "writeBuf", "(", "stream", ".", "buf", ",", "digits", "[", "r1", "]", ")", "\n", "}" ]
// WriteUint32 write uint32 to stream
[ "WriteUint32", "write", "uint32", "to", "stream" ]
0ff49de124c6f76f8494e194af75bde0f1a49a29
https://github.com/json-iterator/go/blob/0ff49de124c6f76f8494e194af75bde0f1a49a29/stream_int.go#L75-L99
train
json-iterator/go
stream_int.go
WriteInt32
func (stream *Stream) WriteInt32(nval int32) { var val uint32 if nval < 0 { val = uint32(-nval) stream.buf = append(stream.buf, '-') } else { val = uint32(nval) } stream.WriteUint32(val) }
go
func (stream *Stream) WriteInt32(nval int32) { var val uint32 if nval < 0 { val = uint32(-nval) stream.buf = append(stream.buf, '-') } else { val = uint32(nval) } stream.WriteUint32(val) }
[ "func", "(", "stream", "*", "Stream", ")", "WriteInt32", "(", "nval", "int32", ")", "{", "var", "val", "uint32", "\n", "if", "nval", "<", "0", "{", "val", "=", "uint32", "(", "-", "nval", ")", "\n", "stream", ".", "buf", "=", "append", "(", "stream", ".", "buf", ",", "'-'", ")", "\n", "}", "else", "{", "val", "=", "uint32", "(", "nval", ")", "\n", "}", "\n", "stream", ".", "WriteUint32", "(", "val", ")", "\n", "}" ]
// WriteInt32 write int32 to stream
[ "WriteInt32", "write", "int32", "to", "stream" ]
0ff49de124c6f76f8494e194af75bde0f1a49a29
https://github.com/json-iterator/go/blob/0ff49de124c6f76f8494e194af75bde0f1a49a29/stream_int.go#L102-L111
train
json-iterator/go
stream_int.go
WriteInt64
func (stream *Stream) WriteInt64(nval int64) { var val uint64 if nval < 0 { val = uint64(-nval) stream.buf = append(stream.buf, '-') } else { val = uint64(nval) } stream.WriteUint64(val) }
go
func (stream *Stream) WriteInt64(nval int64) { var val uint64 if nval < 0 { val = uint64(-nval) stream.buf = append(stream.buf, '-') } else { val = uint64(nval) } stream.WriteUint64(val) }
[ "func", "(", "stream", "*", "Stream", ")", "WriteInt64", "(", "nval", "int64", ")", "{", "var", "val", "uint64", "\n", "if", "nval", "<", "0", "{", "val", "=", "uint64", "(", "-", "nval", ")", "\n", "stream", ".", "buf", "=", "append", "(", "stream", ".", "buf", ",", "'-'", ")", "\n", "}", "else", "{", "val", "=", "uint64", "(", "nval", ")", "\n", "}", "\n", "stream", ".", "WriteUint64", "(", "val", ")", "\n", "}" ]
// WriteInt64 write int64 to stream
[ "WriteInt64", "write", "int64", "to", "stream" ]
0ff49de124c6f76f8494e194af75bde0f1a49a29
https://github.com/json-iterator/go/blob/0ff49de124c6f76f8494e194af75bde0f1a49a29/stream_int.go#L171-L180
train
json-iterator/go
reflect.go
ReadVal
func (iter *Iterator) ReadVal(obj interface{}) { cacheKey := reflect2.RTypeOf(obj) decoder := iter.cfg.getDecoderFromCache(cacheKey) if decoder == nil { typ := reflect2.TypeOf(obj) if typ.Kind() != reflect.Ptr { iter.ReportError("ReadVal", "can only unmarshal into pointer") return } decoder = iter.cfg.DecoderOf(typ) } ptr := reflect2.PtrOf(obj) if ptr == nil { iter.ReportError("ReadVal", "can not read into nil pointer") return } decoder.Decode(ptr, iter) }
go
func (iter *Iterator) ReadVal(obj interface{}) { cacheKey := reflect2.RTypeOf(obj) decoder := iter.cfg.getDecoderFromCache(cacheKey) if decoder == nil { typ := reflect2.TypeOf(obj) if typ.Kind() != reflect.Ptr { iter.ReportError("ReadVal", "can only unmarshal into pointer") return } decoder = iter.cfg.DecoderOf(typ) } ptr := reflect2.PtrOf(obj) if ptr == nil { iter.ReportError("ReadVal", "can not read into nil pointer") return } decoder.Decode(ptr, iter) }
[ "func", "(", "iter", "*", "Iterator", ")", "ReadVal", "(", "obj", "interface", "{", "}", ")", "{", "cacheKey", ":=", "reflect2", ".", "RTypeOf", "(", "obj", ")", "\n", "decoder", ":=", "iter", ".", "cfg", ".", "getDecoderFromCache", "(", "cacheKey", ")", "\n", "if", "decoder", "==", "nil", "{", "typ", ":=", "reflect2", ".", "TypeOf", "(", "obj", ")", "\n", "if", "typ", ".", "Kind", "(", ")", "!=", "reflect", ".", "Ptr", "{", "iter", ".", "ReportError", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "return", "\n", "}", "\n", "decoder", "=", "iter", ".", "cfg", ".", "DecoderOf", "(", "typ", ")", "\n", "}", "\n", "ptr", ":=", "reflect2", ".", "PtrOf", "(", "obj", ")", "\n", "if", "ptr", "==", "nil", "{", "iter", ".", "ReportError", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "return", "\n", "}", "\n", "decoder", ".", "Decode", "(", "ptr", ",", "iter", ")", "\n", "}" ]
// ReadVal copy the underlying JSON into go interface, same as json.Unmarshal
[ "ReadVal", "copy", "the", "underlying", "JSON", "into", "go", "interface", "same", "as", "json", ".", "Unmarshal" ]
0ff49de124c6f76f8494e194af75bde0f1a49a29
https://github.com/json-iterator/go/blob/0ff49de124c6f76f8494e194af75bde0f1a49a29/reflect.go#L62-L79
train
json-iterator/go
reflect.go
WriteVal
func (stream *Stream) WriteVal(val interface{}) { if nil == val { stream.WriteNil() return } cacheKey := reflect2.RTypeOf(val) encoder := stream.cfg.getEncoderFromCache(cacheKey) if encoder == nil { typ := reflect2.TypeOf(val) encoder = stream.cfg.EncoderOf(typ) } encoder.Encode(reflect2.PtrOf(val), stream) }
go
func (stream *Stream) WriteVal(val interface{}) { if nil == val { stream.WriteNil() return } cacheKey := reflect2.RTypeOf(val) encoder := stream.cfg.getEncoderFromCache(cacheKey) if encoder == nil { typ := reflect2.TypeOf(val) encoder = stream.cfg.EncoderOf(typ) } encoder.Encode(reflect2.PtrOf(val), stream) }
[ "func", "(", "stream", "*", "Stream", ")", "WriteVal", "(", "val", "interface", "{", "}", ")", "{", "if", "nil", "==", "val", "{", "stream", ".", "WriteNil", "(", ")", "\n", "return", "\n", "}", "\n", "cacheKey", ":=", "reflect2", ".", "RTypeOf", "(", "val", ")", "\n", "encoder", ":=", "stream", ".", "cfg", ".", "getEncoderFromCache", "(", "cacheKey", ")", "\n", "if", "encoder", "==", "nil", "{", "typ", ":=", "reflect2", ".", "TypeOf", "(", "val", ")", "\n", "encoder", "=", "stream", ".", "cfg", ".", "EncoderOf", "(", "typ", ")", "\n", "}", "\n", "encoder", ".", "Encode", "(", "reflect2", ".", "PtrOf", "(", "val", ")", ",", "stream", ")", "\n", "}" ]
// WriteVal copy the go interface into underlying JSON, same as json.Marshal
[ "WriteVal", "copy", "the", "go", "interface", "into", "underlying", "JSON", "same", "as", "json", ".", "Marshal" ]
0ff49de124c6f76f8494e194af75bde0f1a49a29
https://github.com/json-iterator/go/blob/0ff49de124c6f76f8494e194af75bde0f1a49a29/reflect.go#L82-L94
train
json-iterator/go
adapter.go
MarshalIndent
func MarshalIndent(v interface{}, prefix, indent string) ([]byte, error) { return ConfigDefault.MarshalIndent(v, prefix, indent) }
go
func MarshalIndent(v interface{}, prefix, indent string) ([]byte, error) { return ConfigDefault.MarshalIndent(v, prefix, indent) }
[ "func", "MarshalIndent", "(", "v", "interface", "{", "}", ",", "prefix", ",", "indent", "string", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "return", "ConfigDefault", ".", "MarshalIndent", "(", "v", ",", "prefix", ",", "indent", ")", "\n", "}" ]
// MarshalIndent same as json.MarshalIndent. Prefix is not supported.
[ "MarshalIndent", "same", "as", "json", ".", "MarshalIndent", ".", "Prefix", "is", "not", "supported", "." ]
0ff49de124c6f76f8494e194af75bde0f1a49a29
https://github.com/json-iterator/go/blob/0ff49de124c6f76f8494e194af75bde0f1a49a29/adapter.go#L38-L40
train
json-iterator/go
adapter.go
More
func (adapter *Decoder) More() bool { iter := adapter.iter if iter.Error != nil { return false } c := iter.nextToken() if c == 0 { return false } iter.unreadByte() return c != ']' && c != '}' }
go
func (adapter *Decoder) More() bool { iter := adapter.iter if iter.Error != nil { return false } c := iter.nextToken() if c == 0 { return false } iter.unreadByte() return c != ']' && c != '}' }
[ "func", "(", "adapter", "*", "Decoder", ")", "More", "(", ")", "bool", "{", "iter", ":=", "adapter", ".", "iter", "\n", "if", "iter", ".", "Error", "!=", "nil", "{", "return", "false", "\n", "}", "\n", "c", ":=", "iter", ".", "nextToken", "(", ")", "\n", "if", "c", "==", "0", "{", "return", "false", "\n", "}", "\n", "iter", ".", "unreadByte", "(", ")", "\n", "return", "c", "!=", "']'", "&&", "c", "!=", "'}'", "\n", "}" ]
// More is there more?
[ "More", "is", "there", "more?" ]
0ff49de124c6f76f8494e194af75bde0f1a49a29
https://github.com/json-iterator/go/blob/0ff49de124c6f76f8494e194af75bde0f1a49a29/adapter.go#L79-L90
train
json-iterator/go
adapter.go
Buffered
func (adapter *Decoder) Buffered() io.Reader { remaining := adapter.iter.buf[adapter.iter.head:adapter.iter.tail] return bytes.NewReader(remaining) }
go
func (adapter *Decoder) Buffered() io.Reader { remaining := adapter.iter.buf[adapter.iter.head:adapter.iter.tail] return bytes.NewReader(remaining) }
[ "func", "(", "adapter", "*", "Decoder", ")", "Buffered", "(", ")", "io", ".", "Reader", "{", "remaining", ":=", "adapter", ".", "iter", ".", "buf", "[", "adapter", ".", "iter", ".", "head", ":", "adapter", ".", "iter", ".", "tail", "]", "\n", "return", "bytes", ".", "NewReader", "(", "remaining", ")", "\n", "}" ]
// Buffered remaining buffer
[ "Buffered", "remaining", "buffer" ]
0ff49de124c6f76f8494e194af75bde0f1a49a29
https://github.com/json-iterator/go/blob/0ff49de124c6f76f8494e194af75bde0f1a49a29/adapter.go#L93-L96
train
json-iterator/go
adapter.go
SetIndent
func (adapter *Encoder) SetIndent(prefix, indent string) { config := adapter.stream.cfg.configBeforeFrozen config.IndentionStep = len(indent) adapter.stream.cfg = config.frozeWithCacheReuse(adapter.stream.cfg.extraExtensions) }
go
func (adapter *Encoder) SetIndent(prefix, indent string) { config := adapter.stream.cfg.configBeforeFrozen config.IndentionStep = len(indent) adapter.stream.cfg = config.frozeWithCacheReuse(adapter.stream.cfg.extraExtensions) }
[ "func", "(", "adapter", "*", "Encoder", ")", "SetIndent", "(", "prefix", ",", "indent", "string", ")", "{", "config", ":=", "adapter", ".", "stream", ".", "cfg", ".", "configBeforeFrozen", "\n", "config", ".", "IndentionStep", "=", "len", "(", "indent", ")", "\n", "adapter", ".", "stream", ".", "cfg", "=", "config", ".", "frozeWithCacheReuse", "(", "adapter", ".", "stream", ".", "cfg", ".", "extraExtensions", ")", "\n", "}" ]
// SetIndent set the indention. Prefix is not supported
[ "SetIndent", "set", "the", "indention", ".", "Prefix", "is", "not", "supported" ]
0ff49de124c6f76f8494e194af75bde0f1a49a29
https://github.com/json-iterator/go/blob/0ff49de124c6f76f8494e194af75bde0f1a49a29/adapter.go#L134-L138
train
json-iterator/go
adapter.go
SetEscapeHTML
func (adapter *Encoder) SetEscapeHTML(escapeHTML bool) { config := adapter.stream.cfg.configBeforeFrozen config.EscapeHTML = escapeHTML adapter.stream.cfg = config.frozeWithCacheReuse(adapter.stream.cfg.extraExtensions) }
go
func (adapter *Encoder) SetEscapeHTML(escapeHTML bool) { config := adapter.stream.cfg.configBeforeFrozen config.EscapeHTML = escapeHTML adapter.stream.cfg = config.frozeWithCacheReuse(adapter.stream.cfg.extraExtensions) }
[ "func", "(", "adapter", "*", "Encoder", ")", "SetEscapeHTML", "(", "escapeHTML", "bool", ")", "{", "config", ":=", "adapter", ".", "stream", ".", "cfg", ".", "configBeforeFrozen", "\n", "config", ".", "EscapeHTML", "=", "escapeHTML", "\n", "adapter", ".", "stream", ".", "cfg", "=", "config", ".", "frozeWithCacheReuse", "(", "adapter", ".", "stream", ".", "cfg", ".", "extraExtensions", ")", "\n", "}" ]
// SetEscapeHTML escape html by default, set to false to disable
[ "SetEscapeHTML", "escape", "html", "by", "default", "set", "to", "false", "to", "disable" ]
0ff49de124c6f76f8494e194af75bde0f1a49a29
https://github.com/json-iterator/go/blob/0ff49de124c6f76f8494e194af75bde0f1a49a29/adapter.go#L141-L145
train
json-iterator/go
any.go
Wrap
func Wrap(val interface{}) Any { if val == nil { return &nilAny{} } asAny, isAny := val.(Any) if isAny { return asAny } typ := reflect2.TypeOf(val) switch typ.Kind() { case reflect.Slice: return wrapArray(val) case reflect.Struct: return wrapStruct(val) case reflect.Map: return wrapMap(val) case reflect.String: return WrapString(val.(string)) case reflect.Int: if strconv.IntSize == 32 { return WrapInt32(int32(val.(int))) } return WrapInt64(int64(val.(int))) case reflect.Int8: return WrapInt32(int32(val.(int8))) case reflect.Int16: return WrapInt32(int32(val.(int16))) case reflect.Int32: return WrapInt32(val.(int32)) case reflect.Int64: return WrapInt64(val.(int64)) case reflect.Uint: if strconv.IntSize == 32 { return WrapUint32(uint32(val.(uint))) } return WrapUint64(uint64(val.(uint))) case reflect.Uintptr: if ptrSize == 32 { return WrapUint32(uint32(val.(uintptr))) } return WrapUint64(uint64(val.(uintptr))) case reflect.Uint8: return WrapUint32(uint32(val.(uint8))) case reflect.Uint16: return WrapUint32(uint32(val.(uint16))) case reflect.Uint32: return WrapUint32(uint32(val.(uint32))) case reflect.Uint64: return WrapUint64(val.(uint64)) case reflect.Float32: return WrapFloat64(float64(val.(float32))) case reflect.Float64: return WrapFloat64(val.(float64)) case reflect.Bool: if val.(bool) == true { return &trueAny{} } return &falseAny{} } return &invalidAny{baseAny{}, fmt.Errorf("unsupported type: %v", typ)} }
go
func Wrap(val interface{}) Any { if val == nil { return &nilAny{} } asAny, isAny := val.(Any) if isAny { return asAny } typ := reflect2.TypeOf(val) switch typ.Kind() { case reflect.Slice: return wrapArray(val) case reflect.Struct: return wrapStruct(val) case reflect.Map: return wrapMap(val) case reflect.String: return WrapString(val.(string)) case reflect.Int: if strconv.IntSize == 32 { return WrapInt32(int32(val.(int))) } return WrapInt64(int64(val.(int))) case reflect.Int8: return WrapInt32(int32(val.(int8))) case reflect.Int16: return WrapInt32(int32(val.(int16))) case reflect.Int32: return WrapInt32(val.(int32)) case reflect.Int64: return WrapInt64(val.(int64)) case reflect.Uint: if strconv.IntSize == 32 { return WrapUint32(uint32(val.(uint))) } return WrapUint64(uint64(val.(uint))) case reflect.Uintptr: if ptrSize == 32 { return WrapUint32(uint32(val.(uintptr))) } return WrapUint64(uint64(val.(uintptr))) case reflect.Uint8: return WrapUint32(uint32(val.(uint8))) case reflect.Uint16: return WrapUint32(uint32(val.(uint16))) case reflect.Uint32: return WrapUint32(uint32(val.(uint32))) case reflect.Uint64: return WrapUint64(val.(uint64)) case reflect.Float32: return WrapFloat64(float64(val.(float32))) case reflect.Float64: return WrapFloat64(val.(float64)) case reflect.Bool: if val.(bool) == true { return &trueAny{} } return &falseAny{} } return &invalidAny{baseAny{}, fmt.Errorf("unsupported type: %v", typ)} }
[ "func", "Wrap", "(", "val", "interface", "{", "}", ")", "Any", "{", "if", "val", "==", "nil", "{", "return", "&", "nilAny", "{", "}", "\n", "}", "\n", "asAny", ",", "isAny", ":=", "val", ".", "(", "Any", ")", "\n", "if", "isAny", "{", "return", "asAny", "\n", "}", "\n", "typ", ":=", "reflect2", ".", "TypeOf", "(", "val", ")", "\n", "switch", "typ", ".", "Kind", "(", ")", "{", "case", "reflect", ".", "Slice", ":", "return", "wrapArray", "(", "val", ")", "\n", "case", "reflect", ".", "Struct", ":", "return", "wrapStruct", "(", "val", ")", "\n", "case", "reflect", ".", "Map", ":", "return", "wrapMap", "(", "val", ")", "\n", "case", "reflect", ".", "String", ":", "return", "WrapString", "(", "val", ".", "(", "string", ")", ")", "\n", "case", "reflect", ".", "Int", ":", "if", "strconv", ".", "IntSize", "==", "32", "{", "return", "WrapInt32", "(", "int32", "(", "val", ".", "(", "int", ")", ")", ")", "\n", "}", "\n", "return", "WrapInt64", "(", "int64", "(", "val", ".", "(", "int", ")", ")", ")", "\n", "case", "reflect", ".", "Int8", ":", "return", "WrapInt32", "(", "int32", "(", "val", ".", "(", "int8", ")", ")", ")", "\n", "case", "reflect", ".", "Int16", ":", "return", "WrapInt32", "(", "int32", "(", "val", ".", "(", "int16", ")", ")", ")", "\n", "case", "reflect", ".", "Int32", ":", "return", "WrapInt32", "(", "val", ".", "(", "int32", ")", ")", "\n", "case", "reflect", ".", "Int64", ":", "return", "WrapInt64", "(", "val", ".", "(", "int64", ")", ")", "\n", "case", "reflect", ".", "Uint", ":", "if", "strconv", ".", "IntSize", "==", "32", "{", "return", "WrapUint32", "(", "uint32", "(", "val", ".", "(", "uint", ")", ")", ")", "\n", "}", "\n", "return", "WrapUint64", "(", "uint64", "(", "val", ".", "(", "uint", ")", ")", ")", "\n", "case", "reflect", ".", "Uintptr", ":", "if", "ptrSize", "==", "32", "{", "return", "WrapUint32", "(", "uint32", "(", "val", ".", "(", "uintptr", ")", ")", ")", "\n", "}", "\n", "return", "WrapUint64", "(", "uint64", "(", "val", ".", "(", "uintptr", ")", ")", ")", "\n", "case", "reflect", ".", "Uint8", ":", "return", "WrapUint32", "(", "uint32", "(", "val", ".", "(", "uint8", ")", ")", ")", "\n", "case", "reflect", ".", "Uint16", ":", "return", "WrapUint32", "(", "uint32", "(", "val", ".", "(", "uint16", ")", ")", ")", "\n", "case", "reflect", ".", "Uint32", ":", "return", "WrapUint32", "(", "uint32", "(", "val", ".", "(", "uint32", ")", ")", ")", "\n", "case", "reflect", ".", "Uint64", ":", "return", "WrapUint64", "(", "val", ".", "(", "uint64", ")", ")", "\n", "case", "reflect", ".", "Float32", ":", "return", "WrapFloat64", "(", "float64", "(", "val", ".", "(", "float32", ")", ")", ")", "\n", "case", "reflect", ".", "Float64", ":", "return", "WrapFloat64", "(", "val", ".", "(", "float64", ")", ")", "\n", "case", "reflect", ".", "Bool", ":", "if", "val", ".", "(", "bool", ")", "==", "true", "{", "return", "&", "trueAny", "{", "}", "\n", "}", "\n", "return", "&", "falseAny", "{", "}", "\n", "}", "\n", "return", "&", "invalidAny", "{", "baseAny", "{", "}", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "typ", ")", "}", "\n", "}" ]
// Wrap turn a go object into Any interface
[ "Wrap", "turn", "a", "go", "object", "into", "Any", "interface" ]
0ff49de124c6f76f8494e194af75bde0f1a49a29
https://github.com/json-iterator/go/blob/0ff49de124c6f76f8494e194af75bde0f1a49a29/any.go#L86-L146
train
json-iterator/go
iter_skip_sloppy.go
skipNumber
func (iter *Iterator) skipNumber() { for { for i := iter.head; i < iter.tail; i++ { c := iter.buf[i] switch c { case ' ', '\n', '\r', '\t', ',', '}', ']': iter.head = i return } } if !iter.loadMore() { return } } }
go
func (iter *Iterator) skipNumber() { for { for i := iter.head; i < iter.tail; i++ { c := iter.buf[i] switch c { case ' ', '\n', '\r', '\t', ',', '}', ']': iter.head = i return } } if !iter.loadMore() { return } } }
[ "func", "(", "iter", "*", "Iterator", ")", "skipNumber", "(", ")", "{", "for", "{", "for", "i", ":=", "iter", ".", "head", ";", "i", "<", "iter", ".", "tail", ";", "i", "++", "{", "c", ":=", "iter", ".", "buf", "[", "i", "]", "\n", "switch", "c", "{", "case", "' '", ",", "'\\n'", ",", "'\\r'", ",", "'\\t'", ",", "','", ",", "'}'", ",", "']'", ":", "iter", ".", "head", "=", "i", "\n", "return", "\n", "}", "\n", "}", "\n", "if", "!", "iter", ".", "loadMore", "(", ")", "{", "return", "\n", "}", "\n", "}", "\n", "}" ]
// sloppy but faster implementation, do not validate the input json
[ "sloppy", "but", "faster", "implementation", "do", "not", "validate", "the", "input", "json" ]
0ff49de124c6f76f8494e194af75bde0f1a49a29
https://github.com/json-iterator/go/blob/0ff49de124c6f76f8494e194af75bde0f1a49a29/iter_skip_sloppy.go#L7-L21
train
json-iterator/go
stream.go
NewStream
func NewStream(cfg API, out io.Writer, bufSize int) *Stream { return &Stream{ cfg: cfg.(*frozenConfig), out: out, buf: make([]byte, 0, bufSize), Error: nil, indention: 0, } }
go
func NewStream(cfg API, out io.Writer, bufSize int) *Stream { return &Stream{ cfg: cfg.(*frozenConfig), out: out, buf: make([]byte, 0, bufSize), Error: nil, indention: 0, } }
[ "func", "NewStream", "(", "cfg", "API", ",", "out", "io", ".", "Writer", ",", "bufSize", "int", ")", "*", "Stream", "{", "return", "&", "Stream", "{", "cfg", ":", "cfg", ".", "(", "*", "frozenConfig", ")", ",", "out", ":", "out", ",", "buf", ":", "make", "(", "[", "]", "byte", ",", "0", ",", "bufSize", ")", ",", "Error", ":", "nil", ",", "indention", ":", "0", ",", "}", "\n", "}" ]
// NewStream create new stream instance. // cfg can be jsoniter.ConfigDefault. // out can be nil if write to internal buffer. // bufSize is the initial size for the internal buffer in bytes.
[ "NewStream", "create", "new", "stream", "instance", ".", "cfg", "can", "be", "jsoniter", ".", "ConfigDefault", ".", "out", "can", "be", "nil", "if", "write", "to", "internal", "buffer", ".", "bufSize", "is", "the", "initial", "size", "for", "the", "internal", "buffer", "in", "bytes", "." ]
0ff49de124c6f76f8494e194af75bde0f1a49a29
https://github.com/json-iterator/go/blob/0ff49de124c6f76f8494e194af75bde0f1a49a29/stream.go#L22-L30
train
json-iterator/go
stream.go
Reset
func (stream *Stream) Reset(out io.Writer) { stream.out = out stream.buf = stream.buf[:0] }
go
func (stream *Stream) Reset(out io.Writer) { stream.out = out stream.buf = stream.buf[:0] }
[ "func", "(", "stream", "*", "Stream", ")", "Reset", "(", "out", "io", ".", "Writer", ")", "{", "stream", ".", "out", "=", "out", "\n", "stream", ".", "buf", "=", "stream", ".", "buf", "[", ":", "0", "]", "\n", "}" ]
// Reset reuse this stream instance by assign a new writer
[ "Reset", "reuse", "this", "stream", "instance", "by", "assign", "a", "new", "writer" ]
0ff49de124c6f76f8494e194af75bde0f1a49a29
https://github.com/json-iterator/go/blob/0ff49de124c6f76f8494e194af75bde0f1a49a29/stream.go#L38-L41
train
json-iterator/go
stream.go
writeByte
func (stream *Stream) writeByte(c byte) { stream.buf = append(stream.buf, c) }
go
func (stream *Stream) writeByte(c byte) { stream.buf = append(stream.buf, c) }
[ "func", "(", "stream", "*", "Stream", ")", "writeByte", "(", "c", "byte", ")", "{", "stream", ".", "buf", "=", "append", "(", "stream", ".", "buf", ",", "c", ")", "\n", "}" ]
// WriteByte writes a single byte.
[ "WriteByte", "writes", "a", "single", "byte", "." ]
0ff49de124c6f76f8494e194af75bde0f1a49a29
https://github.com/json-iterator/go/blob/0ff49de124c6f76f8494e194af75bde0f1a49a29/stream.go#L78-L80
train
json-iterator/go
stream.go
Flush
func (stream *Stream) Flush() error { if stream.out == nil { return nil } if stream.Error != nil { return stream.Error } n, err := stream.out.Write(stream.buf) if err != nil { if stream.Error == nil { stream.Error = err } return err } stream.buf = stream.buf[n:] return nil }
go
func (stream *Stream) Flush() error { if stream.out == nil { return nil } if stream.Error != nil { return stream.Error } n, err := stream.out.Write(stream.buf) if err != nil { if stream.Error == nil { stream.Error = err } return err } stream.buf = stream.buf[n:] return nil }
[ "func", "(", "stream", "*", "Stream", ")", "Flush", "(", ")", "error", "{", "if", "stream", ".", "out", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "if", "stream", ".", "Error", "!=", "nil", "{", "return", "stream", ".", "Error", "\n", "}", "\n", "n", ",", "err", ":=", "stream", ".", "out", ".", "Write", "(", "stream", ".", "buf", ")", "\n", "if", "err", "!=", "nil", "{", "if", "stream", ".", "Error", "==", "nil", "{", "stream", ".", "Error", "=", "err", "\n", "}", "\n", "return", "err", "\n", "}", "\n", "stream", ".", "buf", "=", "stream", ".", "buf", "[", "n", ":", "]", "\n", "return", "nil", "\n", "}" ]
// Flush writes any buffered data to the underlying io.Writer.
[ "Flush", "writes", "any", "buffered", "data", "to", "the", "underlying", "io", ".", "Writer", "." ]
0ff49de124c6f76f8494e194af75bde0f1a49a29
https://github.com/json-iterator/go/blob/0ff49de124c6f76f8494e194af75bde0f1a49a29/stream.go#L99-L115
train
json-iterator/go
stream.go
WriteBool
func (stream *Stream) WriteBool(val bool) { if val { stream.WriteTrue() } else { stream.WriteFalse() } }
go
func (stream *Stream) WriteBool(val bool) { if val { stream.WriteTrue() } else { stream.WriteFalse() } }
[ "func", "(", "stream", "*", "Stream", ")", "WriteBool", "(", "val", "bool", ")", "{", "if", "val", "{", "stream", ".", "WriteTrue", "(", ")", "\n", "}", "else", "{", "stream", ".", "WriteFalse", "(", ")", "\n", "}", "\n", "}" ]
// WriteBool write true or false into stream
[ "WriteBool", "write", "true", "or", "false", "into", "stream" ]
0ff49de124c6f76f8494e194af75bde0f1a49a29
https://github.com/json-iterator/go/blob/0ff49de124c6f76f8494e194af75bde0f1a49a29/stream.go#L138-L144
train
json-iterator/go
stream.go
WriteObjectStart
func (stream *Stream) WriteObjectStart() { stream.indention += stream.cfg.indentionStep stream.writeByte('{') stream.writeIndention(0) }
go
func (stream *Stream) WriteObjectStart() { stream.indention += stream.cfg.indentionStep stream.writeByte('{') stream.writeIndention(0) }
[ "func", "(", "stream", "*", "Stream", ")", "WriteObjectStart", "(", ")", "{", "stream", ".", "indention", "+=", "stream", ".", "cfg", ".", "indentionStep", "\n", "stream", ".", "writeByte", "(", "'{'", ")", "\n", "stream", ".", "writeIndention", "(", "0", ")", "\n", "}" ]
// WriteObjectStart write { with possible indention
[ "WriteObjectStart", "write", "{", "with", "possible", "indention" ]
0ff49de124c6f76f8494e194af75bde0f1a49a29
https://github.com/json-iterator/go/blob/0ff49de124c6f76f8494e194af75bde0f1a49a29/stream.go#L147-L151
train
json-iterator/go
stream.go
WriteObjectEnd
func (stream *Stream) WriteObjectEnd() { stream.writeIndention(stream.cfg.indentionStep) stream.indention -= stream.cfg.indentionStep stream.writeByte('}') }
go
func (stream *Stream) WriteObjectEnd() { stream.writeIndention(stream.cfg.indentionStep) stream.indention -= stream.cfg.indentionStep stream.writeByte('}') }
[ "func", "(", "stream", "*", "Stream", ")", "WriteObjectEnd", "(", ")", "{", "stream", ".", "writeIndention", "(", "stream", ".", "cfg", ".", "indentionStep", ")", "\n", "stream", ".", "indention", "-=", "stream", ".", "cfg", ".", "indentionStep", "\n", "stream", ".", "writeByte", "(", "'}'", ")", "\n", "}" ]
// WriteObjectEnd write } with possible indention
[ "WriteObjectEnd", "write", "}", "with", "possible", "indention" ]
0ff49de124c6f76f8494e194af75bde0f1a49a29
https://github.com/json-iterator/go/blob/0ff49de124c6f76f8494e194af75bde0f1a49a29/stream.go#L164-L168
train
json-iterator/go
stream.go
WriteArrayStart
func (stream *Stream) WriteArrayStart() { stream.indention += stream.cfg.indentionStep stream.writeByte('[') stream.writeIndention(0) }
go
func (stream *Stream) WriteArrayStart() { stream.indention += stream.cfg.indentionStep stream.writeByte('[') stream.writeIndention(0) }
[ "func", "(", "stream", "*", "Stream", ")", "WriteArrayStart", "(", ")", "{", "stream", ".", "indention", "+=", "stream", ".", "cfg", ".", "indentionStep", "\n", "stream", ".", "writeByte", "(", "'['", ")", "\n", "stream", ".", "writeIndention", "(", "0", ")", "\n", "}" ]
// WriteArrayStart write [ with possible indention
[ "WriteArrayStart", "write", "[", "with", "possible", "indention" ]
0ff49de124c6f76f8494e194af75bde0f1a49a29
https://github.com/json-iterator/go/blob/0ff49de124c6f76f8494e194af75bde0f1a49a29/stream.go#L184-L188
train
json-iterator/go
stream.go
WriteArrayEnd
func (stream *Stream) WriteArrayEnd() { stream.writeIndention(stream.cfg.indentionStep) stream.indention -= stream.cfg.indentionStep stream.writeByte(']') }
go
func (stream *Stream) WriteArrayEnd() { stream.writeIndention(stream.cfg.indentionStep) stream.indention -= stream.cfg.indentionStep stream.writeByte(']') }
[ "func", "(", "stream", "*", "Stream", ")", "WriteArrayEnd", "(", ")", "{", "stream", ".", "writeIndention", "(", "stream", ".", "cfg", ".", "indentionStep", ")", "\n", "stream", ".", "indention", "-=", "stream", ".", "cfg", ".", "indentionStep", "\n", "stream", ".", "writeByte", "(", "']'", ")", "\n", "}" ]
// WriteArrayEnd write ] with possible indention
[ "WriteArrayEnd", "write", "]", "with", "possible", "indention" ]
0ff49de124c6f76f8494e194af75bde0f1a49a29
https://github.com/json-iterator/go/blob/0ff49de124c6f76f8494e194af75bde0f1a49a29/stream.go#L196-L200
train
json-iterator/go
iter_str.go
ReadString
func (iter *Iterator) ReadString() (ret string) { c := iter.nextToken() if c == '"' { for i := iter.head; i < iter.tail; i++ { c := iter.buf[i] if c == '"' { ret = string(iter.buf[iter.head:i]) iter.head = i + 1 return ret } else if c == '\\' { break } else if c < ' ' { iter.ReportError("ReadString", fmt.Sprintf(`invalid control character found: %d`, c)) return } } return iter.readStringSlowPath() } else if c == 'n' { iter.skipThreeBytes('u', 'l', 'l') return "" } iter.ReportError("ReadString", `expects " or n, but found `+string([]byte{c})) return }
go
func (iter *Iterator) ReadString() (ret string) { c := iter.nextToken() if c == '"' { for i := iter.head; i < iter.tail; i++ { c := iter.buf[i] if c == '"' { ret = string(iter.buf[iter.head:i]) iter.head = i + 1 return ret } else if c == '\\' { break } else if c < ' ' { iter.ReportError("ReadString", fmt.Sprintf(`invalid control character found: %d`, c)) return } } return iter.readStringSlowPath() } else if c == 'n' { iter.skipThreeBytes('u', 'l', 'l') return "" } iter.ReportError("ReadString", `expects " or n, but found `+string([]byte{c})) return }
[ "func", "(", "iter", "*", "Iterator", ")", "ReadString", "(", ")", "(", "ret", "string", ")", "{", "c", ":=", "iter", ".", "nextToken", "(", ")", "\n", "if", "c", "==", "'\"'", "{", "for", "i", ":=", "iter", ".", "head", ";", "i", "<", "iter", ".", "tail", ";", "i", "++", "{", "c", ":=", "iter", ".", "buf", "[", "i", "]", "\n", "if", "c", "==", "'\"'", "{", "ret", "=", "string", "(", "iter", ".", "buf", "[", "iter", ".", "head", ":", "i", "]", ")", "\n", "iter", ".", "head", "=", "i", "+", "1", "\n", "return", "ret", "\n", "}", "else", "if", "c", "==", "'\\\\'", "{", "break", "\n", "}", "else", "if", "c", "<", "' '", "{", "iter", ".", "ReportError", "(", "\"", "\"", ",", "fmt", ".", "Sprintf", "(", "`invalid control character found: %d`", ",", "c", ")", ")", "\n", "return", "\n", "}", "\n", "}", "\n", "return", "iter", ".", "readStringSlowPath", "(", ")", "\n", "}", "else", "if", "c", "==", "'n'", "{", "iter", ".", "skipThreeBytes", "(", "'u'", ",", "'l'", ",", "'l'", ")", "\n", "return", "\"", "\"", "\n", "}", "\n", "iter", ".", "ReportError", "(", "\"", "\"", ",", "`expects \" or n, but found `", "+", "string", "(", "[", "]", "byte", "{", "c", "}", ")", ")", "\n", "return", "\n", "}" ]
// ReadString read string from iterator
[ "ReadString", "read", "string", "from", "iterator" ]
0ff49de124c6f76f8494e194af75bde0f1a49a29
https://github.com/json-iterator/go/blob/0ff49de124c6f76f8494e194af75bde0f1a49a29/iter_str.go#L9-L33
train
json-iterator/go
iter_object.go
ReadObject
func (iter *Iterator) ReadObject() (ret string) { c := iter.nextToken() switch c { case 'n': iter.skipThreeBytes('u', 'l', 'l') return "" // null case '{': c = iter.nextToken() if c == '"' { iter.unreadByte() field := iter.ReadString() c = iter.nextToken() if c != ':' { iter.ReportError("ReadObject", "expect : after object field, but found "+string([]byte{c})) } return field } if c == '}' { return "" // end of object } iter.ReportError("ReadObject", `expect " after {, but found `+string([]byte{c})) return case ',': field := iter.ReadString() c = iter.nextToken() if c != ':' { iter.ReportError("ReadObject", "expect : after object field, but found "+string([]byte{c})) } return field case '}': return "" // end of object default: iter.ReportError("ReadObject", fmt.Sprintf(`expect { or , or } or n, but found %s`, string([]byte{c}))) return } }
go
func (iter *Iterator) ReadObject() (ret string) { c := iter.nextToken() switch c { case 'n': iter.skipThreeBytes('u', 'l', 'l') return "" // null case '{': c = iter.nextToken() if c == '"' { iter.unreadByte() field := iter.ReadString() c = iter.nextToken() if c != ':' { iter.ReportError("ReadObject", "expect : after object field, but found "+string([]byte{c})) } return field } if c == '}' { return "" // end of object } iter.ReportError("ReadObject", `expect " after {, but found `+string([]byte{c})) return case ',': field := iter.ReadString() c = iter.nextToken() if c != ':' { iter.ReportError("ReadObject", "expect : after object field, but found "+string([]byte{c})) } return field case '}': return "" // end of object default: iter.ReportError("ReadObject", fmt.Sprintf(`expect { or , or } or n, but found %s`, string([]byte{c}))) return } }
[ "func", "(", "iter", "*", "Iterator", ")", "ReadObject", "(", ")", "(", "ret", "string", ")", "{", "c", ":=", "iter", ".", "nextToken", "(", ")", "\n", "switch", "c", "{", "case", "'n'", ":", "iter", ".", "skipThreeBytes", "(", "'u'", ",", "'l'", ",", "'l'", ")", "\n", "return", "\"", "\"", "// null", "\n", "case", "'{'", ":", "c", "=", "iter", ".", "nextToken", "(", ")", "\n", "if", "c", "==", "'\"'", "{", "iter", ".", "unreadByte", "(", ")", "\n", "field", ":=", "iter", ".", "ReadString", "(", ")", "\n", "c", "=", "iter", ".", "nextToken", "(", ")", "\n", "if", "c", "!=", "':'", "{", "iter", ".", "ReportError", "(", "\"", "\"", ",", "\"", "\"", "+", "string", "(", "[", "]", "byte", "{", "c", "}", ")", ")", "\n", "}", "\n", "return", "field", "\n", "}", "\n", "if", "c", "==", "'}'", "{", "return", "\"", "\"", "// end of object", "\n", "}", "\n", "iter", ".", "ReportError", "(", "\"", "\"", ",", "`expect \" after {, but found `", "+", "string", "(", "[", "]", "byte", "{", "c", "}", ")", ")", "\n", "return", "\n", "case", "','", ":", "field", ":=", "iter", ".", "ReadString", "(", ")", "\n", "c", "=", "iter", ".", "nextToken", "(", ")", "\n", "if", "c", "!=", "':'", "{", "iter", ".", "ReportError", "(", "\"", "\"", ",", "\"", "\"", "+", "string", "(", "[", "]", "byte", "{", "c", "}", ")", ")", "\n", "}", "\n", "return", "field", "\n", "case", "'}'", ":", "return", "\"", "\"", "// end of object", "\n", "default", ":", "iter", ".", "ReportError", "(", "\"", "\"", ",", "fmt", ".", "Sprintf", "(", "`expect { or , or } or n, but found %s`", ",", "string", "(", "[", "]", "byte", "{", "c", "}", ")", ")", ")", "\n", "return", "\n", "}", "\n", "}" ]
// ReadObject read one field from object. // If object ended, returns empty string. // Otherwise, returns the field name.
[ "ReadObject", "read", "one", "field", "from", "object", ".", "If", "object", "ended", "returns", "empty", "string", ".", "Otherwise", "returns", "the", "field", "name", "." ]
0ff49de124c6f76f8494e194af75bde0f1a49a29
https://github.com/json-iterator/go/blob/0ff49de124c6f76f8494e194af75bde0f1a49a29/iter_object.go#L11-L46
train
json-iterator/go
iter_object.go
ReadObjectCB
func (iter *Iterator) ReadObjectCB(callback func(*Iterator, string) bool) bool { c := iter.nextToken() var field string if c == '{' { c = iter.nextToken() if c == '"' { iter.unreadByte() field = iter.ReadString() c = iter.nextToken() if c != ':' { iter.ReportError("ReadObject", "expect : after object field, but found "+string([]byte{c})) } if !callback(iter, field) { return false } c = iter.nextToken() for c == ',' { field = iter.ReadString() c = iter.nextToken() if c != ':' { iter.ReportError("ReadObject", "expect : after object field, but found "+string([]byte{c})) } if !callback(iter, field) { return false } c = iter.nextToken() } if c != '}' { iter.ReportError("ReadObjectCB", `object not ended with }`) return false } return true } if c == '}' { return true } iter.ReportError("ReadObjectCB", `expect " after }, but found `+string([]byte{c})) return false } if c == 'n' { iter.skipThreeBytes('u', 'l', 'l') return true // null } iter.ReportError("ReadObjectCB", `expect { or n, but found `+string([]byte{c})) return false }
go
func (iter *Iterator) ReadObjectCB(callback func(*Iterator, string) bool) bool { c := iter.nextToken() var field string if c == '{' { c = iter.nextToken() if c == '"' { iter.unreadByte() field = iter.ReadString() c = iter.nextToken() if c != ':' { iter.ReportError("ReadObject", "expect : after object field, but found "+string([]byte{c})) } if !callback(iter, field) { return false } c = iter.nextToken() for c == ',' { field = iter.ReadString() c = iter.nextToken() if c != ':' { iter.ReportError("ReadObject", "expect : after object field, but found "+string([]byte{c})) } if !callback(iter, field) { return false } c = iter.nextToken() } if c != '}' { iter.ReportError("ReadObjectCB", `object not ended with }`) return false } return true } if c == '}' { return true } iter.ReportError("ReadObjectCB", `expect " after }, but found `+string([]byte{c})) return false } if c == 'n' { iter.skipThreeBytes('u', 'l', 'l') return true // null } iter.ReportError("ReadObjectCB", `expect { or n, but found `+string([]byte{c})) return false }
[ "func", "(", "iter", "*", "Iterator", ")", "ReadObjectCB", "(", "callback", "func", "(", "*", "Iterator", ",", "string", ")", "bool", ")", "bool", "{", "c", ":=", "iter", ".", "nextToken", "(", ")", "\n", "var", "field", "string", "\n", "if", "c", "==", "'{'", "{", "c", "=", "iter", ".", "nextToken", "(", ")", "\n", "if", "c", "==", "'\"'", "{", "iter", ".", "unreadByte", "(", ")", "\n", "field", "=", "iter", ".", "ReadString", "(", ")", "\n", "c", "=", "iter", ".", "nextToken", "(", ")", "\n", "if", "c", "!=", "':'", "{", "iter", ".", "ReportError", "(", "\"", "\"", ",", "\"", "\"", "+", "string", "(", "[", "]", "byte", "{", "c", "}", ")", ")", "\n", "}", "\n", "if", "!", "callback", "(", "iter", ",", "field", ")", "{", "return", "false", "\n", "}", "\n", "c", "=", "iter", ".", "nextToken", "(", ")", "\n", "for", "c", "==", "','", "{", "field", "=", "iter", ".", "ReadString", "(", ")", "\n", "c", "=", "iter", ".", "nextToken", "(", ")", "\n", "if", "c", "!=", "':'", "{", "iter", ".", "ReportError", "(", "\"", "\"", ",", "\"", "\"", "+", "string", "(", "[", "]", "byte", "{", "c", "}", ")", ")", "\n", "}", "\n", "if", "!", "callback", "(", "iter", ",", "field", ")", "{", "return", "false", "\n", "}", "\n", "c", "=", "iter", ".", "nextToken", "(", ")", "\n", "}", "\n", "if", "c", "!=", "'}'", "{", "iter", ".", "ReportError", "(", "\"", "\"", ",", "`object not ended with }`", ")", "\n", "return", "false", "\n", "}", "\n", "return", "true", "\n", "}", "\n", "if", "c", "==", "'}'", "{", "return", "true", "\n", "}", "\n", "iter", ".", "ReportError", "(", "\"", "\"", ",", "`expect \" after }, but found `", "+", "string", "(", "[", "]", "byte", "{", "c", "}", ")", ")", "\n", "return", "false", "\n", "}", "\n", "if", "c", "==", "'n'", "{", "iter", ".", "skipThreeBytes", "(", "'u'", ",", "'l'", ",", "'l'", ")", "\n", "return", "true", "// null", "\n", "}", "\n", "iter", ".", "ReportError", "(", "\"", "\"", ",", "`expect { or n, but found `", "+", "string", "(", "[", "]", "byte", "{", "c", "}", ")", ")", "\n", "return", "false", "\n", "}" ]
// ReadObjectCB read object with callback, the key is ascii only and field name not copied
[ "ReadObjectCB", "read", "object", "with", "callback", "the", "key", "is", "ascii", "only", "and", "field", "name", "not", "copied" ]
0ff49de124c6f76f8494e194af75bde0f1a49a29
https://github.com/json-iterator/go/blob/0ff49de124c6f76f8494e194af75bde0f1a49a29/iter_object.go#L111-L156
train
json-iterator/go
stream_str.go
WriteStringWithHTMLEscaped
func (stream *Stream) WriteStringWithHTMLEscaped(s string) { valLen := len(s) stream.buf = append(stream.buf, '"') // write string, the fast path, without utf8 and escape support i := 0 for ; i < valLen; i++ { c := s[i] if c < utf8.RuneSelf && htmlSafeSet[c] { stream.buf = append(stream.buf, c) } else { break } } if i == valLen { stream.buf = append(stream.buf, '"') return } writeStringSlowPathWithHTMLEscaped(stream, i, s, valLen) }
go
func (stream *Stream) WriteStringWithHTMLEscaped(s string) { valLen := len(s) stream.buf = append(stream.buf, '"') // write string, the fast path, without utf8 and escape support i := 0 for ; i < valLen; i++ { c := s[i] if c < utf8.RuneSelf && htmlSafeSet[c] { stream.buf = append(stream.buf, c) } else { break } } if i == valLen { stream.buf = append(stream.buf, '"') return } writeStringSlowPathWithHTMLEscaped(stream, i, s, valLen) }
[ "func", "(", "stream", "*", "Stream", ")", "WriteStringWithHTMLEscaped", "(", "s", "string", ")", "{", "valLen", ":=", "len", "(", "s", ")", "\n", "stream", ".", "buf", "=", "append", "(", "stream", ".", "buf", ",", "'\"'", ")", "\n", "// write string, the fast path, without utf8 and escape support", "i", ":=", "0", "\n", "for", ";", "i", "<", "valLen", ";", "i", "++", "{", "c", ":=", "s", "[", "i", "]", "\n", "if", "c", "<", "utf8", ".", "RuneSelf", "&&", "htmlSafeSet", "[", "c", "]", "{", "stream", ".", "buf", "=", "append", "(", "stream", ".", "buf", ",", "c", ")", "\n", "}", "else", "{", "break", "\n", "}", "\n", "}", "\n", "if", "i", "==", "valLen", "{", "stream", ".", "buf", "=", "append", "(", "stream", ".", "buf", ",", "'\"'", ")", "\n", "return", "\n", "}", "\n", "writeStringSlowPathWithHTMLEscaped", "(", "stream", ",", "i", ",", "s", ",", "valLen", ")", "\n", "}" ]
// WriteStringWithHTMLEscaped write string to stream with html special characters escaped
[ "WriteStringWithHTMLEscaped", "write", "string", "to", "stream", "with", "html", "special", "characters", "escaped" ]
0ff49de124c6f76f8494e194af75bde0f1a49a29
https://github.com/json-iterator/go/blob/0ff49de124c6f76f8494e194af75bde0f1a49a29/stream_str.go#L221-L239
train
json-iterator/go
stream_str.go
WriteString
func (stream *Stream) WriteString(s string) { valLen := len(s) stream.buf = append(stream.buf, '"') // write string, the fast path, without utf8 and escape support i := 0 for ; i < valLen; i++ { c := s[i] if c > 31 && c != '"' && c != '\\' { stream.buf = append(stream.buf, c) } else { break } } if i == valLen { stream.buf = append(stream.buf, '"') return } writeStringSlowPath(stream, i, s, valLen) }
go
func (stream *Stream) WriteString(s string) { valLen := len(s) stream.buf = append(stream.buf, '"') // write string, the fast path, without utf8 and escape support i := 0 for ; i < valLen; i++ { c := s[i] if c > 31 && c != '"' && c != '\\' { stream.buf = append(stream.buf, c) } else { break } } if i == valLen { stream.buf = append(stream.buf, '"') return } writeStringSlowPath(stream, i, s, valLen) }
[ "func", "(", "stream", "*", "Stream", ")", "WriteString", "(", "s", "string", ")", "{", "valLen", ":=", "len", "(", "s", ")", "\n", "stream", ".", "buf", "=", "append", "(", "stream", ".", "buf", ",", "'\"'", ")", "\n", "// write string, the fast path, without utf8 and escape support", "i", ":=", "0", "\n", "for", ";", "i", "<", "valLen", ";", "i", "++", "{", "c", ":=", "s", "[", "i", "]", "\n", "if", "c", ">", "31", "&&", "c", "!=", "'\"'", "&&", "c", "!=", "'\\\\'", "{", "stream", ".", "buf", "=", "append", "(", "stream", ".", "buf", ",", "c", ")", "\n", "}", "else", "{", "break", "\n", "}", "\n", "}", "\n", "if", "i", "==", "valLen", "{", "stream", ".", "buf", "=", "append", "(", "stream", ".", "buf", ",", "'\"'", ")", "\n", "return", "\n", "}", "\n", "writeStringSlowPath", "(", "stream", ",", "i", ",", "s", ",", "valLen", ")", "\n", "}" ]
// WriteString write string to stream without html escape
[ "WriteString", "write", "string", "to", "stream", "without", "html", "escape" ]
0ff49de124c6f76f8494e194af75bde0f1a49a29
https://github.com/json-iterator/go/blob/0ff49de124c6f76f8494e194af75bde0f1a49a29/stream_str.go#L311-L329
train
json-iterator/go
reflect_extension.go
GetField
func (structDescriptor *StructDescriptor) GetField(fieldName string) *Binding { for _, binding := range structDescriptor.Fields { if binding.Field.Name() == fieldName { return binding } } return nil }
go
func (structDescriptor *StructDescriptor) GetField(fieldName string) *Binding { for _, binding := range structDescriptor.Fields { if binding.Field.Name() == fieldName { return binding } } return nil }
[ "func", "(", "structDescriptor", "*", "StructDescriptor", ")", "GetField", "(", "fieldName", "string", ")", "*", "Binding", "{", "for", "_", ",", "binding", ":=", "range", "structDescriptor", ".", "Fields", "{", "if", "binding", ".", "Field", ".", "Name", "(", ")", "==", "fieldName", "{", "return", "binding", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// GetField get one field from the descriptor by its name. // Can not use map here to keep field orders.
[ "GetField", "get", "one", "field", "from", "the", "descriptor", "by", "its", "name", ".", "Can", "not", "use", "map", "here", "to", "keep", "field", "orders", "." ]
0ff49de124c6f76f8494e194af75bde0f1a49a29
https://github.com/json-iterator/go/blob/0ff49de124c6f76f8494e194af75bde0f1a49a29/reflect_extension.go#L27-L34
train
json-iterator/go
reflect_extension.go
RegisterFieldDecoderFunc
func RegisterFieldDecoderFunc(typ string, field string, fun DecoderFunc) { RegisterFieldDecoder(typ, field, &funcDecoder{fun}) }
go
func RegisterFieldDecoderFunc(typ string, field string, fun DecoderFunc) { RegisterFieldDecoder(typ, field, &funcDecoder{fun}) }
[ "func", "RegisterFieldDecoderFunc", "(", "typ", "string", ",", "field", "string", ",", "fun", "DecoderFunc", ")", "{", "RegisterFieldDecoder", "(", "typ", ",", "field", ",", "&", "funcDecoder", "{", "fun", "}", ")", "\n", "}" ]
// RegisterFieldDecoderFunc register TypeDecoder for a struct field with function
[ "RegisterFieldDecoderFunc", "register", "TypeDecoder", "for", "a", "struct", "field", "with", "function" ]
0ff49de124c6f76f8494e194af75bde0f1a49a29
https://github.com/json-iterator/go/blob/0ff49de124c6f76f8494e194af75bde0f1a49a29/reflect_extension.go#L209-L211
train
json-iterator/go
reflect_extension.go
RegisterFieldDecoder
func RegisterFieldDecoder(typ string, field string, decoder ValDecoder) { fieldDecoders[fmt.Sprintf("%s/%s", typ, field)] = decoder }
go
func RegisterFieldDecoder(typ string, field string, decoder ValDecoder) { fieldDecoders[fmt.Sprintf("%s/%s", typ, field)] = decoder }
[ "func", "RegisterFieldDecoder", "(", "typ", "string", ",", "field", "string", ",", "decoder", "ValDecoder", ")", "{", "fieldDecoders", "[", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "typ", ",", "field", ")", "]", "=", "decoder", "\n", "}" ]
// RegisterFieldDecoder register TypeDecoder for a struct field
[ "RegisterFieldDecoder", "register", "TypeDecoder", "for", "a", "struct", "field" ]
0ff49de124c6f76f8494e194af75bde0f1a49a29
https://github.com/json-iterator/go/blob/0ff49de124c6f76f8494e194af75bde0f1a49a29/reflect_extension.go#L214-L216
train
json-iterator/go
reflect_extension.go
RegisterFieldEncoder
func RegisterFieldEncoder(typ string, field string, encoder ValEncoder) { fieldEncoders[fmt.Sprintf("%s/%s", typ, field)] = encoder }
go
func RegisterFieldEncoder(typ string, field string, encoder ValEncoder) { fieldEncoders[fmt.Sprintf("%s/%s", typ, field)] = encoder }
[ "func", "RegisterFieldEncoder", "(", "typ", "string", ",", "field", "string", ",", "encoder", "ValEncoder", ")", "{", "fieldEncoders", "[", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "typ", ",", "field", ")", "]", "=", "encoder", "\n", "}" ]
// RegisterFieldEncoder register TypeEncoder for a struct field
[ "RegisterFieldEncoder", "register", "TypeEncoder", "for", "a", "struct", "field" ]
0ff49de124c6f76f8494e194af75bde0f1a49a29
https://github.com/json-iterator/go/blob/0ff49de124c6f76f8494e194af75bde0f1a49a29/reflect_extension.go#L234-L236
train
json-iterator/go
iter_float.go
ReadBigFloat
func (iter *Iterator) ReadBigFloat() (ret *big.Float) { str := iter.readNumberAsString() if iter.Error != nil && iter.Error != io.EOF { return nil } prec := 64 if len(str) > prec { prec = len(str) } val, _, err := big.ParseFloat(str, 10, uint(prec), big.ToZero) if err != nil { iter.Error = err return nil } return val }
go
func (iter *Iterator) ReadBigFloat() (ret *big.Float) { str := iter.readNumberAsString() if iter.Error != nil && iter.Error != io.EOF { return nil } prec := 64 if len(str) > prec { prec = len(str) } val, _, err := big.ParseFloat(str, 10, uint(prec), big.ToZero) if err != nil { iter.Error = err return nil } return val }
[ "func", "(", "iter", "*", "Iterator", ")", "ReadBigFloat", "(", ")", "(", "ret", "*", "big", ".", "Float", ")", "{", "str", ":=", "iter", ".", "readNumberAsString", "(", ")", "\n", "if", "iter", ".", "Error", "!=", "nil", "&&", "iter", ".", "Error", "!=", "io", ".", "EOF", "{", "return", "nil", "\n", "}", "\n", "prec", ":=", "64", "\n", "if", "len", "(", "str", ")", ">", "prec", "{", "prec", "=", "len", "(", "str", ")", "\n", "}", "\n", "val", ",", "_", ",", "err", ":=", "big", ".", "ParseFloat", "(", "str", ",", "10", ",", "uint", "(", "prec", ")", ",", "big", ".", "ToZero", ")", "\n", "if", "err", "!=", "nil", "{", "iter", ".", "Error", "=", "err", "\n", "return", "nil", "\n", "}", "\n", "return", "val", "\n", "}" ]
// ReadBigFloat read big.Float
[ "ReadBigFloat", "read", "big", ".", "Float" ]
0ff49de124c6f76f8494e194af75bde0f1a49a29
https://github.com/json-iterator/go/blob/0ff49de124c6f76f8494e194af75bde0f1a49a29/iter_float.go#L36-L51
train
json-iterator/go
iter_float.go
ReadBigInt
func (iter *Iterator) ReadBigInt() (ret *big.Int) { str := iter.readNumberAsString() if iter.Error != nil && iter.Error != io.EOF { return nil } ret = big.NewInt(0) var success bool ret, success = ret.SetString(str, 10) if !success { iter.ReportError("ReadBigInt", "invalid big int") return nil } return ret }
go
func (iter *Iterator) ReadBigInt() (ret *big.Int) { str := iter.readNumberAsString() if iter.Error != nil && iter.Error != io.EOF { return nil } ret = big.NewInt(0) var success bool ret, success = ret.SetString(str, 10) if !success { iter.ReportError("ReadBigInt", "invalid big int") return nil } return ret }
[ "func", "(", "iter", "*", "Iterator", ")", "ReadBigInt", "(", ")", "(", "ret", "*", "big", ".", "Int", ")", "{", "str", ":=", "iter", ".", "readNumberAsString", "(", ")", "\n", "if", "iter", ".", "Error", "!=", "nil", "&&", "iter", ".", "Error", "!=", "io", ".", "EOF", "{", "return", "nil", "\n", "}", "\n", "ret", "=", "big", ".", "NewInt", "(", "0", ")", "\n", "var", "success", "bool", "\n", "ret", ",", "success", "=", "ret", ".", "SetString", "(", "str", ",", "10", ")", "\n", "if", "!", "success", "{", "iter", ".", "ReportError", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "return", "nil", "\n", "}", "\n", "return", "ret", "\n", "}" ]
// ReadBigInt read big.Int
[ "ReadBigInt", "read", "big", ".", "Int" ]
0ff49de124c6f76f8494e194af75bde0f1a49a29
https://github.com/json-iterator/go/blob/0ff49de124c6f76f8494e194af75bde0f1a49a29/iter_float.go#L54-L67
train
json-iterator/go
iter_float.go
ReadFloat32
func (iter *Iterator) ReadFloat32() (ret float32) { c := iter.nextToken() if c == '-' { return -iter.readPositiveFloat32() } iter.unreadByte() return iter.readPositiveFloat32() }
go
func (iter *Iterator) ReadFloat32() (ret float32) { c := iter.nextToken() if c == '-' { return -iter.readPositiveFloat32() } iter.unreadByte() return iter.readPositiveFloat32() }
[ "func", "(", "iter", "*", "Iterator", ")", "ReadFloat32", "(", ")", "(", "ret", "float32", ")", "{", "c", ":=", "iter", ".", "nextToken", "(", ")", "\n", "if", "c", "==", "'-'", "{", "return", "-", "iter", ".", "readPositiveFloat32", "(", ")", "\n", "}", "\n", "iter", ".", "unreadByte", "(", ")", "\n", "return", "iter", ".", "readPositiveFloat32", "(", ")", "\n", "}" ]
//ReadFloat32 read float32
[ "ReadFloat32", "read", "float32" ]
0ff49de124c6f76f8494e194af75bde0f1a49a29
https://github.com/json-iterator/go/blob/0ff49de124c6f76f8494e194af75bde0f1a49a29/iter_float.go#L70-L77
train
json-iterator/go
iter_float.go
ReadFloat64
func (iter *Iterator) ReadFloat64() (ret float64) { c := iter.nextToken() if c == '-' { return -iter.readPositiveFloat64() } iter.unreadByte() return iter.readPositiveFloat64() }
go
func (iter *Iterator) ReadFloat64() (ret float64) { c := iter.nextToken() if c == '-' { return -iter.readPositiveFloat64() } iter.unreadByte() return iter.readPositiveFloat64() }
[ "func", "(", "iter", "*", "Iterator", ")", "ReadFloat64", "(", ")", "(", "ret", "float64", ")", "{", "c", ":=", "iter", ".", "nextToken", "(", ")", "\n", "if", "c", "==", "'-'", "{", "return", "-", "iter", ".", "readPositiveFloat64", "(", ")", "\n", "}", "\n", "iter", ".", "unreadByte", "(", ")", "\n", "return", "iter", ".", "readPositiveFloat64", "(", ")", "\n", "}" ]
// ReadFloat64 read float64
[ "ReadFloat64", "read", "float64" ]
0ff49de124c6f76f8494e194af75bde0f1a49a29
https://github.com/json-iterator/go/blob/0ff49de124c6f76f8494e194af75bde0f1a49a29/iter_float.go#L207-L214
train
json-iterator/go
iter_float.go
ReadNumber
func (iter *Iterator) ReadNumber() (ret json.Number) { return json.Number(iter.readNumberAsString()) }
go
func (iter *Iterator) ReadNumber() (ret json.Number) { return json.Number(iter.readNumberAsString()) }
[ "func", "(", "iter", "*", "Iterator", ")", "ReadNumber", "(", ")", "(", "ret", "json", ".", "Number", ")", "{", "return", "json", ".", "Number", "(", "iter", ".", "readNumberAsString", "(", ")", ")", "\n", "}" ]
// ReadNumber read json.Number
[ "ReadNumber", "read", "json", ".", "Number" ]
0ff49de124c6f76f8494e194af75bde0f1a49a29
https://github.com/json-iterator/go/blob/0ff49de124c6f76f8494e194af75bde0f1a49a29/iter_float.go#L337-L339
train
json-iterator/go
iter_skip.go
ReadNil
func (iter *Iterator) ReadNil() (ret bool) { c := iter.nextToken() if c == 'n' { iter.skipThreeBytes('u', 'l', 'l') // null return true } iter.unreadByte() return false }
go
func (iter *Iterator) ReadNil() (ret bool) { c := iter.nextToken() if c == 'n' { iter.skipThreeBytes('u', 'l', 'l') // null return true } iter.unreadByte() return false }
[ "func", "(", "iter", "*", "Iterator", ")", "ReadNil", "(", ")", "(", "ret", "bool", ")", "{", "c", ":=", "iter", ".", "nextToken", "(", ")", "\n", "if", "c", "==", "'n'", "{", "iter", ".", "skipThreeBytes", "(", "'u'", ",", "'l'", ",", "'l'", ")", "// null", "\n", "return", "true", "\n", "}", "\n", "iter", ".", "unreadByte", "(", ")", "\n", "return", "false", "\n", "}" ]
// ReadNil reads a json object as nil and // returns whether it's a nil or not
[ "ReadNil", "reads", "a", "json", "object", "as", "nil", "and", "returns", "whether", "it", "s", "a", "nil", "or", "not" ]
0ff49de124c6f76f8494e194af75bde0f1a49a29
https://github.com/json-iterator/go/blob/0ff49de124c6f76f8494e194af75bde0f1a49a29/iter_skip.go#L7-L15
train
json-iterator/go
iter_skip.go
ReadBool
func (iter *Iterator) ReadBool() (ret bool) { c := iter.nextToken() if c == 't' { iter.skipThreeBytes('r', 'u', 'e') return true } if c == 'f' { iter.skipFourBytes('a', 'l', 's', 'e') return false } iter.ReportError("ReadBool", "expect t or f, but found "+string([]byte{c})) return }
go
func (iter *Iterator) ReadBool() (ret bool) { c := iter.nextToken() if c == 't' { iter.skipThreeBytes('r', 'u', 'e') return true } if c == 'f' { iter.skipFourBytes('a', 'l', 's', 'e') return false } iter.ReportError("ReadBool", "expect t or f, but found "+string([]byte{c})) return }
[ "func", "(", "iter", "*", "Iterator", ")", "ReadBool", "(", ")", "(", "ret", "bool", ")", "{", "c", ":=", "iter", ".", "nextToken", "(", ")", "\n", "if", "c", "==", "'t'", "{", "iter", ".", "skipThreeBytes", "(", "'r'", ",", "'u'", ",", "'e'", ")", "\n", "return", "true", "\n", "}", "\n", "if", "c", "==", "'f'", "{", "iter", ".", "skipFourBytes", "(", "'a'", ",", "'l'", ",", "'s'", ",", "'e'", ")", "\n", "return", "false", "\n", "}", "\n", "iter", ".", "ReportError", "(", "\"", "\"", ",", "\"", "\"", "+", "string", "(", "[", "]", "byte", "{", "c", "}", ")", ")", "\n", "return", "\n", "}" ]
// ReadBool reads a json object as BoolValue
[ "ReadBool", "reads", "a", "json", "object", "as", "BoolValue" ]
0ff49de124c6f76f8494e194af75bde0f1a49a29
https://github.com/json-iterator/go/blob/0ff49de124c6f76f8494e194af75bde0f1a49a29/iter_skip.go#L18-L30
train
json-iterator/go
iter_skip.go
Skip
func (iter *Iterator) Skip() { c := iter.nextToken() switch c { case '"': iter.skipString() case 'n': iter.skipThreeBytes('u', 'l', 'l') // null case 't': iter.skipThreeBytes('r', 'u', 'e') // true case 'f': iter.skipFourBytes('a', 'l', 's', 'e') // false case '0': iter.unreadByte() iter.ReadFloat32() case '-', '1', '2', '3', '4', '5', '6', '7', '8', '9': iter.skipNumber() case '[': iter.skipArray() case '{': iter.skipObject() default: iter.ReportError("Skip", fmt.Sprintf("do not know how to skip: %v", c)) return } }
go
func (iter *Iterator) Skip() { c := iter.nextToken() switch c { case '"': iter.skipString() case 'n': iter.skipThreeBytes('u', 'l', 'l') // null case 't': iter.skipThreeBytes('r', 'u', 'e') // true case 'f': iter.skipFourBytes('a', 'l', 's', 'e') // false case '0': iter.unreadByte() iter.ReadFloat32() case '-', '1', '2', '3', '4', '5', '6', '7', '8', '9': iter.skipNumber() case '[': iter.skipArray() case '{': iter.skipObject() default: iter.ReportError("Skip", fmt.Sprintf("do not know how to skip: %v", c)) return } }
[ "func", "(", "iter", "*", "Iterator", ")", "Skip", "(", ")", "{", "c", ":=", "iter", ".", "nextToken", "(", ")", "\n", "switch", "c", "{", "case", "'\"'", ":", "iter", ".", "skipString", "(", ")", "\n", "case", "'n'", ":", "iter", ".", "skipThreeBytes", "(", "'u'", ",", "'l'", ",", "'l'", ")", "// null", "\n", "case", "'t'", ":", "iter", ".", "skipThreeBytes", "(", "'r'", ",", "'u'", ",", "'e'", ")", "// true", "\n", "case", "'f'", ":", "iter", ".", "skipFourBytes", "(", "'a'", ",", "'l'", ",", "'s'", ",", "'e'", ")", "// false", "\n", "case", "'0'", ":", "iter", ".", "unreadByte", "(", ")", "\n", "iter", ".", "ReadFloat32", "(", ")", "\n", "case", "'-'", ",", "'1'", ",", "'2'", ",", "'3'", ",", "'4'", ",", "'5'", ",", "'6'", ",", "'7'", ",", "'8'", ",", "'9'", ":", "iter", ".", "skipNumber", "(", ")", "\n", "case", "'['", ":", "iter", ".", "skipArray", "(", ")", "\n", "case", "'{'", ":", "iter", ".", "skipObject", "(", ")", "\n", "default", ":", "iter", ".", "ReportError", "(", "\"", "\"", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "c", ")", ")", "\n", "return", "\n", "}", "\n", "}" ]
// Skip skips a json object and positions to relatively the next json object
[ "Skip", "skips", "a", "json", "object", "and", "positions", "to", "relatively", "the", "next", "json", "object" ]
0ff49de124c6f76f8494e194af75bde0f1a49a29
https://github.com/json-iterator/go/blob/0ff49de124c6f76f8494e194af75bde0f1a49a29/iter_skip.go#L71-L95
train
json-iterator/go
iter_int.go
ReadUint
func (iter *Iterator) ReadUint() uint { if strconv.IntSize == 32 { return uint(iter.ReadUint32()) } return uint(iter.ReadUint64()) }
go
func (iter *Iterator) ReadUint() uint { if strconv.IntSize == 32 { return uint(iter.ReadUint32()) } return uint(iter.ReadUint64()) }
[ "func", "(", "iter", "*", "Iterator", ")", "ReadUint", "(", ")", "uint", "{", "if", "strconv", ".", "IntSize", "==", "32", "{", "return", "uint", "(", "iter", ".", "ReadUint32", "(", ")", ")", "\n", "}", "\n", "return", "uint", "(", "iter", ".", "ReadUint64", "(", ")", ")", "\n", "}" ]
// ReadUint read uint
[ "ReadUint", "read", "uint" ]
0ff49de124c6f76f8494e194af75bde0f1a49a29
https://github.com/json-iterator/go/blob/0ff49de124c6f76f8494e194af75bde0f1a49a29/iter_int.go#L24-L29
train
json-iterator/go
iter_int.go
ReadInt
func (iter *Iterator) ReadInt() int { if strconv.IntSize == 32 { return int(iter.ReadInt32()) } return int(iter.ReadInt64()) }
go
func (iter *Iterator) ReadInt() int { if strconv.IntSize == 32 { return int(iter.ReadInt32()) } return int(iter.ReadInt64()) }
[ "func", "(", "iter", "*", "Iterator", ")", "ReadInt", "(", ")", "int", "{", "if", "strconv", ".", "IntSize", "==", "32", "{", "return", "int", "(", "iter", ".", "ReadInt32", "(", ")", ")", "\n", "}", "\n", "return", "int", "(", "iter", ".", "ReadInt64", "(", ")", ")", "\n", "}" ]
// ReadInt read int
[ "ReadInt", "read", "int" ]
0ff49de124c6f76f8494e194af75bde0f1a49a29
https://github.com/json-iterator/go/blob/0ff49de124c6f76f8494e194af75bde0f1a49a29/iter_int.go#L32-L37
train
json-iterator/go
iter_int.go
ReadInt8
func (iter *Iterator) ReadInt8() (ret int8) { c := iter.nextToken() if c == '-' { val := iter.readUint32(iter.readByte()) if val > math.MaxInt8+1 { iter.ReportError("ReadInt8", "overflow: "+strconv.FormatInt(int64(val), 10)) return } return -int8(val) } val := iter.readUint32(c) if val > math.MaxInt8 { iter.ReportError("ReadInt8", "overflow: "+strconv.FormatInt(int64(val), 10)) return } return int8(val) }
go
func (iter *Iterator) ReadInt8() (ret int8) { c := iter.nextToken() if c == '-' { val := iter.readUint32(iter.readByte()) if val > math.MaxInt8+1 { iter.ReportError("ReadInt8", "overflow: "+strconv.FormatInt(int64(val), 10)) return } return -int8(val) } val := iter.readUint32(c) if val > math.MaxInt8 { iter.ReportError("ReadInt8", "overflow: "+strconv.FormatInt(int64(val), 10)) return } return int8(val) }
[ "func", "(", "iter", "*", "Iterator", ")", "ReadInt8", "(", ")", "(", "ret", "int8", ")", "{", "c", ":=", "iter", ".", "nextToken", "(", ")", "\n", "if", "c", "==", "'-'", "{", "val", ":=", "iter", ".", "readUint32", "(", "iter", ".", "readByte", "(", ")", ")", "\n", "if", "val", ">", "math", ".", "MaxInt8", "+", "1", "{", "iter", ".", "ReportError", "(", "\"", "\"", ",", "\"", "\"", "+", "strconv", ".", "FormatInt", "(", "int64", "(", "val", ")", ",", "10", ")", ")", "\n", "return", "\n", "}", "\n", "return", "-", "int8", "(", "val", ")", "\n", "}", "\n", "val", ":=", "iter", ".", "readUint32", "(", "c", ")", "\n", "if", "val", ">", "math", ".", "MaxInt8", "{", "iter", ".", "ReportError", "(", "\"", "\"", ",", "\"", "\"", "+", "strconv", ".", "FormatInt", "(", "int64", "(", "val", ")", ",", "10", ")", ")", "\n", "return", "\n", "}", "\n", "return", "int8", "(", "val", ")", "\n", "}" ]
// ReadInt8 read int8
[ "ReadInt8", "read", "int8" ]
0ff49de124c6f76f8494e194af75bde0f1a49a29
https://github.com/json-iterator/go/blob/0ff49de124c6f76f8494e194af75bde0f1a49a29/iter_int.go#L40-L56
train
json-iterator/go
iter_int.go
ReadUint8
func (iter *Iterator) ReadUint8() (ret uint8) { val := iter.readUint32(iter.nextToken()) if val > math.MaxUint8 { iter.ReportError("ReadUint8", "overflow: "+strconv.FormatInt(int64(val), 10)) return } return uint8(val) }
go
func (iter *Iterator) ReadUint8() (ret uint8) { val := iter.readUint32(iter.nextToken()) if val > math.MaxUint8 { iter.ReportError("ReadUint8", "overflow: "+strconv.FormatInt(int64(val), 10)) return } return uint8(val) }
[ "func", "(", "iter", "*", "Iterator", ")", "ReadUint8", "(", ")", "(", "ret", "uint8", ")", "{", "val", ":=", "iter", ".", "readUint32", "(", "iter", ".", "nextToken", "(", ")", ")", "\n", "if", "val", ">", "math", ".", "MaxUint8", "{", "iter", ".", "ReportError", "(", "\"", "\"", ",", "\"", "\"", "+", "strconv", ".", "FormatInt", "(", "int64", "(", "val", ")", ",", "10", ")", ")", "\n", "return", "\n", "}", "\n", "return", "uint8", "(", "val", ")", "\n", "}" ]
// ReadUint8 read uint8
[ "ReadUint8", "read", "uint8" ]
0ff49de124c6f76f8494e194af75bde0f1a49a29
https://github.com/json-iterator/go/blob/0ff49de124c6f76f8494e194af75bde0f1a49a29/iter_int.go#L59-L66
train
json-iterator/go
iter_int.go
ReadInt16
func (iter *Iterator) ReadInt16() (ret int16) { c := iter.nextToken() if c == '-' { val := iter.readUint32(iter.readByte()) if val > math.MaxInt16+1 { iter.ReportError("ReadInt16", "overflow: "+strconv.FormatInt(int64(val), 10)) return } return -int16(val) } val := iter.readUint32(c) if val > math.MaxInt16 { iter.ReportError("ReadInt16", "overflow: "+strconv.FormatInt(int64(val), 10)) return } return int16(val) }
go
func (iter *Iterator) ReadInt16() (ret int16) { c := iter.nextToken() if c == '-' { val := iter.readUint32(iter.readByte()) if val > math.MaxInt16+1 { iter.ReportError("ReadInt16", "overflow: "+strconv.FormatInt(int64(val), 10)) return } return -int16(val) } val := iter.readUint32(c) if val > math.MaxInt16 { iter.ReportError("ReadInt16", "overflow: "+strconv.FormatInt(int64(val), 10)) return } return int16(val) }
[ "func", "(", "iter", "*", "Iterator", ")", "ReadInt16", "(", ")", "(", "ret", "int16", ")", "{", "c", ":=", "iter", ".", "nextToken", "(", ")", "\n", "if", "c", "==", "'-'", "{", "val", ":=", "iter", ".", "readUint32", "(", "iter", ".", "readByte", "(", ")", ")", "\n", "if", "val", ">", "math", ".", "MaxInt16", "+", "1", "{", "iter", ".", "ReportError", "(", "\"", "\"", ",", "\"", "\"", "+", "strconv", ".", "FormatInt", "(", "int64", "(", "val", ")", ",", "10", ")", ")", "\n", "return", "\n", "}", "\n", "return", "-", "int16", "(", "val", ")", "\n", "}", "\n", "val", ":=", "iter", ".", "readUint32", "(", "c", ")", "\n", "if", "val", ">", "math", ".", "MaxInt16", "{", "iter", ".", "ReportError", "(", "\"", "\"", ",", "\"", "\"", "+", "strconv", ".", "FormatInt", "(", "int64", "(", "val", ")", ",", "10", ")", ")", "\n", "return", "\n", "}", "\n", "return", "int16", "(", "val", ")", "\n", "}" ]
// ReadInt16 read int16
[ "ReadInt16", "read", "int16" ]
0ff49de124c6f76f8494e194af75bde0f1a49a29
https://github.com/json-iterator/go/blob/0ff49de124c6f76f8494e194af75bde0f1a49a29/iter_int.go#L69-L85
train
json-iterator/go
iter_int.go
ReadUint16
func (iter *Iterator) ReadUint16() (ret uint16) { val := iter.readUint32(iter.nextToken()) if val > math.MaxUint16 { iter.ReportError("ReadUint16", "overflow: "+strconv.FormatInt(int64(val), 10)) return } return uint16(val) }
go
func (iter *Iterator) ReadUint16() (ret uint16) { val := iter.readUint32(iter.nextToken()) if val > math.MaxUint16 { iter.ReportError("ReadUint16", "overflow: "+strconv.FormatInt(int64(val), 10)) return } return uint16(val) }
[ "func", "(", "iter", "*", "Iterator", ")", "ReadUint16", "(", ")", "(", "ret", "uint16", ")", "{", "val", ":=", "iter", ".", "readUint32", "(", "iter", ".", "nextToken", "(", ")", ")", "\n", "if", "val", ">", "math", ".", "MaxUint16", "{", "iter", ".", "ReportError", "(", "\"", "\"", ",", "\"", "\"", "+", "strconv", ".", "FormatInt", "(", "int64", "(", "val", ")", ",", "10", ")", ")", "\n", "return", "\n", "}", "\n", "return", "uint16", "(", "val", ")", "\n", "}" ]
// ReadUint16 read uint16
[ "ReadUint16", "read", "uint16" ]
0ff49de124c6f76f8494e194af75bde0f1a49a29
https://github.com/json-iterator/go/blob/0ff49de124c6f76f8494e194af75bde0f1a49a29/iter_int.go#L88-L95
train
json-iterator/go
iter_int.go
ReadInt32
func (iter *Iterator) ReadInt32() (ret int32) { c := iter.nextToken() if c == '-' { val := iter.readUint32(iter.readByte()) if val > math.MaxInt32+1 { iter.ReportError("ReadInt32", "overflow: "+strconv.FormatInt(int64(val), 10)) return } return -int32(val) } val := iter.readUint32(c) if val > math.MaxInt32 { iter.ReportError("ReadInt32", "overflow: "+strconv.FormatInt(int64(val), 10)) return } return int32(val) }
go
func (iter *Iterator) ReadInt32() (ret int32) { c := iter.nextToken() if c == '-' { val := iter.readUint32(iter.readByte()) if val > math.MaxInt32+1 { iter.ReportError("ReadInt32", "overflow: "+strconv.FormatInt(int64(val), 10)) return } return -int32(val) } val := iter.readUint32(c) if val > math.MaxInt32 { iter.ReportError("ReadInt32", "overflow: "+strconv.FormatInt(int64(val), 10)) return } return int32(val) }
[ "func", "(", "iter", "*", "Iterator", ")", "ReadInt32", "(", ")", "(", "ret", "int32", ")", "{", "c", ":=", "iter", ".", "nextToken", "(", ")", "\n", "if", "c", "==", "'-'", "{", "val", ":=", "iter", ".", "readUint32", "(", "iter", ".", "readByte", "(", ")", ")", "\n", "if", "val", ">", "math", ".", "MaxInt32", "+", "1", "{", "iter", ".", "ReportError", "(", "\"", "\"", ",", "\"", "\"", "+", "strconv", ".", "FormatInt", "(", "int64", "(", "val", ")", ",", "10", ")", ")", "\n", "return", "\n", "}", "\n", "return", "-", "int32", "(", "val", ")", "\n", "}", "\n", "val", ":=", "iter", ".", "readUint32", "(", "c", ")", "\n", "if", "val", ">", "math", ".", "MaxInt32", "{", "iter", ".", "ReportError", "(", "\"", "\"", ",", "\"", "\"", "+", "strconv", ".", "FormatInt", "(", "int64", "(", "val", ")", ",", "10", ")", ")", "\n", "return", "\n", "}", "\n", "return", "int32", "(", "val", ")", "\n", "}" ]
// ReadInt32 read int32
[ "ReadInt32", "read", "int32" ]
0ff49de124c6f76f8494e194af75bde0f1a49a29
https://github.com/json-iterator/go/blob/0ff49de124c6f76f8494e194af75bde0f1a49a29/iter_int.go#L98-L114
train
json-iterator/go
iter_int.go
ReadInt64
func (iter *Iterator) ReadInt64() (ret int64) { c := iter.nextToken() if c == '-' { val := iter.readUint64(iter.readByte()) if val > math.MaxInt64+1 { iter.ReportError("ReadInt64", "overflow: "+strconv.FormatUint(uint64(val), 10)) return } return -int64(val) } val := iter.readUint64(c) if val > math.MaxInt64 { iter.ReportError("ReadInt64", "overflow: "+strconv.FormatUint(uint64(val), 10)) return } return int64(val) }
go
func (iter *Iterator) ReadInt64() (ret int64) { c := iter.nextToken() if c == '-' { val := iter.readUint64(iter.readByte()) if val > math.MaxInt64+1 { iter.ReportError("ReadInt64", "overflow: "+strconv.FormatUint(uint64(val), 10)) return } return -int64(val) } val := iter.readUint64(c) if val > math.MaxInt64 { iter.ReportError("ReadInt64", "overflow: "+strconv.FormatUint(uint64(val), 10)) return } return int64(val) }
[ "func", "(", "iter", "*", "Iterator", ")", "ReadInt64", "(", ")", "(", "ret", "int64", ")", "{", "c", ":=", "iter", ".", "nextToken", "(", ")", "\n", "if", "c", "==", "'-'", "{", "val", ":=", "iter", ".", "readUint64", "(", "iter", ".", "readByte", "(", ")", ")", "\n", "if", "val", ">", "math", ".", "MaxInt64", "+", "1", "{", "iter", ".", "ReportError", "(", "\"", "\"", ",", "\"", "\"", "+", "strconv", ".", "FormatUint", "(", "uint64", "(", "val", ")", ",", "10", ")", ")", "\n", "return", "\n", "}", "\n", "return", "-", "int64", "(", "val", ")", "\n", "}", "\n", "val", ":=", "iter", ".", "readUint64", "(", "c", ")", "\n", "if", "val", ">", "math", ".", "MaxInt64", "{", "iter", ".", "ReportError", "(", "\"", "\"", ",", "\"", "\"", "+", "strconv", ".", "FormatUint", "(", "uint64", "(", "val", ")", ",", "10", ")", ")", "\n", "return", "\n", "}", "\n", "return", "int64", "(", "val", ")", "\n", "}" ]
// ReadInt64 read int64
[ "ReadInt64", "read", "int64" ]
0ff49de124c6f76f8494e194af75bde0f1a49a29
https://github.com/json-iterator/go/blob/0ff49de124c6f76f8494e194af75bde0f1a49a29/iter_int.go#L220-L236
train
docker/cli
cli/command/container/cp.go
NewCopyCommand
func NewCopyCommand(dockerCli command.Cli) *cobra.Command { var opts copyOptions cmd := &cobra.Command{ Use: `cp [OPTIONS] CONTAINER:SRC_PATH DEST_PATH|- docker cp [OPTIONS] SRC_PATH|- CONTAINER:DEST_PATH`, Short: "Copy files/folders between a container and the local filesystem", Long: strings.Join([]string{ "Copy files/folders between a container and the local filesystem\n", "\nUse '-' as the source to read a tar archive from stdin\n", "and extract it to a directory destination in a container.\n", "Use '-' as the destination to stream a tar archive of a\n", "container source to stdout.", }, ""), Args: cli.ExactArgs(2), RunE: func(cmd *cobra.Command, args []string) error { if args[0] == "" { return errors.New("source can not be empty") } if args[1] == "" { return errors.New("destination can not be empty") } opts.source = args[0] opts.destination = args[1] return runCopy(dockerCli, opts) }, } flags := cmd.Flags() flags.BoolVarP(&opts.followLink, "follow-link", "L", false, "Always follow symbol link in SRC_PATH") flags.BoolVarP(&opts.copyUIDGID, "archive", "a", false, "Archive mode (copy all uid/gid information)") return cmd }
go
func NewCopyCommand(dockerCli command.Cli) *cobra.Command { var opts copyOptions cmd := &cobra.Command{ Use: `cp [OPTIONS] CONTAINER:SRC_PATH DEST_PATH|- docker cp [OPTIONS] SRC_PATH|- CONTAINER:DEST_PATH`, Short: "Copy files/folders between a container and the local filesystem", Long: strings.Join([]string{ "Copy files/folders between a container and the local filesystem\n", "\nUse '-' as the source to read a tar archive from stdin\n", "and extract it to a directory destination in a container.\n", "Use '-' as the destination to stream a tar archive of a\n", "container source to stdout.", }, ""), Args: cli.ExactArgs(2), RunE: func(cmd *cobra.Command, args []string) error { if args[0] == "" { return errors.New("source can not be empty") } if args[1] == "" { return errors.New("destination can not be empty") } opts.source = args[0] opts.destination = args[1] return runCopy(dockerCli, opts) }, } flags := cmd.Flags() flags.BoolVarP(&opts.followLink, "follow-link", "L", false, "Always follow symbol link in SRC_PATH") flags.BoolVarP(&opts.copyUIDGID, "archive", "a", false, "Archive mode (copy all uid/gid information)") return cmd }
[ "func", "NewCopyCommand", "(", "dockerCli", "command", ".", "Cli", ")", "*", "cobra", ".", "Command", "{", "var", "opts", "copyOptions", "\n\n", "cmd", ":=", "&", "cobra", ".", "Command", "{", "Use", ":", "`cp [OPTIONS] CONTAINER:SRC_PATH DEST_PATH|-\n\tdocker cp [OPTIONS] SRC_PATH|- CONTAINER:DEST_PATH`", ",", "Short", ":", "\"", "\"", ",", "Long", ":", "strings", ".", "Join", "(", "[", "]", "string", "{", "\"", "\\n", "\"", ",", "\"", "\\n", "\\n", "\"", ",", "\"", "\\n", "\"", ",", "\"", "\\n", "\"", ",", "\"", "\"", ",", "}", ",", "\"", "\"", ")", ",", "Args", ":", "cli", ".", "ExactArgs", "(", "2", ")", ",", "RunE", ":", "func", "(", "cmd", "*", "cobra", ".", "Command", ",", "args", "[", "]", "string", ")", "error", "{", "if", "args", "[", "0", "]", "==", "\"", "\"", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "args", "[", "1", "]", "==", "\"", "\"", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "opts", ".", "source", "=", "args", "[", "0", "]", "\n", "opts", ".", "destination", "=", "args", "[", "1", "]", "\n", "return", "runCopy", "(", "dockerCli", ",", "opts", ")", "\n", "}", ",", "}", "\n\n", "flags", ":=", "cmd", ".", "Flags", "(", ")", "\n", "flags", ".", "BoolVarP", "(", "&", "opts", ".", "followLink", ",", "\"", "\"", ",", "\"", "\"", ",", "false", ",", "\"", "\"", ")", "\n", "flags", ".", "BoolVarP", "(", "&", "opts", ".", "copyUIDGID", ",", "\"", "\"", ",", "\"", "\"", ",", "false", ",", "\"", "\"", ")", "\n", "return", "cmd", "\n", "}" ]
// NewCopyCommand creates a new `docker cp` command
[ "NewCopyCommand", "creates", "a", "new", "docker", "cp", "command" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/command/container/cp.go#L43-L75
train
docker/cli
cli/command/container/attach.go
NewAttachCommand
func NewAttachCommand(dockerCli command.Cli) *cobra.Command { var opts attachOptions cmd := &cobra.Command{ Use: "attach [OPTIONS] CONTAINER", Short: "Attach local standard input, output, and error streams to a running container", Args: cli.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { opts.container = args[0] return runAttach(dockerCli, &opts) }, } flags := cmd.Flags() flags.BoolVar(&opts.noStdin, "no-stdin", false, "Do not attach STDIN") flags.BoolVar(&opts.proxy, "sig-proxy", true, "Proxy all received signals to the process") flags.StringVar(&opts.detachKeys, "detach-keys", "", "Override the key sequence for detaching a container") return cmd }
go
func NewAttachCommand(dockerCli command.Cli) *cobra.Command { var opts attachOptions cmd := &cobra.Command{ Use: "attach [OPTIONS] CONTAINER", Short: "Attach local standard input, output, and error streams to a running container", Args: cli.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { opts.container = args[0] return runAttach(dockerCli, &opts) }, } flags := cmd.Flags() flags.BoolVar(&opts.noStdin, "no-stdin", false, "Do not attach STDIN") flags.BoolVar(&opts.proxy, "sig-proxy", true, "Proxy all received signals to the process") flags.StringVar(&opts.detachKeys, "detach-keys", "", "Override the key sequence for detaching a container") return cmd }
[ "func", "NewAttachCommand", "(", "dockerCli", "command", ".", "Cli", ")", "*", "cobra", ".", "Command", "{", "var", "opts", "attachOptions", "\n\n", "cmd", ":=", "&", "cobra", ".", "Command", "{", "Use", ":", "\"", "\"", ",", "Short", ":", "\"", "\"", ",", "Args", ":", "cli", ".", "ExactArgs", "(", "1", ")", ",", "RunE", ":", "func", "(", "cmd", "*", "cobra", ".", "Command", ",", "args", "[", "]", "string", ")", "error", "{", "opts", ".", "container", "=", "args", "[", "0", "]", "\n", "return", "runAttach", "(", "dockerCli", ",", "&", "opts", ")", "\n", "}", ",", "}", "\n\n", "flags", ":=", "cmd", ".", "Flags", "(", ")", "\n", "flags", ".", "BoolVar", "(", "&", "opts", ".", "noStdin", ",", "\"", "\"", ",", "false", ",", "\"", "\"", ")", "\n", "flags", ".", "BoolVar", "(", "&", "opts", ".", "proxy", ",", "\"", "\"", ",", "true", ",", "\"", "\"", ")", "\n", "flags", ".", "StringVar", "(", "&", "opts", ".", "detachKeys", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "return", "cmd", "\n", "}" ]
// NewAttachCommand creates a new cobra.Command for `docker attach`
[ "NewAttachCommand", "creates", "a", "new", "cobra", ".", "Command", "for", "docker", "attach" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/command/container/attach.go#L47-L65
train
docker/cli
cli/command/container/export.go
NewExportCommand
func NewExportCommand(dockerCli command.Cli) *cobra.Command { var opts exportOptions cmd := &cobra.Command{ Use: "export [OPTIONS] CONTAINER", Short: "Export a container's filesystem as a tar archive", Args: cli.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { opts.container = args[0] return runExport(dockerCli, opts) }, } flags := cmd.Flags() flags.StringVarP(&opts.output, "output", "o", "", "Write to a file, instead of STDOUT") return cmd }
go
func NewExportCommand(dockerCli command.Cli) *cobra.Command { var opts exportOptions cmd := &cobra.Command{ Use: "export [OPTIONS] CONTAINER", Short: "Export a container's filesystem as a tar archive", Args: cli.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { opts.container = args[0] return runExport(dockerCli, opts) }, } flags := cmd.Flags() flags.StringVarP(&opts.output, "output", "o", "", "Write to a file, instead of STDOUT") return cmd }
[ "func", "NewExportCommand", "(", "dockerCli", "command", ".", "Cli", ")", "*", "cobra", ".", "Command", "{", "var", "opts", "exportOptions", "\n\n", "cmd", ":=", "&", "cobra", ".", "Command", "{", "Use", ":", "\"", "\"", ",", "Short", ":", "\"", "\"", ",", "Args", ":", "cli", ".", "ExactArgs", "(", "1", ")", ",", "RunE", ":", "func", "(", "cmd", "*", "cobra", ".", "Command", ",", "args", "[", "]", "string", ")", "error", "{", "opts", ".", "container", "=", "args", "[", "0", "]", "\n", "return", "runExport", "(", "dockerCli", ",", "opts", ")", "\n", "}", ",", "}", "\n\n", "flags", ":=", "cmd", ".", "Flags", "(", ")", "\n\n", "flags", ".", "StringVarP", "(", "&", "opts", ".", "output", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n\n", "return", "cmd", "\n", "}" ]
// NewExportCommand creates a new `docker export` command
[ "NewExportCommand", "creates", "a", "new", "docker", "export", "command" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/command/container/export.go#L19-L37
train
docker/cli
cli/command/stack/kubernetes/cli.go
NewOptions
func NewOptions(flags *flag.FlagSet, orchestrator command.Orchestrator) Options { opts := Options{ Orchestrator: orchestrator, } if namespace, err := flags.GetString("namespace"); err == nil { opts.Namespace = namespace } if kubeConfig, err := flags.GetString("kubeconfig"); err == nil { opts.Config = kubeConfig } return opts }
go
func NewOptions(flags *flag.FlagSet, orchestrator command.Orchestrator) Options { opts := Options{ Orchestrator: orchestrator, } if namespace, err := flags.GetString("namespace"); err == nil { opts.Namespace = namespace } if kubeConfig, err := flags.GetString("kubeconfig"); err == nil { opts.Config = kubeConfig } return opts }
[ "func", "NewOptions", "(", "flags", "*", "flag", ".", "FlagSet", ",", "orchestrator", "command", ".", "Orchestrator", ")", "Options", "{", "opts", ":=", "Options", "{", "Orchestrator", ":", "orchestrator", ",", "}", "\n", "if", "namespace", ",", "err", ":=", "flags", ".", "GetString", "(", "\"", "\"", ")", ";", "err", "==", "nil", "{", "opts", ".", "Namespace", "=", "namespace", "\n", "}", "\n", "if", "kubeConfig", ",", "err", ":=", "flags", ".", "GetString", "(", "\"", "\"", ")", ";", "err", "==", "nil", "{", "opts", ".", "Config", "=", "kubeConfig", "\n", "}", "\n", "return", "opts", "\n", "}" ]
// NewOptions returns an Options initialized with command line flags
[ "NewOptions", "returns", "an", "Options", "initialized", "with", "command", "line", "flags" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/command/stack/kubernetes/cli.go#L36-L47
train
docker/cli
cli/command/stack/kubernetes/cli.go
WrapCli
func WrapCli(dockerCli command.Cli, opts Options) (*KubeCli, error) { cli := &KubeCli{ Cli: dockerCli, } var ( clientConfig clientcmd.ClientConfig err error ) if dockerCli.CurrentContext() == "" { clientConfig = kubernetes.NewKubernetesConfig(opts.Config) } else { clientConfig, err = kubecontext.ConfigFromContext(dockerCli.CurrentContext(), dockerCli.ContextStore()) } if err != nil { return nil, err } cli.kubeNamespace = opts.Namespace if opts.Namespace == "" { configNamespace, _, err := clientConfig.Namespace() switch { case os.IsNotExist(err), os.IsPermission(err): return nil, errors.Wrap(err, "unable to load configuration file") case err != nil: return nil, err } cli.kubeNamespace = configNamespace } config, err := clientConfig.ClientConfig() if err != nil { return nil, err } cli.kubeConfig = config clientSet, err := kubeclient.NewForConfig(config) if err != nil { return nil, err } cli.clientSet = clientSet if opts.Orchestrator.HasAll() { if err := cli.checkHostsMatch(); err != nil { return nil, err } } return cli, nil }
go
func WrapCli(dockerCli command.Cli, opts Options) (*KubeCli, error) { cli := &KubeCli{ Cli: dockerCli, } var ( clientConfig clientcmd.ClientConfig err error ) if dockerCli.CurrentContext() == "" { clientConfig = kubernetes.NewKubernetesConfig(opts.Config) } else { clientConfig, err = kubecontext.ConfigFromContext(dockerCli.CurrentContext(), dockerCli.ContextStore()) } if err != nil { return nil, err } cli.kubeNamespace = opts.Namespace if opts.Namespace == "" { configNamespace, _, err := clientConfig.Namespace() switch { case os.IsNotExist(err), os.IsPermission(err): return nil, errors.Wrap(err, "unable to load configuration file") case err != nil: return nil, err } cli.kubeNamespace = configNamespace } config, err := clientConfig.ClientConfig() if err != nil { return nil, err } cli.kubeConfig = config clientSet, err := kubeclient.NewForConfig(config) if err != nil { return nil, err } cli.clientSet = clientSet if opts.Orchestrator.HasAll() { if err := cli.checkHostsMatch(); err != nil { return nil, err } } return cli, nil }
[ "func", "WrapCli", "(", "dockerCli", "command", ".", "Cli", ",", "opts", "Options", ")", "(", "*", "KubeCli", ",", "error", ")", "{", "cli", ":=", "&", "KubeCli", "{", "Cli", ":", "dockerCli", ",", "}", "\n", "var", "(", "clientConfig", "clientcmd", ".", "ClientConfig", "\n", "err", "error", "\n", ")", "\n", "if", "dockerCli", ".", "CurrentContext", "(", ")", "==", "\"", "\"", "{", "clientConfig", "=", "kubernetes", ".", "NewKubernetesConfig", "(", "opts", ".", "Config", ")", "\n", "}", "else", "{", "clientConfig", ",", "err", "=", "kubecontext", ".", "ConfigFromContext", "(", "dockerCli", ".", "CurrentContext", "(", ")", ",", "dockerCli", ".", "ContextStore", "(", ")", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "cli", ".", "kubeNamespace", "=", "opts", ".", "Namespace", "\n", "if", "opts", ".", "Namespace", "==", "\"", "\"", "{", "configNamespace", ",", "_", ",", "err", ":=", "clientConfig", ".", "Namespace", "(", ")", "\n", "switch", "{", "case", "os", ".", "IsNotExist", "(", "err", ")", ",", "os", ".", "IsPermission", "(", "err", ")", ":", "return", "nil", ",", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "case", "err", "!=", "nil", ":", "return", "nil", ",", "err", "\n", "}", "\n", "cli", ".", "kubeNamespace", "=", "configNamespace", "\n", "}", "\n\n", "config", ",", "err", ":=", "clientConfig", ".", "ClientConfig", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "cli", ".", "kubeConfig", "=", "config", "\n\n", "clientSet", ",", "err", ":=", "kubeclient", ".", "NewForConfig", "(", "config", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "cli", ".", "clientSet", "=", "clientSet", "\n\n", "if", "opts", ".", "Orchestrator", ".", "HasAll", "(", ")", "{", "if", "err", ":=", "cli", ".", "checkHostsMatch", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n", "return", "cli", ",", "nil", "\n", "}" ]
// WrapCli wraps command.Cli with kubernetes specifics
[ "WrapCli", "wraps", "command", ".", "Cli", "with", "kubernetes", "specifics" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/command/stack/kubernetes/cli.go#L56-L103
train
docker/cli
cli/command/stack/deploy.go
RunDeploy
func RunDeploy(dockerCli command.Cli, flags *pflag.FlagSet, config *composetypes.Config, commonOrchestrator command.Orchestrator, opts options.Deploy) error { return runOrchestratedCommand(dockerCli, flags, commonOrchestrator, func() error { return swarm.RunDeploy(dockerCli, opts, config) }, func(kli *kubernetes.KubeCli) error { return kubernetes.RunDeploy(kli, opts, config) }) }
go
func RunDeploy(dockerCli command.Cli, flags *pflag.FlagSet, config *composetypes.Config, commonOrchestrator command.Orchestrator, opts options.Deploy) error { return runOrchestratedCommand(dockerCli, flags, commonOrchestrator, func() error { return swarm.RunDeploy(dockerCli, opts, config) }, func(kli *kubernetes.KubeCli) error { return kubernetes.RunDeploy(kli, opts, config) }) }
[ "func", "RunDeploy", "(", "dockerCli", "command", ".", "Cli", ",", "flags", "*", "pflag", ".", "FlagSet", ",", "config", "*", "composetypes", ".", "Config", ",", "commonOrchestrator", "command", ".", "Orchestrator", ",", "opts", "options", ".", "Deploy", ")", "error", "{", "return", "runOrchestratedCommand", "(", "dockerCli", ",", "flags", ",", "commonOrchestrator", ",", "func", "(", ")", "error", "{", "return", "swarm", ".", "RunDeploy", "(", "dockerCli", ",", "opts", ",", "config", ")", "}", ",", "func", "(", "kli", "*", "kubernetes", ".", "KubeCli", ")", "error", "{", "return", "kubernetes", ".", "RunDeploy", "(", "kli", ",", "opts", ",", "config", ")", "}", ")", "\n", "}" ]
// RunDeploy performs a stack deploy against the specified orchestrator
[ "RunDeploy", "performs", "a", "stack", "deploy", "against", "the", "specified", "orchestrator" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/command/stack/deploy.go#L77-L81
train
docker/cli
cli/command/node/cmd.go
NewNodeCommand
func NewNodeCommand(dockerCli command.Cli) *cobra.Command { cmd := &cobra.Command{ Use: "node", Short: "Manage Swarm nodes", Args: cli.NoArgs, RunE: command.ShowHelp(dockerCli.Err()), Annotations: map[string]string{ "version": "1.24", "swarm": "", }, } cmd.AddCommand( newDemoteCommand(dockerCli), newInspectCommand(dockerCli), newListCommand(dockerCli), newPromoteCommand(dockerCli), newRemoveCommand(dockerCli), newPsCommand(dockerCli), newUpdateCommand(dockerCli), ) return cmd }
go
func NewNodeCommand(dockerCli command.Cli) *cobra.Command { cmd := &cobra.Command{ Use: "node", Short: "Manage Swarm nodes", Args: cli.NoArgs, RunE: command.ShowHelp(dockerCli.Err()), Annotations: map[string]string{ "version": "1.24", "swarm": "", }, } cmd.AddCommand( newDemoteCommand(dockerCli), newInspectCommand(dockerCli), newListCommand(dockerCli), newPromoteCommand(dockerCli), newRemoveCommand(dockerCli), newPsCommand(dockerCli), newUpdateCommand(dockerCli), ) return cmd }
[ "func", "NewNodeCommand", "(", "dockerCli", "command", ".", "Cli", ")", "*", "cobra", ".", "Command", "{", "cmd", ":=", "&", "cobra", ".", "Command", "{", "Use", ":", "\"", "\"", ",", "Short", ":", "\"", "\"", ",", "Args", ":", "cli", ".", "NoArgs", ",", "RunE", ":", "command", ".", "ShowHelp", "(", "dockerCli", ".", "Err", "(", ")", ")", ",", "Annotations", ":", "map", "[", "string", "]", "string", "{", "\"", "\"", ":", "\"", "\"", ",", "\"", "\"", ":", "\"", "\"", ",", "}", ",", "}", "\n", "cmd", ".", "AddCommand", "(", "newDemoteCommand", "(", "dockerCli", ")", ",", "newInspectCommand", "(", "dockerCli", ")", ",", "newListCommand", "(", "dockerCli", ")", ",", "newPromoteCommand", "(", "dockerCli", ")", ",", "newRemoveCommand", "(", "dockerCli", ")", ",", "newPsCommand", "(", "dockerCli", ")", ",", "newUpdateCommand", "(", "dockerCli", ")", ",", ")", "\n", "return", "cmd", "\n", "}" ]
// NewNodeCommand returns a cobra command for `node` subcommands
[ "NewNodeCommand", "returns", "a", "cobra", "command", "for", "node", "subcommands" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/command/node/cmd.go#L15-L36
train
docker/cli
cli/command/stack/list.go
RunList
func RunList(cmd *cobra.Command, dockerCli command.Cli, opts options.List, orchestrator command.Orchestrator) error { stacks := []*formatter.Stack{} if orchestrator.HasSwarm() { ss, err := swarm.GetStacks(dockerCli) if err != nil { return err } stacks = append(stacks, ss...) } if orchestrator.HasKubernetes() { kubeCli, err := kubernetes.WrapCli(dockerCli, kubernetes.NewOptions(cmd.Flags(), orchestrator)) if err != nil { return err } ss, err := kubernetes.GetStacks(kubeCli, opts) if err != nil { return err } stacks = append(stacks, ss...) } return format(dockerCli, opts, orchestrator, stacks) }
go
func RunList(cmd *cobra.Command, dockerCli command.Cli, opts options.List, orchestrator command.Orchestrator) error { stacks := []*formatter.Stack{} if orchestrator.HasSwarm() { ss, err := swarm.GetStacks(dockerCli) if err != nil { return err } stacks = append(stacks, ss...) } if orchestrator.HasKubernetes() { kubeCli, err := kubernetes.WrapCli(dockerCli, kubernetes.NewOptions(cmd.Flags(), orchestrator)) if err != nil { return err } ss, err := kubernetes.GetStacks(kubeCli, opts) if err != nil { return err } stacks = append(stacks, ss...) } return format(dockerCli, opts, orchestrator, stacks) }
[ "func", "RunList", "(", "cmd", "*", "cobra", ".", "Command", ",", "dockerCli", "command", ".", "Cli", ",", "opts", "options", ".", "List", ",", "orchestrator", "command", ".", "Orchestrator", ")", "error", "{", "stacks", ":=", "[", "]", "*", "formatter", ".", "Stack", "{", "}", "\n", "if", "orchestrator", ".", "HasSwarm", "(", ")", "{", "ss", ",", "err", ":=", "swarm", ".", "GetStacks", "(", "dockerCli", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "stacks", "=", "append", "(", "stacks", ",", "ss", "...", ")", "\n", "}", "\n", "if", "orchestrator", ".", "HasKubernetes", "(", ")", "{", "kubeCli", ",", "err", ":=", "kubernetes", ".", "WrapCli", "(", "dockerCli", ",", "kubernetes", ".", "NewOptions", "(", "cmd", ".", "Flags", "(", ")", ",", "orchestrator", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "ss", ",", "err", ":=", "kubernetes", ".", "GetStacks", "(", "kubeCli", ",", "opts", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "stacks", "=", "append", "(", "stacks", ",", "ss", "...", ")", "\n", "}", "\n", "return", "format", "(", "dockerCli", ",", "opts", ",", "orchestrator", ",", "stacks", ")", "\n", "}" ]
// RunList performs a stack list against the specified orchestrator
[ "RunList", "performs", "a", "stack", "list", "against", "the", "specified", "orchestrator" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/command/stack/list.go#L39-L60
train
docker/cli
cli/command/node/formatter.go
NewFormat
func NewFormat(source string, quiet bool) formatter.Format { switch source { case formatter.PrettyFormatKey: return nodeInspectPrettyTemplate case formatter.TableFormatKey: if quiet { return formatter.DefaultQuietFormat } return defaultNodeTableFormat case formatter.RawFormatKey: if quiet { return `node_id: {{.ID}}` } return `node_id: {{.ID}}\nhostname: {{.Hostname}}\nstatus: {{.Status}}\navailability: {{.Availability}}\nmanager_status: {{.ManagerStatus}}\n` } return formatter.Format(source) }
go
func NewFormat(source string, quiet bool) formatter.Format { switch source { case formatter.PrettyFormatKey: return nodeInspectPrettyTemplate case formatter.TableFormatKey: if quiet { return formatter.DefaultQuietFormat } return defaultNodeTableFormat case formatter.RawFormatKey: if quiet { return `node_id: {{.ID}}` } return `node_id: {{.ID}}\nhostname: {{.Hostname}}\nstatus: {{.Status}}\navailability: {{.Availability}}\nmanager_status: {{.ManagerStatus}}\n` } return formatter.Format(source) }
[ "func", "NewFormat", "(", "source", "string", ",", "quiet", "bool", ")", "formatter", ".", "Format", "{", "switch", "source", "{", "case", "formatter", ".", "PrettyFormatKey", ":", "return", "nodeInspectPrettyTemplate", "\n", "case", "formatter", ".", "TableFormatKey", ":", "if", "quiet", "{", "return", "formatter", ".", "DefaultQuietFormat", "\n", "}", "\n", "return", "defaultNodeTableFormat", "\n", "case", "formatter", ".", "RawFormatKey", ":", "if", "quiet", "{", "return", "`node_id: {{.ID}}`", "\n", "}", "\n", "return", "`node_id: {{.ID}}\\nhostname: {{.Hostname}}\\nstatus: {{.Status}}\\navailability: {{.Availability}}\\nmanager_status: {{.ManagerStatus}}\\n`", "\n", "}", "\n", "return", "formatter", ".", "Format", "(", "source", ")", "\n", "}" ]
// NewFormat returns a Format for rendering using a node Context
[ "NewFormat", "returns", "a", "Format", "for", "rendering", "using", "a", "node", "Context" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/command/node/formatter.go#L84-L100
train
docker/cli
cli/command/node/formatter.go
InspectFormatWrite
func InspectFormatWrite(ctx formatter.Context, refs []string, getRef inspect.GetRefFunc) error { if ctx.Format != nodeInspectPrettyTemplate { return inspect.Inspect(ctx.Output, refs, string(ctx.Format), getRef) } render := func(format func(subContext formatter.SubContext) error) error { for _, ref := range refs { nodeI, _, err := getRef(ref) if err != nil { return err } node, ok := nodeI.(swarm.Node) if !ok { return fmt.Errorf("got wrong object to inspect :%v", ok) } if err := format(&nodeInspectContext{Node: node}); err != nil { return err } } return nil } return ctx.Write(&nodeInspectContext{}, render) }
go
func InspectFormatWrite(ctx formatter.Context, refs []string, getRef inspect.GetRefFunc) error { if ctx.Format != nodeInspectPrettyTemplate { return inspect.Inspect(ctx.Output, refs, string(ctx.Format), getRef) } render := func(format func(subContext formatter.SubContext) error) error { for _, ref := range refs { nodeI, _, err := getRef(ref) if err != nil { return err } node, ok := nodeI.(swarm.Node) if !ok { return fmt.Errorf("got wrong object to inspect :%v", ok) } if err := format(&nodeInspectContext{Node: node}); err != nil { return err } } return nil } return ctx.Write(&nodeInspectContext{}, render) }
[ "func", "InspectFormatWrite", "(", "ctx", "formatter", ".", "Context", ",", "refs", "[", "]", "string", ",", "getRef", "inspect", ".", "GetRefFunc", ")", "error", "{", "if", "ctx", ".", "Format", "!=", "nodeInspectPrettyTemplate", "{", "return", "inspect", ".", "Inspect", "(", "ctx", ".", "Output", ",", "refs", ",", "string", "(", "ctx", ".", "Format", ")", ",", "getRef", ")", "\n", "}", "\n", "render", ":=", "func", "(", "format", "func", "(", "subContext", "formatter", ".", "SubContext", ")", "error", ")", "error", "{", "for", "_", ",", "ref", ":=", "range", "refs", "{", "nodeI", ",", "_", ",", "err", ":=", "getRef", "(", "ref", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "node", ",", "ok", ":=", "nodeI", ".", "(", "swarm", ".", "Node", ")", "\n", "if", "!", "ok", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "ok", ")", "\n", "}", "\n", "if", "err", ":=", "format", "(", "&", "nodeInspectContext", "{", "Node", ":", "node", "}", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}", "\n", "return", "ctx", ".", "Write", "(", "&", "nodeInspectContext", "{", "}", ",", "render", ")", "\n", "}" ]
// InspectFormatWrite renders the context for a list of nodes
[ "InspectFormatWrite", "renders", "the", "context", "for", "a", "list", "of", "nodes" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/command/node/formatter.go#L184-L205
train
docker/cli
cli/command/formatter/volume.go
NewVolumeFormat
func NewVolumeFormat(source string, quiet bool) Format { switch source { case TableFormatKey: if quiet { return defaultVolumeQuietFormat } return defaultVolumeTableFormat case RawFormatKey: if quiet { return `name: {{.Name}}` } return `name: {{.Name}}\ndriver: {{.Driver}}\n` } return Format(source) }
go
func NewVolumeFormat(source string, quiet bool) Format { switch source { case TableFormatKey: if quiet { return defaultVolumeQuietFormat } return defaultVolumeTableFormat case RawFormatKey: if quiet { return `name: {{.Name}}` } return `name: {{.Name}}\ndriver: {{.Driver}}\n` } return Format(source) }
[ "func", "NewVolumeFormat", "(", "source", "string", ",", "quiet", "bool", ")", "Format", "{", "switch", "source", "{", "case", "TableFormatKey", ":", "if", "quiet", "{", "return", "defaultVolumeQuietFormat", "\n", "}", "\n", "return", "defaultVolumeTableFormat", "\n", "case", "RawFormatKey", ":", "if", "quiet", "{", "return", "`name: {{.Name}}`", "\n", "}", "\n", "return", "`name: {{.Name}}\\ndriver: {{.Driver}}\\n`", "\n", "}", "\n", "return", "Format", "(", "source", ")", "\n", "}" ]
// NewVolumeFormat returns a format for use with a volume Context
[ "NewVolumeFormat", "returns", "a", "format", "for", "use", "with", "a", "volume", "Context" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/command/formatter/volume.go#L22-L36
train
docker/cli
cli/command/formatter/volume.go
VolumeWrite
func VolumeWrite(ctx Context, volumes []*types.Volume) error { render := func(format func(subContext SubContext) error) error { for _, volume := range volumes { if err := format(&volumeContext{v: *volume}); err != nil { return err } } return nil } return ctx.Write(newVolumeContext(), render) }
go
func VolumeWrite(ctx Context, volumes []*types.Volume) error { render := func(format func(subContext SubContext) error) error { for _, volume := range volumes { if err := format(&volumeContext{v: *volume}); err != nil { return err } } return nil } return ctx.Write(newVolumeContext(), render) }
[ "func", "VolumeWrite", "(", "ctx", "Context", ",", "volumes", "[", "]", "*", "types", ".", "Volume", ")", "error", "{", "render", ":=", "func", "(", "format", "func", "(", "subContext", "SubContext", ")", "error", ")", "error", "{", "for", "_", ",", "volume", ":=", "range", "volumes", "{", "if", "err", ":=", "format", "(", "&", "volumeContext", "{", "v", ":", "*", "volume", "}", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}", "\n", "return", "ctx", ".", "Write", "(", "newVolumeContext", "(", ")", ",", "render", ")", "\n", "}" ]
// VolumeWrite writes formatted volumes using the Context
[ "VolumeWrite", "writes", "formatted", "volumes", "using", "the", "Context" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/command/formatter/volume.go#L39-L49
train
docker/cli
cli/command/registry/login.go
NewLoginCommand
func NewLoginCommand(dockerCli command.Cli) *cobra.Command { var opts loginOptions cmd := &cobra.Command{ Use: "login [OPTIONS] [SERVER]", Short: "Log in to a Docker registry", Long: "Log in to a Docker registry.\nIf no server is specified, the default is defined by the daemon.", Args: cli.RequiresMaxArgs(1), RunE: func(cmd *cobra.Command, args []string) error { if len(args) > 0 { opts.serverAddress = args[0] } return runLogin(dockerCli, opts) }, } flags := cmd.Flags() flags.StringVarP(&opts.user, "username", "u", "", "Username") flags.StringVarP(&opts.password, "password", "p", "", "Password") flags.BoolVarP(&opts.passwordStdin, "password-stdin", "", false, "Take the password from stdin") return cmd }
go
func NewLoginCommand(dockerCli command.Cli) *cobra.Command { var opts loginOptions cmd := &cobra.Command{ Use: "login [OPTIONS] [SERVER]", Short: "Log in to a Docker registry", Long: "Log in to a Docker registry.\nIf no server is specified, the default is defined by the daemon.", Args: cli.RequiresMaxArgs(1), RunE: func(cmd *cobra.Command, args []string) error { if len(args) > 0 { opts.serverAddress = args[0] } return runLogin(dockerCli, opts) }, } flags := cmd.Flags() flags.StringVarP(&opts.user, "username", "u", "", "Username") flags.StringVarP(&opts.password, "password", "p", "", "Password") flags.BoolVarP(&opts.passwordStdin, "password-stdin", "", false, "Take the password from stdin") return cmd }
[ "func", "NewLoginCommand", "(", "dockerCli", "command", ".", "Cli", ")", "*", "cobra", ".", "Command", "{", "var", "opts", "loginOptions", "\n\n", "cmd", ":=", "&", "cobra", ".", "Command", "{", "Use", ":", "\"", "\"", ",", "Short", ":", "\"", "\"", ",", "Long", ":", "\"", "\\n", "\"", ",", "Args", ":", "cli", ".", "RequiresMaxArgs", "(", "1", ")", ",", "RunE", ":", "func", "(", "cmd", "*", "cobra", ".", "Command", ",", "args", "[", "]", "string", ")", "error", "{", "if", "len", "(", "args", ")", ">", "0", "{", "opts", ".", "serverAddress", "=", "args", "[", "0", "]", "\n", "}", "\n", "return", "runLogin", "(", "dockerCli", ",", "opts", ")", "\n", "}", ",", "}", "\n\n", "flags", ":=", "cmd", ".", "Flags", "(", ")", "\n\n", "flags", ".", "StringVarP", "(", "&", "opts", ".", "user", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "flags", ".", "StringVarP", "(", "&", "opts", ".", "password", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "flags", ".", "BoolVarP", "(", "&", "opts", ".", "passwordStdin", ",", "\"", "\"", ",", "\"", "\"", ",", "false", ",", "\"", "\"", ")", "\n\n", "return", "cmd", "\n", "}" ]
// NewLoginCommand creates a new `docker login` command
[ "NewLoginCommand", "creates", "a", "new", "docker", "login", "command" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/command/registry/login.go#L33-L56
train
docker/cli
cli/command/container/kill.go
NewKillCommand
func NewKillCommand(dockerCli command.Cli) *cobra.Command { var opts killOptions cmd := &cobra.Command{ Use: "kill [OPTIONS] CONTAINER [CONTAINER...]", Short: "Kill one or more running containers", Args: cli.RequiresMinArgs(1), RunE: func(cmd *cobra.Command, args []string) error { opts.containers = args return runKill(dockerCli, &opts) }, } flags := cmd.Flags() flags.StringVarP(&opts.signal, "signal", "s", "KILL", "Signal to send to the container") return cmd }
go
func NewKillCommand(dockerCli command.Cli) *cobra.Command { var opts killOptions cmd := &cobra.Command{ Use: "kill [OPTIONS] CONTAINER [CONTAINER...]", Short: "Kill one or more running containers", Args: cli.RequiresMinArgs(1), RunE: func(cmd *cobra.Command, args []string) error { opts.containers = args return runKill(dockerCli, &opts) }, } flags := cmd.Flags() flags.StringVarP(&opts.signal, "signal", "s", "KILL", "Signal to send to the container") return cmd }
[ "func", "NewKillCommand", "(", "dockerCli", "command", ".", "Cli", ")", "*", "cobra", ".", "Command", "{", "var", "opts", "killOptions", "\n\n", "cmd", ":=", "&", "cobra", ".", "Command", "{", "Use", ":", "\"", "\"", ",", "Short", ":", "\"", "\"", ",", "Args", ":", "cli", ".", "RequiresMinArgs", "(", "1", ")", ",", "RunE", ":", "func", "(", "cmd", "*", "cobra", ".", "Command", ",", "args", "[", "]", "string", ")", "error", "{", "opts", ".", "containers", "=", "args", "\n", "return", "runKill", "(", "dockerCli", ",", "&", "opts", ")", "\n", "}", ",", "}", "\n\n", "flags", ":=", "cmd", ".", "Flags", "(", ")", "\n", "flags", ".", "StringVarP", "(", "&", "opts", ".", "signal", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "return", "cmd", "\n", "}" ]
// NewKillCommand creates a new cobra.Command for `docker kill`
[ "NewKillCommand", "creates", "a", "new", "cobra", ".", "Command", "for", "docker", "kill" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/command/container/kill.go#L21-L37
train
docker/cli
cli/manifest/types/types.go
OCIPlatform
func OCIPlatform(ps *manifestlist.PlatformSpec) *ocispec.Platform { if ps == nil { return nil } return &ocispec.Platform{ Architecture: ps.Architecture, OS: ps.OS, OSVersion: ps.OSVersion, OSFeatures: ps.OSFeatures, Variant: ps.Variant, } }
go
func OCIPlatform(ps *manifestlist.PlatformSpec) *ocispec.Platform { if ps == nil { return nil } return &ocispec.Platform{ Architecture: ps.Architecture, OS: ps.OS, OSVersion: ps.OSVersion, OSFeatures: ps.OSFeatures, Variant: ps.Variant, } }
[ "func", "OCIPlatform", "(", "ps", "*", "manifestlist", ".", "PlatformSpec", ")", "*", "ocispec", ".", "Platform", "{", "if", "ps", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "return", "&", "ocispec", ".", "Platform", "{", "Architecture", ":", "ps", ".", "Architecture", ",", "OS", ":", "ps", ".", "OS", ",", "OSVersion", ":", "ps", ".", "OSVersion", ",", "OSFeatures", ":", "ps", ".", "OSFeatures", ",", "Variant", ":", "ps", ".", "Variant", ",", "}", "\n", "}" ]
// OCIPlatform creates an OCI platform from a manifest list platform spec
[ "OCIPlatform", "creates", "an", "OCI", "platform", "from", "a", "manifest", "list", "platform", "spec" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/manifest/types/types.go#L26-L37
train
docker/cli
cli/manifest/types/types.go
PlatformSpecFromOCI
func PlatformSpecFromOCI(p *ocispec.Platform) *manifestlist.PlatformSpec { if p == nil { return nil } return &manifestlist.PlatformSpec{ Architecture: p.Architecture, OS: p.OS, OSVersion: p.OSVersion, OSFeatures: p.OSFeatures, Variant: p.Variant, } }
go
func PlatformSpecFromOCI(p *ocispec.Platform) *manifestlist.PlatformSpec { if p == nil { return nil } return &manifestlist.PlatformSpec{ Architecture: p.Architecture, OS: p.OS, OSVersion: p.OSVersion, OSFeatures: p.OSFeatures, Variant: p.Variant, } }
[ "func", "PlatformSpecFromOCI", "(", "p", "*", "ocispec", ".", "Platform", ")", "*", "manifestlist", ".", "PlatformSpec", "{", "if", "p", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "return", "&", "manifestlist", ".", "PlatformSpec", "{", "Architecture", ":", "p", ".", "Architecture", ",", "OS", ":", "p", ".", "OS", ",", "OSVersion", ":", "p", ".", "OSVersion", ",", "OSFeatures", ":", "p", ".", "OSFeatures", ",", "Variant", ":", "p", ".", "Variant", ",", "}", "\n", "}" ]
// PlatformSpecFromOCI creates a platform spec from OCI platform
[ "PlatformSpecFromOCI", "creates", "a", "platform", "spec", "from", "OCI", "platform" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/manifest/types/types.go#L40-L51
train
docker/cli
cli/manifest/types/types.go
Blobs
func (i ImageManifest) Blobs() []digest.Digest { digests := []digest.Digest{} for _, descriptor := range i.SchemaV2Manifest.References() { digests = append(digests, descriptor.Digest) } return digests }
go
func (i ImageManifest) Blobs() []digest.Digest { digests := []digest.Digest{} for _, descriptor := range i.SchemaV2Manifest.References() { digests = append(digests, descriptor.Digest) } return digests }
[ "func", "(", "i", "ImageManifest", ")", "Blobs", "(", ")", "[", "]", "digest", ".", "Digest", "{", "digests", ":=", "[", "]", "digest", ".", "Digest", "{", "}", "\n", "for", "_", ",", "descriptor", ":=", "range", "i", ".", "SchemaV2Manifest", ".", "References", "(", ")", "{", "digests", "=", "append", "(", "digests", ",", "descriptor", ".", "Digest", ")", "\n", "}", "\n", "return", "digests", "\n", "}" ]
// Blobs returns the digests for all the blobs referenced by this manifest
[ "Blobs", "returns", "the", "digests", "for", "all", "the", "blobs", "referenced", "by", "this", "manifest" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/manifest/types/types.go#L54-L60
train
docker/cli
cli/manifest/types/types.go
Payload
func (i ImageManifest) Payload() (string, []byte, error) { // TODO: If available, read content from a content store by digest switch { case i.SchemaV2Manifest != nil: return i.SchemaV2Manifest.Payload() default: return "", nil, errors.Errorf("%s has no payload", i.Ref) } }
go
func (i ImageManifest) Payload() (string, []byte, error) { // TODO: If available, read content from a content store by digest switch { case i.SchemaV2Manifest != nil: return i.SchemaV2Manifest.Payload() default: return "", nil, errors.Errorf("%s has no payload", i.Ref) } }
[ "func", "(", "i", "ImageManifest", ")", "Payload", "(", ")", "(", "string", ",", "[", "]", "byte", ",", "error", ")", "{", "// TODO: If available, read content from a content store by digest", "switch", "{", "case", "i", ".", "SchemaV2Manifest", "!=", "nil", ":", "return", "i", ".", "SchemaV2Manifest", ".", "Payload", "(", ")", "\n", "default", ":", "return", "\"", "\"", ",", "nil", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "i", ".", "Ref", ")", "\n", "}", "\n", "}" ]
// Payload returns the media type and bytes for the manifest
[ "Payload", "returns", "the", "media", "type", "and", "bytes", "for", "the", "manifest" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/manifest/types/types.go#L63-L71
train
docker/cli
cli/manifest/types/types.go
References
func (i ImageManifest) References() []distribution.Descriptor { switch { case i.SchemaV2Manifest != nil: return i.SchemaV2Manifest.References() default: return nil } }
go
func (i ImageManifest) References() []distribution.Descriptor { switch { case i.SchemaV2Manifest != nil: return i.SchemaV2Manifest.References() default: return nil } }
[ "func", "(", "i", "ImageManifest", ")", "References", "(", ")", "[", "]", "distribution", ".", "Descriptor", "{", "switch", "{", "case", "i", ".", "SchemaV2Manifest", "!=", "nil", ":", "return", "i", ".", "SchemaV2Manifest", ".", "References", "(", ")", "\n", "default", ":", "return", "nil", "\n", "}", "\n", "}" ]
// References implements the distribution.Manifest interface. It delegates to // the underlying manifest.
[ "References", "implements", "the", "distribution", ".", "Manifest", "interface", ".", "It", "delegates", "to", "the", "underlying", "manifest", "." ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/manifest/types/types.go#L75-L82
train
docker/cli
cli/manifest/types/types.go
NewImageManifest
func NewImageManifest(ref reference.Named, desc ocispec.Descriptor, manifest *schema2.DeserializedManifest) ImageManifest { return ImageManifest{ Ref: &SerializableNamed{Named: ref}, Descriptor: desc, SchemaV2Manifest: manifest, } }
go
func NewImageManifest(ref reference.Named, desc ocispec.Descriptor, manifest *schema2.DeserializedManifest) ImageManifest { return ImageManifest{ Ref: &SerializableNamed{Named: ref}, Descriptor: desc, SchemaV2Manifest: manifest, } }
[ "func", "NewImageManifest", "(", "ref", "reference", ".", "Named", ",", "desc", "ocispec", ".", "Descriptor", ",", "manifest", "*", "schema2", ".", "DeserializedManifest", ")", "ImageManifest", "{", "return", "ImageManifest", "{", "Ref", ":", "&", "SerializableNamed", "{", "Named", ":", "ref", "}", ",", "Descriptor", ":", "desc", ",", "SchemaV2Manifest", ":", "manifest", ",", "}", "\n", "}" ]
// NewImageManifest returns a new ImageManifest object. The values for Platform // are initialized from those in the image
[ "NewImageManifest", "returns", "a", "new", "ImageManifest", "object", ".", "The", "values", "for", "Platform", "are", "initialized", "from", "those", "in", "the", "image" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/manifest/types/types.go#L86-L92
train
docker/cli
cli/manifest/types/types.go
UnmarshalJSON
func (s *SerializableNamed) UnmarshalJSON(b []byte) error { var raw string if err := json.Unmarshal(b, &raw); err != nil { return errors.Wrapf(err, "invalid named reference bytes: %s", b) } var err error s.Named, err = reference.ParseNamed(raw) return err }
go
func (s *SerializableNamed) UnmarshalJSON(b []byte) error { var raw string if err := json.Unmarshal(b, &raw); err != nil { return errors.Wrapf(err, "invalid named reference bytes: %s", b) } var err error s.Named, err = reference.ParseNamed(raw) return err }
[ "func", "(", "s", "*", "SerializableNamed", ")", "UnmarshalJSON", "(", "b", "[", "]", "byte", ")", "error", "{", "var", "raw", "string", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "b", ",", "&", "raw", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "b", ")", "\n", "}", "\n", "var", "err", "error", "\n", "s", ".", "Named", ",", "err", "=", "reference", ".", "ParseNamed", "(", "raw", ")", "\n", "return", "err", "\n", "}" ]
// UnmarshalJSON loads the Named reference from JSON bytes
[ "UnmarshalJSON", "loads", "the", "Named", "reference", "from", "JSON", "bytes" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/manifest/types/types.go#L101-L109
train
docker/cli
cli/command/stack/kubernetes/stack.go
getServices
func (s *Stack) getServices() []string { services := make([]string, len(s.Spec.Services)) for i, service := range s.Spec.Services { services[i] = service.Name } sort.Strings(services) return services }
go
func (s *Stack) getServices() []string { services := make([]string, len(s.Spec.Services)) for i, service := range s.Spec.Services { services[i] = service.Name } sort.Strings(services) return services }
[ "func", "(", "s", "*", "Stack", ")", "getServices", "(", ")", "[", "]", "string", "{", "services", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "s", ".", "Spec", ".", "Services", ")", ")", "\n", "for", "i", ",", "service", ":=", "range", "s", ".", "Spec", ".", "Services", "{", "services", "[", "i", "]", "=", "service", ".", "Name", "\n", "}", "\n", "sort", ".", "Strings", "(", "services", ")", "\n", "return", "services", "\n", "}" ]
// getServices returns all the stack service names, sorted lexicographically
[ "getServices", "returns", "all", "the", "stack", "service", "names", "sorted", "lexicographically" ]
3273c2e23546dddd0ff8bb499f4aba02fe60bf30
https://github.com/docker/cli/blob/3273c2e23546dddd0ff8bb499f4aba02fe60bf30/cli/command/stack/kubernetes/stack.go#L44-L51
train