id
int32
0
167k
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
list
docstring
stringlengths
6
2.61k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
85
252
18,700
pkg/sftp
request.go
requestMethod
func requestMethod(p requestPacket) (method string) { switch p.(type) { case *sshFxpReadPacket, *sshFxpWritePacket, *sshFxpOpenPacket: // set in open() above case *sshFxpOpendirPacket, *sshFxpReaddirPacket: // set in opendir() above case *sshFxpSetstatPacket, *sshFxpFsetstatPacket: method = "Setstat" case *sshFxpRenamePacket: method = "Rename" case *sshFxpSymlinkPacket: method = "Symlink" case *sshFxpRemovePacket: method = "Remove" case *sshFxpStatPacket, *sshFxpLstatPacket, *sshFxpFstatPacket: method = "Stat" case *sshFxpRmdirPacket: method = "Rmdir" case *sshFxpReadlinkPacket: method = "Readlink" case *sshFxpMkdirPacket: method = "Mkdir" } return method }
go
func requestMethod(p requestPacket) (method string) { switch p.(type) { case *sshFxpReadPacket, *sshFxpWritePacket, *sshFxpOpenPacket: // set in open() above case *sshFxpOpendirPacket, *sshFxpReaddirPacket: // set in opendir() above case *sshFxpSetstatPacket, *sshFxpFsetstatPacket: method = "Setstat" case *sshFxpRenamePacket: method = "Rename" case *sshFxpSymlinkPacket: method = "Symlink" case *sshFxpRemovePacket: method = "Remove" case *sshFxpStatPacket, *sshFxpLstatPacket, *sshFxpFstatPacket: method = "Stat" case *sshFxpRmdirPacket: method = "Rmdir" case *sshFxpReadlinkPacket: method = "Readlink" case *sshFxpMkdirPacket: method = "Mkdir" } return method }
[ "func", "requestMethod", "(", "p", "requestPacket", ")", "(", "method", "string", ")", "{", "switch", "p", ".", "(", "type", ")", "{", "case", "*", "sshFxpReadPacket", ",", "*", "sshFxpWritePacket", ",", "*", "sshFxpOpenPacket", ":", "// set in open() above", ...
// init attributes of request object from packet data
[ "init", "attributes", "of", "request", "object", "from", "packet", "data" ]
5bcd86d72480cb6de4bc5804f832e27855ba033f
https://github.com/pkg/sftp/blob/5bcd86d72480cb6de4bc5804f832e27855ba033f/request.go#L359-L383
18,701
pkg/sftp
client.go
MaxConcurrentRequestsPerFile
func MaxConcurrentRequestsPerFile(n int) ClientOption { return func(c *Client) error { if n < 1 { return errors.Errorf("n must be greater or equal to 1") } c.maxConcurrentRequests = n return nil } }
go
func MaxConcurrentRequestsPerFile(n int) ClientOption { return func(c *Client) error { if n < 1 { return errors.Errorf("n must be greater or equal to 1") } c.maxConcurrentRequests = n return nil } }
[ "func", "MaxConcurrentRequestsPerFile", "(", "n", "int", ")", "ClientOption", "{", "return", "func", "(", "c", "*", "Client", ")", "error", "{", "if", "n", "<", "1", "{", "return", "errors", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "c", ...
// MaxConcurrentRequestsPerFile sets the maximum concurrent requests allowed for a single file. // // The default maximum concurrent requests is 64.
[ "MaxConcurrentRequestsPerFile", "sets", "the", "maximum", "concurrent", "requests", "allowed", "for", "a", "single", "file", ".", "The", "default", "maximum", "concurrent", "requests", "is", "64", "." ]
5bcd86d72480cb6de4bc5804f832e27855ba033f
https://github.com/pkg/sftp/blob/5bcd86d72480cb6de4bc5804f832e27855ba033f/client.go#L82-L90
18,702
pkg/sftp
client.go
NewClient
func NewClient(conn *ssh.Client, opts ...ClientOption) (*Client, error) { s, err := conn.NewSession() if err != nil { return nil, err } if err := s.RequestSubsystem("sftp"); err != nil { return nil, err } pw, err := s.StdinPipe() if err != nil { return nil, err } pr, err := s.StdoutPipe() if err != nil { return nil, err } return NewClientPipe(pr, pw, opts...) }
go
func NewClient(conn *ssh.Client, opts ...ClientOption) (*Client, error) { s, err := conn.NewSession() if err != nil { return nil, err } if err := s.RequestSubsystem("sftp"); err != nil { return nil, err } pw, err := s.StdinPipe() if err != nil { return nil, err } pr, err := s.StdoutPipe() if err != nil { return nil, err } return NewClientPipe(pr, pw, opts...) }
[ "func", "NewClient", "(", "conn", "*", "ssh", ".", "Client", ",", "opts", "...", "ClientOption", ")", "(", "*", "Client", ",", "error", ")", "{", "s", ",", "err", ":=", "conn", ".", "NewSession", "(", ")", "\n", "if", "err", "!=", "nil", "{", "re...
// NewClient creates a new SFTP client on conn, using zero or more option // functions.
[ "NewClient", "creates", "a", "new", "SFTP", "client", "on", "conn", "using", "zero", "or", "more", "option", "functions", "." ]
5bcd86d72480cb6de4bc5804f832e27855ba033f
https://github.com/pkg/sftp/blob/5bcd86d72480cb6de4bc5804f832e27855ba033f/client.go#L94-L112
18,703
pkg/sftp
client.go
Walk
func (c *Client) Walk(root string) *fs.Walker { return fs.WalkFS(root, c) }
go
func (c *Client) Walk(root string) *fs.Walker { return fs.WalkFS(root, c) }
[ "func", "(", "c", "*", "Client", ")", "Walk", "(", "root", "string", ")", "*", "fs", ".", "Walker", "{", "return", "fs", ".", "WalkFS", "(", "root", ",", "c", ")", "\n", "}" ]
// Walk returns a new Walker rooted at root.
[ "Walk", "returns", "a", "new", "Walker", "rooted", "at", "root", "." ]
5bcd86d72480cb6de4bc5804f832e27855ba033f
https://github.com/pkg/sftp/blob/5bcd86d72480cb6de4bc5804f832e27855ba033f/client.go#L199-L201
18,704
pkg/sftp
client.go
ReadDir
func (c *Client) ReadDir(p string) ([]os.FileInfo, error) { handle, err := c.opendir(p) if err != nil { return nil, err } defer c.close(handle) // this has to defer earlier than the lock below var attrs []os.FileInfo var done = false for !done { id := c.nextID() typ, data, err1 := c.sendPacket(sshFxpReaddirPacket{ ID: id, Handle: handle, }) if err1 != nil { err = err1 done = true break } switch typ { case ssh_FXP_NAME: sid, data := unmarshalUint32(data) if sid != id { return nil, &unexpectedIDErr{id, sid} } count, data := unmarshalUint32(data) for i := uint32(0); i < count; i++ { var filename string filename, data = unmarshalString(data) _, data = unmarshalString(data) // discard longname var attr *FileStat attr, data = unmarshalAttrs(data) if filename == "." || filename == ".." { continue } attrs = append(attrs, fileInfoFromStat(attr, path.Base(filename))) } case ssh_FXP_STATUS: // TODO(dfc) scope warning! err = normaliseError(unmarshalStatus(id, data)) done = true default: return nil, unimplementedPacketErr(typ) } } if err == io.EOF { err = nil } return attrs, err }
go
func (c *Client) ReadDir(p string) ([]os.FileInfo, error) { handle, err := c.opendir(p) if err != nil { return nil, err } defer c.close(handle) // this has to defer earlier than the lock below var attrs []os.FileInfo var done = false for !done { id := c.nextID() typ, data, err1 := c.sendPacket(sshFxpReaddirPacket{ ID: id, Handle: handle, }) if err1 != nil { err = err1 done = true break } switch typ { case ssh_FXP_NAME: sid, data := unmarshalUint32(data) if sid != id { return nil, &unexpectedIDErr{id, sid} } count, data := unmarshalUint32(data) for i := uint32(0); i < count; i++ { var filename string filename, data = unmarshalString(data) _, data = unmarshalString(data) // discard longname var attr *FileStat attr, data = unmarshalAttrs(data) if filename == "." || filename == ".." { continue } attrs = append(attrs, fileInfoFromStat(attr, path.Base(filename))) } case ssh_FXP_STATUS: // TODO(dfc) scope warning! err = normaliseError(unmarshalStatus(id, data)) done = true default: return nil, unimplementedPacketErr(typ) } } if err == io.EOF { err = nil } return attrs, err }
[ "func", "(", "c", "*", "Client", ")", "ReadDir", "(", "p", "string", ")", "(", "[", "]", "os", ".", "FileInfo", ",", "error", ")", "{", "handle", ",", "err", ":=", "c", ".", "opendir", "(", "p", ")", "\n", "if", "err", "!=", "nil", "{", "retu...
// ReadDir reads the directory named by dirname and returns a list of // directory entries.
[ "ReadDir", "reads", "the", "directory", "named", "by", "dirname", "and", "returns", "a", "list", "of", "directory", "entries", "." ]
5bcd86d72480cb6de4bc5804f832e27855ba033f
https://github.com/pkg/sftp/blob/5bcd86d72480cb6de4bc5804f832e27855ba033f/client.go#L205-L254
18,705
pkg/sftp
client.go
Stat
func (c *Client) Stat(p string) (os.FileInfo, error) { id := c.nextID() typ, data, err := c.sendPacket(sshFxpStatPacket{ ID: id, Path: p, }) if err != nil { return nil, err } switch typ { case ssh_FXP_ATTRS: sid, data := unmarshalUint32(data) if sid != id { return nil, &unexpectedIDErr{id, sid} } attr, _ := unmarshalAttrs(data) return fileInfoFromStat(attr, path.Base(p)), nil case ssh_FXP_STATUS: return nil, normaliseError(unmarshalStatus(id, data)) default: return nil, unimplementedPacketErr(typ) } }
go
func (c *Client) Stat(p string) (os.FileInfo, error) { id := c.nextID() typ, data, err := c.sendPacket(sshFxpStatPacket{ ID: id, Path: p, }) if err != nil { return nil, err } switch typ { case ssh_FXP_ATTRS: sid, data := unmarshalUint32(data) if sid != id { return nil, &unexpectedIDErr{id, sid} } attr, _ := unmarshalAttrs(data) return fileInfoFromStat(attr, path.Base(p)), nil case ssh_FXP_STATUS: return nil, normaliseError(unmarshalStatus(id, data)) default: return nil, unimplementedPacketErr(typ) } }
[ "func", "(", "c", "*", "Client", ")", "Stat", "(", "p", "string", ")", "(", "os", ".", "FileInfo", ",", "error", ")", "{", "id", ":=", "c", ".", "nextID", "(", ")", "\n", "typ", ",", "data", ",", "err", ":=", "c", ".", "sendPacket", "(", "ssh...
// Stat returns a FileInfo structure describing the file specified by path 'p'. // If 'p' is a symbolic link, the returned FileInfo structure describes the referent file.
[ "Stat", "returns", "a", "FileInfo", "structure", "describing", "the", "file", "specified", "by", "path", "p", ".", "If", "p", "is", "a", "symbolic", "link", "the", "returned", "FileInfo", "structure", "describes", "the", "referent", "file", "." ]
5bcd86d72480cb6de4bc5804f832e27855ba033f
https://github.com/pkg/sftp/blob/5bcd86d72480cb6de4bc5804f832e27855ba033f/client.go#L282-L304
18,706
pkg/sftp
client.go
ReadLink
func (c *Client) ReadLink(p string) (string, error) { id := c.nextID() typ, data, err := c.sendPacket(sshFxpReadlinkPacket{ ID: id, Path: p, }) if err != nil { return "", err } switch typ { case ssh_FXP_NAME: sid, data := unmarshalUint32(data) if sid != id { return "", &unexpectedIDErr{id, sid} } count, data := unmarshalUint32(data) if count != 1 { return "", unexpectedCount(1, count) } filename, _ := unmarshalString(data) // ignore dummy attributes return filename, nil case ssh_FXP_STATUS: return "", normaliseError(unmarshalStatus(id, data)) default: return "", unimplementedPacketErr(typ) } }
go
func (c *Client) ReadLink(p string) (string, error) { id := c.nextID() typ, data, err := c.sendPacket(sshFxpReadlinkPacket{ ID: id, Path: p, }) if err != nil { return "", err } switch typ { case ssh_FXP_NAME: sid, data := unmarshalUint32(data) if sid != id { return "", &unexpectedIDErr{id, sid} } count, data := unmarshalUint32(data) if count != 1 { return "", unexpectedCount(1, count) } filename, _ := unmarshalString(data) // ignore dummy attributes return filename, nil case ssh_FXP_STATUS: return "", normaliseError(unmarshalStatus(id, data)) default: return "", unimplementedPacketErr(typ) } }
[ "func", "(", "c", "*", "Client", ")", "ReadLink", "(", "p", "string", ")", "(", "string", ",", "error", ")", "{", "id", ":=", "c", ".", "nextID", "(", ")", "\n", "typ", ",", "data", ",", "err", ":=", "c", ".", "sendPacket", "(", "sshFxpReadlinkPa...
// ReadLink reads the target of a symbolic link.
[ "ReadLink", "reads", "the", "target", "of", "a", "symbolic", "link", "." ]
5bcd86d72480cb6de4bc5804f832e27855ba033f
https://github.com/pkg/sftp/blob/5bcd86d72480cb6de4bc5804f832e27855ba033f/client.go#L333-L359
18,707
pkg/sftp
client.go
Symlink
func (c *Client) Symlink(oldname, newname string) error { id := c.nextID() typ, data, err := c.sendPacket(sshFxpSymlinkPacket{ ID: id, Linkpath: newname, Targetpath: oldname, }) if err != nil { return err } switch typ { case ssh_FXP_STATUS: return normaliseError(unmarshalStatus(id, data)) default: return unimplementedPacketErr(typ) } }
go
func (c *Client) Symlink(oldname, newname string) error { id := c.nextID() typ, data, err := c.sendPacket(sshFxpSymlinkPacket{ ID: id, Linkpath: newname, Targetpath: oldname, }) if err != nil { return err } switch typ { case ssh_FXP_STATUS: return normaliseError(unmarshalStatus(id, data)) default: return unimplementedPacketErr(typ) } }
[ "func", "(", "c", "*", "Client", ")", "Symlink", "(", "oldname", ",", "newname", "string", ")", "error", "{", "id", ":=", "c", ".", "nextID", "(", ")", "\n", "typ", ",", "data", ",", "err", ":=", "c", ".", "sendPacket", "(", "sshFxpSymlinkPacket", ...
// Symlink creates a symbolic link at 'newname', pointing at target 'oldname'
[ "Symlink", "creates", "a", "symbolic", "link", "at", "newname", "pointing", "at", "target", "oldname" ]
5bcd86d72480cb6de4bc5804f832e27855ba033f
https://github.com/pkg/sftp/blob/5bcd86d72480cb6de4bc5804f832e27855ba033f/client.go#L362-L378
18,708
pkg/sftp
client.go
setstat
func (c *Client) setstat(path string, flags uint32, attrs interface{}) error { id := c.nextID() typ, data, err := c.sendPacket(sshFxpSetstatPacket{ ID: id, Path: path, Flags: flags, Attrs: attrs, }) if err != nil { return err } switch typ { case ssh_FXP_STATUS: return normaliseError(unmarshalStatus(id, data)) default: return unimplementedPacketErr(typ) } }
go
func (c *Client) setstat(path string, flags uint32, attrs interface{}) error { id := c.nextID() typ, data, err := c.sendPacket(sshFxpSetstatPacket{ ID: id, Path: path, Flags: flags, Attrs: attrs, }) if err != nil { return err } switch typ { case ssh_FXP_STATUS: return normaliseError(unmarshalStatus(id, data)) default: return unimplementedPacketErr(typ) } }
[ "func", "(", "c", "*", "Client", ")", "setstat", "(", "path", "string", ",", "flags", "uint32", ",", "attrs", "interface", "{", "}", ")", "error", "{", "id", ":=", "c", ".", "nextID", "(", ")", "\n", "typ", ",", "data", ",", "err", ":=", "c", "...
// setstat is a convience wrapper to allow for changing of various parts of the file descriptor.
[ "setstat", "is", "a", "convience", "wrapper", "to", "allow", "for", "changing", "of", "various", "parts", "of", "the", "file", "descriptor", "." ]
5bcd86d72480cb6de4bc5804f832e27855ba033f
https://github.com/pkg/sftp/blob/5bcd86d72480cb6de4bc5804f832e27855ba033f/client.go#L381-L398
18,709
pkg/sftp
client.go
Chown
func (c *Client) Chown(path string, uid, gid int) error { type owner struct { UID uint32 GID uint32 } attrs := owner{uint32(uid), uint32(gid)} return c.setstat(path, ssh_FILEXFER_ATTR_UIDGID, attrs) }
go
func (c *Client) Chown(path string, uid, gid int) error { type owner struct { UID uint32 GID uint32 } attrs := owner{uint32(uid), uint32(gid)} return c.setstat(path, ssh_FILEXFER_ATTR_UIDGID, attrs) }
[ "func", "(", "c", "*", "Client", ")", "Chown", "(", "path", "string", ",", "uid", ",", "gid", "int", ")", "error", "{", "type", "owner", "struct", "{", "UID", "uint32", "\n", "GID", "uint32", "\n", "}", "\n", "attrs", ":=", "owner", "{", "uint32", ...
// Chown changes the user and group owners of the named file.
[ "Chown", "changes", "the", "user", "and", "group", "owners", "of", "the", "named", "file", "." ]
5bcd86d72480cb6de4bc5804f832e27855ba033f
https://github.com/pkg/sftp/blob/5bcd86d72480cb6de4bc5804f832e27855ba033f/client.go#L411-L418
18,710
pkg/sftp
client.go
Chmod
func (c *Client) Chmod(path string, mode os.FileMode) error { return c.setstat(path, ssh_FILEXFER_ATTR_PERMISSIONS, uint32(mode)) }
go
func (c *Client) Chmod(path string, mode os.FileMode) error { return c.setstat(path, ssh_FILEXFER_ATTR_PERMISSIONS, uint32(mode)) }
[ "func", "(", "c", "*", "Client", ")", "Chmod", "(", "path", "string", ",", "mode", "os", ".", "FileMode", ")", "error", "{", "return", "c", ".", "setstat", "(", "path", ",", "ssh_FILEXFER_ATTR_PERMISSIONS", ",", "uint32", "(", "mode", ")", ")", "\n", ...
// Chmod changes the permissions of the named file.
[ "Chmod", "changes", "the", "permissions", "of", "the", "named", "file", "." ]
5bcd86d72480cb6de4bc5804f832e27855ba033f
https://github.com/pkg/sftp/blob/5bcd86d72480cb6de4bc5804f832e27855ba033f/client.go#L421-L423
18,711
pkg/sftp
client.go
Truncate
func (c *Client) Truncate(path string, size int64) error { return c.setstat(path, ssh_FILEXFER_ATTR_SIZE, uint64(size)) }
go
func (c *Client) Truncate(path string, size int64) error { return c.setstat(path, ssh_FILEXFER_ATTR_SIZE, uint64(size)) }
[ "func", "(", "c", "*", "Client", ")", "Truncate", "(", "path", "string", ",", "size", "int64", ")", "error", "{", "return", "c", ".", "setstat", "(", "path", ",", "ssh_FILEXFER_ATTR_SIZE", ",", "uint64", "(", "size", ")", ")", "\n", "}" ]
// Truncate sets the size of the named file. Although it may be safely assumed // that if the size is less than its current size it will be truncated to fit, // the SFTP protocol does not specify what behavior the server should do when setting // size greater than the current size.
[ "Truncate", "sets", "the", "size", "of", "the", "named", "file", ".", "Although", "it", "may", "be", "safely", "assumed", "that", "if", "the", "size", "is", "less", "than", "its", "current", "size", "it", "will", "be", "truncated", "to", "fit", "the", ...
5bcd86d72480cb6de4bc5804f832e27855ba033f
https://github.com/pkg/sftp/blob/5bcd86d72480cb6de4bc5804f832e27855ba033f/client.go#L429-L431
18,712
pkg/sftp
client.go
Open
func (c *Client) Open(path string) (*File, error) { return c.open(path, flags(os.O_RDONLY)) }
go
func (c *Client) Open(path string) (*File, error) { return c.open(path, flags(os.O_RDONLY)) }
[ "func", "(", "c", "*", "Client", ")", "Open", "(", "path", "string", ")", "(", "*", "File", ",", "error", ")", "{", "return", "c", ".", "open", "(", "path", ",", "flags", "(", "os", ".", "O_RDONLY", ")", ")", "\n", "}" ]
// Open opens the named file for reading. If successful, methods on the // returned file can be used for reading; the associated file descriptor // has mode O_RDONLY.
[ "Open", "opens", "the", "named", "file", "for", "reading", ".", "If", "successful", "methods", "on", "the", "returned", "file", "can", "be", "used", "for", "reading", ";", "the", "associated", "file", "descriptor", "has", "mode", "O_RDONLY", "." ]
5bcd86d72480cb6de4bc5804f832e27855ba033f
https://github.com/pkg/sftp/blob/5bcd86d72480cb6de4bc5804f832e27855ba033f/client.go#L436-L438
18,713
pkg/sftp
client.go
close
func (c *Client) close(handle string) error { id := c.nextID() typ, data, err := c.sendPacket(sshFxpClosePacket{ ID: id, Handle: handle, }) if err != nil { return err } switch typ { case ssh_FXP_STATUS: return normaliseError(unmarshalStatus(id, data)) default: return unimplementedPacketErr(typ) } }
go
func (c *Client) close(handle string) error { id := c.nextID() typ, data, err := c.sendPacket(sshFxpClosePacket{ ID: id, Handle: handle, }) if err != nil { return err } switch typ { case ssh_FXP_STATUS: return normaliseError(unmarshalStatus(id, data)) default: return unimplementedPacketErr(typ) } }
[ "func", "(", "c", "*", "Client", ")", "close", "(", "handle", "string", ")", "error", "{", "id", ":=", "c", ".", "nextID", "(", ")", "\n", "typ", ",", "data", ",", "err", ":=", "c", ".", "sendPacket", "(", "sshFxpClosePacket", "{", "ID", ":", "id...
// close closes a handle handle previously returned in the response // to SSH_FXP_OPEN or SSH_FXP_OPENDIR. The handle becomes invalid // immediately after this request has been sent.
[ "close", "closes", "a", "handle", "handle", "previously", "returned", "in", "the", "response", "to", "SSH_FXP_OPEN", "or", "SSH_FXP_OPENDIR", ".", "The", "handle", "becomes", "invalid", "immediately", "after", "this", "request", "has", "been", "sent", "." ]
5bcd86d72480cb6de4bc5804f832e27855ba033f
https://github.com/pkg/sftp/blob/5bcd86d72480cb6de4bc5804f832e27855ba033f/client.go#L475-L490
18,714
pkg/sftp
client.go
StatVFS
func (c *Client) StatVFS(path string) (*StatVFS, error) { // send the StatVFS packet to the server id := c.nextID() typ, data, err := c.sendPacket(sshFxpStatvfsPacket{ ID: id, Path: path, }) if err != nil { return nil, err } switch typ { // server responded with valid data case ssh_FXP_EXTENDED_REPLY: var response StatVFS err = binary.Read(bytes.NewReader(data), binary.BigEndian, &response) if err != nil { return nil, errors.New("can not parse reply") } return &response, nil // the resquest failed case ssh_FXP_STATUS: return nil, errors.New(fxp(ssh_FXP_STATUS).String()) default: return nil, unimplementedPacketErr(typ) } }
go
func (c *Client) StatVFS(path string) (*StatVFS, error) { // send the StatVFS packet to the server id := c.nextID() typ, data, err := c.sendPacket(sshFxpStatvfsPacket{ ID: id, Path: path, }) if err != nil { return nil, err } switch typ { // server responded with valid data case ssh_FXP_EXTENDED_REPLY: var response StatVFS err = binary.Read(bytes.NewReader(data), binary.BigEndian, &response) if err != nil { return nil, errors.New("can not parse reply") } return &response, nil // the resquest failed case ssh_FXP_STATUS: return nil, errors.New(fxp(ssh_FXP_STATUS).String()) default: return nil, unimplementedPacketErr(typ) } }
[ "func", "(", "c", "*", "Client", ")", "StatVFS", "(", "path", "string", ")", "(", "*", "StatVFS", ",", "error", ")", "{", "// send the StatVFS packet to the server", "id", ":=", "c", ".", "nextID", "(", ")", "\n", "typ", ",", "data", ",", "err", ":=", ...
// StatVFS retrieves VFS statistics from a remote host. // // It implements the statvfs@openssh.com SSH_FXP_EXTENDED feature // from http://www.opensource.apple.com/source/OpenSSH/OpenSSH-175/openssh/PROTOCOL?txt.
[ "StatVFS", "retrieves", "VFS", "statistics", "from", "a", "remote", "host", ".", "It", "implements", "the", "statvfs" ]
5bcd86d72480cb6de4bc5804f832e27855ba033f
https://github.com/pkg/sftp/blob/5bcd86d72480cb6de4bc5804f832e27855ba033f/client.go#L520-L549
18,715
pkg/sftp
client.go
Remove
func (c *Client) Remove(path string) error { err := c.removeFile(path) if err, ok := err.(*StatusError); ok { switch err.Code { // some servers, *cough* osx *cough*, return EPERM, not ENODIR. // serv-u returns ssh_FX_FILE_IS_A_DIRECTORY case ssh_FX_PERMISSION_DENIED, ssh_FX_FAILURE, ssh_FX_FILE_IS_A_DIRECTORY: return c.RemoveDirectory(path) } } return err }
go
func (c *Client) Remove(path string) error { err := c.removeFile(path) if err, ok := err.(*StatusError); ok { switch err.Code { // some servers, *cough* osx *cough*, return EPERM, not ENODIR. // serv-u returns ssh_FX_FILE_IS_A_DIRECTORY case ssh_FX_PERMISSION_DENIED, ssh_FX_FAILURE, ssh_FX_FILE_IS_A_DIRECTORY: return c.RemoveDirectory(path) } } return err }
[ "func", "(", "c", "*", "Client", ")", "Remove", "(", "path", "string", ")", "error", "{", "err", ":=", "c", ".", "removeFile", "(", "path", ")", "\n", "if", "err", ",", "ok", ":=", "err", ".", "(", "*", "StatusError", ")", ";", "ok", "{", "swit...
// Remove removes the specified file or directory. An error will be returned if no // file or directory with the specified path exists, or if the specified directory // is not empty.
[ "Remove", "removes", "the", "specified", "file", "or", "directory", ".", "An", "error", "will", "be", "returned", "if", "no", "file", "or", "directory", "with", "the", "specified", "path", "exists", "or", "if", "the", "specified", "directory", "is", "not", ...
5bcd86d72480cb6de4bc5804f832e27855ba033f
https://github.com/pkg/sftp/blob/5bcd86d72480cb6de4bc5804f832e27855ba033f/client.go#L559-L570
18,716
pkg/sftp
client.go
Rename
func (c *Client) Rename(oldname, newname string) error { id := c.nextID() typ, data, err := c.sendPacket(sshFxpRenamePacket{ ID: id, Oldpath: oldname, Newpath: newname, }) if err != nil { return err } switch typ { case ssh_FXP_STATUS: return normaliseError(unmarshalStatus(id, data)) default: return unimplementedPacketErr(typ) } }
go
func (c *Client) Rename(oldname, newname string) error { id := c.nextID() typ, data, err := c.sendPacket(sshFxpRenamePacket{ ID: id, Oldpath: oldname, Newpath: newname, }) if err != nil { return err } switch typ { case ssh_FXP_STATUS: return normaliseError(unmarshalStatus(id, data)) default: return unimplementedPacketErr(typ) } }
[ "func", "(", "c", "*", "Client", ")", "Rename", "(", "oldname", ",", "newname", "string", ")", "error", "{", "id", ":=", "c", ".", "nextID", "(", ")", "\n", "typ", ",", "data", ",", "err", ":=", "c", ".", "sendPacket", "(", "sshFxpRenamePacket", "{...
// Rename renames a file.
[ "Rename", "renames", "a", "file", "." ]
5bcd86d72480cb6de4bc5804f832e27855ba033f
https://github.com/pkg/sftp/blob/5bcd86d72480cb6de4bc5804f832e27855ba033f/client.go#L608-L624
18,717
pkg/sftp
client.go
MkdirAll
func (c *Client) MkdirAll(path string) error { // Most of this code mimics https://golang.org/src/os/path.go?s=514:561#L13 // Fast path: if we can tell whether path is a directory or file, stop with success or error. dir, err := c.Stat(path) if err == nil { if dir.IsDir() { return nil } return &os.PathError{Op: "mkdir", Path: path, Err: syscall.ENOTDIR} } // Slow path: make sure parent exists and then call Mkdir for path. i := len(path) for i > 0 && os.IsPathSeparator(path[i-1]) { // Skip trailing path separator. i-- } j := i for j > 0 && !os.IsPathSeparator(path[j-1]) { // Scan backward over element. j-- } if j > 1 { // Create parent err = c.MkdirAll(path[0 : j-1]) if err != nil { return err } } // Parent now exists; invoke Mkdir and use its result. err = c.Mkdir(path) if err != nil { // Handle arguments like "foo/." by // double-checking that directory doesn't exist. dir, err1 := c.Lstat(path) if err1 == nil && dir.IsDir() { return nil } return err } return nil }
go
func (c *Client) MkdirAll(path string) error { // Most of this code mimics https://golang.org/src/os/path.go?s=514:561#L13 // Fast path: if we can tell whether path is a directory or file, stop with success or error. dir, err := c.Stat(path) if err == nil { if dir.IsDir() { return nil } return &os.PathError{Op: "mkdir", Path: path, Err: syscall.ENOTDIR} } // Slow path: make sure parent exists and then call Mkdir for path. i := len(path) for i > 0 && os.IsPathSeparator(path[i-1]) { // Skip trailing path separator. i-- } j := i for j > 0 && !os.IsPathSeparator(path[j-1]) { // Scan backward over element. j-- } if j > 1 { // Create parent err = c.MkdirAll(path[0 : j-1]) if err != nil { return err } } // Parent now exists; invoke Mkdir and use its result. err = c.Mkdir(path) if err != nil { // Handle arguments like "foo/." by // double-checking that directory doesn't exist. dir, err1 := c.Lstat(path) if err1 == nil && dir.IsDir() { return nil } return err } return nil }
[ "func", "(", "c", "*", "Client", ")", "MkdirAll", "(", "path", "string", ")", "error", "{", "// Most of this code mimics https://golang.org/src/os/path.go?s=514:561#L13", "// Fast path: if we can tell whether path is a directory or file, stop with success or error.", "dir", ",", "e...
// MkdirAll creates a directory named path, along with any necessary parents, // and returns nil, or else returns an error. // If path is already a directory, MkdirAll does nothing and returns nil. // If path contains a regular file, an error is returned
[ "MkdirAll", "creates", "a", "directory", "named", "path", "along", "with", "any", "necessary", "parents", "and", "returns", "nil", "or", "else", "returns", "an", "error", ".", "If", "path", "is", "already", "a", "directory", "MkdirAll", "does", "nothing", "a...
5bcd86d72480cb6de4bc5804f832e27855ba033f
https://github.com/pkg/sftp/blob/5bcd86d72480cb6de4bc5804f832e27855ba033f/client.go#L704-L746
18,718
pkg/sftp
client.go
applyOptions
func (c *Client) applyOptions(opts ...ClientOption) error { for _, f := range opts { if err := f(c); err != nil { return err } } return nil }
go
func (c *Client) applyOptions(opts ...ClientOption) error { for _, f := range opts { if err := f(c); err != nil { return err } } return nil }
[ "func", "(", "c", "*", "Client", ")", "applyOptions", "(", "opts", "...", "ClientOption", ")", "error", "{", "for", "_", ",", "f", ":=", "range", "opts", "{", "if", "err", ":=", "f", "(", "c", ")", ";", "err", "!=", "nil", "{", "return", "err", ...
// applyOptions applies options functions to the Client. // If an error is encountered, option processing ceases.
[ "applyOptions", "applies", "options", "functions", "to", "the", "Client", ".", "If", "an", "error", "is", "encountered", "option", "processing", "ceases", "." ]
5bcd86d72480cb6de4bc5804f832e27855ba033f
https://github.com/pkg/sftp/blob/5bcd86d72480cb6de4bc5804f832e27855ba033f/client.go#L750-L757
18,719
pkg/sftp
client.go
Stat
func (f *File) Stat() (os.FileInfo, error) { fs, err := f.c.fstat(f.handle) if err != nil { return nil, err } return fileInfoFromStat(fs, path.Base(f.path)), nil }
go
func (f *File) Stat() (os.FileInfo, error) { fs, err := f.c.fstat(f.handle) if err != nil { return nil, err } return fileInfoFromStat(fs, path.Base(f.path)), nil }
[ "func", "(", "f", "*", "File", ")", "Stat", "(", ")", "(", "os", ".", "FileInfo", ",", "error", ")", "{", "fs", ",", "err", ":=", "f", ".", "c", ".", "fstat", "(", "f", ".", "handle", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil...
// Stat returns the FileInfo structure describing file. If there is an // error.
[ "Stat", "returns", "the", "FileInfo", "structure", "describing", "file", ".", "If", "there", "is", "an", "error", "." ]
5bcd86d72480cb6de4bc5804f832e27855ba033f
https://github.com/pkg/sftp/blob/5bcd86d72480cb6de4bc5804f832e27855ba033f/client.go#L1020-L1026
18,720
pkg/sftp
client.go
Seek
func (f *File) Seek(offset int64, whence int) (int64, error) { switch whence { case io.SeekStart: f.offset = uint64(offset) case io.SeekCurrent: f.offset = uint64(int64(f.offset) + offset) case io.SeekEnd: fi, err := f.Stat() if err != nil { return int64(f.offset), err } f.offset = uint64(fi.Size() + offset) default: return int64(f.offset), unimplementedSeekWhence(whence) } return int64(f.offset), nil }
go
func (f *File) Seek(offset int64, whence int) (int64, error) { switch whence { case io.SeekStart: f.offset = uint64(offset) case io.SeekCurrent: f.offset = uint64(int64(f.offset) + offset) case io.SeekEnd: fi, err := f.Stat() if err != nil { return int64(f.offset), err } f.offset = uint64(fi.Size() + offset) default: return int64(f.offset), unimplementedSeekWhence(whence) } return int64(f.offset), nil }
[ "func", "(", "f", "*", "File", ")", "Seek", "(", "offset", "int64", ",", "whence", "int", ")", "(", "int64", ",", "error", ")", "{", "switch", "whence", "{", "case", "io", ".", "SeekStart", ":", "f", ".", "offset", "=", "uint64", "(", "offset", "...
// Seek implements io.Seeker by setting the client offset for the next Read or // Write. It returns the next offset read. Seeking before or after the end of // the file is undefined. Seeking relative to the end calls Stat.
[ "Seek", "implements", "io", ".", "Seeker", "by", "setting", "the", "client", "offset", "for", "the", "next", "Read", "or", "Write", ".", "It", "returns", "the", "next", "offset", "read", ".", "Seeking", "before", "or", "after", "the", "end", "of", "the",...
5bcd86d72480cb6de4bc5804f832e27855ba033f
https://github.com/pkg/sftp/blob/5bcd86d72480cb6de4bc5804f832e27855ba033f/client.go#L1172-L1188
18,721
pkg/sftp
client.go
Chmod
func (f *File) Chmod(mode os.FileMode) error { return f.c.Chmod(f.path, mode) }
go
func (f *File) Chmod(mode os.FileMode) error { return f.c.Chmod(f.path, mode) }
[ "func", "(", "f", "*", "File", ")", "Chmod", "(", "mode", "os", ".", "FileMode", ")", "error", "{", "return", "f", ".", "c", ".", "Chmod", "(", "f", ".", "path", ",", "mode", ")", "\n", "}" ]
// Chmod changes the permissions of the current file.
[ "Chmod", "changes", "the", "permissions", "of", "the", "current", "file", "." ]
5bcd86d72480cb6de4bc5804f832e27855ba033f
https://github.com/pkg/sftp/blob/5bcd86d72480cb6de4bc5804f832e27855ba033f/client.go#L1196-L1198
18,722
pkg/sftp
client.go
Truncate
func (f *File) Truncate(size int64) error { return f.c.Truncate(f.path, size) }
go
func (f *File) Truncate(size int64) error { return f.c.Truncate(f.path, size) }
[ "func", "(", "f", "*", "File", ")", "Truncate", "(", "size", "int64", ")", "error", "{", "return", "f", ".", "c", ".", "Truncate", "(", "f", ".", "path", ",", "size", ")", "\n", "}" ]
// Truncate sets the size of the current file. Although it may be safely assumed // that if the size is less than its current size it will be truncated to fit, // the SFTP protocol does not specify what behavior the server should do when setting // size greater than the current size.
[ "Truncate", "sets", "the", "size", "of", "the", "current", "file", ".", "Although", "it", "may", "be", "safely", "assumed", "that", "if", "the", "size", "is", "less", "than", "its", "current", "size", "it", "will", "be", "truncated", "to", "fit", "the", ...
5bcd86d72480cb6de4bc5804f832e27855ba033f
https://github.com/pkg/sftp/blob/5bcd86d72480cb6de4bc5804f832e27855ba033f/client.go#L1204-L1206
18,723
pkg/sftp
client.go
normaliseError
func normaliseError(err error) error { switch err := err.(type) { case *StatusError: switch err.Code { case ssh_FX_EOF: return io.EOF case ssh_FX_NO_SUCH_FILE: return os.ErrNotExist case ssh_FX_OK: return nil default: return err } default: return err } }
go
func normaliseError(err error) error { switch err := err.(type) { case *StatusError: switch err.Code { case ssh_FX_EOF: return io.EOF case ssh_FX_NO_SUCH_FILE: return os.ErrNotExist case ssh_FX_OK: return nil default: return err } default: return err } }
[ "func", "normaliseError", "(", "err", "error", ")", "error", "{", "switch", "err", ":=", "err", ".", "(", "type", ")", "{", "case", "*", "StatusError", ":", "switch", "err", ".", "Code", "{", "case", "ssh_FX_EOF", ":", "return", "io", ".", "EOF", "\n...
// normaliseError normalises an error into a more standard form that can be // checked against stdlib errors like io.EOF or os.ErrNotExist.
[ "normaliseError", "normalises", "an", "error", "into", "a", "more", "standard", "form", "that", "can", "be", "checked", "against", "stdlib", "errors", "like", "io", ".", "EOF", "or", "os", ".", "ErrNotExist", "." ]
5bcd86d72480cb6de4bc5804f832e27855ba033f
https://github.com/pkg/sftp/blob/5bcd86d72480cb6de4bc5804f832e27855ba033f/client.go#L1217-L1233
18,724
pkg/sftp
client.go
flags
func flags(f int) uint32 { var out uint32 switch f & os.O_WRONLY { case os.O_WRONLY: out |= ssh_FXF_WRITE case os.O_RDONLY: out |= ssh_FXF_READ } if f&os.O_RDWR == os.O_RDWR { out |= ssh_FXF_READ | ssh_FXF_WRITE } if f&os.O_APPEND == os.O_APPEND { out |= ssh_FXF_APPEND } if f&os.O_CREATE == os.O_CREATE { out |= ssh_FXF_CREAT } if f&os.O_TRUNC == os.O_TRUNC { out |= ssh_FXF_TRUNC } if f&os.O_EXCL == os.O_EXCL { out |= ssh_FXF_EXCL } return out }
go
func flags(f int) uint32 { var out uint32 switch f & os.O_WRONLY { case os.O_WRONLY: out |= ssh_FXF_WRITE case os.O_RDONLY: out |= ssh_FXF_READ } if f&os.O_RDWR == os.O_RDWR { out |= ssh_FXF_READ | ssh_FXF_WRITE } if f&os.O_APPEND == os.O_APPEND { out |= ssh_FXF_APPEND } if f&os.O_CREATE == os.O_CREATE { out |= ssh_FXF_CREAT } if f&os.O_TRUNC == os.O_TRUNC { out |= ssh_FXF_TRUNC } if f&os.O_EXCL == os.O_EXCL { out |= ssh_FXF_EXCL } return out }
[ "func", "flags", "(", "f", "int", ")", "uint32", "{", "var", "out", "uint32", "\n", "switch", "f", "&", "os", ".", "O_WRONLY", "{", "case", "os", ".", "O_WRONLY", ":", "out", "|=", "ssh_FXF_WRITE", "\n", "case", "os", ".", "O_RDONLY", ":", "out", "...
// flags converts the flags passed to OpenFile into ssh flags. // Unsupported flags are ignored.
[ "flags", "converts", "the", "flags", "passed", "to", "OpenFile", "into", "ssh", "flags", ".", "Unsupported", "flags", "are", "ignored", "." ]
5bcd86d72480cb6de4bc5804f832e27855ba033f
https://github.com/pkg/sftp/blob/5bcd86d72480cb6de4bc5804f832e27855ba033f/client.go#L1259-L1283
18,725
pkg/sftp
attrs.go
toFileMode
func toFileMode(mode uint32) os.FileMode { var fm = os.FileMode(mode & 0777) switch mode & syscall.S_IFMT { case syscall.S_IFBLK: fm |= os.ModeDevice case syscall.S_IFCHR: fm |= os.ModeDevice | os.ModeCharDevice case syscall.S_IFDIR: fm |= os.ModeDir case syscall.S_IFIFO: fm |= os.ModeNamedPipe case syscall.S_IFLNK: fm |= os.ModeSymlink case syscall.S_IFREG: // nothing to do case syscall.S_IFSOCK: fm |= os.ModeSocket } if mode&syscall.S_ISGID != 0 { fm |= os.ModeSetgid } if mode&syscall.S_ISUID != 0 { fm |= os.ModeSetuid } if mode&syscall.S_ISVTX != 0 { fm |= os.ModeSticky } return fm }
go
func toFileMode(mode uint32) os.FileMode { var fm = os.FileMode(mode & 0777) switch mode & syscall.S_IFMT { case syscall.S_IFBLK: fm |= os.ModeDevice case syscall.S_IFCHR: fm |= os.ModeDevice | os.ModeCharDevice case syscall.S_IFDIR: fm |= os.ModeDir case syscall.S_IFIFO: fm |= os.ModeNamedPipe case syscall.S_IFLNK: fm |= os.ModeSymlink case syscall.S_IFREG: // nothing to do case syscall.S_IFSOCK: fm |= os.ModeSocket } if mode&syscall.S_ISGID != 0 { fm |= os.ModeSetgid } if mode&syscall.S_ISUID != 0 { fm |= os.ModeSetuid } if mode&syscall.S_ISVTX != 0 { fm |= os.ModeSticky } return fm }
[ "func", "toFileMode", "(", "mode", "uint32", ")", "os", ".", "FileMode", "{", "var", "fm", "=", "os", ".", "FileMode", "(", "mode", "&", "0777", ")", "\n", "switch", "mode", "&", "syscall", ".", "S_IFMT", "{", "case", "syscall", ".", "S_IFBLK", ":", ...
// toFileMode converts sftp filemode bits to the os.FileMode specification
[ "toFileMode", "converts", "sftp", "filemode", "bits", "to", "the", "os", ".", "FileMode", "specification" ]
5bcd86d72480cb6de4bc5804f832e27855ba033f
https://github.com/pkg/sftp/blob/5bcd86d72480cb6de4bc5804f832e27855ba033f/attrs.go#L174-L202
18,726
pkg/sftp
attrs.go
fromFileMode
func fromFileMode(mode os.FileMode) uint32 { ret := uint32(0) if mode&os.ModeDevice != 0 { if mode&os.ModeCharDevice != 0 { ret |= syscall.S_IFCHR } else { ret |= syscall.S_IFBLK } } if mode&os.ModeDir != 0 { ret |= syscall.S_IFDIR } if mode&os.ModeSymlink != 0 { ret |= syscall.S_IFLNK } if mode&os.ModeNamedPipe != 0 { ret |= syscall.S_IFIFO } if mode&os.ModeSetgid != 0 { ret |= syscall.S_ISGID } if mode&os.ModeSetuid != 0 { ret |= syscall.S_ISUID } if mode&os.ModeSticky != 0 { ret |= syscall.S_ISVTX } if mode&os.ModeSocket != 0 { ret |= syscall.S_IFSOCK } if mode&os.ModeType == 0 { ret |= syscall.S_IFREG } ret |= uint32(mode & os.ModePerm) return ret }
go
func fromFileMode(mode os.FileMode) uint32 { ret := uint32(0) if mode&os.ModeDevice != 0 { if mode&os.ModeCharDevice != 0 { ret |= syscall.S_IFCHR } else { ret |= syscall.S_IFBLK } } if mode&os.ModeDir != 0 { ret |= syscall.S_IFDIR } if mode&os.ModeSymlink != 0 { ret |= syscall.S_IFLNK } if mode&os.ModeNamedPipe != 0 { ret |= syscall.S_IFIFO } if mode&os.ModeSetgid != 0 { ret |= syscall.S_ISGID } if mode&os.ModeSetuid != 0 { ret |= syscall.S_ISUID } if mode&os.ModeSticky != 0 { ret |= syscall.S_ISVTX } if mode&os.ModeSocket != 0 { ret |= syscall.S_IFSOCK } if mode&os.ModeType == 0 { ret |= syscall.S_IFREG } ret |= uint32(mode & os.ModePerm) return ret }
[ "func", "fromFileMode", "(", "mode", "os", ".", "FileMode", ")", "uint32", "{", "ret", ":=", "uint32", "(", "0", ")", "\n\n", "if", "mode", "&", "os", ".", "ModeDevice", "!=", "0", "{", "if", "mode", "&", "os", ".", "ModeCharDevice", "!=", "0", "{"...
// fromFileMode converts from the os.FileMode specification to sftp filemode bits
[ "fromFileMode", "converts", "from", "the", "os", ".", "FileMode", "specification", "to", "sftp", "filemode", "bits" ]
5bcd86d72480cb6de4bc5804f832e27855ba033f
https://github.com/pkg/sftp/blob/5bcd86d72480cb6de4bc5804f832e27855ba033f/attrs.go#L205-L243
18,727
pkg/sftp
server.go
WithDebug
func WithDebug(w io.Writer) ServerOption { return func(s *Server) error { s.debugStream = w return nil } }
go
func WithDebug(w io.Writer) ServerOption { return func(s *Server) error { s.debugStream = w return nil } }
[ "func", "WithDebug", "(", "w", "io", ".", "Writer", ")", "ServerOption", "{", "return", "func", "(", "s", "*", "Server", ")", "error", "{", "s", ".", "debugStream", "=", "w", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// WithDebug enables Server debugging output to the supplied io.Writer.
[ "WithDebug", "enables", "Server", "debugging", "output", "to", "the", "supplied", "io", ".", "Writer", "." ]
5bcd86d72480cb6de4bc5804f832e27855ba033f
https://github.com/pkg/sftp/blob/5bcd86d72480cb6de4bc5804f832e27855ba033f/server.go#L105-L110
18,728
pkg/sftp
server.go
sftpServerWorker
func (svr *Server) sftpServerWorker(pktChan chan orderedRequest) error { for pkt := range pktChan { // readonly checks readonly := true switch pkt := pkt.requestPacket.(type) { case notReadOnly: readonly = false case *sshFxpOpenPacket: readonly = pkt.readonly() case *sshFxpExtendedPacket: readonly = pkt.readonly() } // If server is operating read-only and a write operation is requested, // return permission denied if !readonly && svr.readOnly { svr.sendPacket(orderedResponse{ responsePacket: statusFromError(pkt, syscall.EPERM), orderid: pkt.orderId()}) continue } if err := handlePacket(svr, pkt); err != nil { return err } } return nil }
go
func (svr *Server) sftpServerWorker(pktChan chan orderedRequest) error { for pkt := range pktChan { // readonly checks readonly := true switch pkt := pkt.requestPacket.(type) { case notReadOnly: readonly = false case *sshFxpOpenPacket: readonly = pkt.readonly() case *sshFxpExtendedPacket: readonly = pkt.readonly() } // If server is operating read-only and a write operation is requested, // return permission denied if !readonly && svr.readOnly { svr.sendPacket(orderedResponse{ responsePacket: statusFromError(pkt, syscall.EPERM), orderid: pkt.orderId()}) continue } if err := handlePacket(svr, pkt); err != nil { return err } } return nil }
[ "func", "(", "svr", "*", "Server", ")", "sftpServerWorker", "(", "pktChan", "chan", "orderedRequest", ")", "error", "{", "for", "pkt", ":=", "range", "pktChan", "{", "// readonly checks", "readonly", ":=", "true", "\n", "switch", "pkt", ":=", "pkt", ".", "...
// Up to N parallel servers
[ "Up", "to", "N", "parallel", "servers" ]
5bcd86d72480cb6de4bc5804f832e27855ba033f
https://github.com/pkg/sftp/blob/5bcd86d72480cb6de4bc5804f832e27855ba033f/server.go#L126-L153
18,729
pkg/sftp
server.go
Serve
func (svr *Server) Serve() error { var wg sync.WaitGroup runWorker := func(ch chan orderedRequest) { wg.Add(1) go func() { defer wg.Done() if err := svr.sftpServerWorker(ch); err != nil { svr.conn.Close() // shuts down recvPacket } }() } pktChan := svr.pktMgr.workerChan(runWorker) var err error var pkt requestPacket var pktType uint8 var pktBytes []byte for { pktType, pktBytes, err = svr.recvPacket() if err != nil { break } pkt, err = makePacket(rxPacket{fxp(pktType), pktBytes}) if err != nil { switch errors.Cause(err) { case errUnknownExtendedPacket: if err := svr.serverConn.sendError(pkt, ErrSshFxOpUnsupported); err != nil { debug("failed to send err packet: %v", err) svr.conn.Close() // shuts down recvPacket break } default: debug("makePacket err: %v", err) svr.conn.Close() // shuts down recvPacket break } } pktChan <- svr.pktMgr.newOrderedRequest(pkt) } close(pktChan) // shuts down sftpServerWorkers wg.Wait() // wait for all workers to exit // close any still-open files for handle, file := range svr.openFiles { fmt.Fprintf(svr.debugStream, "sftp server file with handle %q left open: %v\n", handle, file.Name()) file.Close() } return err // error from recvPacket }
go
func (svr *Server) Serve() error { var wg sync.WaitGroup runWorker := func(ch chan orderedRequest) { wg.Add(1) go func() { defer wg.Done() if err := svr.sftpServerWorker(ch); err != nil { svr.conn.Close() // shuts down recvPacket } }() } pktChan := svr.pktMgr.workerChan(runWorker) var err error var pkt requestPacket var pktType uint8 var pktBytes []byte for { pktType, pktBytes, err = svr.recvPacket() if err != nil { break } pkt, err = makePacket(rxPacket{fxp(pktType), pktBytes}) if err != nil { switch errors.Cause(err) { case errUnknownExtendedPacket: if err := svr.serverConn.sendError(pkt, ErrSshFxOpUnsupported); err != nil { debug("failed to send err packet: %v", err) svr.conn.Close() // shuts down recvPacket break } default: debug("makePacket err: %v", err) svr.conn.Close() // shuts down recvPacket break } } pktChan <- svr.pktMgr.newOrderedRequest(pkt) } close(pktChan) // shuts down sftpServerWorkers wg.Wait() // wait for all workers to exit // close any still-open files for handle, file := range svr.openFiles { fmt.Fprintf(svr.debugStream, "sftp server file with handle %q left open: %v\n", handle, file.Name()) file.Close() } return err // error from recvPacket }
[ "func", "(", "svr", "*", "Server", ")", "Serve", "(", ")", "error", "{", "var", "wg", "sync", ".", "WaitGroup", "\n", "runWorker", ":=", "func", "(", "ch", "chan", "orderedRequest", ")", "{", "wg", ".", "Add", "(", "1", ")", "\n", "go", "func", "...
// Serve serves SFTP connections until the streams stop or the SFTP subsystem // is stopped.
[ "Serve", "serves", "SFTP", "connections", "until", "the", "streams", "stop", "or", "the", "SFTP", "subsystem", "is", "stopped", "." ]
5bcd86d72480cb6de4bc5804f832e27855ba033f
https://github.com/pkg/sftp/blob/5bcd86d72480cb6de4bc5804f832e27855ba033f/server.go#L291-L342
18,730
pkg/sftp
server.go
translateErrno
func translateErrno(errno syscall.Errno) uint32 { switch errno { case 0: return ssh_FX_OK case syscall.ENOENT: return ssh_FX_NO_SUCH_FILE case syscall.EPERM: return ssh_FX_PERMISSION_DENIED } return ssh_FX_FAILURE }
go
func translateErrno(errno syscall.Errno) uint32 { switch errno { case 0: return ssh_FX_OK case syscall.ENOENT: return ssh_FX_NO_SUCH_FILE case syscall.EPERM: return ssh_FX_PERMISSION_DENIED } return ssh_FX_FAILURE }
[ "func", "translateErrno", "(", "errno", "syscall", ".", "Errno", ")", "uint32", "{", "switch", "errno", "{", "case", "0", ":", "return", "ssh_FX_OK", "\n", "case", "syscall", ".", "ENOENT", ":", "return", "ssh_FX_NO_SUCH_FILE", "\n", "case", "syscall", ".", ...
// translateErrno translates a syscall error number to a SFTP error code.
[ "translateErrno", "translates", "a", "syscall", "error", "number", "to", "a", "SFTP", "error", "code", "." ]
5bcd86d72480cb6de4bc5804f832e27855ba033f
https://github.com/pkg/sftp/blob/5bcd86d72480cb6de4bc5804f832e27855ba033f/server.go#L526-L537
18,731
pkg/sftp
match.go
Split
func Split(path string) (dir, file string) { i := len(path) - 1 for i >= 0 && !isPathSeparator(path[i]) { i-- } return path[:i+1], path[i+1:] }
go
func Split(path string) (dir, file string) { i := len(path) - 1 for i >= 0 && !isPathSeparator(path[i]) { i-- } return path[:i+1], path[i+1:] }
[ "func", "Split", "(", "path", "string", ")", "(", "dir", ",", "file", "string", ")", "{", "i", ":=", "len", "(", "path", ")", "-", "1", "\n", "for", "i", ">=", "0", "&&", "!", "isPathSeparator", "(", "path", "[", "i", "]", ")", "{", "i", "--"...
// Split splits path immediately following the final Separator, // separating it into a directory and file name component. // If there is no Separator in path, Split returns an empty dir // and file set to path. // The returned values have the property that path = dir+file.
[ "Split", "splits", "path", "immediately", "following", "the", "final", "Separator", "separating", "it", "into", "a", "directory", "and", "file", "name", "component", ".", "If", "there", "is", "no", "Separator", "in", "path", "Split", "returns", "an", "empty", ...
5bcd86d72480cb6de4bc5804f832e27855ba033f
https://github.com/pkg/sftp/blob/5bcd86d72480cb6de4bc5804f832e27855ba033f/match.go#L186-L192
18,732
pkg/sftp
match.go
cleanGlobPath
func cleanGlobPath(path string) string { switch path { case "": return "." case string(separator): // do nothing to the path return path default: return path[0 : len(path)-1] // chop off trailing separator } }
go
func cleanGlobPath(path string) string { switch path { case "": return "." case string(separator): // do nothing to the path return path default: return path[0 : len(path)-1] // chop off trailing separator } }
[ "func", "cleanGlobPath", "(", "path", "string", ")", "string", "{", "switch", "path", "{", "case", "\"", "\"", ":", "return", "\"", "\"", "\n", "case", "string", "(", "separator", ")", ":", "// do nothing to the path", "return", "path", "\n", "default", ":...
// cleanGlobPath prepares path for glob matching.
[ "cleanGlobPath", "prepares", "path", "for", "glob", "matching", "." ]
5bcd86d72480cb6de4bc5804f832e27855ba033f
https://github.com/pkg/sftp/blob/5bcd86d72480cb6de4bc5804f832e27855ba033f/match.go#L240-L250
18,733
pkg/sftp
packet-typing.go
makePacket
func makePacket(p rxPacket) (requestPacket, error) { var pkt requestPacket switch p.pktType { case ssh_FXP_INIT: pkt = &sshFxInitPacket{} case ssh_FXP_LSTAT: pkt = &sshFxpLstatPacket{} case ssh_FXP_OPEN: pkt = &sshFxpOpenPacket{} case ssh_FXP_CLOSE: pkt = &sshFxpClosePacket{} case ssh_FXP_READ: pkt = &sshFxpReadPacket{} case ssh_FXP_WRITE: pkt = &sshFxpWritePacket{} case ssh_FXP_FSTAT: pkt = &sshFxpFstatPacket{} case ssh_FXP_SETSTAT: pkt = &sshFxpSetstatPacket{} case ssh_FXP_FSETSTAT: pkt = &sshFxpFsetstatPacket{} case ssh_FXP_OPENDIR: pkt = &sshFxpOpendirPacket{} case ssh_FXP_READDIR: pkt = &sshFxpReaddirPacket{} case ssh_FXP_REMOVE: pkt = &sshFxpRemovePacket{} case ssh_FXP_MKDIR: pkt = &sshFxpMkdirPacket{} case ssh_FXP_RMDIR: pkt = &sshFxpRmdirPacket{} case ssh_FXP_REALPATH: pkt = &sshFxpRealpathPacket{} case ssh_FXP_STAT: pkt = &sshFxpStatPacket{} case ssh_FXP_RENAME: pkt = &sshFxpRenamePacket{} case ssh_FXP_READLINK: pkt = &sshFxpReadlinkPacket{} case ssh_FXP_SYMLINK: pkt = &sshFxpSymlinkPacket{} case ssh_FXP_EXTENDED: pkt = &sshFxpExtendedPacket{} default: return nil, errors.Errorf("unhandled packet type: %s", p.pktType) } if err := pkt.UnmarshalBinary(p.pktBytes); err != nil { // Return partially unpacked packet to allow callers to return // error messages appropriately with necessary id() method. return pkt, err } return pkt, nil }
go
func makePacket(p rxPacket) (requestPacket, error) { var pkt requestPacket switch p.pktType { case ssh_FXP_INIT: pkt = &sshFxInitPacket{} case ssh_FXP_LSTAT: pkt = &sshFxpLstatPacket{} case ssh_FXP_OPEN: pkt = &sshFxpOpenPacket{} case ssh_FXP_CLOSE: pkt = &sshFxpClosePacket{} case ssh_FXP_READ: pkt = &sshFxpReadPacket{} case ssh_FXP_WRITE: pkt = &sshFxpWritePacket{} case ssh_FXP_FSTAT: pkt = &sshFxpFstatPacket{} case ssh_FXP_SETSTAT: pkt = &sshFxpSetstatPacket{} case ssh_FXP_FSETSTAT: pkt = &sshFxpFsetstatPacket{} case ssh_FXP_OPENDIR: pkt = &sshFxpOpendirPacket{} case ssh_FXP_READDIR: pkt = &sshFxpReaddirPacket{} case ssh_FXP_REMOVE: pkt = &sshFxpRemovePacket{} case ssh_FXP_MKDIR: pkt = &sshFxpMkdirPacket{} case ssh_FXP_RMDIR: pkt = &sshFxpRmdirPacket{} case ssh_FXP_REALPATH: pkt = &sshFxpRealpathPacket{} case ssh_FXP_STAT: pkt = &sshFxpStatPacket{} case ssh_FXP_RENAME: pkt = &sshFxpRenamePacket{} case ssh_FXP_READLINK: pkt = &sshFxpReadlinkPacket{} case ssh_FXP_SYMLINK: pkt = &sshFxpSymlinkPacket{} case ssh_FXP_EXTENDED: pkt = &sshFxpExtendedPacket{} default: return nil, errors.Errorf("unhandled packet type: %s", p.pktType) } if err := pkt.UnmarshalBinary(p.pktBytes); err != nil { // Return partially unpacked packet to allow callers to return // error messages appropriately with necessary id() method. return pkt, err } return pkt, nil }
[ "func", "makePacket", "(", "p", "rxPacket", ")", "(", "requestPacket", ",", "error", ")", "{", "var", "pkt", "requestPacket", "\n", "switch", "p", ".", "pktType", "{", "case", "ssh_FXP_INIT", ":", "pkt", "=", "&", "sshFxInitPacket", "{", "}", "\n", "case...
// take raw incoming packet data and build packet objects
[ "take", "raw", "incoming", "packet", "data", "and", "build", "packet", "objects" ]
5bcd86d72480cb6de4bc5804f832e27855ba033f
https://github.com/pkg/sftp/blob/5bcd86d72480cb6de4bc5804f832e27855ba033f/packet-typing.go#L82-L134
18,734
pkg/sftp
packet.go
sendPacket
func sendPacket(w io.Writer, m encoding.BinaryMarshaler) error { bb, err := m.MarshalBinary() if err != nil { return errors.Errorf("binary marshaller failed: %v", err) } if debugDumpTxPacketBytes { debug("send packet: %s %d bytes %x", fxp(bb[0]), len(bb), bb[1:]) } else if debugDumpTxPacket { debug("send packet: %s %d bytes", fxp(bb[0]), len(bb)) } // Slide packet down 4 bytes to make room for length header. packet := append(bb, make([]byte, 4)...) // optimistically assume bb has capacity copy(packet[4:], bb) binary.BigEndian.PutUint32(packet[:4], uint32(len(bb))) _, err = w.Write(packet) if err != nil { return errors.Errorf("failed to send packet: %v", err) } return nil }
go
func sendPacket(w io.Writer, m encoding.BinaryMarshaler) error { bb, err := m.MarshalBinary() if err != nil { return errors.Errorf("binary marshaller failed: %v", err) } if debugDumpTxPacketBytes { debug("send packet: %s %d bytes %x", fxp(bb[0]), len(bb), bb[1:]) } else if debugDumpTxPacket { debug("send packet: %s %d bytes", fxp(bb[0]), len(bb)) } // Slide packet down 4 bytes to make room for length header. packet := append(bb, make([]byte, 4)...) // optimistically assume bb has capacity copy(packet[4:], bb) binary.BigEndian.PutUint32(packet[:4], uint32(len(bb))) _, err = w.Write(packet) if err != nil { return errors.Errorf("failed to send packet: %v", err) } return nil }
[ "func", "sendPacket", "(", "w", "io", ".", "Writer", ",", "m", "encoding", ".", "BinaryMarshaler", ")", "error", "{", "bb", ",", "err", ":=", "m", ".", "MarshalBinary", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Errorf",...
// sendPacket marshals p according to RFC 4234.
[ "sendPacket", "marshals", "p", "according", "to", "RFC", "4234", "." ]
5bcd86d72480cb6de4bc5804f832e27855ba033f
https://github.com/pkg/sftp/blob/5bcd86d72480cb6de4bc5804f832e27855ba033f/packet.go#L118-L138
18,735
pkg/sftp
packet.go
MarshalBinary
func (p *StatVFS) MarshalBinary() ([]byte, error) { var buf bytes.Buffer buf.Write([]byte{ssh_FXP_EXTENDED_REPLY}) err := binary.Write(&buf, binary.BigEndian, p) return buf.Bytes(), err }
go
func (p *StatVFS) MarshalBinary() ([]byte, error) { var buf bytes.Buffer buf.Write([]byte{ssh_FXP_EXTENDED_REPLY}) err := binary.Write(&buf, binary.BigEndian, p) return buf.Bytes(), err }
[ "func", "(", "p", "*", "StatVFS", ")", "MarshalBinary", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "var", "buf", "bytes", ".", "Buffer", "\n", "buf", ".", "Write", "(", "[", "]", "byte", "{", "ssh_FXP_EXTENDED_REPLY", "}", ")", "\n", ...
// Convert to ssh_FXP_EXTENDED_REPLY packet binary format
[ "Convert", "to", "ssh_FXP_EXTENDED_REPLY", "packet", "binary", "format" ]
5bcd86d72480cb6de4bc5804f832e27855ba033f
https://github.com/pkg/sftp/blob/5bcd86d72480cb6de4bc5804f832e27855ba033f/packet.go#L860-L865
18,736
pkg/sftp
packet-manager.go
readyPacket
func (s *packetManager) readyPacket(pkt orderedResponse) { s.responses <- pkt s.working.Done() }
go
func (s *packetManager) readyPacket(pkt orderedResponse) { s.responses <- pkt s.working.Done() }
[ "func", "(", "s", "*", "packetManager", ")", "readyPacket", "(", "pkt", "orderedResponse", ")", "{", "s", ".", "responses", "<-", "pkt", "\n", "s", ".", "working", ".", "Done", "(", ")", "\n", "}" ]
// register outgoing packets as being ready
[ "register", "outgoing", "packets", "as", "being", "ready" ]
5bcd86d72480cb6de4bc5804f832e27855ba033f
https://github.com/pkg/sftp/blob/5bcd86d72480cb6de4bc5804f832e27855ba033f/packet-manager.go#L90-L93
18,737
pkg/sftp
packet-manager.go
workerChan
func (s *packetManager) workerChan(runWorker func(chan orderedRequest), ) chan orderedRequest { // multiple workers for faster read/writes rwChan := make(chan orderedRequest, SftpServerWorkerCount) for i := 0; i < SftpServerWorkerCount; i++ { runWorker(rwChan) } // single worker to enforce sequential processing of everything else cmdChan := make(chan orderedRequest) runWorker(cmdChan) pktChan := make(chan orderedRequest, SftpServerWorkerCount) go func() { for pkt := range pktChan { switch pkt.requestPacket.(type) { case *sshFxpReadPacket, *sshFxpWritePacket: s.incomingPacket(pkt) rwChan <- pkt continue case *sshFxpClosePacket: // wait for reads/writes to finish when file is closed // incomingPacket() call must occur after this s.working.Wait() } s.incomingPacket(pkt) // all non-RW use sequential cmdChan cmdChan <- pkt } close(rwChan) close(cmdChan) s.close() }() return pktChan }
go
func (s *packetManager) workerChan(runWorker func(chan orderedRequest), ) chan orderedRequest { // multiple workers for faster read/writes rwChan := make(chan orderedRequest, SftpServerWorkerCount) for i := 0; i < SftpServerWorkerCount; i++ { runWorker(rwChan) } // single worker to enforce sequential processing of everything else cmdChan := make(chan orderedRequest) runWorker(cmdChan) pktChan := make(chan orderedRequest, SftpServerWorkerCount) go func() { for pkt := range pktChan { switch pkt.requestPacket.(type) { case *sshFxpReadPacket, *sshFxpWritePacket: s.incomingPacket(pkt) rwChan <- pkt continue case *sshFxpClosePacket: // wait for reads/writes to finish when file is closed // incomingPacket() call must occur after this s.working.Wait() } s.incomingPacket(pkt) // all non-RW use sequential cmdChan cmdChan <- pkt } close(rwChan) close(cmdChan) s.close() }() return pktChan }
[ "func", "(", "s", "*", "packetManager", ")", "workerChan", "(", "runWorker", "func", "(", "chan", "orderedRequest", ")", ",", ")", "chan", "orderedRequest", "{", "// multiple workers for faster read/writes", "rwChan", ":=", "make", "(", "chan", "orderedRequest", "...
// Passed a worker function, returns a channel for incoming packets. // Keep process packet responses in the order they are received while // maximizing throughput of file transfers.
[ "Passed", "a", "worker", "function", "returns", "a", "channel", "for", "incoming", "packets", ".", "Keep", "process", "packet", "responses", "in", "the", "order", "they", "are", "received", "while", "maximizing", "throughput", "of", "file", "transfers", "." ]
5bcd86d72480cb6de4bc5804f832e27855ba033f
https://github.com/pkg/sftp/blob/5bcd86d72480cb6de4bc5804f832e27855ba033f/packet-manager.go#L105-L141
18,738
pkg/sftp
packet-manager.go
maybeSendPackets
func (s *packetManager) maybeSendPackets() { for { if len(s.outgoing) == 0 || len(s.incoming) == 0 { debug("break! -- outgoing: %v; incoming: %v", len(s.outgoing), len(s.incoming)) break } out := s.outgoing[0] in := s.incoming[0] // debug("incoming: %v", ids(s.incoming)) // debug("outgoing: %v", ids(s.outgoing)) if in.orderId() == out.orderId() { debug("Sending packet: %v", out.id()) s.sender.sendPacket(out.(encoding.BinaryMarshaler)) // pop off heads copy(s.incoming, s.incoming[1:]) // shift left s.incoming[len(s.incoming)-1] = nil // clear last s.incoming = s.incoming[:len(s.incoming)-1] // remove last copy(s.outgoing, s.outgoing[1:]) // shift left s.outgoing[len(s.outgoing)-1] = nil // clear last s.outgoing = s.outgoing[:len(s.outgoing)-1] // remove last } else { break } } }
go
func (s *packetManager) maybeSendPackets() { for { if len(s.outgoing) == 0 || len(s.incoming) == 0 { debug("break! -- outgoing: %v; incoming: %v", len(s.outgoing), len(s.incoming)) break } out := s.outgoing[0] in := s.incoming[0] // debug("incoming: %v", ids(s.incoming)) // debug("outgoing: %v", ids(s.outgoing)) if in.orderId() == out.orderId() { debug("Sending packet: %v", out.id()) s.sender.sendPacket(out.(encoding.BinaryMarshaler)) // pop off heads copy(s.incoming, s.incoming[1:]) // shift left s.incoming[len(s.incoming)-1] = nil // clear last s.incoming = s.incoming[:len(s.incoming)-1] // remove last copy(s.outgoing, s.outgoing[1:]) // shift left s.outgoing[len(s.outgoing)-1] = nil // clear last s.outgoing = s.outgoing[:len(s.outgoing)-1] // remove last } else { break } } }
[ "func", "(", "s", "*", "packetManager", ")", "maybeSendPackets", "(", ")", "{", "for", "{", "if", "len", "(", "s", ".", "outgoing", ")", "==", "0", "||", "len", "(", "s", ".", "incoming", ")", "==", "0", "{", "debug", "(", "\"", "\"", ",", "len...
// send as many packets as are ready
[ "send", "as", "many", "packets", "as", "are", "ready" ]
5bcd86d72480cb6de4bc5804f832e27855ba033f
https://github.com/pkg/sftp/blob/5bcd86d72480cb6de4bc5804f832e27855ba033f/packet-manager.go#L163-L188
18,739
pkg/sftp
conn.go
Close
func (c *clientConn) Close() error { defer c.wg.Wait() return c.conn.Close() }
go
func (c *clientConn) Close() error { defer c.wg.Wait() return c.conn.Close() }
[ "func", "(", "c", "*", "clientConn", ")", "Close", "(", ")", "error", "{", "defer", "c", ".", "wg", ".", "Wait", "(", ")", "\n", "return", "c", ".", "conn", ".", "Close", "(", ")", "\n", "}" ]
// Close closes the SFTP session.
[ "Close", "closes", "the", "SFTP", "session", "." ]
5bcd86d72480cb6de4bc5804f832e27855ba033f
https://github.com/pkg/sftp/blob/5bcd86d72480cb6de4bc5804f832e27855ba033f/conn.go#L53-L56
18,740
pkg/sftp
conn.go
recv
func (c *clientConn) recv() error { defer func() { c.conn.Lock() c.conn.Close() c.conn.Unlock() }() for { typ, data, err := c.recvPacket() if err != nil { return err } sid, _ := unmarshalUint32(data) c.Lock() ch, ok := c.inflight[sid] delete(c.inflight, sid) c.Unlock() if !ok { // This is an unexpected occurrence. Send the error // back to all listeners so that they terminate // gracefully. return errors.Errorf("sid: %v not fond", sid) } ch <- result{typ: typ, data: data} } }
go
func (c *clientConn) recv() error { defer func() { c.conn.Lock() c.conn.Close() c.conn.Unlock() }() for { typ, data, err := c.recvPacket() if err != nil { return err } sid, _ := unmarshalUint32(data) c.Lock() ch, ok := c.inflight[sid] delete(c.inflight, sid) c.Unlock() if !ok { // This is an unexpected occurrence. Send the error // back to all listeners so that they terminate // gracefully. return errors.Errorf("sid: %v not fond", sid) } ch <- result{typ: typ, data: data} } }
[ "func", "(", "c", "*", "clientConn", ")", "recv", "(", ")", "error", "{", "defer", "func", "(", ")", "{", "c", ".", "conn", ".", "Lock", "(", ")", "\n", "c", ".", "conn", ".", "Close", "(", ")", "\n", "c", ".", "conn", ".", "Unlock", "(", "...
// recv continuously reads from the server and forwards responses to the // appropriate channel.
[ "recv", "continuously", "reads", "from", "the", "server", "and", "forwards", "responses", "to", "the", "appropriate", "channel", "." ]
5bcd86d72480cb6de4bc5804f832e27855ba033f
https://github.com/pkg/sftp/blob/5bcd86d72480cb6de4bc5804f832e27855ba033f/conn.go#L68-L92
18,741
pkg/sftp
conn.go
broadcastErr
func (c *clientConn) broadcastErr(err error) { c.Lock() listeners := make([]chan<- result, 0, len(c.inflight)) for _, ch := range c.inflight { listeners = append(listeners, ch) } c.Unlock() for _, ch := range listeners { ch <- result{err: err} } c.err = err close(c.closed) }
go
func (c *clientConn) broadcastErr(err error) { c.Lock() listeners := make([]chan<- result, 0, len(c.inflight)) for _, ch := range c.inflight { listeners = append(listeners, ch) } c.Unlock() for _, ch := range listeners { ch <- result{err: err} } c.err = err close(c.closed) }
[ "func", "(", "c", "*", "clientConn", ")", "broadcastErr", "(", "err", "error", ")", "{", "c", ".", "Lock", "(", ")", "\n", "listeners", ":=", "make", "(", "[", "]", "chan", "<-", "result", ",", "0", ",", "len", "(", "c", ".", "inflight", ")", "...
// broadcastErr sends an error to all goroutines waiting for a response.
[ "broadcastErr", "sends", "an", "error", "to", "all", "goroutines", "waiting", "for", "a", "response", "." ]
5bcd86d72480cb6de4bc5804f832e27855ba033f
https://github.com/pkg/sftp/blob/5bcd86d72480cb6de4bc5804f832e27855ba033f/conn.go#L126-L138
18,742
pkg/sftp
request-server.go
closeRequest
func (rs *RequestServer) closeRequest(handle string) error { rs.openRequestLock.Lock() defer rs.openRequestLock.Unlock() if r, ok := rs.openRequests[handle]; ok { delete(rs.openRequests, handle) return r.close() } return syscall.EBADF }
go
func (rs *RequestServer) closeRequest(handle string) error { rs.openRequestLock.Lock() defer rs.openRequestLock.Unlock() if r, ok := rs.openRequests[handle]; ok { delete(rs.openRequests, handle) return r.close() } return syscall.EBADF }
[ "func", "(", "rs", "*", "RequestServer", ")", "closeRequest", "(", "handle", "string", ")", "error", "{", "rs", ".", "openRequestLock", ".", "Lock", "(", ")", "\n", "defer", "rs", ".", "openRequestLock", ".", "Unlock", "(", ")", "\n", "if", "r", ",", ...
// Close the Request and clear from openRequests map
[ "Close", "the", "Request", "and", "clear", "from", "openRequests", "map" ]
5bcd86d72480cb6de4bc5804f832e27855ba033f
https://github.com/pkg/sftp/blob/5bcd86d72480cb6de4bc5804f832e27855ba033f/request-server.go#L76-L84
18,743
pkg/sftp
request-server.go
Serve
func (rs *RequestServer) Serve() error { ctx, cancel := context.WithCancel(context.Background()) defer cancel() var wg sync.WaitGroup runWorker := func(ch chan orderedRequest) { wg.Add(1) go func() { defer wg.Done() if err := rs.packetWorker(ctx, ch); err != nil { rs.conn.Close() // shuts down recvPacket } }() } pktChan := rs.pktMgr.workerChan(runWorker) var err error var pkt requestPacket var pktType uint8 var pktBytes []byte for { pktType, pktBytes, err = rs.recvPacket() if err != nil { break } pkt, err = makePacket(rxPacket{fxp(pktType), pktBytes}) if err != nil { switch errors.Cause(err) { case errUnknownExtendedPacket: if err := rs.serverConn.sendError(pkt, ErrSshFxOpUnsupported); err != nil { debug("failed to send err packet: %v", err) rs.conn.Close() // shuts down recvPacket break } default: debug("makePacket err: %v", err) rs.conn.Close() // shuts down recvPacket break } } pktChan <- rs.pktMgr.newOrderedRequest(pkt) } close(pktChan) // shuts down sftpServerWorkers wg.Wait() // wait for all workers to exit // make sure all open requests are properly closed // (eg. possible on dropped connections, client crashes, etc.) for handle, req := range rs.openRequests { delete(rs.openRequests, handle) req.close() } return err }
go
func (rs *RequestServer) Serve() error { ctx, cancel := context.WithCancel(context.Background()) defer cancel() var wg sync.WaitGroup runWorker := func(ch chan orderedRequest) { wg.Add(1) go func() { defer wg.Done() if err := rs.packetWorker(ctx, ch); err != nil { rs.conn.Close() // shuts down recvPacket } }() } pktChan := rs.pktMgr.workerChan(runWorker) var err error var pkt requestPacket var pktType uint8 var pktBytes []byte for { pktType, pktBytes, err = rs.recvPacket() if err != nil { break } pkt, err = makePacket(rxPacket{fxp(pktType), pktBytes}) if err != nil { switch errors.Cause(err) { case errUnknownExtendedPacket: if err := rs.serverConn.sendError(pkt, ErrSshFxOpUnsupported); err != nil { debug("failed to send err packet: %v", err) rs.conn.Close() // shuts down recvPacket break } default: debug("makePacket err: %v", err) rs.conn.Close() // shuts down recvPacket break } } pktChan <- rs.pktMgr.newOrderedRequest(pkt) } close(pktChan) // shuts down sftpServerWorkers wg.Wait() // wait for all workers to exit // make sure all open requests are properly closed // (eg. possible on dropped connections, client crashes, etc.) for handle, req := range rs.openRequests { delete(rs.openRequests, handle) req.close() } return err }
[ "func", "(", "rs", "*", "RequestServer", ")", "Serve", "(", ")", "error", "{", "ctx", ",", "cancel", ":=", "context", ".", "WithCancel", "(", "context", ".", "Background", "(", ")", ")", "\n", "defer", "cancel", "(", ")", "\n", "var", "wg", "sync", ...
// Serve requests for user session
[ "Serve", "requests", "for", "user", "session" ]
5bcd86d72480cb6de4bc5804f832e27855ba033f
https://github.com/pkg/sftp/blob/5bcd86d72480cb6de4bc5804f832e27855ba033f/request-server.go#L90-L145
18,744
pkg/sftp
request-server.go
cleanPacketPath
func cleanPacketPath(pkt *sshFxpRealpathPacket) responsePacket { path := cleanPath(pkt.getPath()) return &sshFxpNamePacket{ ID: pkt.id(), NameAttrs: []sshFxpNameAttr{{ Name: path, LongName: path, Attrs: emptyFileStat, }}, } }
go
func cleanPacketPath(pkt *sshFxpRealpathPacket) responsePacket { path := cleanPath(pkt.getPath()) return &sshFxpNamePacket{ ID: pkt.id(), NameAttrs: []sshFxpNameAttr{{ Name: path, LongName: path, Attrs: emptyFileStat, }}, } }
[ "func", "cleanPacketPath", "(", "pkt", "*", "sshFxpRealpathPacket", ")", "responsePacket", "{", "path", ":=", "cleanPath", "(", "pkt", ".", "getPath", "(", ")", ")", "\n", "return", "&", "sshFxpNamePacket", "{", "ID", ":", "pkt", ".", "id", "(", ")", ","...
// clean and return name packet for file
[ "clean", "and", "return", "name", "packet", "for", "file" ]
5bcd86d72480cb6de4bc5804f832e27855ba033f
https://github.com/pkg/sftp/blob/5bcd86d72480cb6de4bc5804f832e27855ba033f/request-server.go#L200-L210
18,745
pkg/sftp
request-attrs.go
Attributes
func (r *Request) Attributes() *FileStat { fs, _ := getFileStat(r.Flags, r.Attrs) return fs }
go
func (r *Request) Attributes() *FileStat { fs, _ := getFileStat(r.Flags, r.Attrs) return fs }
[ "func", "(", "r", "*", "Request", ")", "Attributes", "(", ")", "*", "FileStat", "{", "fs", ",", "_", ":=", "getFileStat", "(", "r", ".", "Flags", ",", "r", ".", "Attrs", ")", "\n", "return", "fs", "\n", "}" ]
// Attributres parses file attributes byte blob and return them in a // FileStat object.
[ "Attributres", "parses", "file", "attributes", "byte", "blob", "and", "return", "them", "in", "a", "FileStat", "object", "." ]
5bcd86d72480cb6de4bc5804f832e27855ba033f
https://github.com/pkg/sftp/blob/5bcd86d72480cb6de4bc5804f832e27855ba033f/request-attrs.go#L60-L63
18,746
shurcooL/graphql
ident/ident.go
ToMixedCaps
func (n Name) ToMixedCaps() string { for i, word := range n { if strings.EqualFold(word, "IDs") { // Special case, plural form of ID initialism. n[i] = "IDs" continue } if initialism, ok := isInitialism(word); ok { n[i] = initialism continue } if brand, ok := isBrand(word); ok { n[i] = brand continue } r, size := utf8.DecodeRuneInString(word) n[i] = string(unicode.ToUpper(r)) + strings.ToLower(word[size:]) } return strings.Join(n, "") }
go
func (n Name) ToMixedCaps() string { for i, word := range n { if strings.EqualFold(word, "IDs") { // Special case, plural form of ID initialism. n[i] = "IDs" continue } if initialism, ok := isInitialism(word); ok { n[i] = initialism continue } if brand, ok := isBrand(word); ok { n[i] = brand continue } r, size := utf8.DecodeRuneInString(word) n[i] = string(unicode.ToUpper(r)) + strings.ToLower(word[size:]) } return strings.Join(n, "") }
[ "func", "(", "n", "Name", ")", "ToMixedCaps", "(", ")", "string", "{", "for", "i", ",", "word", ":=", "range", "n", "{", "if", "strings", ".", "EqualFold", "(", "word", ",", "\"", "\"", ")", "{", "// Special case, plural form of ID initialism.", "n", "["...
// ToMixedCaps expresses identifer name in MixedCaps naming convention. // // E.g., "ClientMutationID".
[ "ToMixedCaps", "expresses", "identifer", "name", "in", "MixedCaps", "naming", "convention", ".", "E", ".", "g", ".", "ClientMutationID", "." ]
d48a9a75455f6af30244670bc0c9d0e38e7392b5
https://github.com/shurcooL/graphql/blob/d48a9a75455f6af30244670bc0c9d0e38e7392b5/ident/ident.go#L124-L142
18,747
shurcooL/graphql
ident/ident.go
ToLowerCamelCase
func (n Name) ToLowerCamelCase() string { for i, word := range n { if i == 0 { n[i] = strings.ToLower(word) continue } r, size := utf8.DecodeRuneInString(word) n[i] = string(unicode.ToUpper(r)) + strings.ToLower(word[size:]) } return strings.Join(n, "") }
go
func (n Name) ToLowerCamelCase() string { for i, word := range n { if i == 0 { n[i] = strings.ToLower(word) continue } r, size := utf8.DecodeRuneInString(word) n[i] = string(unicode.ToUpper(r)) + strings.ToLower(word[size:]) } return strings.Join(n, "") }
[ "func", "(", "n", "Name", ")", "ToLowerCamelCase", "(", ")", "string", "{", "for", "i", ",", "word", ":=", "range", "n", "{", "if", "i", "==", "0", "{", "n", "[", "i", "]", "=", "strings", ".", "ToLower", "(", "word", ")", "\n", "continue", "\n...
// ToLowerCamelCase expresses identifer name in lowerCamelCase naming convention. // // E.g., "clientMutationId".
[ "ToLowerCamelCase", "expresses", "identifer", "name", "in", "lowerCamelCase", "naming", "convention", ".", "E", ".", "g", ".", "clientMutationId", "." ]
d48a9a75455f6af30244670bc0c9d0e38e7392b5
https://github.com/shurcooL/graphql/blob/d48a9a75455f6af30244670bc0c9d0e38e7392b5/ident/ident.go#L147-L157
18,748
shurcooL/graphql
ident/ident.go
isInitialism
func isInitialism(word string) (string, bool) { initialism := strings.ToUpper(word) _, ok := initialisms[initialism] return initialism, ok }
go
func isInitialism(word string) (string, bool) { initialism := strings.ToUpper(word) _, ok := initialisms[initialism] return initialism, ok }
[ "func", "isInitialism", "(", "word", "string", ")", "(", "string", ",", "bool", ")", "{", "initialism", ":=", "strings", ".", "ToUpper", "(", "word", ")", "\n", "_", ",", "ok", ":=", "initialisms", "[", "initialism", "]", "\n", "return", "initialism", ...
// isInitialism reports whether word is an initialism.
[ "isInitialism", "reports", "whether", "word", "is", "an", "initialism", "." ]
d48a9a75455f6af30244670bc0c9d0e38e7392b5
https://github.com/shurcooL/graphql/blob/d48a9a75455f6af30244670bc0c9d0e38e7392b5/ident/ident.go#L160-L164
18,749
shurcooL/graphql
ident/ident.go
isTwoInitialisms
func isTwoInitialisms(word string) (string, string, bool) { word = strings.ToUpper(word) for i := 2; i <= len(word)-2; i++ { // Shortest initialism is 2 characters long. _, ok1 := initialisms[word[:i]] _, ok2 := initialisms[word[i:]] if ok1 && ok2 { return word[:i], word[i:], true } } return "", "", false }
go
func isTwoInitialisms(word string) (string, string, bool) { word = strings.ToUpper(word) for i := 2; i <= len(word)-2; i++ { // Shortest initialism is 2 characters long. _, ok1 := initialisms[word[:i]] _, ok2 := initialisms[word[i:]] if ok1 && ok2 { return word[:i], word[i:], true } } return "", "", false }
[ "func", "isTwoInitialisms", "(", "word", "string", ")", "(", "string", ",", "string", ",", "bool", ")", "{", "word", "=", "strings", ".", "ToUpper", "(", "word", ")", "\n", "for", "i", ":=", "2", ";", "i", "<=", "len", "(", "word", ")", "-", "2",...
// isTwoInitialisms reports whether word is two initialisms.
[ "isTwoInitialisms", "reports", "whether", "word", "is", "two", "initialisms", "." ]
d48a9a75455f6af30244670bc0c9d0e38e7392b5
https://github.com/shurcooL/graphql/blob/d48a9a75455f6af30244670bc0c9d0e38e7392b5/ident/ident.go#L167-L177
18,750
shurcooL/graphql
ident/ident.go
isBrand
func isBrand(word string) (string, bool) { brand, ok := brands[strings.ToLower(word)] return brand, ok }
go
func isBrand(word string) (string, bool) { brand, ok := brands[strings.ToLower(word)] return brand, ok }
[ "func", "isBrand", "(", "word", "string", ")", "(", "string", ",", "bool", ")", "{", "brand", ",", "ok", ":=", "brands", "[", "strings", ".", "ToLower", "(", "word", ")", "]", "\n", "return", "brand", ",", "ok", "\n", "}" ]
// isBrand reports whether word is a brand.
[ "isBrand", "reports", "whether", "word", "is", "a", "brand", "." ]
d48a9a75455f6af30244670bc0c9d0e38e7392b5
https://github.com/shurcooL/graphql/blob/d48a9a75455f6af30244670bc0c9d0e38e7392b5/ident/ident.go#L229-L232
18,751
shurcooL/graphql
query.go
writeQuery
func writeQuery(w io.Writer, t reflect.Type, inline bool) { switch t.Kind() { case reflect.Ptr, reflect.Slice: writeQuery(w, t.Elem(), false) case reflect.Struct: // If the type implements json.Unmarshaler, it's a scalar. Don't expand it. if reflect.PtrTo(t).Implements(jsonUnmarshaler) { return } if !inline { io.WriteString(w, "{") } for i := 0; i < t.NumField(); i++ { if i != 0 { io.WriteString(w, ",") } f := t.Field(i) value, ok := f.Tag.Lookup("graphql") inlineField := f.Anonymous && !ok if !inlineField { if ok { io.WriteString(w, value) } else { io.WriteString(w, ident.ParseMixedCaps(f.Name).ToLowerCamelCase()) } } writeQuery(w, f.Type, inlineField) } if !inline { io.WriteString(w, "}") } } }
go
func writeQuery(w io.Writer, t reflect.Type, inline bool) { switch t.Kind() { case reflect.Ptr, reflect.Slice: writeQuery(w, t.Elem(), false) case reflect.Struct: // If the type implements json.Unmarshaler, it's a scalar. Don't expand it. if reflect.PtrTo(t).Implements(jsonUnmarshaler) { return } if !inline { io.WriteString(w, "{") } for i := 0; i < t.NumField(); i++ { if i != 0 { io.WriteString(w, ",") } f := t.Field(i) value, ok := f.Tag.Lookup("graphql") inlineField := f.Anonymous && !ok if !inlineField { if ok { io.WriteString(w, value) } else { io.WriteString(w, ident.ParseMixedCaps(f.Name).ToLowerCamelCase()) } } writeQuery(w, f.Type, inlineField) } if !inline { io.WriteString(w, "}") } } }
[ "func", "writeQuery", "(", "w", "io", ".", "Writer", ",", "t", "reflect", ".", "Type", ",", "inline", "bool", ")", "{", "switch", "t", ".", "Kind", "(", ")", "{", "case", "reflect", ".", "Ptr", ",", "reflect", ".", "Slice", ":", "writeQuery", "(", ...
// writeQuery writes a minified query for t to w. // If inline is true, the struct fields of t are inlined into parent struct.
[ "writeQuery", "writes", "a", "minified", "query", "for", "t", "to", "w", ".", "If", "inline", "is", "true", "the", "struct", "fields", "of", "t", "are", "inlined", "into", "parent", "struct", "." ]
d48a9a75455f6af30244670bc0c9d0e38e7392b5
https://github.com/shurcooL/graphql/blob/d48a9a75455f6af30244670bc0c9d0e38e7392b5/query.go#L97-L129
18,752
shurcooL/graphql
graphql.go
NewClient
func NewClient(url string, httpClient *http.Client) *Client { if httpClient == nil { httpClient = http.DefaultClient } return &Client{ url: url, httpClient: httpClient, } }
go
func NewClient(url string, httpClient *http.Client) *Client { if httpClient == nil { httpClient = http.DefaultClient } return &Client{ url: url, httpClient: httpClient, } }
[ "func", "NewClient", "(", "url", "string", ",", "httpClient", "*", "http", ".", "Client", ")", "*", "Client", "{", "if", "httpClient", "==", "nil", "{", "httpClient", "=", "http", ".", "DefaultClient", "\n", "}", "\n", "return", "&", "Client", "{", "ur...
// NewClient creates a GraphQL client targeting the specified GraphQL server URL. // If httpClient is nil, then http.DefaultClient is used.
[ "NewClient", "creates", "a", "GraphQL", "client", "targeting", "the", "specified", "GraphQL", "server", "URL", ".", "If", "httpClient", "is", "nil", "then", "http", ".", "DefaultClient", "is", "used", "." ]
d48a9a75455f6af30244670bc0c9d0e38e7392b5
https://github.com/shurcooL/graphql/blob/d48a9a75455f6af30244670bc0c9d0e38e7392b5/graphql.go#L23-L31
18,753
shurcooL/graphql
graphql.go
Query
func (c *Client) Query(ctx context.Context, q interface{}, variables map[string]interface{}) error { return c.do(ctx, queryOperation, q, variables) }
go
func (c *Client) Query(ctx context.Context, q interface{}, variables map[string]interface{}) error { return c.do(ctx, queryOperation, q, variables) }
[ "func", "(", "c", "*", "Client", ")", "Query", "(", "ctx", "context", ".", "Context", ",", "q", "interface", "{", "}", ",", "variables", "map", "[", "string", "]", "interface", "{", "}", ")", "error", "{", "return", "c", ".", "do", "(", "ctx", ",...
// Query executes a single GraphQL query request, // with a query derived from q, populating the response into it. // q should be a pointer to struct that corresponds to the GraphQL schema.
[ "Query", "executes", "a", "single", "GraphQL", "query", "request", "with", "a", "query", "derived", "from", "q", "populating", "the", "response", "into", "it", ".", "q", "should", "be", "a", "pointer", "to", "struct", "that", "corresponds", "to", "the", "G...
d48a9a75455f6af30244670bc0c9d0e38e7392b5
https://github.com/shurcooL/graphql/blob/d48a9a75455f6af30244670bc0c9d0e38e7392b5/graphql.go#L36-L38
18,754
shurcooL/graphql
graphql.go
Mutate
func (c *Client) Mutate(ctx context.Context, m interface{}, variables map[string]interface{}) error { return c.do(ctx, mutationOperation, m, variables) }
go
func (c *Client) Mutate(ctx context.Context, m interface{}, variables map[string]interface{}) error { return c.do(ctx, mutationOperation, m, variables) }
[ "func", "(", "c", "*", "Client", ")", "Mutate", "(", "ctx", "context", ".", "Context", ",", "m", "interface", "{", "}", ",", "variables", "map", "[", "string", "]", "interface", "{", "}", ")", "error", "{", "return", "c", ".", "do", "(", "ctx", "...
// Mutate executes a single GraphQL mutation request, // with a mutation derived from m, populating the response into it. // m should be a pointer to struct that corresponds to the GraphQL schema.
[ "Mutate", "executes", "a", "single", "GraphQL", "mutation", "request", "with", "a", "mutation", "derived", "from", "m", "populating", "the", "response", "into", "it", ".", "m", "should", "be", "a", "pointer", "to", "struct", "that", "corresponds", "to", "the...
d48a9a75455f6af30244670bc0c9d0e38e7392b5
https://github.com/shurcooL/graphql/blob/d48a9a75455f6af30244670bc0c9d0e38e7392b5/graphql.go#L43-L45
18,755
shurcooL/graphql
graphql.go
do
func (c *Client) do(ctx context.Context, op operationType, v interface{}, variables map[string]interface{}) error { var query string switch op { case queryOperation: query = constructQuery(v, variables) case mutationOperation: query = constructMutation(v, variables) } in := struct { Query string `json:"query"` Variables map[string]interface{} `json:"variables,omitempty"` }{ Query: query, Variables: variables, } var buf bytes.Buffer err := json.NewEncoder(&buf).Encode(in) if err != nil { return err } resp, err := ctxhttp.Post(ctx, c.httpClient, c.url, "application/json", &buf) if err != nil { return err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { body, _ := ioutil.ReadAll(resp.Body) return fmt.Errorf("non-200 OK status code: %v body: %q", resp.Status, body) } var out struct { Data *json.RawMessage Errors errors //Extensions interface{} // Unused. } err = json.NewDecoder(resp.Body).Decode(&out) if err != nil { // TODO: Consider including response body in returned error, if deemed helpful. return err } if out.Data != nil { err := jsonutil.UnmarshalGraphQL(*out.Data, v) if err != nil { // TODO: Consider including response body in returned error, if deemed helpful. return err } } if len(out.Errors) > 0 { return out.Errors } return nil }
go
func (c *Client) do(ctx context.Context, op operationType, v interface{}, variables map[string]interface{}) error { var query string switch op { case queryOperation: query = constructQuery(v, variables) case mutationOperation: query = constructMutation(v, variables) } in := struct { Query string `json:"query"` Variables map[string]interface{} `json:"variables,omitempty"` }{ Query: query, Variables: variables, } var buf bytes.Buffer err := json.NewEncoder(&buf).Encode(in) if err != nil { return err } resp, err := ctxhttp.Post(ctx, c.httpClient, c.url, "application/json", &buf) if err != nil { return err } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { body, _ := ioutil.ReadAll(resp.Body) return fmt.Errorf("non-200 OK status code: %v body: %q", resp.Status, body) } var out struct { Data *json.RawMessage Errors errors //Extensions interface{} // Unused. } err = json.NewDecoder(resp.Body).Decode(&out) if err != nil { // TODO: Consider including response body in returned error, if deemed helpful. return err } if out.Data != nil { err := jsonutil.UnmarshalGraphQL(*out.Data, v) if err != nil { // TODO: Consider including response body in returned error, if deemed helpful. return err } } if len(out.Errors) > 0 { return out.Errors } return nil }
[ "func", "(", "c", "*", "Client", ")", "do", "(", "ctx", "context", ".", "Context", ",", "op", "operationType", ",", "v", "interface", "{", "}", ",", "variables", "map", "[", "string", "]", "interface", "{", "}", ")", "error", "{", "var", "query", "...
// do executes a single GraphQL operation.
[ "do", "executes", "a", "single", "GraphQL", "operation", "." ]
d48a9a75455f6af30244670bc0c9d0e38e7392b5
https://github.com/shurcooL/graphql/blob/d48a9a75455f6af30244670bc0c9d0e38e7392b5/graphql.go#L48-L98
18,756
shurcooL/graphql
internal/jsonutil/graphql.go
Decode
func (d *decoder) Decode(v interface{}) error { rv := reflect.ValueOf(v) if rv.Kind() != reflect.Ptr { return fmt.Errorf("cannot decode into non-pointer %T", v) } d.vs = [][]reflect.Value{{rv.Elem()}} return d.decode() }
go
func (d *decoder) Decode(v interface{}) error { rv := reflect.ValueOf(v) if rv.Kind() != reflect.Ptr { return fmt.Errorf("cannot decode into non-pointer %T", v) } d.vs = [][]reflect.Value{{rv.Elem()}} return d.decode() }
[ "func", "(", "d", "*", "decoder", ")", "Decode", "(", "v", "interface", "{", "}", ")", "error", "{", "rv", ":=", "reflect", ".", "ValueOf", "(", "v", ")", "\n", "if", "rv", ".", "Kind", "(", ")", "!=", "reflect", ".", "Ptr", "{", "return", "fmt...
// Decode decodes a single JSON value from d.tokenizer into v.
[ "Decode", "decodes", "a", "single", "JSON", "value", "from", "d", ".", "tokenizer", "into", "v", "." ]
d48a9a75455f6af30244670bc0c9d0e38e7392b5
https://github.com/shurcooL/graphql/blob/d48a9a75455f6af30244670bc0c9d0e38e7392b5/internal/jsonutil/graphql.go#L60-L67
18,757
shurcooL/graphql
internal/jsonutil/graphql.go
pushState
func (d *decoder) pushState(s json.Delim) { d.parseState = append(d.parseState, s) }
go
func (d *decoder) pushState(s json.Delim) { d.parseState = append(d.parseState, s) }
[ "func", "(", "d", "*", "decoder", ")", "pushState", "(", "s", "json", ".", "Delim", ")", "{", "d", ".", "parseState", "=", "append", "(", "d", ".", "parseState", ",", "s", ")", "\n", "}" ]
// pushState pushes a new parse state s onto the stack.
[ "pushState", "pushes", "a", "new", "parse", "state", "s", "onto", "the", "stack", "." ]
d48a9a75455f6af30244670bc0c9d0e38e7392b5
https://github.com/shurcooL/graphql/blob/d48a9a75455f6af30244670bc0c9d0e38e7392b5/internal/jsonutil/graphql.go#L225-L227
18,758
shurcooL/graphql
internal/jsonutil/graphql.go
state
func (d *decoder) state() json.Delim { if len(d.parseState) == 0 { return 0 } return d.parseState[len(d.parseState)-1] }
go
func (d *decoder) state() json.Delim { if len(d.parseState) == 0 { return 0 } return d.parseState[len(d.parseState)-1] }
[ "func", "(", "d", "*", "decoder", ")", "state", "(", ")", "json", ".", "Delim", "{", "if", "len", "(", "d", ".", "parseState", ")", "==", "0", "{", "return", "0", "\n", "}", "\n", "return", "d", ".", "parseState", "[", "len", "(", "d", ".", "...
// state reports the parse state on top of stack, or 0 if empty.
[ "state", "reports", "the", "parse", "state", "on", "top", "of", "stack", "or", "0", "if", "empty", "." ]
d48a9a75455f6af30244670bc0c9d0e38e7392b5
https://github.com/shurcooL/graphql/blob/d48a9a75455f6af30244670bc0c9d0e38e7392b5/internal/jsonutil/graphql.go#L236-L241
18,759
shurcooL/graphql
internal/jsonutil/graphql.go
popAllVs
func (d *decoder) popAllVs() { var nonEmpty [][]reflect.Value for i := range d.vs { d.vs[i] = d.vs[i][:len(d.vs[i])-1] if len(d.vs[i]) > 0 { nonEmpty = append(nonEmpty, d.vs[i]) } } d.vs = nonEmpty }
go
func (d *decoder) popAllVs() { var nonEmpty [][]reflect.Value for i := range d.vs { d.vs[i] = d.vs[i][:len(d.vs[i])-1] if len(d.vs[i]) > 0 { nonEmpty = append(nonEmpty, d.vs[i]) } } d.vs = nonEmpty }
[ "func", "(", "d", "*", "decoder", ")", "popAllVs", "(", ")", "{", "var", "nonEmpty", "[", "]", "[", "]", "reflect", ".", "Value", "\n", "for", "i", ":=", "range", "d", ".", "vs", "{", "d", ".", "vs", "[", "i", "]", "=", "d", ".", "vs", "[",...
// popAllVs pops from all d.vs stacks, keeping only non-empty ones.
[ "popAllVs", "pops", "from", "all", "d", ".", "vs", "stacks", "keeping", "only", "non", "-", "empty", "ones", "." ]
d48a9a75455f6af30244670bc0c9d0e38e7392b5
https://github.com/shurcooL/graphql/blob/d48a9a75455f6af30244670bc0c9d0e38e7392b5/internal/jsonutil/graphql.go#L244-L253
18,760
shurcooL/graphql
internal/jsonutil/graphql.go
fieldByGraphQLName
func fieldByGraphQLName(v reflect.Value, name string) reflect.Value { for i := 0; i < v.NumField(); i++ { if v.Type().Field(i).PkgPath != "" { // Skip unexported field. continue } if hasGraphQLName(v.Type().Field(i), name) { return v.Field(i) } } return reflect.Value{} }
go
func fieldByGraphQLName(v reflect.Value, name string) reflect.Value { for i := 0; i < v.NumField(); i++ { if v.Type().Field(i).PkgPath != "" { // Skip unexported field. continue } if hasGraphQLName(v.Type().Field(i), name) { return v.Field(i) } } return reflect.Value{} }
[ "func", "fieldByGraphQLName", "(", "v", "reflect", ".", "Value", ",", "name", "string", ")", "reflect", ".", "Value", "{", "for", "i", ":=", "0", ";", "i", "<", "v", ".", "NumField", "(", ")", ";", "i", "++", "{", "if", "v", ".", "Type", "(", "...
// fieldByGraphQLName returns an exported struct field of struct v // that matches GraphQL name, or invalid reflect.Value if none found.
[ "fieldByGraphQLName", "returns", "an", "exported", "struct", "field", "of", "struct", "v", "that", "matches", "GraphQL", "name", "or", "invalid", "reflect", ".", "Value", "if", "none", "found", "." ]
d48a9a75455f6af30244670bc0c9d0e38e7392b5
https://github.com/shurcooL/graphql/blob/d48a9a75455f6af30244670bc0c9d0e38e7392b5/internal/jsonutil/graphql.go#L257-L268
18,761
shurcooL/graphql
internal/jsonutil/graphql.go
hasGraphQLName
func hasGraphQLName(f reflect.StructField, name string) bool { value, ok := f.Tag.Lookup("graphql") if !ok { // TODO: caseconv package is relatively slow. Optimize it, then consider using it here. //return caseconv.MixedCapsToLowerCamelCase(f.Name) == name return strings.EqualFold(f.Name, name) } value = strings.TrimSpace(value) // TODO: Parse better. if strings.HasPrefix(value, "...") { // GraphQL fragment. It doesn't have a name. return false } if i := strings.Index(value, "("); i != -1 { value = value[:i] } if i := strings.Index(value, ":"); i != -1 { value = value[:i] } return strings.TrimSpace(value) == name }
go
func hasGraphQLName(f reflect.StructField, name string) bool { value, ok := f.Tag.Lookup("graphql") if !ok { // TODO: caseconv package is relatively slow. Optimize it, then consider using it here. //return caseconv.MixedCapsToLowerCamelCase(f.Name) == name return strings.EqualFold(f.Name, name) } value = strings.TrimSpace(value) // TODO: Parse better. if strings.HasPrefix(value, "...") { // GraphQL fragment. It doesn't have a name. return false } if i := strings.Index(value, "("); i != -1 { value = value[:i] } if i := strings.Index(value, ":"); i != -1 { value = value[:i] } return strings.TrimSpace(value) == name }
[ "func", "hasGraphQLName", "(", "f", "reflect", ".", "StructField", ",", "name", "string", ")", "bool", "{", "value", ",", "ok", ":=", "f", ".", "Tag", ".", "Lookup", "(", "\"", "\"", ")", "\n", "if", "!", "ok", "{", "// TODO: caseconv package is relative...
// hasGraphQLName reports whether struct field f has GraphQL name.
[ "hasGraphQLName", "reports", "whether", "struct", "field", "f", "has", "GraphQL", "name", "." ]
d48a9a75455f6af30244670bc0c9d0e38e7392b5
https://github.com/shurcooL/graphql/blob/d48a9a75455f6af30244670bc0c9d0e38e7392b5/internal/jsonutil/graphql.go#L271-L290
18,762
shurcooL/graphql
internal/jsonutil/graphql.go
isGraphQLFragment
func isGraphQLFragment(f reflect.StructField) bool { value, ok := f.Tag.Lookup("graphql") if !ok { return false } value = strings.TrimSpace(value) // TODO: Parse better. return strings.HasPrefix(value, "...") }
go
func isGraphQLFragment(f reflect.StructField) bool { value, ok := f.Tag.Lookup("graphql") if !ok { return false } value = strings.TrimSpace(value) // TODO: Parse better. return strings.HasPrefix(value, "...") }
[ "func", "isGraphQLFragment", "(", "f", "reflect", ".", "StructField", ")", "bool", "{", "value", ",", "ok", ":=", "f", ".", "Tag", ".", "Lookup", "(", "\"", "\"", ")", "\n", "if", "!", "ok", "{", "return", "false", "\n", "}", "\n", "value", "=", ...
// isGraphQLFragment reports whether struct field f is a GraphQL fragment.
[ "isGraphQLFragment", "reports", "whether", "struct", "field", "f", "is", "a", "GraphQL", "fragment", "." ]
d48a9a75455f6af30244670bc0c9d0e38e7392b5
https://github.com/shurcooL/graphql/blob/d48a9a75455f6af30244670bc0c9d0e38e7392b5/internal/jsonutil/graphql.go#L293-L300
18,763
shurcooL/graphql
internal/jsonutil/graphql.go
unmarshalValue
func unmarshalValue(value json.Token, v reflect.Value) error { b, err := json.Marshal(value) // TODO: Short-circuit (if profiling says it's worth it). if err != nil { return err } return json.Unmarshal(b, v.Addr().Interface()) }
go
func unmarshalValue(value json.Token, v reflect.Value) error { b, err := json.Marshal(value) // TODO: Short-circuit (if profiling says it's worth it). if err != nil { return err } return json.Unmarshal(b, v.Addr().Interface()) }
[ "func", "unmarshalValue", "(", "value", "json", ".", "Token", ",", "v", "reflect", ".", "Value", ")", "error", "{", "b", ",", "err", ":=", "json", ".", "Marshal", "(", "value", ")", "// TODO: Short-circuit (if profiling says it's worth it).", "\n", "if", "err"...
// unmarshalValue unmarshals JSON value into v. // v must be addressable and not obtained by the use of unexported // struct fields, otherwise unmarshalValue will panic.
[ "unmarshalValue", "unmarshals", "JSON", "value", "into", "v", ".", "v", "must", "be", "addressable", "and", "not", "obtained", "by", "the", "use", "of", "unexported", "struct", "fields", "otherwise", "unmarshalValue", "will", "panic", "." ]
d48a9a75455f6af30244670bc0c9d0e38e7392b5
https://github.com/shurcooL/graphql/blob/d48a9a75455f6af30244670bc0c9d0e38e7392b5/internal/jsonutil/graphql.go#L305-L311
18,764
h2non/bimg
image.go
Resize
func (i *Image) Resize(width, height int) ([]byte, error) { options := Options{ Width: width, Height: height, Embed: true, } return i.Process(options) }
go
func (i *Image) Resize(width, height int) ([]byte, error) { options := Options{ Width: width, Height: height, Embed: true, } return i.Process(options) }
[ "func", "(", "i", "*", "Image", ")", "Resize", "(", "width", ",", "height", "int", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "options", ":=", "Options", "{", "Width", ":", "width", ",", "Height", ":", "height", ",", "Embed", ":", "true"...
// Resize resizes the image to fixed width and height.
[ "Resize", "resizes", "the", "image", "to", "fixed", "width", "and", "height", "." ]
15cd11560781e3a634d3857b845d4c9c93aa454b
https://github.com/h2non/bimg/blob/15cd11560781e3a634d3857b845d4c9c93aa454b/image.go#L14-L21
18,765
h2non/bimg
image.go
Crop
func (i *Image) Crop(width, height int, gravity Gravity) ([]byte, error) { options := Options{ Width: width, Height: height, Gravity: gravity, Crop: true, } return i.Process(options) }
go
func (i *Image) Crop(width, height int, gravity Gravity) ([]byte, error) { options := Options{ Width: width, Height: height, Gravity: gravity, Crop: true, } return i.Process(options) }
[ "func", "(", "i", "*", "Image", ")", "Crop", "(", "width", ",", "height", "int", ",", "gravity", "Gravity", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "options", ":=", "Options", "{", "Width", ":", "width", ",", "Height", ":", "height", ...
// Crop crops the image to the exact size specified.
[ "Crop", "crops", "the", "image", "to", "the", "exact", "size", "specified", "." ]
15cd11560781e3a634d3857b845d4c9c93aa454b
https://github.com/h2non/bimg/blob/15cd11560781e3a634d3857b845d4c9c93aa454b/image.go#L93-L101
18,766
h2non/bimg
image.go
Watermark
func (i *Image) Watermark(w Watermark) ([]byte, error) { options := Options{Watermark: w} return i.Process(options) }
go
func (i *Image) Watermark(w Watermark) ([]byte, error) { options := Options{Watermark: w} return i.Process(options) }
[ "func", "(", "i", "*", "Image", ")", "Watermark", "(", "w", "Watermark", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "options", ":=", "Options", "{", "Watermark", ":", "w", "}", "\n", "return", "i", ".", "Process", "(", "options", ")", "\...
// Watermark adds text as watermark on the given image.
[ "Watermark", "adds", "text", "as", "watermark", "on", "the", "given", "image", "." ]
15cd11560781e3a634d3857b845d4c9c93aa454b
https://github.com/h2non/bimg/blob/15cd11560781e3a634d3857b845d4c9c93aa454b/image.go#L133-L136
18,767
h2non/bimg
image.go
WatermarkImage
func (i *Image) WatermarkImage(w WatermarkImage) ([]byte, error) { options := Options{WatermarkImage: w} return i.Process(options) }
go
func (i *Image) WatermarkImage(w WatermarkImage) ([]byte, error) { options := Options{WatermarkImage: w} return i.Process(options) }
[ "func", "(", "i", "*", "Image", ")", "WatermarkImage", "(", "w", "WatermarkImage", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "options", ":=", "Options", "{", "WatermarkImage", ":", "w", "}", "\n", "return", "i", ".", "Process", "(", "option...
// WatermarkImage adds image as watermark on the given image.
[ "WatermarkImage", "adds", "image", "as", "watermark", "on", "the", "given", "image", "." ]
15cd11560781e3a634d3857b845d4c9c93aa454b
https://github.com/h2non/bimg/blob/15cd11560781e3a634d3857b845d4c9c93aa454b/image.go#L139-L142
18,768
h2non/bimg
image.go
Flip
func (i *Image) Flip() ([]byte, error) { options := Options{Flip: true} return i.Process(options) }
go
func (i *Image) Flip() ([]byte, error) { options := Options{Flip: true} return i.Process(options) }
[ "func", "(", "i", "*", "Image", ")", "Flip", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "options", ":=", "Options", "{", "Flip", ":", "true", "}", "\n", "return", "i", ".", "Process", "(", "options", ")", "\n", "}" ]
// Flip flips the image about the vertical Y axis.
[ "Flip", "flips", "the", "image", "about", "the", "vertical", "Y", "axis", "." ]
15cd11560781e3a634d3857b845d4c9c93aa454b
https://github.com/h2non/bimg/blob/15cd11560781e3a634d3857b845d4c9c93aa454b/image.go#L158-L161
18,769
h2non/bimg
image.go
Convert
func (i *Image) Convert(t ImageType) ([]byte, error) { options := Options{Type: t} return i.Process(options) }
go
func (i *Image) Convert(t ImageType) ([]byte, error) { options := Options{Type: t} return i.Process(options) }
[ "func", "(", "i", "*", "Image", ")", "Convert", "(", "t", "ImageType", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "options", ":=", "Options", "{", "Type", ":", "t", "}", "\n", "return", "i", ".", "Process", "(", "options", ")", "\n", "...
// Convert converts image to another format.
[ "Convert", "converts", "image", "to", "another", "format", "." ]
15cd11560781e3a634d3857b845d4c9c93aa454b
https://github.com/h2non/bimg/blob/15cd11560781e3a634d3857b845d4c9c93aa454b/image.go#L170-L173
18,770
h2non/bimg
image.go
Colourspace
func (i *Image) Colourspace(c Interpretation) ([]byte, error) { options := Options{Interpretation: c} return i.Process(options) }
go
func (i *Image) Colourspace(c Interpretation) ([]byte, error) { options := Options{Interpretation: c} return i.Process(options) }
[ "func", "(", "i", "*", "Image", ")", "Colourspace", "(", "c", "Interpretation", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "options", ":=", "Options", "{", "Interpretation", ":", "c", "}", "\n", "return", "i", ".", "Process", "(", "options",...
// Colourspace performs a color space conversion bsaed on the given interpretation.
[ "Colourspace", "performs", "a", "color", "space", "conversion", "bsaed", "on", "the", "given", "interpretation", "." ]
15cd11560781e3a634d3857b845d4c9c93aa454b
https://github.com/h2non/bimg/blob/15cd11560781e3a634d3857b845d4c9c93aa454b/image.go#L176-L179
18,771
h2non/bimg
image.go
Process
func (i *Image) Process(o Options) ([]byte, error) { image, err := Resize(i.buffer, o) if err != nil { return nil, err } i.buffer = image return image, nil }
go
func (i *Image) Process(o Options) ([]byte, error) { image, err := Resize(i.buffer, o) if err != nil { return nil, err } i.buffer = image return image, nil }
[ "func", "(", "i", "*", "Image", ")", "Process", "(", "o", "Options", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "image", ",", "err", ":=", "Resize", "(", "i", ".", "buffer", ",", "o", ")", "\n", "if", "err", "!=", "nil", "{", "return...
// Process processes the image based on the given transformation options, // talking with libvips bindings accordingly and returning the resultant // image buffer.
[ "Process", "processes", "the", "image", "based", "on", "the", "given", "transformation", "options", "talking", "with", "libvips", "bindings", "accordingly", "and", "returning", "the", "resultant", "image", "buffer", "." ]
15cd11560781e3a634d3857b845d4c9c93aa454b
https://github.com/h2non/bimg/blob/15cd11560781e3a634d3857b845d4c9c93aa454b/image.go#L191-L198
18,772
h2non/bimg
metadata.go
Size
func Size(buf []byte) (ImageSize, error) { metadata, err := Metadata(buf) if err != nil { return ImageSize{}, err } return ImageSize{ Width: int(metadata.Size.Width), Height: int(metadata.Size.Height), }, nil }
go
func Size(buf []byte) (ImageSize, error) { metadata, err := Metadata(buf) if err != nil { return ImageSize{}, err } return ImageSize{ Width: int(metadata.Size.Width), Height: int(metadata.Size.Height), }, nil }
[ "func", "Size", "(", "buf", "[", "]", "byte", ")", "(", "ImageSize", ",", "error", ")", "{", "metadata", ",", "err", ":=", "Metadata", "(", "buf", ")", "\n", "if", "err", "!=", "nil", "{", "return", "ImageSize", "{", "}", ",", "err", "\n", "}", ...
// Size returns the image size by width and height pixels.
[ "Size", "returns", "the", "image", "size", "by", "width", "and", "height", "pixels", "." ]
15cd11560781e3a634d3857b845d4c9c93aa454b
https://github.com/h2non/bimg/blob/15cd11560781e3a634d3857b845d4c9c93aa454b/metadata.go#L28-L38
18,773
h2non/bimg
resize.go
Resize
func Resize(buf []byte, o Options) ([]byte, error) { // Required in order to prevent premature garbage collection. See: // https://github.com/h2non/bimg/pull/162 defer runtime.KeepAlive(buf) return resizer(buf, o) }
go
func Resize(buf []byte, o Options) ([]byte, error) { // Required in order to prevent premature garbage collection. See: // https://github.com/h2non/bimg/pull/162 defer runtime.KeepAlive(buf) return resizer(buf, o) }
[ "func", "Resize", "(", "buf", "[", "]", "byte", ",", "o", "Options", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "// Required in order to prevent premature garbage collection. See:", "// https://github.com/h2non/bimg/pull/162", "defer", "runtime", ".", "KeepAl...
// Resize is used to transform a given image as byte buffer // with the passed options.
[ "Resize", "is", "used", "to", "transform", "a", "given", "image", "as", "byte", "buffer", "with", "the", "passed", "options", "." ]
15cd11560781e3a634d3857b845d4c9c93aa454b
https://github.com/h2non/bimg/blob/15cd11560781e3a634d3857b845d4c9c93aa454b/resize.go#L11-L16
18,774
h2non/bimg
file.go
Write
func Write(path string, buf []byte) error { return ioutil.WriteFile(path, buf, 0644) }
go
func Write(path string, buf []byte) error { return ioutil.WriteFile(path, buf, 0644) }
[ "func", "Write", "(", "path", "string", ",", "buf", "[", "]", "byte", ")", "error", "{", "return", "ioutil", ".", "WriteFile", "(", "path", ",", "buf", ",", "0644", ")", "\n", "}" ]
// Write writes the given byte buffer into disk // to the given file path.
[ "Write", "writes", "the", "given", "byte", "buffer", "into", "disk", "to", "the", "given", "file", "path", "." ]
15cd11560781e3a634d3857b845d4c9c93aa454b
https://github.com/h2non/bimg/blob/15cd11560781e3a634d3857b845d4c9c93aa454b/file.go#L13-L15
18,775
h2non/bimg
type.go
discoverSupportedImageTypes
func discoverSupportedImageTypes() { imageMutex.Lock() for imageType := range ImageTypes { SupportedImageTypes[imageType] = SupportedImageType{ Load: VipsIsTypeSupported(imageType), Save: VipsIsTypeSupportedSave(imageType), } } imageMutex.Unlock() }
go
func discoverSupportedImageTypes() { imageMutex.Lock() for imageType := range ImageTypes { SupportedImageTypes[imageType] = SupportedImageType{ Load: VipsIsTypeSupported(imageType), Save: VipsIsTypeSupportedSave(imageType), } } imageMutex.Unlock() }
[ "func", "discoverSupportedImageTypes", "(", ")", "{", "imageMutex", ".", "Lock", "(", ")", "\n", "for", "imageType", ":=", "range", "ImageTypes", "{", "SupportedImageTypes", "[", "imageType", "]", "=", "SupportedImageType", "{", "Load", ":", "VipsIsTypeSupported",...
// discoverSupportedImageTypes is used to fill SupportedImageTypes map.
[ "discoverSupportedImageTypes", "is", "used", "to", "fill", "SupportedImageTypes", "map", "." ]
15cd11560781e3a634d3857b845d4c9c93aa454b
https://github.com/h2non/bimg/blob/15cd11560781e3a634d3857b845d4c9c93aa454b/type.go#L68-L77
18,776
h2non/bimg
type.go
isBinary
func isBinary(buf []byte) bool { if len(buf) < 24 { return false } for i := 0; i < 24; i++ { charCode, _ := utf8.DecodeRuneInString(string(buf[i])) if charCode == 65533 || charCode <= 8 { return true } } return false }
go
func isBinary(buf []byte) bool { if len(buf) < 24 { return false } for i := 0; i < 24; i++ { charCode, _ := utf8.DecodeRuneInString(string(buf[i])) if charCode == 65533 || charCode <= 8 { return true } } return false }
[ "func", "isBinary", "(", "buf", "[", "]", "byte", ")", "bool", "{", "if", "len", "(", "buf", ")", "<", "24", "{", "return", "false", "\n", "}", "\n", "for", "i", ":=", "0", ";", "i", "<", "24", ";", "i", "++", "{", "charCode", ",", "_", ":=...
// isBinary checks if the given buffer is a binary file.
[ "isBinary", "checks", "if", "the", "given", "buffer", "is", "a", "binary", "file", "." ]
15cd11560781e3a634d3857b845d4c9c93aa454b
https://github.com/h2non/bimg/blob/15cd11560781e3a634d3857b845d4c9c93aa454b/type.go#L80-L91
18,777
h2non/bimg
type.go
IsSVGImage
func IsSVGImage(buf []byte) bool { return !isBinary(buf) && svgRegex.Match(htmlCommentRegex.ReplaceAll(buf, []byte{})) }
go
func IsSVGImage(buf []byte) bool { return !isBinary(buf) && svgRegex.Match(htmlCommentRegex.ReplaceAll(buf, []byte{})) }
[ "func", "IsSVGImage", "(", "buf", "[", "]", "byte", ")", "bool", "{", "return", "!", "isBinary", "(", "buf", ")", "&&", "svgRegex", ".", "Match", "(", "htmlCommentRegex", ".", "ReplaceAll", "(", "buf", ",", "[", "]", "byte", "{", "}", ")", ")", "\n...
// IsSVGImage returns true if the given buffer is a valid SVG image.
[ "IsSVGImage", "returns", "true", "if", "the", "given", "buffer", "is", "a", "valid", "SVG", "image", "." ]
15cd11560781e3a634d3857b845d4c9c93aa454b
https://github.com/h2non/bimg/blob/15cd11560781e3a634d3857b845d4c9c93aa454b/type.go#L94-L96
18,778
h2non/bimg
type.go
IsImageTypeSupportedByVips
func IsImageTypeSupportedByVips(t ImageType) SupportedImageType { imageMutex.RLock() // Discover supported image types and cache the result itShouldDiscover := len(SupportedImageTypes) == 0 if itShouldDiscover { imageMutex.RUnlock() discoverSupportedImageTypes() } // Check if image type is actually supported supported, ok := SupportedImageTypes[t] if !itShouldDiscover { imageMutex.RUnlock() } if ok { return supported } return SupportedImageType{Load: false, Save: false} }
go
func IsImageTypeSupportedByVips(t ImageType) SupportedImageType { imageMutex.RLock() // Discover supported image types and cache the result itShouldDiscover := len(SupportedImageTypes) == 0 if itShouldDiscover { imageMutex.RUnlock() discoverSupportedImageTypes() } // Check if image type is actually supported supported, ok := SupportedImageTypes[t] if !itShouldDiscover { imageMutex.RUnlock() } if ok { return supported } return SupportedImageType{Load: false, Save: false} }
[ "func", "IsImageTypeSupportedByVips", "(", "t", "ImageType", ")", "SupportedImageType", "{", "imageMutex", ".", "RLock", "(", ")", "\n\n", "// Discover supported image types and cache the result", "itShouldDiscover", ":=", "len", "(", "SupportedImageTypes", ")", "==", "0"...
// IsImageTypeSupportedByVips returns true if the given image type // is supported by current libvips compilation.
[ "IsImageTypeSupportedByVips", "returns", "true", "if", "the", "given", "image", "type", "is", "supported", "by", "current", "libvips", "compilation", "." ]
15cd11560781e3a634d3857b845d4c9c93aa454b
https://github.com/h2non/bimg/blob/15cd11560781e3a634d3857b845d4c9c93aa454b/type.go#L110-L130
18,779
h2non/bimg
type.go
IsTypeSupported
func IsTypeSupported(t ImageType) bool { _, ok := ImageTypes[t] return ok && IsImageTypeSupportedByVips(t).Load }
go
func IsTypeSupported(t ImageType) bool { _, ok := ImageTypes[t] return ok && IsImageTypeSupportedByVips(t).Load }
[ "func", "IsTypeSupported", "(", "t", "ImageType", ")", "bool", "{", "_", ",", "ok", ":=", "ImageTypes", "[", "t", "]", "\n", "return", "ok", "&&", "IsImageTypeSupportedByVips", "(", "t", ")", ".", "Load", "\n", "}" ]
// IsTypeSupported checks if a given image type is supported
[ "IsTypeSupported", "checks", "if", "a", "given", "image", "type", "is", "supported" ]
15cd11560781e3a634d3857b845d4c9c93aa454b
https://github.com/h2non/bimg/blob/15cd11560781e3a634d3857b845d4c9c93aa454b/type.go#L133-L136
18,780
h2non/bimg
type.go
IsTypeNameSupported
func IsTypeNameSupported(t string) bool { for imageType, name := range ImageTypes { if name == t { return IsImageTypeSupportedByVips(imageType).Load } } return false }
go
func IsTypeNameSupported(t string) bool { for imageType, name := range ImageTypes { if name == t { return IsImageTypeSupportedByVips(imageType).Load } } return false }
[ "func", "IsTypeNameSupported", "(", "t", "string", ")", "bool", "{", "for", "imageType", ",", "name", ":=", "range", "ImageTypes", "{", "if", "name", "==", "t", "{", "return", "IsImageTypeSupportedByVips", "(", "imageType", ")", ".", "Load", "\n", "}", "\n...
// IsTypeNameSupported checks if a given image type name is supported
[ "IsTypeNameSupported", "checks", "if", "a", "given", "image", "type", "name", "is", "supported" ]
15cd11560781e3a634d3857b845d4c9c93aa454b
https://github.com/h2non/bimg/blob/15cd11560781e3a634d3857b845d4c9c93aa454b/type.go#L139-L146
18,781
h2non/bimg
type.go
IsTypeSupportedSave
func IsTypeSupportedSave(t ImageType) bool { _, ok := ImageTypes[t] return ok && IsImageTypeSupportedByVips(t).Save }
go
func IsTypeSupportedSave(t ImageType) bool { _, ok := ImageTypes[t] return ok && IsImageTypeSupportedByVips(t).Save }
[ "func", "IsTypeSupportedSave", "(", "t", "ImageType", ")", "bool", "{", "_", ",", "ok", ":=", "ImageTypes", "[", "t", "]", "\n", "return", "ok", "&&", "IsImageTypeSupportedByVips", "(", "t", ")", ".", "Save", "\n", "}" ]
// IsTypeSupportedSave checks if a given image type is support for saving
[ "IsTypeSupportedSave", "checks", "if", "a", "given", "image", "type", "is", "support", "for", "saving" ]
15cd11560781e3a634d3857b845d4c9c93aa454b
https://github.com/h2non/bimg/blob/15cd11560781e3a634d3857b845d4c9c93aa454b/type.go#L149-L152
18,782
h2non/bimg
type.go
IsTypeNameSupportedSave
func IsTypeNameSupportedSave(t string) bool { for imageType, name := range ImageTypes { if name == t { return IsImageTypeSupportedByVips(imageType).Save } } return false }
go
func IsTypeNameSupportedSave(t string) bool { for imageType, name := range ImageTypes { if name == t { return IsImageTypeSupportedByVips(imageType).Save } } return false }
[ "func", "IsTypeNameSupportedSave", "(", "t", "string", ")", "bool", "{", "for", "imageType", ",", "name", ":=", "range", "ImageTypes", "{", "if", "name", "==", "t", "{", "return", "IsImageTypeSupportedByVips", "(", "imageType", ")", ".", "Save", "\n", "}", ...
// IsTypeNameSupportedSave checks if a given image type name is supported for // saving
[ "IsTypeNameSupportedSave", "checks", "if", "a", "given", "image", "type", "name", "is", "supported", "for", "saving" ]
15cd11560781e3a634d3857b845d4c9c93aa454b
https://github.com/h2non/bimg/blob/15cd11560781e3a634d3857b845d4c9c93aa454b/type.go#L156-L163
18,783
h2non/bimg
vips.go
Initialize
func Initialize() { if C.VIPS_MAJOR_VERSION <= 7 && C.VIPS_MINOR_VERSION < 40 { panic("unsupported libvips version!") } m.Lock() runtime.LockOSThread() defer m.Unlock() defer runtime.UnlockOSThread() err := C.vips_init(C.CString("bimg")) if err != 0 { panic("unable to start vips!") } // Set libvips cache params C.vips_cache_set_max_mem(maxCacheMem) C.vips_cache_set_max(maxCacheSize) // Define a custom thread concurrency limit in libvips (this may generate thread-unsafe issues) // See: https://github.com/jcupitt/libvips/issues/261#issuecomment-92850414 if os.Getenv("VIPS_CONCURRENCY") == "" { C.vips_concurrency_set(1) } // Enable libvips cache tracing if os.Getenv("VIPS_TRACE") != "" { C.vips_enable_cache_set_trace() } initialized = true }
go
func Initialize() { if C.VIPS_MAJOR_VERSION <= 7 && C.VIPS_MINOR_VERSION < 40 { panic("unsupported libvips version!") } m.Lock() runtime.LockOSThread() defer m.Unlock() defer runtime.UnlockOSThread() err := C.vips_init(C.CString("bimg")) if err != 0 { panic("unable to start vips!") } // Set libvips cache params C.vips_cache_set_max_mem(maxCacheMem) C.vips_cache_set_max(maxCacheSize) // Define a custom thread concurrency limit in libvips (this may generate thread-unsafe issues) // See: https://github.com/jcupitt/libvips/issues/261#issuecomment-92850414 if os.Getenv("VIPS_CONCURRENCY") == "" { C.vips_concurrency_set(1) } // Enable libvips cache tracing if os.Getenv("VIPS_TRACE") != "" { C.vips_enable_cache_set_trace() } initialized = true }
[ "func", "Initialize", "(", ")", "{", "if", "C", ".", "VIPS_MAJOR_VERSION", "<=", "7", "&&", "C", ".", "VIPS_MINOR_VERSION", "<", "40", "{", "panic", "(", "\"", "\"", ")", "\n", "}", "\n\n", "m", ".", "Lock", "(", ")", "\n", "runtime", ".", "LockOST...
// Initialize is used to explicitly start libvips in thread-safe way. // Only call this function if you have previously turned off libvips.
[ "Initialize", "is", "used", "to", "explicitly", "start", "libvips", "in", "thread", "-", "safe", "way", ".", "Only", "call", "this", "function", "if", "you", "have", "previously", "turned", "off", "libvips", "." ]
15cd11560781e3a634d3857b845d4c9c93aa454b
https://github.com/h2non/bimg/blob/15cd11560781e3a634d3857b845d4c9c93aa454b/vips.go#L85-L116
18,784
h2non/bimg
vips.go
Shutdown
func Shutdown() { m.Lock() defer m.Unlock() if initialized { C.vips_shutdown() initialized = false } }
go
func Shutdown() { m.Lock() defer m.Unlock() if initialized { C.vips_shutdown() initialized = false } }
[ "func", "Shutdown", "(", ")", "{", "m", ".", "Lock", "(", ")", "\n", "defer", "m", ".", "Unlock", "(", ")", "\n\n", "if", "initialized", "{", "C", ".", "vips_shutdown", "(", ")", "\n", "initialized", "=", "false", "\n", "}", "\n", "}" ]
// Shutdown is used to shutdown libvips in a thread-safe way. // You can call this to drop caches as well. // If libvips was already initialized, the function is no-op
[ "Shutdown", "is", "used", "to", "shutdown", "libvips", "in", "a", "thread", "-", "safe", "way", ".", "You", "can", "call", "this", "to", "drop", "caches", "as", "well", ".", "If", "libvips", "was", "already", "initialized", "the", "function", "is", "no",...
15cd11560781e3a634d3857b845d4c9c93aa454b
https://github.com/h2non/bimg/blob/15cd11560781e3a634d3857b845d4c9c93aa454b/vips.go#L121-L129
18,785
h2non/bimg
vips.go
VipsIsTypeSupported
func VipsIsTypeSupported(t ImageType) bool { if t == JPEG { return int(C.vips_type_find_bridge(C.JPEG)) != 0 } if t == WEBP { return int(C.vips_type_find_bridge(C.WEBP)) != 0 } if t == PNG { return int(C.vips_type_find_bridge(C.PNG)) != 0 } if t == GIF { return int(C.vips_type_find_bridge(C.GIF)) != 0 } if t == PDF { return int(C.vips_type_find_bridge(C.PDF)) != 0 } if t == SVG { return int(C.vips_type_find_bridge(C.SVG)) != 0 } if t == TIFF { return int(C.vips_type_find_bridge(C.TIFF)) != 0 } if t == MAGICK { return int(C.vips_type_find_bridge(C.MAGICK)) != 0 } return false }
go
func VipsIsTypeSupported(t ImageType) bool { if t == JPEG { return int(C.vips_type_find_bridge(C.JPEG)) != 0 } if t == WEBP { return int(C.vips_type_find_bridge(C.WEBP)) != 0 } if t == PNG { return int(C.vips_type_find_bridge(C.PNG)) != 0 } if t == GIF { return int(C.vips_type_find_bridge(C.GIF)) != 0 } if t == PDF { return int(C.vips_type_find_bridge(C.PDF)) != 0 } if t == SVG { return int(C.vips_type_find_bridge(C.SVG)) != 0 } if t == TIFF { return int(C.vips_type_find_bridge(C.TIFF)) != 0 } if t == MAGICK { return int(C.vips_type_find_bridge(C.MAGICK)) != 0 } return false }
[ "func", "VipsIsTypeSupported", "(", "t", "ImageType", ")", "bool", "{", "if", "t", "==", "JPEG", "{", "return", "int", "(", "C", ".", "vips_type_find_bridge", "(", "C", ".", "JPEG", ")", ")", "!=", "0", "\n", "}", "\n", "if", "t", "==", "WEBP", "{"...
// VipsIsTypeSupported returns true if the given image type // is supported by the current libvips compilation.
[ "VipsIsTypeSupported", "returns", "true", "if", "the", "given", "image", "type", "is", "supported", "by", "the", "current", "libvips", "compilation", "." ]
15cd11560781e3a634d3857b845d4c9c93aa454b
https://github.com/h2non/bimg/blob/15cd11560781e3a634d3857b845d4c9c93aa454b/vips.go#L163-L189
18,786
h2non/bimg
vips.go
VipsIsTypeSupportedSave
func VipsIsTypeSupportedSave(t ImageType) bool { if t == JPEG { return int(C.vips_type_find_save_bridge(C.JPEG)) != 0 } if t == WEBP { return int(C.vips_type_find_save_bridge(C.WEBP)) != 0 } if t == PNG { return int(C.vips_type_find_save_bridge(C.PNG)) != 0 } if t == TIFF { return int(C.vips_type_find_save_bridge(C.TIFF)) != 0 } return false }
go
func VipsIsTypeSupportedSave(t ImageType) bool { if t == JPEG { return int(C.vips_type_find_save_bridge(C.JPEG)) != 0 } if t == WEBP { return int(C.vips_type_find_save_bridge(C.WEBP)) != 0 } if t == PNG { return int(C.vips_type_find_save_bridge(C.PNG)) != 0 } if t == TIFF { return int(C.vips_type_find_save_bridge(C.TIFF)) != 0 } return false }
[ "func", "VipsIsTypeSupportedSave", "(", "t", "ImageType", ")", "bool", "{", "if", "t", "==", "JPEG", "{", "return", "int", "(", "C", ".", "vips_type_find_save_bridge", "(", "C", ".", "JPEG", ")", ")", "!=", "0", "\n", "}", "\n", "if", "t", "==", "WEB...
// VipsIsTypeSupportedSave returns true if the given image type // is supported by the current libvips compilation for the // save operation.
[ "VipsIsTypeSupportedSave", "returns", "true", "if", "the", "given", "image", "type", "is", "supported", "by", "the", "current", "libvips", "compilation", "for", "the", "save", "operation", "." ]
15cd11560781e3a634d3857b845d4c9c93aa454b
https://github.com/h2non/bimg/blob/15cd11560781e3a634d3857b845d4c9c93aa454b/vips.go#L194-L208
18,787
tylertreat/BoomFilters
inverse.go
NewInverseBloomFilter
func NewInverseBloomFilter(capacity uint) *InverseBloomFilter { return &InverseBloomFilter{ array: make([]*[]byte, capacity), hashPool: &sync.Pool{New: func() interface{} { return fnv.New32() }}, capacity: capacity, } }
go
func NewInverseBloomFilter(capacity uint) *InverseBloomFilter { return &InverseBloomFilter{ array: make([]*[]byte, capacity), hashPool: &sync.Pool{New: func() interface{} { return fnv.New32() }}, capacity: capacity, } }
[ "func", "NewInverseBloomFilter", "(", "capacity", "uint", ")", "*", "InverseBloomFilter", "{", "return", "&", "InverseBloomFilter", "{", "array", ":", "make", "(", "[", "]", "*", "[", "]", "byte", ",", "capacity", ")", ",", "hashPool", ":", "&", "sync", ...
// NewInverseBloomFilter creates and returns a new InverseBloomFilter with the // specified capacity.
[ "NewInverseBloomFilter", "creates", "and", "returns", "a", "new", "InverseBloomFilter", "with", "the", "specified", "capacity", "." ]
611b3dbe80e85df3a0a10a43997d4d5784e86245
https://github.com/tylertreat/BoomFilters/blob/611b3dbe80e85df3a0a10a43997d4d5784e86245/inverse.go#L68-L74
18,788
tylertreat/BoomFilters
inverse.go
Add
func (i *InverseBloomFilter) Add(data []byte) Filter { index := i.index(data) i.getAndSet(index, data) return i }
go
func (i *InverseBloomFilter) Add(data []byte) Filter { index := i.index(data) i.getAndSet(index, data) return i }
[ "func", "(", "i", "*", "InverseBloomFilter", ")", "Add", "(", "data", "[", "]", "byte", ")", "Filter", "{", "index", ":=", "i", ".", "index", "(", "data", ")", "\n", "i", ".", "getAndSet", "(", "index", ",", "data", ")", "\n", "return", "i", "\n"...
// Add will add the data to the filter. It returns the filter to allow for // chaining.
[ "Add", "will", "add", "the", "data", "to", "the", "filter", ".", "It", "returns", "the", "filter", "to", "allow", "for", "chaining", "." ]
611b3dbe80e85df3a0a10a43997d4d5784e86245
https://github.com/tylertreat/BoomFilters/blob/611b3dbe80e85df3a0a10a43997d4d5784e86245/inverse.go#L93-L97
18,789
tylertreat/BoomFilters
inverse.go
getAndSet
func (i *InverseBloomFilter) getAndSet(index uint32, data []byte) []byte { indexPtr := (*unsafe.Pointer)(unsafe.Pointer(&i.array[index])) keyUnsafe := unsafe.Pointer(&data) var oldKey []byte for { oldKeyUnsafe := atomic.LoadPointer(indexPtr) if atomic.CompareAndSwapPointer(indexPtr, oldKeyUnsafe, keyUnsafe) { oldKeyPtr := (*[]byte)(oldKeyUnsafe) if oldKeyPtr != nil { oldKey = *oldKeyPtr } break } } return oldKey }
go
func (i *InverseBloomFilter) getAndSet(index uint32, data []byte) []byte { indexPtr := (*unsafe.Pointer)(unsafe.Pointer(&i.array[index])) keyUnsafe := unsafe.Pointer(&data) var oldKey []byte for { oldKeyUnsafe := atomic.LoadPointer(indexPtr) if atomic.CompareAndSwapPointer(indexPtr, oldKeyUnsafe, keyUnsafe) { oldKeyPtr := (*[]byte)(oldKeyUnsafe) if oldKeyPtr != nil { oldKey = *oldKeyPtr } break } } return oldKey }
[ "func", "(", "i", "*", "InverseBloomFilter", ")", "getAndSet", "(", "index", "uint32", ",", "data", "[", "]", "byte", ")", "[", "]", "byte", "{", "indexPtr", ":=", "(", "*", "unsafe", ".", "Pointer", ")", "(", "unsafe", ".", "Pointer", "(", "&", "i...
// getAndSet returns the data that was in the slice at the given index after // putting the new data in the slice at that index, atomically.
[ "getAndSet", "returns", "the", "data", "that", "was", "in", "the", "slice", "at", "the", "given", "index", "after", "putting", "the", "new", "data", "in", "the", "slice", "at", "that", "index", "atomically", "." ]
611b3dbe80e85df3a0a10a43997d4d5784e86245
https://github.com/tylertreat/BoomFilters/blob/611b3dbe80e85df3a0a10a43997d4d5784e86245/inverse.go#L113-L128
18,790
tylertreat/BoomFilters
inverse.go
index
func (i *InverseBloomFilter) index(data []byte) uint32 { hash := i.hashPool.Get().(hash.Hash32) hash.Write(data) index := hash.Sum32() % uint32(i.capacity) hash.Reset() i.hashPool.Put(hash) return index }
go
func (i *InverseBloomFilter) index(data []byte) uint32 { hash := i.hashPool.Get().(hash.Hash32) hash.Write(data) index := hash.Sum32() % uint32(i.capacity) hash.Reset() i.hashPool.Put(hash) return index }
[ "func", "(", "i", "*", "InverseBloomFilter", ")", "index", "(", "data", "[", "]", "byte", ")", "uint32", "{", "hash", ":=", "i", ".", "hashPool", ".", "Get", "(", ")", ".", "(", "hash", ".", "Hash32", ")", "\n", "hash", ".", "Write", "(", "data",...
// index returns the array index for the given data.
[ "index", "returns", "the", "array", "index", "for", "the", "given", "data", "." ]
611b3dbe80e85df3a0a10a43997d4d5784e86245
https://github.com/tylertreat/BoomFilters/blob/611b3dbe80e85df3a0a10a43997d4d5784e86245/inverse.go#L131-L138
18,791
tylertreat/BoomFilters
inverse.go
SetHashFactory
func (i *InverseBloomFilter) SetHashFactory(h func() hash.Hash32) { i.hashPool = &sync.Pool{New: func() interface{} { return h() }} }
go
func (i *InverseBloomFilter) SetHashFactory(h func() hash.Hash32) { i.hashPool = &sync.Pool{New: func() interface{} { return h() }} }
[ "func", "(", "i", "*", "InverseBloomFilter", ")", "SetHashFactory", "(", "h", "func", "(", ")", "hash", ".", "Hash32", ")", "{", "i", ".", "hashPool", "=", "&", "sync", ".", "Pool", "{", "New", ":", "func", "(", ")", "interface", "{", "}", "{", "...
// SetHashFactory sets the hashing function factory used in the filter.
[ "SetHashFactory", "sets", "the", "hashing", "function", "factory", "used", "in", "the", "filter", "." ]
611b3dbe80e85df3a0a10a43997d4d5784e86245
https://github.com/tylertreat/BoomFilters/blob/611b3dbe80e85df3a0a10a43997d4d5784e86245/inverse.go#L141-L143
18,792
tylertreat/BoomFilters
deletable.go
NewDeletableBloomFilter
func NewDeletableBloomFilter(n, r uint, fpRate float64) *DeletableBloomFilter { var ( m = OptimalM(n, fpRate) k = OptimalK(fpRate) ) return &DeletableBloomFilter{ buckets: NewBuckets(m-r, 1), collisions: NewBuckets(r+1, 1), hash: fnv.New64(), m: m - r, regionSize: (m - r) / r, k: k, indexBuffer: make([]uint, k), } }
go
func NewDeletableBloomFilter(n, r uint, fpRate float64) *DeletableBloomFilter { var ( m = OptimalM(n, fpRate) k = OptimalK(fpRate) ) return &DeletableBloomFilter{ buckets: NewBuckets(m-r, 1), collisions: NewBuckets(r+1, 1), hash: fnv.New64(), m: m - r, regionSize: (m - r) / r, k: k, indexBuffer: make([]uint, k), } }
[ "func", "NewDeletableBloomFilter", "(", "n", ",", "r", "uint", ",", "fpRate", "float64", ")", "*", "DeletableBloomFilter", "{", "var", "(", "m", "=", "OptimalM", "(", "n", ",", "fpRate", ")", "\n", "k", "=", "OptimalK", "(", "fpRate", ")", "\n", ")", ...
// NewDeletableBloomFilter creates a new DeletableBloomFilter optimized to // store n items with a specified target false-positive rate. The r value // determines the number of bits to use to store collision information. This // controls the deletability of an element. Refer to the paper for selecting an // optimal value.
[ "NewDeletableBloomFilter", "creates", "a", "new", "DeletableBloomFilter", "optimized", "to", "store", "n", "items", "with", "a", "specified", "target", "false", "-", "positive", "rate", ".", "The", "r", "value", "determines", "the", "number", "of", "bits", "to",...
611b3dbe80e85df3a0a10a43997d4d5784e86245
https://github.com/tylertreat/BoomFilters/blob/611b3dbe80e85df3a0a10a43997d4d5784e86245/deletable.go#L38-L52
18,793
tylertreat/BoomFilters
counting.go
NewCountingBloomFilter
func NewCountingBloomFilter(n uint, b uint8, fpRate float64) *CountingBloomFilter { var ( m = OptimalM(n, fpRate) k = OptimalK(fpRate) ) return &CountingBloomFilter{ buckets: NewBuckets(m, b), hash: fnv.New64(), m: m, k: k, indexBuffer: make([]uint, k), } }
go
func NewCountingBloomFilter(n uint, b uint8, fpRate float64) *CountingBloomFilter { var ( m = OptimalM(n, fpRate) k = OptimalK(fpRate) ) return &CountingBloomFilter{ buckets: NewBuckets(m, b), hash: fnv.New64(), m: m, k: k, indexBuffer: make([]uint, k), } }
[ "func", "NewCountingBloomFilter", "(", "n", "uint", ",", "b", "uint8", ",", "fpRate", "float64", ")", "*", "CountingBloomFilter", "{", "var", "(", "m", "=", "OptimalM", "(", "n", ",", "fpRate", ")", "\n", "k", "=", "OptimalK", "(", "fpRate", ")", "\n",...
// NewCountingBloomFilter creates a new Counting Bloom Filter optimized to // store n items with a specified target false-positive rate and bucket size. // If you don't know how many bits to use for buckets, use // NewDefaultCountingBloomFilter for a sensible default.
[ "NewCountingBloomFilter", "creates", "a", "new", "Counting", "Bloom", "Filter", "optimized", "to", "store", "n", "items", "with", "a", "specified", "target", "false", "-", "positive", "rate", "and", "bucket", "size", ".", "If", "you", "don", "t", "know", "ho...
611b3dbe80e85df3a0a10a43997d4d5784e86245
https://github.com/tylertreat/BoomFilters/blob/611b3dbe80e85df3a0a10a43997d4d5784e86245/counting.go#L37-L49
18,794
tylertreat/BoomFilters
countmin.go
NewCountMinSketch
func NewCountMinSketch(epsilon, delta float64) *CountMinSketch { var ( width = uint(math.Ceil(math.E / epsilon)) depth = uint(math.Ceil(math.Log(1 / delta))) matrix = make([][]uint64, depth) ) for i := uint(0); i < depth; i++ { matrix[i] = make([]uint64, width) } return &CountMinSketch{ matrix: matrix, width: width, depth: depth, epsilon: epsilon, delta: delta, hash: fnv.New64(), } }
go
func NewCountMinSketch(epsilon, delta float64) *CountMinSketch { var ( width = uint(math.Ceil(math.E / epsilon)) depth = uint(math.Ceil(math.Log(1 / delta))) matrix = make([][]uint64, depth) ) for i := uint(0); i < depth; i++ { matrix[i] = make([]uint64, width) } return &CountMinSketch{ matrix: matrix, width: width, depth: depth, epsilon: epsilon, delta: delta, hash: fnv.New64(), } }
[ "func", "NewCountMinSketch", "(", "epsilon", ",", "delta", "float64", ")", "*", "CountMinSketch", "{", "var", "(", "width", "=", "uint", "(", "math", ".", "Ceil", "(", "math", ".", "E", "/", "epsilon", ")", ")", "\n", "depth", "=", "uint", "(", "math...
// NewCountMinSketch creates a new Count-Min Sketch whose relative accuracy is // within a factor of epsilon with probability delta. Both of these parameters // affect the space and time complexity.
[ "NewCountMinSketch", "creates", "a", "new", "Count", "-", "Min", "Sketch", "whose", "relative", "accuracy", "is", "within", "a", "factor", "of", "epsilon", "with", "probability", "delta", ".", "Both", "of", "these", "parameters", "affect", "the", "space", "and...
611b3dbe80e85df3a0a10a43997d4d5784e86245
https://github.com/tylertreat/BoomFilters/blob/611b3dbe80e85df3a0a10a43997d4d5784e86245/countmin.go#L46-L65
18,795
tylertreat/BoomFilters
countmin.go
Add
func (c *CountMinSketch) Add(data []byte) *CountMinSketch { lower, upper := hashKernel(data, c.hash) // Increment count in each row. for i := uint(0); i < c.depth; i++ { c.matrix[i][(uint(lower)+uint(upper)*i)%c.width]++ } c.count++ return c }
go
func (c *CountMinSketch) Add(data []byte) *CountMinSketch { lower, upper := hashKernel(data, c.hash) // Increment count in each row. for i := uint(0); i < c.depth; i++ { c.matrix[i][(uint(lower)+uint(upper)*i)%c.width]++ } c.count++ return c }
[ "func", "(", "c", "*", "CountMinSketch", ")", "Add", "(", "data", "[", "]", "byte", ")", "*", "CountMinSketch", "{", "lower", ",", "upper", ":=", "hashKernel", "(", "data", ",", "c", ".", "hash", ")", "\n\n", "// Increment count in each row.", "for", "i"...
// Add will add the data to the set. Returns the CountMinSketch to allow for // chaining.
[ "Add", "will", "add", "the", "data", "to", "the", "set", ".", "Returns", "the", "CountMinSketch", "to", "allow", "for", "chaining", "." ]
611b3dbe80e85df3a0a10a43997d4d5784e86245
https://github.com/tylertreat/BoomFilters/blob/611b3dbe80e85df3a0a10a43997d4d5784e86245/countmin.go#L84-L94
18,796
tylertreat/BoomFilters
countmin.go
Merge
func (c *CountMinSketch) Merge(other *CountMinSketch) error { if c.depth != other.depth { return errors.New("matrix depth must match") } if c.width != other.width { return errors.New("matrix width must match") } for i := uint(0); i < c.depth; i++ { for j := uint(0); j < c.width; j++ { c.matrix[i][j] += other.matrix[i][j] } } c.count += other.count return nil }
go
func (c *CountMinSketch) Merge(other *CountMinSketch) error { if c.depth != other.depth { return errors.New("matrix depth must match") } if c.width != other.width { return errors.New("matrix width must match") } for i := uint(0); i < c.depth; i++ { for j := uint(0); j < c.width; j++ { c.matrix[i][j] += other.matrix[i][j] } } c.count += other.count return nil }
[ "func", "(", "c", "*", "CountMinSketch", ")", "Merge", "(", "other", "*", "CountMinSketch", ")", "error", "{", "if", "c", ".", "depth", "!=", "other", ".", "depth", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if",...
// Merge combines this CountMinSketch with another. Returns an error if the // matrix width and depth are not equal.
[ "Merge", "combines", "this", "CountMinSketch", "with", "another", ".", "Returns", "an", "error", "if", "the", "matrix", "width", "and", "depth", "are", "not", "equal", "." ]
611b3dbe80e85df3a0a10a43997d4d5784e86245
https://github.com/tylertreat/BoomFilters/blob/611b3dbe80e85df3a0a10a43997d4d5784e86245/countmin.go#L114-L131
18,797
tylertreat/BoomFilters
countmin.go
Reset
func (c *CountMinSketch) Reset() *CountMinSketch { matrix := make([][]uint64, c.depth) for i := uint(0); i < c.depth; i++ { matrix[i] = make([]uint64, c.width) } c.matrix = matrix c.count = 0 return c }
go
func (c *CountMinSketch) Reset() *CountMinSketch { matrix := make([][]uint64, c.depth) for i := uint(0); i < c.depth; i++ { matrix[i] = make([]uint64, c.width) } c.matrix = matrix c.count = 0 return c }
[ "func", "(", "c", "*", "CountMinSketch", ")", "Reset", "(", ")", "*", "CountMinSketch", "{", "matrix", ":=", "make", "(", "[", "]", "[", "]", "uint64", ",", "c", ".", "depth", ")", "\n", "for", "i", ":=", "uint", "(", "0", ")", ";", "i", "<", ...
// Reset restores the CountMinSketch to its original state. It returns itself // to allow for chaining.
[ "Reset", "restores", "the", "CountMinSketch", "to", "its", "original", "state", ".", "It", "returns", "itself", "to", "allow", "for", "chaining", "." ]
611b3dbe80e85df3a0a10a43997d4d5784e86245
https://github.com/tylertreat/BoomFilters/blob/611b3dbe80e85df3a0a10a43997d4d5784e86245/countmin.go#L135-L144
18,798
tylertreat/BoomFilters
countmin.go
WriteDataTo
func (c *CountMinSketch) WriteDataTo(stream io.Writer) (int, error) { buf := new(bytes.Buffer) // serialize epsilon and delta as cms configuration check err := binary.Write(buf, binary.LittleEndian, c.epsilon) if err != nil { return 0, err } err = binary.Write(buf, binary.LittleEndian, c.delta) if err != nil { return 0, err } err = binary.Write(buf, binary.LittleEndian, c.count) if err != nil { return 0, err } // encode matrix for i := range c.matrix { err = binary.Write(buf, binary.LittleEndian, c.matrix[i]) if err != nil { return 0, err } } return stream.Write(buf.Bytes()) }
go
func (c *CountMinSketch) WriteDataTo(stream io.Writer) (int, error) { buf := new(bytes.Buffer) // serialize epsilon and delta as cms configuration check err := binary.Write(buf, binary.LittleEndian, c.epsilon) if err != nil { return 0, err } err = binary.Write(buf, binary.LittleEndian, c.delta) if err != nil { return 0, err } err = binary.Write(buf, binary.LittleEndian, c.count) if err != nil { return 0, err } // encode matrix for i := range c.matrix { err = binary.Write(buf, binary.LittleEndian, c.matrix[i]) if err != nil { return 0, err } } return stream.Write(buf.Bytes()) }
[ "func", "(", "c", "*", "CountMinSketch", ")", "WriteDataTo", "(", "stream", "io", ".", "Writer", ")", "(", "int", ",", "error", ")", "{", "buf", ":=", "new", "(", "bytes", ".", "Buffer", ")", "\n", "// serialize epsilon and delta as cms configuration check", ...
// WriteDataTo writes a binary representation of the CMS data to // an io stream. It returns the number of bytes written and error
[ "WriteDataTo", "writes", "a", "binary", "representation", "of", "the", "CMS", "data", "to", "an", "io", "stream", ".", "It", "returns", "the", "number", "of", "bytes", "written", "and", "error" ]
611b3dbe80e85df3a0a10a43997d4d5784e86245
https://github.com/tylertreat/BoomFilters/blob/611b3dbe80e85df3a0a10a43997d4d5784e86245/countmin.go#L153-L177
18,799
tylertreat/BoomFilters
cuckoo.go
indexOf
func (b bucket) indexOf(f []byte) int { for i, fingerprint := range b { if bytes.Equal(f, fingerprint) { return i } } return -1 }
go
func (b bucket) indexOf(f []byte) int { for i, fingerprint := range b { if bytes.Equal(f, fingerprint) { return i } } return -1 }
[ "func", "(", "b", "bucket", ")", "indexOf", "(", "f", "[", "]", "byte", ")", "int", "{", "for", "i", ",", "fingerprint", ":=", "range", "b", "{", "if", "bytes", ".", "Equal", "(", "f", ",", "fingerprint", ")", "{", "return", "i", "\n", "}", "\n...
// indexOf returns the entry index of the given fingerprint or -1 if it's not // in the bucket.
[ "indexOf", "returns", "the", "entry", "index", "of", "the", "given", "fingerprint", "or", "-", "1", "if", "it", "s", "not", "in", "the", "bucket", "." ]
611b3dbe80e85df3a0a10a43997d4d5784e86245
https://github.com/tylertreat/BoomFilters/blob/611b3dbe80e85df3a0a10a43997d4d5784e86245/cuckoo.go#L28-L35