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
listlengths
21
1.41k
docstring
stringlengths
6
2.61k
docstring_tokens
listlengths
3
215
sha
stringlengths
40
40
url
stringlengths
85
252
12,200
palantir/godel
framework/godellauncher/task.go
AddFlag
func (f VerifyFlag) AddFlag(fset *pflag.FlagSet) (interface{}, error) { switch f.Type { case StringFlag: return fset.String(f.Name, "", f.Description), nil case BoolFlag: return fset.Bool(f.Name, false, f.Description), nil default: return nil, errors.Errorf("unrecognized flag type: %v", f.Type) } }
go
func (f VerifyFlag) AddFlag(fset *pflag.FlagSet) (interface{}, error) { switch f.Type { case StringFlag: return fset.String(f.Name, "", f.Description), nil case BoolFlag: return fset.Bool(f.Name, false, f.Description), nil default: return nil, errors.Errorf("unrecognized flag type: %v", f.Type) } }
[ "func", "(", "f", "VerifyFlag", ")", "AddFlag", "(", "fset", "*", "pflag", ".", "FlagSet", ")", "(", "interface", "{", "}", ",", "error", ")", "{", "switch", "f", ".", "Type", "{", "case", "StringFlag", ":", "return", "fset", ".", "String", "(", "f", ".", "Name", ",", "\"", "\"", ",", "f", ".", "Description", ")", ",", "nil", "\n", "case", "BoolFlag", ":", "return", "fset", ".", "Bool", "(", "f", ".", "Name", ",", "false", ",", "f", ".", "Description", ")", ",", "nil", "\n", "default", ":", "return", "nil", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "f", ".", "Type", ")", "\n", "}", "\n", "}" ]
// AddFlag adds the flag represented by VerifyFlag to the specified pflag.FlagSet. Returns the pointer to the value that // can be used to retrieve the value.
[ "AddFlag", "adds", "the", "flag", "represented", "by", "VerifyFlag", "to", "the", "specified", "pflag", ".", "FlagSet", ".", "Returns", "the", "pointer", "to", "the", "value", "that", "can", "be", "used", "to", "retrieve", "the", "value", "." ]
3410152fb9e7ba34206a144c5c26a7829d52b488
https://github.com/palantir/godel/blob/3410152fb9e7ba34206a144c5c26a7829d52b488/framework/godellauncher/task.go#L90-L99
12,201
palantir/godel
pkg/versionedconfig/versionedconfig.go
ConfigVersion
func ConfigVersion(in []byte) (string, error) { var cfgWithVersion ConfigWithVersion if err := yaml.Unmarshal(in, &cfgWithVersion); err != nil { return "", errors.Wrapf(err, "failed to unmarshal YAML") } return cfgWithVersion.Version, nil }
go
func ConfigVersion(in []byte) (string, error) { var cfgWithVersion ConfigWithVersion if err := yaml.Unmarshal(in, &cfgWithVersion); err != nil { return "", errors.Wrapf(err, "failed to unmarshal YAML") } return cfgWithVersion.Version, nil }
[ "func", "ConfigVersion", "(", "in", "[", "]", "byte", ")", "(", "string", ",", "error", ")", "{", "var", "cfgWithVersion", "ConfigWithVersion", "\n", "if", "err", ":=", "yaml", ".", "Unmarshal", "(", "in", ",", "&", "cfgWithVersion", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "errors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "return", "cfgWithVersion", ".", "Version", ",", "nil", "\n", "}" ]
// ConfigVersion unmarshals the provided bytes as YAML and returns the value of the top-level "version" key. The value // of this key must be a string. If the input is valid YAML but does not contain a "version" key, returns the empty // string. Returns an error if the input is not valid YAML or cannot be unmarshaled as YAML as specified.
[ "ConfigVersion", "unmarshals", "the", "provided", "bytes", "as", "YAML", "and", "returns", "the", "value", "of", "the", "top", "-", "level", "version", "key", ".", "The", "value", "of", "this", "key", "must", "be", "a", "string", ".", "If", "the", "input", "is", "valid", "YAML", "but", "does", "not", "contain", "a", "version", "key", "returns", "the", "empty", "string", ".", "Returns", "an", "error", "if", "the", "input", "is", "not", "valid", "YAML", "or", "cannot", "be", "unmarshaled", "as", "YAML", "as", "specified", "." ]
3410152fb9e7ba34206a144c5c26a7829d52b488
https://github.com/palantir/godel/blob/3410152fb9e7ba34206a144c5c26a7829d52b488/pkg/versionedconfig/versionedconfig.go#L30-L36
12,202
palantir/godel
framework/builtintasks/installupdate/layout/operations.go
Move
func Move(src, dst string) error { if err := verifyDstPathSafe(dst); err != nil { return errors.Wrapf(err, "cannot move directory to path %s", dst) } if err := os.Rename(src, dst); err != nil { return errors.Wrapf(err, "failed to rename %s to %s", src, dst) } return nil }
go
func Move(src, dst string) error { if err := verifyDstPathSafe(dst); err != nil { return errors.Wrapf(err, "cannot move directory to path %s", dst) } if err := os.Rename(src, dst); err != nil { return errors.Wrapf(err, "failed to rename %s to %s", src, dst) } return nil }
[ "func", "Move", "(", "src", ",", "dst", "string", ")", "error", "{", "if", "err", ":=", "verifyDstPathSafe", "(", "dst", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "dst", ")", "\n", "}", "\n", "if", "err", ":=", "os", ".", "Rename", "(", "src", ",", "dst", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "src", ",", "dst", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Move the file or directory at src to dst. Conceptually, this is equivalent to executing "mv src dst". dst must not // already exist and the path up to it must already exist. Uses os.Rename to execute the move, which means that there // may be platform-specific restrictions such as not being able to move the directory between different volumes.
[ "Move", "the", "file", "or", "directory", "at", "src", "to", "dst", ".", "Conceptually", "this", "is", "equivalent", "to", "executing", "mv", "src", "dst", ".", "dst", "must", "not", "already", "exist", "and", "the", "path", "up", "to", "it", "must", "already", "exist", ".", "Uses", "os", ".", "Rename", "to", "execute", "the", "move", "which", "means", "that", "there", "may", "be", "platform", "-", "specific", "restrictions", "such", "as", "not", "being", "able", "to", "move", "the", "directory", "between", "different", "volumes", "." ]
3410152fb9e7ba34206a144c5c26a7829d52b488
https://github.com/palantir/godel/blob/3410152fb9e7ba34206a144c5c26a7829d52b488/framework/builtintasks/installupdate/layout/operations.go#L31-L39
12,203
palantir/godel
framework/builtintasks/installupdate/layout/operations.go
CopyDir
func CopyDir(src, dst string) error { if err := verifyDstPathSafe(dst); err != nil { return errors.Wrapf(err, "cannot copy directory to path %s", dst) } srcInfo, err := os.Stat(src) if err != nil { return errors.Wrapf(err, "failed to stat source directory %s", src) } if err := os.Mkdir(dst, srcInfo.Mode()); err != nil { return errors.Wrapf(err, "failed to create destination directory %s", dst) } files, err := ioutil.ReadDir(src) if err != nil { return errors.Wrapf(err, "failed to read directory %s", src) } for _, f := range files { srcPath := path.Join(src, f.Name()) dstPath := path.Join(dst, f.Name()) if f.IsDir() { err = CopyDir(srcPath, dstPath) } else { err = CopyFile(srcPath, dstPath) } if err != nil { return errors.Wrapf(err, "failed to copy %s to %s", srcPath, dstPath) } } return nil }
go
func CopyDir(src, dst string) error { if err := verifyDstPathSafe(dst); err != nil { return errors.Wrapf(err, "cannot copy directory to path %s", dst) } srcInfo, err := os.Stat(src) if err != nil { return errors.Wrapf(err, "failed to stat source directory %s", src) } if err := os.Mkdir(dst, srcInfo.Mode()); err != nil { return errors.Wrapf(err, "failed to create destination directory %s", dst) } files, err := ioutil.ReadDir(src) if err != nil { return errors.Wrapf(err, "failed to read directory %s", src) } for _, f := range files { srcPath := path.Join(src, f.Name()) dstPath := path.Join(dst, f.Name()) if f.IsDir() { err = CopyDir(srcPath, dstPath) } else { err = CopyFile(srcPath, dstPath) } if err != nil { return errors.Wrapf(err, "failed to copy %s to %s", srcPath, dstPath) } } return nil }
[ "func", "CopyDir", "(", "src", ",", "dst", "string", ")", "error", "{", "if", "err", ":=", "verifyDstPathSafe", "(", "dst", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "dst", ")", "\n", "}", "\n\n", "srcInfo", ",", "err", ":=", "os", ".", "Stat", "(", "src", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "src", ")", "\n", "}", "\n\n", "if", "err", ":=", "os", ".", "Mkdir", "(", "dst", ",", "srcInfo", ".", "Mode", "(", ")", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "dst", ")", "\n", "}", "\n\n", "files", ",", "err", ":=", "ioutil", ".", "ReadDir", "(", "src", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "src", ")", "\n", "}", "\n\n", "for", "_", ",", "f", ":=", "range", "files", "{", "srcPath", ":=", "path", ".", "Join", "(", "src", ",", "f", ".", "Name", "(", ")", ")", "\n", "dstPath", ":=", "path", ".", "Join", "(", "dst", ",", "f", ".", "Name", "(", ")", ")", "\n\n", "if", "f", ".", "IsDir", "(", ")", "{", "err", "=", "CopyDir", "(", "srcPath", ",", "dstPath", ")", "\n", "}", "else", "{", "err", "=", "CopyFile", "(", "srcPath", ",", "dstPath", ")", "\n", "}", "\n\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "srcPath", ",", "dstPath", ")", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// CopyDir recursively copies the src directory to the path specified by dst. dst must not already exist and the path up // to it must already exist.
[ "CopyDir", "recursively", "copies", "the", "src", "directory", "to", "the", "path", "specified", "by", "dst", ".", "dst", "must", "not", "already", "exist", "and", "the", "path", "up", "to", "it", "must", "already", "exist", "." ]
3410152fb9e7ba34206a144c5c26a7829d52b488
https://github.com/palantir/godel/blob/3410152fb9e7ba34206a144c5c26a7829d52b488/framework/builtintasks/installupdate/layout/operations.go#L43-L78
12,204
palantir/godel
framework/builtintasks/installupdate/layout/operations.go
SyncDirAdditive
func SyncDirAdditive(src, dst string) error { srcInfos, err := ioutil.ReadDir(src) if err != nil { return errors.Wrapf(err, "failed to open %s", src) } for _, srcInfo := range srcInfos { srcPath := path.Join(src, srcInfo.Name()) dstPath := path.Join(dst, srcInfo.Name()) if dstInfo, err := os.Stat(dstPath); os.IsNotExist(err) { // safe to copy if srcInfo.IsDir() { err = CopyDir(srcPath, dstPath) } else { err = CopyFile(srcPath, dstPath) } if err != nil { return errors.Wrapf(err, "failed to copy %s to %s", srcPath, dstPath) } } else if err != nil { return errors.Wrapf(err, "failed to stat %s", dstPath) } else if srcInfo.IsDir() && dstInfo.IsDir() { // if source and destination are both directories, sync recursively if err = SyncDirAdditive(srcPath, dstPath); err != nil { return errors.Wrapf(err, "failed to sync %s to %s", srcPath, dstPath) } } } return nil }
go
func SyncDirAdditive(src, dst string) error { srcInfos, err := ioutil.ReadDir(src) if err != nil { return errors.Wrapf(err, "failed to open %s", src) } for _, srcInfo := range srcInfos { srcPath := path.Join(src, srcInfo.Name()) dstPath := path.Join(dst, srcInfo.Name()) if dstInfo, err := os.Stat(dstPath); os.IsNotExist(err) { // safe to copy if srcInfo.IsDir() { err = CopyDir(srcPath, dstPath) } else { err = CopyFile(srcPath, dstPath) } if err != nil { return errors.Wrapf(err, "failed to copy %s to %s", srcPath, dstPath) } } else if err != nil { return errors.Wrapf(err, "failed to stat %s", dstPath) } else if srcInfo.IsDir() && dstInfo.IsDir() { // if source and destination are both directories, sync recursively if err = SyncDirAdditive(srcPath, dstPath); err != nil { return errors.Wrapf(err, "failed to sync %s to %s", srcPath, dstPath) } } } return nil }
[ "func", "SyncDirAdditive", "(", "src", ",", "dst", "string", ")", "error", "{", "srcInfos", ",", "err", ":=", "ioutil", ".", "ReadDir", "(", "src", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "src", ")", "\n", "}", "\n\n", "for", "_", ",", "srcInfo", ":=", "range", "srcInfos", "{", "srcPath", ":=", "path", ".", "Join", "(", "src", ",", "srcInfo", ".", "Name", "(", ")", ")", "\n", "dstPath", ":=", "path", ".", "Join", "(", "dst", ",", "srcInfo", ".", "Name", "(", ")", ")", "\n\n", "if", "dstInfo", ",", "err", ":=", "os", ".", "Stat", "(", "dstPath", ")", ";", "os", ".", "IsNotExist", "(", "err", ")", "{", "// safe to copy", "if", "srcInfo", ".", "IsDir", "(", ")", "{", "err", "=", "CopyDir", "(", "srcPath", ",", "dstPath", ")", "\n", "}", "else", "{", "err", "=", "CopyFile", "(", "srcPath", ",", "dstPath", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "srcPath", ",", "dstPath", ")", "\n", "}", "\n", "}", "else", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "dstPath", ")", "\n", "}", "else", "if", "srcInfo", ".", "IsDir", "(", ")", "&&", "dstInfo", ".", "IsDir", "(", ")", "{", "// if source and destination are both directories, sync recursively", "if", "err", "=", "SyncDirAdditive", "(", "srcPath", ",", "dstPath", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "srcPath", ",", "dstPath", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// SyncDirAdditive copies all of the files and directories in src that are not in dst. Directories that are present in // both are handled recursively. Basically a recursive merge with source preservation.
[ "SyncDirAdditive", "copies", "all", "of", "the", "files", "and", "directories", "in", "src", "that", "are", "not", "in", "dst", ".", "Directories", "that", "are", "present", "in", "both", "are", "handled", "recursively", ".", "Basically", "a", "recursive", "merge", "with", "source", "preservation", "." ]
3410152fb9e7ba34206a144c5c26a7829d52b488
https://github.com/palantir/godel/blob/3410152fb9e7ba34206a144c5c26a7829d52b488/framework/builtintasks/installupdate/layout/operations.go#L253-L283
12,205
palantir/godel
framework/builtintasks/installupdate/layout/operations.go
verifyDstPathSafe
func verifyDstPathSafe(dst string) error { if _, err := os.Stat(dst); !os.IsNotExist(err) { return errors.Wrapf(err, "destination path %s already exists", dst) } if _, err := os.Stat(path.Dir(dst)); os.IsNotExist(err) { return errors.Wrapf(err, "parent directory of destination path %s does not exist", dst) } return nil }
go
func verifyDstPathSafe(dst string) error { if _, err := os.Stat(dst); !os.IsNotExist(err) { return errors.Wrapf(err, "destination path %s already exists", dst) } if _, err := os.Stat(path.Dir(dst)); os.IsNotExist(err) { return errors.Wrapf(err, "parent directory of destination path %s does not exist", dst) } return nil }
[ "func", "verifyDstPathSafe", "(", "dst", "string", ")", "error", "{", "if", "_", ",", "err", ":=", "os", ".", "Stat", "(", "dst", ")", ";", "!", "os", ".", "IsNotExist", "(", "err", ")", "{", "return", "errors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "dst", ")", "\n", "}", "\n", "if", "_", ",", "err", ":=", "os", ".", "Stat", "(", "path", ".", "Dir", "(", "dst", ")", ")", ";", "os", ".", "IsNotExist", "(", "err", ")", "{", "return", "errors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "dst", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// verifyDstPathSafe verifies that the provided destination path does not exist, but that the path to its parent does.
[ "verifyDstPathSafe", "verifies", "that", "the", "provided", "destination", "path", "does", "not", "exist", "but", "that", "the", "path", "to", "its", "parent", "does", "." ]
3410152fb9e7ba34206a144c5c26a7829d52b488
https://github.com/palantir/godel/blob/3410152fb9e7ba34206a144c5c26a7829d52b488/framework/builtintasks/installupdate/layout/operations.go#L311-L319
12,206
palantir/godel
godelgetter/download.go
Download
func Download(pkgSrc PkgSrc, dstFilePath string, w io.Writer) (rErr error) { wantChecksum := pkgSrc.Checksum() if info, err := os.Stat(dstFilePath); err == nil { if info.IsDir() { return errors.Errorf("destination path %s already exists and is a directory", dstFilePath) } if wantChecksum != "" { // if file already exists at destination and checksum is known, verify checksum of existing file. // If it matches, use existing file. checksum, err := computeSHA256Checksum(dstFilePath) if err != nil { return errors.Wrapf(err, "failed to compute checksum of %s", dstFilePath) } if checksum == wantChecksum { return nil } } } // open reader from source r, size, err := pkgSrc.Reader() if err != nil { return err } defer func() { if err := r.Close(); err != nil && rErr == nil { rErr = errors.Wrapf(err, "failed to close reader for %s in defer", pkgSrc.Path()) } }() // create new file for package (overwrite any existing file) dstFile, err := os.Create(dstFilePath) if err != nil { return errors.Wrapf(err, "failed to create file %s", dstFilePath) } defer func() { if err := dstFile.Close(); err != nil && rErr == nil { rErr = errors.Wrapf(err, "failed to close file %s in defer", dstFilePath) } }() h := sha256.New() mw := io.MultiWriter(h, dstFile) _, _ = fmt.Fprintf(w, "Getting package from %v...\n", pkgSrc.Path()) if err := copyWithProgress(mw, r, size, w); err != nil { return errors.Wrapf(err, "failed to copy package %s to %s", pkgSrc.Path(), dstFilePath) } // verify checksum if provided if wantChecksum != "" { actualChecksum := hex.EncodeToString(h.Sum(nil)) if wantChecksum != actualChecksum { return errors.Errorf("SHA-256 checksum of downloaded package did not match expected checksum: expected %s, was %s", wantChecksum, actualChecksum) } } return nil }
go
func Download(pkgSrc PkgSrc, dstFilePath string, w io.Writer) (rErr error) { wantChecksum := pkgSrc.Checksum() if info, err := os.Stat(dstFilePath); err == nil { if info.IsDir() { return errors.Errorf("destination path %s already exists and is a directory", dstFilePath) } if wantChecksum != "" { // if file already exists at destination and checksum is known, verify checksum of existing file. // If it matches, use existing file. checksum, err := computeSHA256Checksum(dstFilePath) if err != nil { return errors.Wrapf(err, "failed to compute checksum of %s", dstFilePath) } if checksum == wantChecksum { return nil } } } // open reader from source r, size, err := pkgSrc.Reader() if err != nil { return err } defer func() { if err := r.Close(); err != nil && rErr == nil { rErr = errors.Wrapf(err, "failed to close reader for %s in defer", pkgSrc.Path()) } }() // create new file for package (overwrite any existing file) dstFile, err := os.Create(dstFilePath) if err != nil { return errors.Wrapf(err, "failed to create file %s", dstFilePath) } defer func() { if err := dstFile.Close(); err != nil && rErr == nil { rErr = errors.Wrapf(err, "failed to close file %s in defer", dstFilePath) } }() h := sha256.New() mw := io.MultiWriter(h, dstFile) _, _ = fmt.Fprintf(w, "Getting package from %v...\n", pkgSrc.Path()) if err := copyWithProgress(mw, r, size, w); err != nil { return errors.Wrapf(err, "failed to copy package %s to %s", pkgSrc.Path(), dstFilePath) } // verify checksum if provided if wantChecksum != "" { actualChecksum := hex.EncodeToString(h.Sum(nil)) if wantChecksum != actualChecksum { return errors.Errorf("SHA-256 checksum of downloaded package did not match expected checksum: expected %s, was %s", wantChecksum, actualChecksum) } } return nil }
[ "func", "Download", "(", "pkgSrc", "PkgSrc", ",", "dstFilePath", "string", ",", "w", "io", ".", "Writer", ")", "(", "rErr", "error", ")", "{", "wantChecksum", ":=", "pkgSrc", ".", "Checksum", "(", ")", "\n", "if", "info", ",", "err", ":=", "os", ".", "Stat", "(", "dstFilePath", ")", ";", "err", "==", "nil", "{", "if", "info", ".", "IsDir", "(", ")", "{", "return", "errors", ".", "Errorf", "(", "\"", "\"", ",", "dstFilePath", ")", "\n", "}", "\n", "if", "wantChecksum", "!=", "\"", "\"", "{", "// if file already exists at destination and checksum is known, verify checksum of existing file.", "// If it matches, use existing file.", "checksum", ",", "err", ":=", "computeSHA256Checksum", "(", "dstFilePath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "dstFilePath", ")", "\n", "}", "\n", "if", "checksum", "==", "wantChecksum", "{", "return", "nil", "\n", "}", "\n", "}", "\n", "}", "\n\n", "// open reader from source", "r", ",", "size", ",", "err", ":=", "pkgSrc", ".", "Reader", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "func", "(", ")", "{", "if", "err", ":=", "r", ".", "Close", "(", ")", ";", "err", "!=", "nil", "&&", "rErr", "==", "nil", "{", "rErr", "=", "errors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "pkgSrc", ".", "Path", "(", ")", ")", "\n", "}", "\n", "}", "(", ")", "\n\n", "// create new file for package (overwrite any existing file)", "dstFile", ",", "err", ":=", "os", ".", "Create", "(", "dstFilePath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "dstFilePath", ")", "\n", "}", "\n", "defer", "func", "(", ")", "{", "if", "err", ":=", "dstFile", ".", "Close", "(", ")", ";", "err", "!=", "nil", "&&", "rErr", "==", "nil", "{", "rErr", "=", "errors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "dstFilePath", ")", "\n", "}", "\n", "}", "(", ")", "\n\n", "h", ":=", "sha256", ".", "New", "(", ")", "\n", "mw", ":=", "io", ".", "MultiWriter", "(", "h", ",", "dstFile", ")", "\n\n", "_", ",", "_", "=", "fmt", ".", "Fprintf", "(", "w", ",", "\"", "\\n", "\"", ",", "pkgSrc", ".", "Path", "(", ")", ")", "\n", "if", "err", ":=", "copyWithProgress", "(", "mw", ",", "r", ",", "size", ",", "w", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "pkgSrc", ".", "Path", "(", ")", ",", "dstFilePath", ")", "\n", "}", "\n\n", "// verify checksum if provided", "if", "wantChecksum", "!=", "\"", "\"", "{", "actualChecksum", ":=", "hex", ".", "EncodeToString", "(", "h", ".", "Sum", "(", "nil", ")", ")", "\n", "if", "wantChecksum", "!=", "actualChecksum", "{", "return", "errors", ".", "Errorf", "(", "\"", "\"", ",", "wantChecksum", ",", "actualChecksum", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Download downloads the provided package to the specified path. The parent directory of the path must exist. If the // destination file already exists, it is overwritten. The download progress is written to the provided writer.
[ "Download", "downloads", "the", "provided", "package", "to", "the", "specified", "path", ".", "The", "parent", "directory", "of", "the", "path", "must", "exist", ".", "If", "the", "destination", "file", "already", "exists", "it", "is", "overwritten", ".", "The", "download", "progress", "is", "written", "to", "the", "provided", "writer", "." ]
3410152fb9e7ba34206a144c5c26a7829d52b488
https://github.com/palantir/godel/blob/3410152fb9e7ba34206a144c5c26a7829d52b488/godelgetter/download.go#L66-L123
12,207
palantir/godel
framework/godellauncher/projectpaths.go
ListProjectPaths
func ListProjectPaths(projectDir string, include, exclude matcher.Matcher) ([]string, error) { wd, err := os.Getwd() if err != nil { return nil, errors.Wrapf(err, "failed to determine working directory") } if !filepath.IsAbs(projectDir) { projectDir = path.Join(wd, projectDir) } relPathPrefix, err := filepath.Rel(wd, projectDir) if err != nil { return nil, errors.Wrapf(err, "failed to determine relative path") } files, err := matcher.ListFiles(projectDir, include, exclude) if err != nil { return nil, err } if relPathPrefix != "" { for i, file := range files { files[i] = path.Join(relPathPrefix, file) } } return files, nil }
go
func ListProjectPaths(projectDir string, include, exclude matcher.Matcher) ([]string, error) { wd, err := os.Getwd() if err != nil { return nil, errors.Wrapf(err, "failed to determine working directory") } if !filepath.IsAbs(projectDir) { projectDir = path.Join(wd, projectDir) } relPathPrefix, err := filepath.Rel(wd, projectDir) if err != nil { return nil, errors.Wrapf(err, "failed to determine relative path") } files, err := matcher.ListFiles(projectDir, include, exclude) if err != nil { return nil, err } if relPathPrefix != "" { for i, file := range files { files[i] = path.Join(relPathPrefix, file) } } return files, nil }
[ "func", "ListProjectPaths", "(", "projectDir", "string", ",", "include", ",", "exclude", "matcher", ".", "Matcher", ")", "(", "[", "]", "string", ",", "error", ")", "{", "wd", ",", "err", ":=", "os", ".", "Getwd", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "if", "!", "filepath", ".", "IsAbs", "(", "projectDir", ")", "{", "projectDir", "=", "path", ".", "Join", "(", "wd", ",", "projectDir", ")", "\n", "}", "\n", "relPathPrefix", ",", "err", ":=", "filepath", ".", "Rel", "(", "wd", ",", "projectDir", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "files", ",", "err", ":=", "matcher", ".", "ListFiles", "(", "projectDir", ",", "include", ",", "exclude", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "relPathPrefix", "!=", "\"", "\"", "{", "for", "i", ",", "file", ":=", "range", "files", "{", "files", "[", "i", "]", "=", "path", ".", "Join", "(", "relPathPrefix", ",", "file", ")", "\n", "}", "\n", "}", "\n", "return", "files", ",", "nil", "\n", "}" ]
// ListProjectPaths lists all of the paths in the provided project directory that matches the provided include matcher // and does not match the provided exclude matcher. The paths are relative to the current working directory.
[ "ListProjectPaths", "lists", "all", "of", "the", "paths", "in", "the", "provided", "project", "directory", "that", "matches", "the", "provided", "include", "matcher", "and", "does", "not", "match", "the", "provided", "exclude", "matcher", ".", "The", "paths", "are", "relative", "to", "the", "current", "working", "directory", "." ]
3410152fb9e7ba34206a144c5c26a7829d52b488
https://github.com/palantir/godel/blob/3410152fb9e7ba34206a144c5c26a7829d52b488/framework/godellauncher/projectpaths.go#L28-L51
12,208
palantir/godel
framework/builtintasks/installupdate/layout/layout.go
AllPaths
func AllPaths(dir string) (map[string]bool, error) { m := make(map[string]bool) return m, allPaths(m, nil, dir) }
go
func AllPaths(dir string) (map[string]bool, error) { m := make(map[string]bool) return m, allPaths(m, nil, dir) }
[ "func", "AllPaths", "(", "dir", "string", ")", "(", "map", "[", "string", "]", "bool", ",", "error", ")", "{", "m", ":=", "make", "(", "map", "[", "string", "]", "bool", ")", "\n", "return", "m", ",", "allPaths", "(", "m", ",", "nil", ",", "dir", ")", "\n", "}" ]
// AllPaths returns a map that contains all of the paths in the provided directory. The paths are relative to the // directory. The boolean key is true if the path is a directory, false otherwise.
[ "AllPaths", "returns", "a", "map", "that", "contains", "all", "of", "the", "paths", "in", "the", "provided", "directory", ".", "The", "paths", "are", "relative", "to", "the", "directory", ".", "The", "boolean", "key", "is", "true", "if", "the", "path", "is", "a", "directory", "false", "otherwise", "." ]
3410152fb9e7ba34206a144c5c26a7829d52b488
https://github.com/palantir/godel/blob/3410152fb9e7ba34206a144c5c26a7829d52b488/framework/builtintasks/installupdate/layout/layout.go#L30-L33
12,209
palantir/godel
framework/artifactresolver/resolver.go
pluginTGZContentHash
func pluginTGZContentHash(tgzContentReader io.Reader) (string, error) { hasher := sha256.New() if err := CopySingleFileTGZContent(hasher, tgzContentReader); err != nil { return "", err } return hex.EncodeToString(hasher.Sum(nil)), nil }
go
func pluginTGZContentHash(tgzContentReader io.Reader) (string, error) { hasher := sha256.New() if err := CopySingleFileTGZContent(hasher, tgzContentReader); err != nil { return "", err } return hex.EncodeToString(hasher.Sum(nil)), nil }
[ "func", "pluginTGZContentHash", "(", "tgzContentReader", "io", ".", "Reader", ")", "(", "string", ",", "error", ")", "{", "hasher", ":=", "sha256", ".", "New", "(", ")", "\n", "if", "err", ":=", "CopySingleFileTGZContent", "(", "hasher", ",", "tgzContentReader", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "return", "hex", ".", "EncodeToString", "(", "hasher", ".", "Sum", "(", "nil", ")", ")", ",", "nil", "\n", "}" ]
// Computes the SHA-256 hash for the content of the provided reader, which must be a plugin TGZ.
[ "Computes", "the", "SHA", "-", "256", "hash", "for", "the", "content", "of", "the", "provided", "reader", "which", "must", "be", "a", "plugin", "TGZ", "." ]
3410152fb9e7ba34206a144c5c26a7829d52b488
https://github.com/palantir/godel/blob/3410152fb9e7ba34206a144c5c26a7829d52b488/framework/artifactresolver/resolver.go#L107-L113
12,210
palantir/godel
framework/godellauncher/globalconfig.go
ProjectDir
func (g GlobalConfig) ProjectDir() (string, error) { if g.Wrapper == "" { return "", errors.Errorf("wrapper must be specified to determine project directory") } return path.Dir(g.Wrapper), nil }
go
func (g GlobalConfig) ProjectDir() (string, error) { if g.Wrapper == "" { return "", errors.Errorf("wrapper must be specified to determine project directory") } return path.Dir(g.Wrapper), nil }
[ "func", "(", "g", "GlobalConfig", ")", "ProjectDir", "(", ")", "(", "string", ",", "error", ")", "{", "if", "g", ".", "Wrapper", "==", "\"", "\"", "{", "return", "\"", "\"", ",", "errors", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "path", ".", "Dir", "(", "g", ".", "Wrapper", ")", ",", "nil", "\n", "}" ]
// ProjectDir returns the project directory for the global configuration. Returns an error if the wrapper path was not // specified.
[ "ProjectDir", "returns", "the", "project", "directory", "for", "the", "global", "configuration", ".", "Returns", "an", "error", "if", "the", "wrapper", "path", "was", "not", "specified", "." ]
3410152fb9e7ba34206a144c5c26a7829d52b488
https://github.com/palantir/godel/blob/3410152fb9e7ba34206a144c5c26a7829d52b488/framework/godellauncher/globalconfig.go#L43-L48
12,211
clarkduvall/hyperloglog
hyperloglogplus.go
getIndex
func (h *HyperLogLogPlus) getIndex(k uint32) uint32 { if k&1 == 1 { return eb32(k, 32, 32-h.p) } return eb32(k, pPrime+1, pPrime-h.p+1) }
go
func (h *HyperLogLogPlus) getIndex(k uint32) uint32 { if k&1 == 1 { return eb32(k, 32, 32-h.p) } return eb32(k, pPrime+1, pPrime-h.p+1) }
[ "func", "(", "h", "*", "HyperLogLogPlus", ")", "getIndex", "(", "k", "uint32", ")", "uint32", "{", "if", "k", "&", "1", "==", "1", "{", "return", "eb32", "(", "k", ",", "32", ",", "32", "-", "h", ".", "p", ")", "\n", "}", "\n", "return", "eb32", "(", "k", ",", "pPrime", "+", "1", ",", "pPrime", "-", "h", ".", "p", "+", "1", ")", "\n", "}" ]
// Get the index of precision p from the sparse representation.
[ "Get", "the", "index", "of", "precision", "p", "from", "the", "sparse", "representation", "." ]
a0107a5d80040c9b5efb012203b9a08d6817d196
https://github.com/clarkduvall/hyperloglog/blob/a0107a5d80040c9b5efb012203b9a08d6817d196/hyperloglogplus.go#L39-L44
12,212
clarkduvall/hyperloglog
hyperloglogplus.go
mergeSparse
func (h *HyperLogLogPlus) mergeSparse() { keys := make(sortableSlice, 0, len(h.tmpSet)) for k := range h.tmpSet { keys = append(keys, k) } sort.Sort(keys) newList := newCompressedList(int(h.m)) for iter, i := h.sparseList.Iter(), 0; iter.HasNext() || i < len(keys); { if !iter.HasNext() { newList.Append(keys[i]) i++ continue } if i >= len(keys) { newList.Append(iter.Next()) continue } x1, x2 := iter.Peek(), keys[i] if x1 == x2 { newList.Append(iter.Next()) i++ } else if x1 > x2 { newList.Append(x2) i++ } else { newList.Append(iter.Next()) } } h.sparseList = newList h.tmpSet = set{} if uint32(h.sparseList.Len()) > h.m { h.toNormal() } }
go
func (h *HyperLogLogPlus) mergeSparse() { keys := make(sortableSlice, 0, len(h.tmpSet)) for k := range h.tmpSet { keys = append(keys, k) } sort.Sort(keys) newList := newCompressedList(int(h.m)) for iter, i := h.sparseList.Iter(), 0; iter.HasNext() || i < len(keys); { if !iter.HasNext() { newList.Append(keys[i]) i++ continue } if i >= len(keys) { newList.Append(iter.Next()) continue } x1, x2 := iter.Peek(), keys[i] if x1 == x2 { newList.Append(iter.Next()) i++ } else if x1 > x2 { newList.Append(x2) i++ } else { newList.Append(iter.Next()) } } h.sparseList = newList h.tmpSet = set{} if uint32(h.sparseList.Len()) > h.m { h.toNormal() } }
[ "func", "(", "h", "*", "HyperLogLogPlus", ")", "mergeSparse", "(", ")", "{", "keys", ":=", "make", "(", "sortableSlice", ",", "0", ",", "len", "(", "h", ".", "tmpSet", ")", ")", "\n", "for", "k", ":=", "range", "h", ".", "tmpSet", "{", "keys", "=", "append", "(", "keys", ",", "k", ")", "\n", "}", "\n", "sort", ".", "Sort", "(", "keys", ")", "\n\n", "newList", ":=", "newCompressedList", "(", "int", "(", "h", ".", "m", ")", ")", "\n", "for", "iter", ",", "i", ":=", "h", ".", "sparseList", ".", "Iter", "(", ")", ",", "0", ";", "iter", ".", "HasNext", "(", ")", "||", "i", "<", "len", "(", "keys", ")", ";", "{", "if", "!", "iter", ".", "HasNext", "(", ")", "{", "newList", ".", "Append", "(", "keys", "[", "i", "]", ")", "\n", "i", "++", "\n", "continue", "\n", "}", "\n\n", "if", "i", ">=", "len", "(", "keys", ")", "{", "newList", ".", "Append", "(", "iter", ".", "Next", "(", ")", ")", "\n", "continue", "\n", "}", "\n\n", "x1", ",", "x2", ":=", "iter", ".", "Peek", "(", ")", ",", "keys", "[", "i", "]", "\n", "if", "x1", "==", "x2", "{", "newList", ".", "Append", "(", "iter", ".", "Next", "(", ")", ")", "\n", "i", "++", "\n", "}", "else", "if", "x1", ">", "x2", "{", "newList", ".", "Append", "(", "x2", ")", "\n", "i", "++", "\n", "}", "else", "{", "newList", ".", "Append", "(", "iter", ".", "Next", "(", ")", ")", "\n", "}", "\n", "}", "\n\n", "h", ".", "sparseList", "=", "newList", "\n", "h", ".", "tmpSet", "=", "set", "{", "}", "\n\n", "if", "uint32", "(", "h", ".", "sparseList", ".", "Len", "(", ")", ")", ">", "h", ".", "m", "{", "h", ".", "toNormal", "(", ")", "\n", "}", "\n", "}" ]
// Merge tmpSet and sparseList in the sparse representation. // Converts to normal if the sparse list is too large
[ "Merge", "tmpSet", "and", "sparseList", "in", "the", "sparse", "representation", ".", "Converts", "to", "normal", "if", "the", "sparse", "list", "is", "too", "large" ]
a0107a5d80040c9b5efb012203b9a08d6817d196
https://github.com/clarkduvall/hyperloglog/blob/a0107a5d80040c9b5efb012203b9a08d6817d196/hyperloglogplus.go#L59-L97
12,213
clarkduvall/hyperloglog
hyperloglogplus.go
NewPlus
func NewPlus(precision uint8) (*HyperLogLogPlus, error) { if precision > 18 || precision < 4 { return nil, errors.New("precision must be between 4 and 18") } h := &HyperLogLogPlus{} h.p = precision h.m = 1 << precision h.sparse = true h.tmpSet = set{} h.sparseList = newCompressedList(int(h.m)) return h, nil }
go
func NewPlus(precision uint8) (*HyperLogLogPlus, error) { if precision > 18 || precision < 4 { return nil, errors.New("precision must be between 4 and 18") } h := &HyperLogLogPlus{} h.p = precision h.m = 1 << precision h.sparse = true h.tmpSet = set{} h.sparseList = newCompressedList(int(h.m)) return h, nil }
[ "func", "NewPlus", "(", "precision", "uint8", ")", "(", "*", "HyperLogLogPlus", ",", "error", ")", "{", "if", "precision", ">", "18", "||", "precision", "<", "4", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "h", ":=", "&", "HyperLogLogPlus", "{", "}", "\n", "h", ".", "p", "=", "precision", "\n", "h", ".", "m", "=", "1", "<<", "precision", "\n", "h", ".", "sparse", "=", "true", "\n", "h", ".", "tmpSet", "=", "set", "{", "}", "\n", "h", ".", "sparseList", "=", "newCompressedList", "(", "int", "(", "h", ".", "m", ")", ")", "\n", "return", "h", ",", "nil", "\n", "}" ]
// NewPlus returns a new initialized HyperLogLogPlus that uses the HyperLogLog++ // algorithm.
[ "NewPlus", "returns", "a", "new", "initialized", "HyperLogLogPlus", "that", "uses", "the", "HyperLogLog", "++", "algorithm", "." ]
a0107a5d80040c9b5efb012203b9a08d6817d196
https://github.com/clarkduvall/hyperloglog/blob/a0107a5d80040c9b5efb012203b9a08d6817d196/hyperloglogplus.go#L108-L120
12,214
clarkduvall/hyperloglog
hyperloglogplus.go
Clear
func (h *HyperLogLogPlus) Clear() { h.sparse = true h.tmpSet = set{} h.sparseList = newCompressedList(int(h.m)) h.reg = nil }
go
func (h *HyperLogLogPlus) Clear() { h.sparse = true h.tmpSet = set{} h.sparseList = newCompressedList(int(h.m)) h.reg = nil }
[ "func", "(", "h", "*", "HyperLogLogPlus", ")", "Clear", "(", ")", "{", "h", ".", "sparse", "=", "true", "\n", "h", ".", "tmpSet", "=", "set", "{", "}", "\n", "h", ".", "sparseList", "=", "newCompressedList", "(", "int", "(", "h", ".", "m", ")", ")", "\n", "h", ".", "reg", "=", "nil", "\n", "}" ]
// Clear sets HyperLogLogPlus h back to its initial state.
[ "Clear", "sets", "HyperLogLogPlus", "h", "back", "to", "its", "initial", "state", "." ]
a0107a5d80040c9b5efb012203b9a08d6817d196
https://github.com/clarkduvall/hyperloglog/blob/a0107a5d80040c9b5efb012203b9a08d6817d196/hyperloglogplus.go#L123-L128
12,215
clarkduvall/hyperloglog
hyperloglogplus.go
toNormal
func (h *HyperLogLogPlus) toNormal() { h.reg = make([]uint8, h.m) for iter := h.sparseList.Iter(); iter.HasNext(); { i, r := h.decodeHash(iter.Next()) if h.reg[i] < r { h.reg[i] = r } } h.sparse = false h.tmpSet = nil h.sparseList = nil }
go
func (h *HyperLogLogPlus) toNormal() { h.reg = make([]uint8, h.m) for iter := h.sparseList.Iter(); iter.HasNext(); { i, r := h.decodeHash(iter.Next()) if h.reg[i] < r { h.reg[i] = r } } h.sparse = false h.tmpSet = nil h.sparseList = nil }
[ "func", "(", "h", "*", "HyperLogLogPlus", ")", "toNormal", "(", ")", "{", "h", ".", "reg", "=", "make", "(", "[", "]", "uint8", ",", "h", ".", "m", ")", "\n", "for", "iter", ":=", "h", ".", "sparseList", ".", "Iter", "(", ")", ";", "iter", ".", "HasNext", "(", ")", ";", "{", "i", ",", "r", ":=", "h", ".", "decodeHash", "(", "iter", ".", "Next", "(", ")", ")", "\n", "if", "h", ".", "reg", "[", "i", "]", "<", "r", "{", "h", ".", "reg", "[", "i", "]", "=", "r", "\n", "}", "\n", "}", "\n\n", "h", ".", "sparse", "=", "false", "\n", "h", ".", "tmpSet", "=", "nil", "\n", "h", ".", "sparseList", "=", "nil", "\n", "}" ]
// Converts HyperLogLogPlus h to the normal representation from the sparse // representation.
[ "Converts", "HyperLogLogPlus", "h", "to", "the", "normal", "representation", "from", "the", "sparse", "representation", "." ]
a0107a5d80040c9b5efb012203b9a08d6817d196
https://github.com/clarkduvall/hyperloglog/blob/a0107a5d80040c9b5efb012203b9a08d6817d196/hyperloglogplus.go#L132-L144
12,216
clarkduvall/hyperloglog
hyperloglogplus.go
Add
func (h *HyperLogLogPlus) Add(item Hash64) { x := item.Sum64() if h.sparse { h.tmpSet.Add(h.encodeHash(x)) h.maybeMerge() } else { i := eb64(x, 64, 64-h.p) // {x63,...,x64-p} w := x<<h.p | 1<<(h.p-1) // {x63-p,...,x0} zeroBits := clz64(w) + 1 if zeroBits > h.reg[i] { h.reg[i] = zeroBits } } }
go
func (h *HyperLogLogPlus) Add(item Hash64) { x := item.Sum64() if h.sparse { h.tmpSet.Add(h.encodeHash(x)) h.maybeMerge() } else { i := eb64(x, 64, 64-h.p) // {x63,...,x64-p} w := x<<h.p | 1<<(h.p-1) // {x63-p,...,x0} zeroBits := clz64(w) + 1 if zeroBits > h.reg[i] { h.reg[i] = zeroBits } } }
[ "func", "(", "h", "*", "HyperLogLogPlus", ")", "Add", "(", "item", "Hash64", ")", "{", "x", ":=", "item", ".", "Sum64", "(", ")", "\n", "if", "h", ".", "sparse", "{", "h", ".", "tmpSet", ".", "Add", "(", "h", ".", "encodeHash", "(", "x", ")", ")", "\n", "h", ".", "maybeMerge", "(", ")", "\n", "}", "else", "{", "i", ":=", "eb64", "(", "x", ",", "64", ",", "64", "-", "h", ".", "p", ")", "// {x63,...,x64-p}", "\n", "w", ":=", "x", "<<", "h", ".", "p", "|", "1", "<<", "(", "h", ".", "p", "-", "1", ")", "// {x63-p,...,x0}", "\n\n", "zeroBits", ":=", "clz64", "(", "w", ")", "+", "1", "\n", "if", "zeroBits", ">", "h", ".", "reg", "[", "i", "]", "{", "h", ".", "reg", "[", "i", "]", "=", "zeroBits", "\n", "}", "\n", "}", "\n", "}" ]
// Add adds a new item to HyperLogLogPlus h.
[ "Add", "adds", "a", "new", "item", "to", "HyperLogLogPlus", "h", "." ]
a0107a5d80040c9b5efb012203b9a08d6817d196
https://github.com/clarkduvall/hyperloglog/blob/a0107a5d80040c9b5efb012203b9a08d6817d196/hyperloglogplus.go#L147-L161
12,217
clarkduvall/hyperloglog
hyperloglogplus.go
Merge
func (h *HyperLogLogPlus) Merge(other *HyperLogLogPlus) error { if h.p != other.p { return errors.New("precisions must be equal") } if h.sparse && other.sparse { for k := range other.tmpSet { h.tmpSet.Add(k) } for iter := other.sparseList.Iter(); iter.HasNext(); { h.tmpSet.Add(iter.Next()) } h.maybeMerge() return nil } if h.sparse { h.mergeSparseAndToNormal() } if other.sparse { for k := range other.tmpSet { i, r := other.decodeHash(k) if r > h.reg[i] { h.reg[i] = r } } for iter := other.sparseList.Iter(); iter.HasNext(); { i, r := other.decodeHash(iter.Next()) if r > h.reg[i] { h.reg[i] = r } } } else { for i, v := range other.reg { if v > h.reg[i] { h.reg[i] = v } } } return nil }
go
func (h *HyperLogLogPlus) Merge(other *HyperLogLogPlus) error { if h.p != other.p { return errors.New("precisions must be equal") } if h.sparse && other.sparse { for k := range other.tmpSet { h.tmpSet.Add(k) } for iter := other.sparseList.Iter(); iter.HasNext(); { h.tmpSet.Add(iter.Next()) } h.maybeMerge() return nil } if h.sparse { h.mergeSparseAndToNormal() } if other.sparse { for k := range other.tmpSet { i, r := other.decodeHash(k) if r > h.reg[i] { h.reg[i] = r } } for iter := other.sparseList.Iter(); iter.HasNext(); { i, r := other.decodeHash(iter.Next()) if r > h.reg[i] { h.reg[i] = r } } } else { for i, v := range other.reg { if v > h.reg[i] { h.reg[i] = v } } } return nil }
[ "func", "(", "h", "*", "HyperLogLogPlus", ")", "Merge", "(", "other", "*", "HyperLogLogPlus", ")", "error", "{", "if", "h", ".", "p", "!=", "other", ".", "p", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "h", ".", "sparse", "&&", "other", ".", "sparse", "{", "for", "k", ":=", "range", "other", ".", "tmpSet", "{", "h", ".", "tmpSet", ".", "Add", "(", "k", ")", "\n", "}", "\n", "for", "iter", ":=", "other", ".", "sparseList", ".", "Iter", "(", ")", ";", "iter", ".", "HasNext", "(", ")", ";", "{", "h", ".", "tmpSet", ".", "Add", "(", "iter", ".", "Next", "(", ")", ")", "\n", "}", "\n", "h", ".", "maybeMerge", "(", ")", "\n", "return", "nil", "\n", "}", "\n\n", "if", "h", ".", "sparse", "{", "h", ".", "mergeSparseAndToNormal", "(", ")", "\n", "}", "\n\n", "if", "other", ".", "sparse", "{", "for", "k", ":=", "range", "other", ".", "tmpSet", "{", "i", ",", "r", ":=", "other", ".", "decodeHash", "(", "k", ")", "\n", "if", "r", ">", "h", ".", "reg", "[", "i", "]", "{", "h", ".", "reg", "[", "i", "]", "=", "r", "\n", "}", "\n", "}", "\n\n", "for", "iter", ":=", "other", ".", "sparseList", ".", "Iter", "(", ")", ";", "iter", ".", "HasNext", "(", ")", ";", "{", "i", ",", "r", ":=", "other", ".", "decodeHash", "(", "iter", ".", "Next", "(", ")", ")", "\n", "if", "r", ">", "h", ".", "reg", "[", "i", "]", "{", "h", ".", "reg", "[", "i", "]", "=", "r", "\n", "}", "\n", "}", "\n", "}", "else", "{", "for", "i", ",", "v", ":=", "range", "other", ".", "reg", "{", "if", "v", ">", "h", ".", "reg", "[", "i", "]", "{", "h", ".", "reg", "[", "i", "]", "=", "v", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Merge takes another HyperLogLogPlus and combines it with HyperLogLogPlus h.
[ "Merge", "takes", "another", "HyperLogLogPlus", "and", "combines", "it", "with", "HyperLogLogPlus", "h", "." ]
a0107a5d80040c9b5efb012203b9a08d6817d196
https://github.com/clarkduvall/hyperloglog/blob/a0107a5d80040c9b5efb012203b9a08d6817d196/hyperloglogplus.go#L164-L206
12,218
clarkduvall/hyperloglog
hyperloglogplus.go
maybeMerge
func (h *HyperLogLogPlus) maybeMerge() { if uint32(len(h.tmpSet))*100 > h.m { h.mergeSparse() } }
go
func (h *HyperLogLogPlus) maybeMerge() { if uint32(len(h.tmpSet))*100 > h.m { h.mergeSparse() } }
[ "func", "(", "h", "*", "HyperLogLogPlus", ")", "maybeMerge", "(", ")", "{", "if", "uint32", "(", "len", "(", "h", ".", "tmpSet", ")", ")", "*", "100", ">", "h", ".", "m", "{", "h", ".", "mergeSparse", "(", ")", "\n", "}", "\n", "}" ]
// Merges tmpSet if it exceeds the threshold
[ "Merges", "tmpSet", "if", "it", "exceeds", "the", "threshold" ]
a0107a5d80040c9b5efb012203b9a08d6817d196
https://github.com/clarkduvall/hyperloglog/blob/a0107a5d80040c9b5efb012203b9a08d6817d196/hyperloglogplus.go#L209-L213
12,219
clarkduvall/hyperloglog
hyperloglogplus.go
estimateBias
func (h *HyperLogLogPlus) estimateBias(est float64) float64 { estTable, biasTable := rawEstimateData[h.p-4], biasData[h.p-4] if estTable[0] > est { return biasTable[0] } lastEstimate := estTable[len(estTable)-1] if lastEstimate < est { return biasTable[len(biasTable)-1] } var i int for i = 0; i < len(estTable) && estTable[i] < est; i++ { } e1, b1 := estTable[i-1], biasTable[i-1] e2, b2 := estTable[i], biasTable[i] c := (est - e1) / (e2 - e1) return b1*(1-c) + b2*c }
go
func (h *HyperLogLogPlus) estimateBias(est float64) float64 { estTable, biasTable := rawEstimateData[h.p-4], biasData[h.p-4] if estTable[0] > est { return biasTable[0] } lastEstimate := estTable[len(estTable)-1] if lastEstimate < est { return biasTable[len(biasTable)-1] } var i int for i = 0; i < len(estTable) && estTable[i] < est; i++ { } e1, b1 := estTable[i-1], biasTable[i-1] e2, b2 := estTable[i], biasTable[i] c := (est - e1) / (e2 - e1) return b1*(1-c) + b2*c }
[ "func", "(", "h", "*", "HyperLogLogPlus", ")", "estimateBias", "(", "est", "float64", ")", "float64", "{", "estTable", ",", "biasTable", ":=", "rawEstimateData", "[", "h", ".", "p", "-", "4", "]", ",", "biasData", "[", "h", ".", "p", "-", "4", "]", "\n\n", "if", "estTable", "[", "0", "]", ">", "est", "{", "return", "biasTable", "[", "0", "]", "\n", "}", "\n\n", "lastEstimate", ":=", "estTable", "[", "len", "(", "estTable", ")", "-", "1", "]", "\n", "if", "lastEstimate", "<", "est", "{", "return", "biasTable", "[", "len", "(", "biasTable", ")", "-", "1", "]", "\n", "}", "\n\n", "var", "i", "int", "\n", "for", "i", "=", "0", ";", "i", "<", "len", "(", "estTable", ")", "&&", "estTable", "[", "i", "]", "<", "est", ";", "i", "++", "{", "}", "\n\n", "e1", ",", "b1", ":=", "estTable", "[", "i", "-", "1", "]", ",", "biasTable", "[", "i", "-", "1", "]", "\n", "e2", ",", "b2", ":=", "estTable", "[", "i", "]", ",", "biasTable", "[", "i", "]", "\n\n", "c", ":=", "(", "est", "-", "e1", ")", "/", "(", "e2", "-", "e1", ")", "\n", "return", "b1", "*", "(", "1", "-", "c", ")", "+", "b2", "*", "c", "\n", "}" ]
// Estimates the bias using empirically determined values.
[ "Estimates", "the", "bias", "using", "empirically", "determined", "values", "." ]
a0107a5d80040c9b5efb012203b9a08d6817d196
https://github.com/clarkduvall/hyperloglog/blob/a0107a5d80040c9b5efb012203b9a08d6817d196/hyperloglogplus.go#L216-L237
12,220
clarkduvall/hyperloglog
hyperloglogplus.go
GobEncode
func (h *HyperLogLogPlus) GobEncode() ([]byte, error) { buf := bytes.Buffer{} enc := gob.NewEncoder(&buf) if err := enc.Encode(h.reg); err != nil { return nil, err } if err := enc.Encode(h.m); err != nil { return nil, err } if err := enc.Encode(h.p); err != nil { return nil, err } if err := enc.Encode(h.sparse); err != nil { return nil, err } if h.sparse { if err := enc.Encode(h.tmpSet); err != nil { return nil, err } if err := enc.Encode(h.sparseList.Count); err != nil { return nil, err } if err := enc.Encode(h.sparseList.b); err != nil { return nil, err } if err := enc.Encode(h.sparseList.last); err != nil { return nil, err } } return buf.Bytes(), nil }
go
func (h *HyperLogLogPlus) GobEncode() ([]byte, error) { buf := bytes.Buffer{} enc := gob.NewEncoder(&buf) if err := enc.Encode(h.reg); err != nil { return nil, err } if err := enc.Encode(h.m); err != nil { return nil, err } if err := enc.Encode(h.p); err != nil { return nil, err } if err := enc.Encode(h.sparse); err != nil { return nil, err } if h.sparse { if err := enc.Encode(h.tmpSet); err != nil { return nil, err } if err := enc.Encode(h.sparseList.Count); err != nil { return nil, err } if err := enc.Encode(h.sparseList.b); err != nil { return nil, err } if err := enc.Encode(h.sparseList.last); err != nil { return nil, err } } return buf.Bytes(), nil }
[ "func", "(", "h", "*", "HyperLogLogPlus", ")", "GobEncode", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "buf", ":=", "bytes", ".", "Buffer", "{", "}", "\n", "enc", ":=", "gob", ".", "NewEncoder", "(", "&", "buf", ")", "\n", "if", "err", ":=", "enc", ".", "Encode", "(", "h", ".", "reg", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "err", ":=", "enc", ".", "Encode", "(", "h", ".", "m", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "err", ":=", "enc", ".", "Encode", "(", "h", ".", "p", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "err", ":=", "enc", ".", "Encode", "(", "h", ".", "sparse", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "h", ".", "sparse", "{", "if", "err", ":=", "enc", ".", "Encode", "(", "h", ".", "tmpSet", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "err", ":=", "enc", ".", "Encode", "(", "h", ".", "sparseList", ".", "Count", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "err", ":=", "enc", ".", "Encode", "(", "h", ".", "sparseList", ".", "b", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "err", ":=", "enc", ".", "Encode", "(", "h", ".", "sparseList", ".", "last", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n", "return", "buf", ".", "Bytes", "(", ")", ",", "nil", "\n", "}" ]
// Encode HyperLogLogPlus into a gob
[ "Encode", "HyperLogLogPlus", "into", "a", "gob" ]
a0107a5d80040c9b5efb012203b9a08d6817d196
https://github.com/clarkduvall/hyperloglog/blob/a0107a5d80040c9b5efb012203b9a08d6817d196/hyperloglogplus.go#L264-L294
12,221
clarkduvall/hyperloglog
hyperloglogplus.go
GobDecode
func (h *HyperLogLogPlus) GobDecode(b []byte) error { dec := gob.NewDecoder(bytes.NewBuffer(b)) if err := dec.Decode(&h.reg); err != nil { return err } if err := dec.Decode(&h.m); err != nil { return err } if err := dec.Decode(&h.p); err != nil { return err } if err := dec.Decode(&h.sparse); err != nil { return err } if h.sparse { if err := dec.Decode(&h.tmpSet); err != nil { return err } h.sparseList = newCompressedList(int(h.m)) if err := dec.Decode(&h.sparseList.Count); err != nil { return err } if err := dec.Decode(&h.sparseList.b); err != nil { return err } if err := dec.Decode(&h.sparseList.last); err != nil { return err } } return nil }
go
func (h *HyperLogLogPlus) GobDecode(b []byte) error { dec := gob.NewDecoder(bytes.NewBuffer(b)) if err := dec.Decode(&h.reg); err != nil { return err } if err := dec.Decode(&h.m); err != nil { return err } if err := dec.Decode(&h.p); err != nil { return err } if err := dec.Decode(&h.sparse); err != nil { return err } if h.sparse { if err := dec.Decode(&h.tmpSet); err != nil { return err } h.sparseList = newCompressedList(int(h.m)) if err := dec.Decode(&h.sparseList.Count); err != nil { return err } if err := dec.Decode(&h.sparseList.b); err != nil { return err } if err := dec.Decode(&h.sparseList.last); err != nil { return err } } return nil }
[ "func", "(", "h", "*", "HyperLogLogPlus", ")", "GobDecode", "(", "b", "[", "]", "byte", ")", "error", "{", "dec", ":=", "gob", ".", "NewDecoder", "(", "bytes", ".", "NewBuffer", "(", "b", ")", ")", "\n", "if", "err", ":=", "dec", ".", "Decode", "(", "&", "h", ".", "reg", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "dec", ".", "Decode", "(", "&", "h", ".", "m", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "dec", ".", "Decode", "(", "&", "h", ".", "p", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "dec", ".", "Decode", "(", "&", "h", ".", "sparse", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "h", ".", "sparse", "{", "if", "err", ":=", "dec", ".", "Decode", "(", "&", "h", ".", "tmpSet", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "h", ".", "sparseList", "=", "newCompressedList", "(", "int", "(", "h", ".", "m", ")", ")", "\n", "if", "err", ":=", "dec", ".", "Decode", "(", "&", "h", ".", "sparseList", ".", "Count", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "dec", ".", "Decode", "(", "&", "h", ".", "sparseList", ".", "b", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "dec", ".", "Decode", "(", "&", "h", ".", "sparseList", ".", "last", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Decode gob into a HyperLogLogPlus structure
[ "Decode", "gob", "into", "a", "HyperLogLogPlus", "structure" ]
a0107a5d80040c9b5efb012203b9a08d6817d196
https://github.com/clarkduvall/hyperloglog/blob/a0107a5d80040c9b5efb012203b9a08d6817d196/hyperloglogplus.go#L297-L327
12,222
clarkduvall/hyperloglog
common.go
eb32
func eb32(bits uint32, hi uint8, lo uint8) uint32 { m := uint32(((1 << (hi - lo)) - 1) << lo) return (bits & m) >> lo }
go
func eb32(bits uint32, hi uint8, lo uint8) uint32 { m := uint32(((1 << (hi - lo)) - 1) << lo) return (bits & m) >> lo }
[ "func", "eb32", "(", "bits", "uint32", ",", "hi", "uint8", ",", "lo", "uint8", ")", "uint32", "{", "m", ":=", "uint32", "(", "(", "(", "1", "<<", "(", "hi", "-", "lo", ")", ")", "-", "1", ")", "<<", "lo", ")", "\n", "return", "(", "bits", "&", "m", ")", ">>", "lo", "\n", "}" ]
// Extract bits from uint32 using LSB 0 numbering, including lo.
[ "Extract", "bits", "from", "uint32", "using", "LSB", "0", "numbering", "including", "lo", "." ]
a0107a5d80040c9b5efb012203b9a08d6817d196
https://github.com/clarkduvall/hyperloglog/blob/a0107a5d80040c9b5efb012203b9a08d6817d196/common.go#L85-L88
12,223
clarkduvall/hyperloglog
common.go
eb64
func eb64(bits uint64, hi uint8, lo uint8) uint64 { m := uint64(((1 << (hi - lo)) - 1) << lo) return (bits & m) >> lo }
go
func eb64(bits uint64, hi uint8, lo uint8) uint64 { m := uint64(((1 << (hi - lo)) - 1) << lo) return (bits & m) >> lo }
[ "func", "eb64", "(", "bits", "uint64", ",", "hi", "uint8", ",", "lo", "uint8", ")", "uint64", "{", "m", ":=", "uint64", "(", "(", "(", "1", "<<", "(", "hi", "-", "lo", ")", ")", "-", "1", ")", "<<", "lo", ")", "\n", "return", "(", "bits", "&", "m", ")", ">>", "lo", "\n", "}" ]
// Extract bits from uint64 using LSB 0 numbering, including lo.
[ "Extract", "bits", "from", "uint64", "using", "LSB", "0", "numbering", "including", "lo", "." ]
a0107a5d80040c9b5efb012203b9a08d6817d196
https://github.com/clarkduvall/hyperloglog/blob/a0107a5d80040c9b5efb012203b9a08d6817d196/common.go#L91-L94
12,224
clarkduvall/hyperloglog
hyperloglog.go
New
func New(precision uint8) (*HyperLogLog, error) { if precision > 16 || precision < 4 { return nil, errors.New("precision must be between 4 and 16") } h := &HyperLogLog{} h.p = precision h.m = 1 << precision h.reg = make([]uint8, h.m) return h, nil }
go
func New(precision uint8) (*HyperLogLog, error) { if precision > 16 || precision < 4 { return nil, errors.New("precision must be between 4 and 16") } h := &HyperLogLog{} h.p = precision h.m = 1 << precision h.reg = make([]uint8, h.m) return h, nil }
[ "func", "New", "(", "precision", "uint8", ")", "(", "*", "HyperLogLog", ",", "error", ")", "{", "if", "precision", ">", "16", "||", "precision", "<", "4", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "h", ":=", "&", "HyperLogLog", "{", "}", "\n", "h", ".", "p", "=", "precision", "\n", "h", ".", "m", "=", "1", "<<", "precision", "\n", "h", ".", "reg", "=", "make", "(", "[", "]", "uint8", ",", "h", ".", "m", ")", "\n", "return", "h", ",", "nil", "\n", "}" ]
// New returns a new initialized HyperLogLog.
[ "New", "returns", "a", "new", "initialized", "HyperLogLog", "." ]
a0107a5d80040c9b5efb012203b9a08d6817d196
https://github.com/clarkduvall/hyperloglog/blob/a0107a5d80040c9b5efb012203b9a08d6817d196/hyperloglog.go#L30-L40
12,225
clarkduvall/hyperloglog
hyperloglog.go
Add
func (h *HyperLogLog) Add(item Hash32) { x := item.Sum32() i := eb32(x, 32, 32-h.p) // {x31,...,x32-p} w := x<<h.p | 1<<(h.p-1) // {x32-p,...,x0} zeroBits := clz32(w) + 1 if zeroBits > h.reg[i] { h.reg[i] = zeroBits } }
go
func (h *HyperLogLog) Add(item Hash32) { x := item.Sum32() i := eb32(x, 32, 32-h.p) // {x31,...,x32-p} w := x<<h.p | 1<<(h.p-1) // {x32-p,...,x0} zeroBits := clz32(w) + 1 if zeroBits > h.reg[i] { h.reg[i] = zeroBits } }
[ "func", "(", "h", "*", "HyperLogLog", ")", "Add", "(", "item", "Hash32", ")", "{", "x", ":=", "item", ".", "Sum32", "(", ")", "\n", "i", ":=", "eb32", "(", "x", ",", "32", ",", "32", "-", "h", ".", "p", ")", "// {x31,...,x32-p}", "\n", "w", ":=", "x", "<<", "h", ".", "p", "|", "1", "<<", "(", "h", ".", "p", "-", "1", ")", "// {x32-p,...,x0}", "\n\n", "zeroBits", ":=", "clz32", "(", "w", ")", "+", "1", "\n", "if", "zeroBits", ">", "h", ".", "reg", "[", "i", "]", "{", "h", ".", "reg", "[", "i", "]", "=", "zeroBits", "\n", "}", "\n", "}" ]
// Add adds a new item to HyperLogLog h.
[ "Add", "adds", "a", "new", "item", "to", "HyperLogLog", "h", "." ]
a0107a5d80040c9b5efb012203b9a08d6817d196
https://github.com/clarkduvall/hyperloglog/blob/a0107a5d80040c9b5efb012203b9a08d6817d196/hyperloglog.go#L48-L57
12,226
clarkduvall/hyperloglog
hyperloglog.go
Merge
func (h *HyperLogLog) Merge(other *HyperLogLog) error { if h.p != other.p { return errors.New("precisions must be equal") } for i, v := range other.reg { if v > h.reg[i] { h.reg[i] = v } } return nil }
go
func (h *HyperLogLog) Merge(other *HyperLogLog) error { if h.p != other.p { return errors.New("precisions must be equal") } for i, v := range other.reg { if v > h.reg[i] { h.reg[i] = v } } return nil }
[ "func", "(", "h", "*", "HyperLogLog", ")", "Merge", "(", "other", "*", "HyperLogLog", ")", "error", "{", "if", "h", ".", "p", "!=", "other", ".", "p", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "for", "i", ",", "v", ":=", "range", "other", ".", "reg", "{", "if", "v", ">", "h", ".", "reg", "[", "i", "]", "{", "h", ".", "reg", "[", "i", "]", "=", "v", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Merge takes another HyperLogLog and combines it with HyperLogLog h.
[ "Merge", "takes", "another", "HyperLogLog", "and", "combines", "it", "with", "HyperLogLog", "h", "." ]
a0107a5d80040c9b5efb012203b9a08d6817d196
https://github.com/clarkduvall/hyperloglog/blob/a0107a5d80040c9b5efb012203b9a08d6817d196/hyperloglog.go#L60-L71
12,227
clarkduvall/hyperloglog
hyperloglog.go
GobEncode
func (h *HyperLogLog) GobEncode() ([]byte, error) { buf := bytes.Buffer{} enc := gob.NewEncoder(&buf) if err := enc.Encode(h.reg); err != nil { return nil, err } if err := enc.Encode(h.m); err != nil { return nil, err } if err := enc.Encode(h.p); err != nil { return nil, err } return buf.Bytes(), nil }
go
func (h *HyperLogLog) GobEncode() ([]byte, error) { buf := bytes.Buffer{} enc := gob.NewEncoder(&buf) if err := enc.Encode(h.reg); err != nil { return nil, err } if err := enc.Encode(h.m); err != nil { return nil, err } if err := enc.Encode(h.p); err != nil { return nil, err } return buf.Bytes(), nil }
[ "func", "(", "h", "*", "HyperLogLog", ")", "GobEncode", "(", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "buf", ":=", "bytes", ".", "Buffer", "{", "}", "\n", "enc", ":=", "gob", ".", "NewEncoder", "(", "&", "buf", ")", "\n", "if", "err", ":=", "enc", ".", "Encode", "(", "h", ".", "reg", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "err", ":=", "enc", ".", "Encode", "(", "h", ".", "m", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "err", ":=", "enc", ".", "Encode", "(", "h", ".", "p", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "buf", ".", "Bytes", "(", ")", ",", "nil", "\n", "}" ]
// Encode HyperLogLog into a gob
[ "Encode", "HyperLogLog", "into", "a", "gob" ]
a0107a5d80040c9b5efb012203b9a08d6817d196
https://github.com/clarkduvall/hyperloglog/blob/a0107a5d80040c9b5efb012203b9a08d6817d196/hyperloglog.go#L88-L101
12,228
clarkduvall/hyperloglog
hyperloglog.go
GobDecode
func (h *HyperLogLog) GobDecode(b []byte) error { dec := gob.NewDecoder(bytes.NewBuffer(b)) if err := dec.Decode(&h.reg); err != nil { return err } if err := dec.Decode(&h.m); err != nil { return err } if err := dec.Decode(&h.p); err != nil { return err } return nil }
go
func (h *HyperLogLog) GobDecode(b []byte) error { dec := gob.NewDecoder(bytes.NewBuffer(b)) if err := dec.Decode(&h.reg); err != nil { return err } if err := dec.Decode(&h.m); err != nil { return err } if err := dec.Decode(&h.p); err != nil { return err } return nil }
[ "func", "(", "h", "*", "HyperLogLog", ")", "GobDecode", "(", "b", "[", "]", "byte", ")", "error", "{", "dec", ":=", "gob", ".", "NewDecoder", "(", "bytes", ".", "NewBuffer", "(", "b", ")", ")", "\n", "if", "err", ":=", "dec", ".", "Decode", "(", "&", "h", ".", "reg", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "dec", ".", "Decode", "(", "&", "h", ".", "m", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "dec", ".", "Decode", "(", "&", "h", ".", "p", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Decode gob into a HyperLogLog structure
[ "Decode", "gob", "into", "a", "HyperLogLog", "structure" ]
a0107a5d80040c9b5efb012203b9a08d6817d196
https://github.com/clarkduvall/hyperloglog/blob/a0107a5d80040c9b5efb012203b9a08d6817d196/hyperloglog.go#L104-L116
12,229
tdewolff/parse
svg/hash.go
String
func (i Hash) String() string { start := uint32(i >> 8) n := uint32(i & 0xff) if start+n > uint32(len(_Hash_text)) { return "" } return _Hash_text[start : start+n] }
go
func (i Hash) String() string { start := uint32(i >> 8) n := uint32(i & 0xff) if start+n > uint32(len(_Hash_text)) { return "" } return _Hash_text[start : start+n] }
[ "func", "(", "i", "Hash", ")", "String", "(", ")", "string", "{", "start", ":=", "uint32", "(", "i", ">>", "8", ")", "\n", "n", ":=", "uint32", "(", "i", "&", "0xff", ")", "\n", "if", "start", "+", "n", ">", "uint32", "(", "len", "(", "_Hash_text", ")", ")", "{", "return", "\"", "\"", "\n", "}", "\n", "return", "_Hash_text", "[", "start", ":", "start", "+", "n", "]", "\n", "}" ]
// String returns the hash' name.
[ "String", "returns", "the", "hash", "name", "." ]
b8d8be7d83bf428ee370587d439137776d18362c
https://github.com/tdewolff/parse/blob/b8d8be7d83bf428ee370587d439137776d18362c/svg/hash.go#L125-L132
12,230
tdewolff/parse
svg/hash.go
ToHash
func ToHash(s []byte) Hash { if len(s) == 0 || len(s) > _Hash_maxLen { return 0 } h := uint32(_Hash_hash0) for i := 0; i < len(s); i++ { h ^= uint32(s[i]) h *= 16777619 } if i := _Hash_table[h&uint32(len(_Hash_table)-1)]; int(i&0xff) == len(s) { t := _Hash_text[i>>8 : i>>8+i&0xff] for i := 0; i < len(s); i++ { if t[i] != s[i] { goto NEXT } } return i } NEXT: if i := _Hash_table[(h>>16)&uint32(len(_Hash_table)-1)]; int(i&0xff) == len(s) { t := _Hash_text[i>>8 : i>>8+i&0xff] for i := 0; i < len(s); i++ { if t[i] != s[i] { return 0 } } return i } return 0 }
go
func ToHash(s []byte) Hash { if len(s) == 0 || len(s) > _Hash_maxLen { return 0 } h := uint32(_Hash_hash0) for i := 0; i < len(s); i++ { h ^= uint32(s[i]) h *= 16777619 } if i := _Hash_table[h&uint32(len(_Hash_table)-1)]; int(i&0xff) == len(s) { t := _Hash_text[i>>8 : i>>8+i&0xff] for i := 0; i < len(s); i++ { if t[i] != s[i] { goto NEXT } } return i } NEXT: if i := _Hash_table[(h>>16)&uint32(len(_Hash_table)-1)]; int(i&0xff) == len(s) { t := _Hash_text[i>>8 : i>>8+i&0xff] for i := 0; i < len(s); i++ { if t[i] != s[i] { return 0 } } return i } return 0 }
[ "func", "ToHash", "(", "s", "[", "]", "byte", ")", "Hash", "{", "if", "len", "(", "s", ")", "==", "0", "||", "len", "(", "s", ")", ">", "_Hash_maxLen", "{", "return", "0", "\n", "}", "\n", "h", ":=", "uint32", "(", "_Hash_hash0", ")", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "s", ")", ";", "i", "++", "{", "h", "^=", "uint32", "(", "s", "[", "i", "]", ")", "\n", "h", "*=", "16777619", "\n", "}", "\n", "if", "i", ":=", "_Hash_table", "[", "h", "&", "uint32", "(", "len", "(", "_Hash_table", ")", "-", "1", ")", "]", ";", "int", "(", "i", "&", "0xff", ")", "==", "len", "(", "s", ")", "{", "t", ":=", "_Hash_text", "[", "i", ">>", "8", ":", "i", ">>", "8", "+", "i", "&", "0xff", "]", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "s", ")", ";", "i", "++", "{", "if", "t", "[", "i", "]", "!=", "s", "[", "i", "]", "{", "goto", "NEXT", "\n", "}", "\n", "}", "\n", "return", "i", "\n", "}", "\n", "NEXT", ":", "if", "i", ":=", "_Hash_table", "[", "(", "h", ">>", "16", ")", "&", "uint32", "(", "len", "(", "_Hash_table", ")", "-", "1", ")", "]", ";", "int", "(", "i", "&", "0xff", ")", "==", "len", "(", "s", ")", "{", "t", ":=", "_Hash_text", "[", "i", ">>", "8", ":", "i", ">>", "8", "+", "i", "&", "0xff", "]", "\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "s", ")", ";", "i", "++", "{", "if", "t", "[", "i", "]", "!=", "s", "[", "i", "]", "{", "return", "0", "\n", "}", "\n", "}", "\n", "return", "i", "\n", "}", "\n", "return", "0", "\n", "}" ]
// ToHash returns the hash whose name is s. It returns zero if there is no // such hash. It is case sensitive.
[ "ToHash", "returns", "the", "hash", "whose", "name", "is", "s", ".", "It", "returns", "zero", "if", "there", "is", "no", "such", "hash", ".", "It", "is", "case", "sensitive", "." ]
b8d8be7d83bf428ee370587d439137776d18362c
https://github.com/tdewolff/parse/blob/b8d8be7d83bf428ee370587d439137776d18362c/svg/hash.go#L136-L165
12,231
tdewolff/parse
buffer/streamlexer.go
NewStreamLexerSize
func NewStreamLexerSize(r io.Reader, size int) *StreamLexer { // if reader has the bytes in memory already, use that instead if buffer, ok := r.(interface { Bytes() []byte }); ok { return &StreamLexer{ err: io.EOF, buf: buffer.Bytes(), } } return &StreamLexer{ r: r, buf: make([]byte, 0, size), } }
go
func NewStreamLexerSize(r io.Reader, size int) *StreamLexer { // if reader has the bytes in memory already, use that instead if buffer, ok := r.(interface { Bytes() []byte }); ok { return &StreamLexer{ err: io.EOF, buf: buffer.Bytes(), } } return &StreamLexer{ r: r, buf: make([]byte, 0, size), } }
[ "func", "NewStreamLexerSize", "(", "r", "io", ".", "Reader", ",", "size", "int", ")", "*", "StreamLexer", "{", "// if reader has the bytes in memory already, use that instead", "if", "buffer", ",", "ok", ":=", "r", ".", "(", "interface", "{", "Bytes", "(", ")", "[", "]", "byte", "\n", "}", ")", ";", "ok", "{", "return", "&", "StreamLexer", "{", "err", ":", "io", ".", "EOF", ",", "buf", ":", "buffer", ".", "Bytes", "(", ")", ",", "}", "\n", "}", "\n", "return", "&", "StreamLexer", "{", "r", ":", "r", ",", "buf", ":", "make", "(", "[", "]", "byte", ",", "0", ",", "size", ")", ",", "}", "\n", "}" ]
// NewStreamLexerSize returns a new StreamLexer for a given io.Reader and estimated required buffer size. // If the io.Reader implements Bytes, that buffer is used instead.
[ "NewStreamLexerSize", "returns", "a", "new", "StreamLexer", "for", "a", "given", "io", ".", "Reader", "and", "estimated", "required", "buffer", "size", ".", "If", "the", "io", ".", "Reader", "implements", "Bytes", "that", "buffer", "is", "used", "instead", "." ]
b8d8be7d83bf428ee370587d439137776d18362c
https://github.com/tdewolff/parse/blob/b8d8be7d83bf428ee370587d439137776d18362c/buffer/streamlexer.go#L93-L107
12,232
tdewolff/parse
buffer/streamlexer.go
Err
func (z *StreamLexer) Err() error { if z.err == io.EOF && z.pos < len(z.buf) { return nil } return z.err }
go
func (z *StreamLexer) Err() error { if z.err == io.EOF && z.pos < len(z.buf) { return nil } return z.err }
[ "func", "(", "z", "*", "StreamLexer", ")", "Err", "(", ")", "error", "{", "if", "z", ".", "err", "==", "io", ".", "EOF", "&&", "z", ".", "pos", "<", "len", "(", "z", ".", "buf", ")", "{", "return", "nil", "\n", "}", "\n", "return", "z", ".", "err", "\n", "}" ]
// Err returns the error returned from io.Reader. It may still return valid bytes for a while though.
[ "Err", "returns", "the", "error", "returned", "from", "io", ".", "Reader", ".", "It", "may", "still", "return", "valid", "bytes", "for", "a", "while", "though", "." ]
b8d8be7d83bf428ee370587d439137776d18362c
https://github.com/tdewolff/parse/blob/b8d8be7d83bf428ee370587d439137776d18362c/buffer/streamlexer.go#L144-L149
12,233
tdewolff/parse
buffer/streamlexer.go
Shift
func (z *StreamLexer) Shift() []byte { if z.pos > len(z.buf) { // make sure we peeked at least as much as we shift z.read(z.pos - 1) } b := z.buf[z.start:z.pos] z.start = z.pos return b }
go
func (z *StreamLexer) Shift() []byte { if z.pos > len(z.buf) { // make sure we peeked at least as much as we shift z.read(z.pos - 1) } b := z.buf[z.start:z.pos] z.start = z.pos return b }
[ "func", "(", "z", "*", "StreamLexer", ")", "Shift", "(", ")", "[", "]", "byte", "{", "if", "z", ".", "pos", ">", "len", "(", "z", ".", "buf", ")", "{", "// make sure we peeked at least as much as we shift", "z", ".", "read", "(", "z", ".", "pos", "-", "1", ")", "\n", "}", "\n", "b", ":=", "z", ".", "buf", "[", "z", ".", "start", ":", "z", ".", "pos", "]", "\n", "z", ".", "start", "=", "z", ".", "pos", "\n", "return", "b", "\n", "}" ]
// Shift returns the bytes of the current selection and collapses the position to the end of the selection. // It also returns the number of bytes we moved since the last call to Shift. This can be used in calls to Free.
[ "Shift", "returns", "the", "bytes", "of", "the", "current", "selection", "and", "collapses", "the", "position", "to", "the", "end", "of", "the", "selection", ".", "It", "also", "returns", "the", "number", "of", "bytes", "we", "moved", "since", "the", "last", "call", "to", "Shift", ".", "This", "can", "be", "used", "in", "calls", "to", "Free", "." ]
b8d8be7d83bf428ee370587d439137776d18362c
https://github.com/tdewolff/parse/blob/b8d8be7d83bf428ee370587d439137776d18362c/buffer/streamlexer.go#L209-L216
12,234
tdewolff/parse
buffer/streamlexer.go
ShiftLen
func (z *StreamLexer) ShiftLen() int { n := z.start - z.prevStart z.prevStart = z.start return n }
go
func (z *StreamLexer) ShiftLen() int { n := z.start - z.prevStart z.prevStart = z.start return n }
[ "func", "(", "z", "*", "StreamLexer", ")", "ShiftLen", "(", ")", "int", "{", "n", ":=", "z", ".", "start", "-", "z", ".", "prevStart", "\n", "z", ".", "prevStart", "=", "z", ".", "start", "\n", "return", "n", "\n", "}" ]
// ShiftLen returns the number of bytes moved since the last call to ShiftLen. This can be used in calls to Free because it takes into account multiple Shifts or Skips.
[ "ShiftLen", "returns", "the", "number", "of", "bytes", "moved", "since", "the", "last", "call", "to", "ShiftLen", ".", "This", "can", "be", "used", "in", "calls", "to", "Free", "because", "it", "takes", "into", "account", "multiple", "Shifts", "or", "Skips", "." ]
b8d8be7d83bf428ee370587d439137776d18362c
https://github.com/tdewolff/parse/blob/b8d8be7d83bf428ee370587d439137776d18362c/buffer/streamlexer.go#L219-L223
12,235
tdewolff/parse
buffer/lexer.go
NewLexer
func NewLexer(r io.Reader) *Lexer { var b []byte if r != nil { if buffer, ok := r.(interface { Bytes() []byte }); ok { b = buffer.Bytes() } else { var err error b, err = ioutil.ReadAll(r) if err != nil { return &Lexer{ buf: []byte{0}, err: err, } } } } return NewLexerBytes(b) }
go
func NewLexer(r io.Reader) *Lexer { var b []byte if r != nil { if buffer, ok := r.(interface { Bytes() []byte }); ok { b = buffer.Bytes() } else { var err error b, err = ioutil.ReadAll(r) if err != nil { return &Lexer{ buf: []byte{0}, err: err, } } } } return NewLexerBytes(b) }
[ "func", "NewLexer", "(", "r", "io", ".", "Reader", ")", "*", "Lexer", "{", "var", "b", "[", "]", "byte", "\n", "if", "r", "!=", "nil", "{", "if", "buffer", ",", "ok", ":=", "r", ".", "(", "interface", "{", "Bytes", "(", ")", "[", "]", "byte", "\n", "}", ")", ";", "ok", "{", "b", "=", "buffer", ".", "Bytes", "(", ")", "\n", "}", "else", "{", "var", "err", "error", "\n", "b", ",", "err", "=", "ioutil", ".", "ReadAll", "(", "r", ")", "\n", "if", "err", "!=", "nil", "{", "return", "&", "Lexer", "{", "buf", ":", "[", "]", "byte", "{", "0", "}", ",", "err", ":", "err", ",", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "NewLexerBytes", "(", "b", ")", "\n", "}" ]
// NewLexerBytes returns a new Lexer for a given io.Reader, and uses ioutil.ReadAll to read it into a byte slice. // If the io.Reader implements Bytes, that is used instead. // It will append a NULL at the end of the buffer.
[ "NewLexerBytes", "returns", "a", "new", "Lexer", "for", "a", "given", "io", ".", "Reader", "and", "uses", "ioutil", ".", "ReadAll", "to", "read", "it", "into", "a", "byte", "slice", ".", "If", "the", "io", ".", "Reader", "implements", "Bytes", "that", "is", "used", "instead", ".", "It", "will", "append", "a", "NULL", "at", "the", "end", "of", "the", "buffer", "." ]
b8d8be7d83bf428ee370587d439137776d18362c
https://github.com/tdewolff/parse/blob/b8d8be7d83bf428ee370587d439137776d18362c/buffer/lexer.go#L24-L43
12,236
tdewolff/parse
buffer/lexer.go
NewLexerBytes
func NewLexerBytes(b []byte) *Lexer { z := &Lexer{ buf: b, } n := len(b) if n == 0 { z.buf = nullBuffer } else if b[n-1] != 0 { // Append NULL to buffer, but try to avoid reallocation if cap(b) > n { // Overwrite next byte but restore when done b = b[:n+1] c := b[n] b[n] = 0 z.buf = b z.restore = func() { b[n] = c } } else { z.buf = append(b, 0) } } return z }
go
func NewLexerBytes(b []byte) *Lexer { z := &Lexer{ buf: b, } n := len(b) if n == 0 { z.buf = nullBuffer } else if b[n-1] != 0 { // Append NULL to buffer, but try to avoid reallocation if cap(b) > n { // Overwrite next byte but restore when done b = b[:n+1] c := b[n] b[n] = 0 z.buf = b z.restore = func() { b[n] = c } } else { z.buf = append(b, 0) } } return z }
[ "func", "NewLexerBytes", "(", "b", "[", "]", "byte", ")", "*", "Lexer", "{", "z", ":=", "&", "Lexer", "{", "buf", ":", "b", ",", "}", "\n\n", "n", ":=", "len", "(", "b", ")", "\n", "if", "n", "==", "0", "{", "z", ".", "buf", "=", "nullBuffer", "\n", "}", "else", "if", "b", "[", "n", "-", "1", "]", "!=", "0", "{", "// Append NULL to buffer, but try to avoid reallocation", "if", "cap", "(", "b", ")", ">", "n", "{", "// Overwrite next byte but restore when done", "b", "=", "b", "[", ":", "n", "+", "1", "]", "\n", "c", ":=", "b", "[", "n", "]", "\n", "b", "[", "n", "]", "=", "0", "\n\n", "z", ".", "buf", "=", "b", "\n", "z", ".", "restore", "=", "func", "(", ")", "{", "b", "[", "n", "]", "=", "c", "\n", "}", "\n", "}", "else", "{", "z", ".", "buf", "=", "append", "(", "b", ",", "0", ")", "\n", "}", "\n", "}", "\n", "return", "z", "\n", "}" ]
// NewLexerBytes returns a new Lexer for a given byte slice, and appends NULL at the end. // To avoid reallocation, make sure the capacity has room for one more byte.
[ "NewLexerBytes", "returns", "a", "new", "Lexer", "for", "a", "given", "byte", "slice", "and", "appends", "NULL", "at", "the", "end", ".", "To", "avoid", "reallocation", "make", "sure", "the", "capacity", "has", "room", "for", "one", "more", "byte", "." ]
b8d8be7d83bf428ee370587d439137776d18362c
https://github.com/tdewolff/parse/blob/b8d8be7d83bf428ee370587d439137776d18362c/buffer/lexer.go#L47-L72
12,237
tdewolff/parse
buffer/lexer.go
Restore
func (z *Lexer) Restore() { if z.restore != nil { z.restore() z.restore = nil } }
go
func (z *Lexer) Restore() { if z.restore != nil { z.restore() z.restore = nil } }
[ "func", "(", "z", "*", "Lexer", ")", "Restore", "(", ")", "{", "if", "z", ".", "restore", "!=", "nil", "{", "z", ".", "restore", "(", ")", "\n", "z", ".", "restore", "=", "nil", "\n", "}", "\n", "}" ]
// Restore restores the replaced byte past the end of the buffer by NULL.
[ "Restore", "restores", "the", "replaced", "byte", "past", "the", "end", "of", "the", "buffer", "by", "NULL", "." ]
b8d8be7d83bf428ee370587d439137776d18362c
https://github.com/tdewolff/parse/blob/b8d8be7d83bf428ee370587d439137776d18362c/buffer/lexer.go#L75-L80
12,238
tdewolff/parse
buffer/lexer.go
Peek
func (z *Lexer) Peek(pos int) byte { pos += z.pos return z.buf[pos] }
go
func (z *Lexer) Peek(pos int) byte { pos += z.pos return z.buf[pos] }
[ "func", "(", "z", "*", "Lexer", ")", "Peek", "(", "pos", "int", ")", "byte", "{", "pos", "+=", "z", ".", "pos", "\n", "return", "z", ".", "buf", "[", "pos", "]", "\n", "}" ]
// Peek returns the ith byte relative to the end position. // Peek returns 0 when an error has occurred, Err returns the error.
[ "Peek", "returns", "the", "ith", "byte", "relative", "to", "the", "end", "position", ".", "Peek", "returns", "0", "when", "an", "error", "has", "occurred", "Err", "returns", "the", "error", "." ]
b8d8be7d83bf428ee370587d439137776d18362c
https://github.com/tdewolff/parse/blob/b8d8be7d83bf428ee370587d439137776d18362c/buffer/lexer.go#L99-L102
12,239
tdewolff/parse
buffer/lexer.go
Shift
func (z *Lexer) Shift() []byte { b := z.buf[z.start:z.pos] z.start = z.pos return b }
go
func (z *Lexer) Shift() []byte { b := z.buf[z.start:z.pos] z.start = z.pos return b }
[ "func", "(", "z", "*", "Lexer", ")", "Shift", "(", ")", "[", "]", "byte", "{", "b", ":=", "z", ".", "buf", "[", "z", ".", "start", ":", "z", ".", "pos", "]", "\n", "z", ".", "start", "=", "z", ".", "pos", "\n", "return", "b", "\n", "}" ]
// Shift returns the bytes of the current selection and collapses the position to the end of the selection.
[ "Shift", "returns", "the", "bytes", "of", "the", "current", "selection", "and", "collapses", "the", "position", "to", "the", "end", "of", "the", "selection", "." ]
b8d8be7d83bf428ee370587d439137776d18362c
https://github.com/tdewolff/parse/blob/b8d8be7d83bf428ee370587d439137776d18362c/buffer/lexer.go#L144-L148
12,240
tdewolff/parse
common.go
Dimension
func Dimension(b []byte) (int, int) { num := Number(b) if num == 0 || num == len(b) { return num, 0 } else if b[num] == '%' { return num, 1 } else if b[num] >= 'a' && b[num] <= 'z' || b[num] >= 'A' && b[num] <= 'Z' { i := num + 1 for i < len(b) && (b[i] >= 'a' && b[i] <= 'z' || b[i] >= 'A' && b[i] <= 'Z') { i++ } return num, i - num } return num, 0 }
go
func Dimension(b []byte) (int, int) { num := Number(b) if num == 0 || num == len(b) { return num, 0 } else if b[num] == '%' { return num, 1 } else if b[num] >= 'a' && b[num] <= 'z' || b[num] >= 'A' && b[num] <= 'Z' { i := num + 1 for i < len(b) && (b[i] >= 'a' && b[i] <= 'z' || b[i] >= 'A' && b[i] <= 'Z') { i++ } return num, i - num } return num, 0 }
[ "func", "Dimension", "(", "b", "[", "]", "byte", ")", "(", "int", ",", "int", ")", "{", "num", ":=", "Number", "(", "b", ")", "\n", "if", "num", "==", "0", "||", "num", "==", "len", "(", "b", ")", "{", "return", "num", ",", "0", "\n", "}", "else", "if", "b", "[", "num", "]", "==", "'%'", "{", "return", "num", ",", "1", "\n", "}", "else", "if", "b", "[", "num", "]", ">=", "'a'", "&&", "b", "[", "num", "]", "<=", "'z'", "||", "b", "[", "num", "]", ">=", "'A'", "&&", "b", "[", "num", "]", "<=", "'Z'", "{", "i", ":=", "num", "+", "1", "\n", "for", "i", "<", "len", "(", "b", ")", "&&", "(", "b", "[", "i", "]", ">=", "'a'", "&&", "b", "[", "i", "]", "<=", "'z'", "||", "b", "[", "i", "]", ">=", "'A'", "&&", "b", "[", "i", "]", "<=", "'Z'", ")", "{", "i", "++", "\n", "}", "\n", "return", "num", ",", "i", "-", "num", "\n", "}", "\n", "return", "num", ",", "0", "\n", "}" ]
// Dimension parses a byte-slice and returns the length of the number and its unit.
[ "Dimension", "parses", "a", "byte", "-", "slice", "and", "returns", "the", "length", "of", "the", "number", "and", "its", "unit", "." ]
b8d8be7d83bf428ee370587d439137776d18362c
https://github.com/tdewolff/parse/blob/b8d8be7d83bf428ee370587d439137776d18362c/common.go#L68-L82
12,241
tdewolff/parse
common.go
Mediatype
func Mediatype(b []byte) ([]byte, map[string]string) { i := 0 for i < len(b) && b[i] == ' ' { i++ } b = b[i:] n := len(b) mimetype := b var params map[string]string for i := 3; i < n; i++ { // mimetype is at least three characters long if b[i] == ';' || b[i] == ' ' { mimetype = b[:i] if b[i] == ' ' { i++ for i < n && b[i] == ' ' { i++ } if i < n && b[i] != ';' { break } } params = map[string]string{} s := string(b) PARAM: i++ for i < n && s[i] == ' ' { i++ } start := i for i < n && s[i] != '=' && s[i] != ';' && s[i] != ' ' { i++ } key := s[start:i] for i < n && s[i] == ' ' { i++ } if i < n && s[i] == '=' { i++ for i < n && s[i] == ' ' { i++ } start = i for i < n && s[i] != ';' && s[i] != ' ' { i++ } } else { start = i } params[key] = s[start:i] for i < n && s[i] == ' ' { i++ } if i < n && s[i] == ';' { goto PARAM } break } } return mimetype, params }
go
func Mediatype(b []byte) ([]byte, map[string]string) { i := 0 for i < len(b) && b[i] == ' ' { i++ } b = b[i:] n := len(b) mimetype := b var params map[string]string for i := 3; i < n; i++ { // mimetype is at least three characters long if b[i] == ';' || b[i] == ' ' { mimetype = b[:i] if b[i] == ' ' { i++ for i < n && b[i] == ' ' { i++ } if i < n && b[i] != ';' { break } } params = map[string]string{} s := string(b) PARAM: i++ for i < n && s[i] == ' ' { i++ } start := i for i < n && s[i] != '=' && s[i] != ';' && s[i] != ' ' { i++ } key := s[start:i] for i < n && s[i] == ' ' { i++ } if i < n && s[i] == '=' { i++ for i < n && s[i] == ' ' { i++ } start = i for i < n && s[i] != ';' && s[i] != ' ' { i++ } } else { start = i } params[key] = s[start:i] for i < n && s[i] == ' ' { i++ } if i < n && s[i] == ';' { goto PARAM } break } } return mimetype, params }
[ "func", "Mediatype", "(", "b", "[", "]", "byte", ")", "(", "[", "]", "byte", ",", "map", "[", "string", "]", "string", ")", "{", "i", ":=", "0", "\n", "for", "i", "<", "len", "(", "b", ")", "&&", "b", "[", "i", "]", "==", "' '", "{", "i", "++", "\n", "}", "\n", "b", "=", "b", "[", "i", ":", "]", "\n", "n", ":=", "len", "(", "b", ")", "\n", "mimetype", ":=", "b", "\n", "var", "params", "map", "[", "string", "]", "string", "\n", "for", "i", ":=", "3", ";", "i", "<", "n", ";", "i", "++", "{", "// mimetype is at least three characters long", "if", "b", "[", "i", "]", "==", "';'", "||", "b", "[", "i", "]", "==", "' '", "{", "mimetype", "=", "b", "[", ":", "i", "]", "\n", "if", "b", "[", "i", "]", "==", "' '", "{", "i", "++", "\n", "for", "i", "<", "n", "&&", "b", "[", "i", "]", "==", "' '", "{", "i", "++", "\n", "}", "\n", "if", "i", "<", "n", "&&", "b", "[", "i", "]", "!=", "';'", "{", "break", "\n", "}", "\n", "}", "\n", "params", "=", "map", "[", "string", "]", "string", "{", "}", "\n", "s", ":=", "string", "(", "b", ")", "\n", "PARAM", ":", "i", "++", "\n", "for", "i", "<", "n", "&&", "s", "[", "i", "]", "==", "' '", "{", "i", "++", "\n", "}", "\n", "start", ":=", "i", "\n", "for", "i", "<", "n", "&&", "s", "[", "i", "]", "!=", "'='", "&&", "s", "[", "i", "]", "!=", "';'", "&&", "s", "[", "i", "]", "!=", "' '", "{", "i", "++", "\n", "}", "\n", "key", ":=", "s", "[", "start", ":", "i", "]", "\n", "for", "i", "<", "n", "&&", "s", "[", "i", "]", "==", "' '", "{", "i", "++", "\n", "}", "\n", "if", "i", "<", "n", "&&", "s", "[", "i", "]", "==", "'='", "{", "i", "++", "\n", "for", "i", "<", "n", "&&", "s", "[", "i", "]", "==", "' '", "{", "i", "++", "\n", "}", "\n", "start", "=", "i", "\n", "for", "i", "<", "n", "&&", "s", "[", "i", "]", "!=", "';'", "&&", "s", "[", "i", "]", "!=", "' '", "{", "i", "++", "\n", "}", "\n", "}", "else", "{", "start", "=", "i", "\n", "}", "\n", "params", "[", "key", "]", "=", "s", "[", "start", ":", "i", "]", "\n", "for", "i", "<", "n", "&&", "s", "[", "i", "]", "==", "' '", "{", "i", "++", "\n", "}", "\n", "if", "i", "<", "n", "&&", "s", "[", "i", "]", "==", "';'", "{", "goto", "PARAM", "\n", "}", "\n", "break", "\n", "}", "\n", "}", "\n", "return", "mimetype", ",", "params", "\n", "}" ]
// Mediatype parses a given mediatype and splits the mimetype from the parameters. // It works similar to mime.ParseMediaType but is faster.
[ "Mediatype", "parses", "a", "given", "mediatype", "and", "splits", "the", "mimetype", "from", "the", "parameters", ".", "It", "works", "similar", "to", "mime", ".", "ParseMediaType", "but", "is", "faster", "." ]
b8d8be7d83bf428ee370587d439137776d18362c
https://github.com/tdewolff/parse/blob/b8d8be7d83bf428ee370587d439137776d18362c/common.go#L86-L145
12,242
tdewolff/parse
common.go
DataURI
func DataURI(dataURI []byte) ([]byte, []byte, error) { if len(dataURI) > 5 && bytes.Equal(dataURI[:5], []byte("data:")) { dataURI = dataURI[5:] inBase64 := false var mediatype []byte i := 0 for j := 0; j < len(dataURI); j++ { c := dataURI[j] if c == '=' || c == ';' || c == ',' { if c != '=' && bytes.Equal(TrimWhitespace(dataURI[i:j]), []byte("base64")) { if len(mediatype) > 0 { mediatype = mediatype[:len(mediatype)-1] } inBase64 = true i = j } else if c != ',' { mediatype = append(append(mediatype, TrimWhitespace(dataURI[i:j])...), c) i = j + 1 } else { mediatype = append(mediatype, TrimWhitespace(dataURI[i:j])...) } if c == ',' { if len(mediatype) == 0 || mediatype[0] == ';' { mediatype = []byte("text/plain") } data := dataURI[j+1:] if inBase64 { decoded := make([]byte, base64.StdEncoding.DecodedLen(len(data))) n, err := base64.StdEncoding.Decode(decoded, data) if err != nil { return nil, nil, err } data = decoded[:n] } else if unescaped, err := url.QueryUnescape(string(data)); err == nil { data = []byte(unescaped) } return mediatype, data, nil } } } } return nil, nil, ErrBadDataURI }
go
func DataURI(dataURI []byte) ([]byte, []byte, error) { if len(dataURI) > 5 && bytes.Equal(dataURI[:5], []byte("data:")) { dataURI = dataURI[5:] inBase64 := false var mediatype []byte i := 0 for j := 0; j < len(dataURI); j++ { c := dataURI[j] if c == '=' || c == ';' || c == ',' { if c != '=' && bytes.Equal(TrimWhitespace(dataURI[i:j]), []byte("base64")) { if len(mediatype) > 0 { mediatype = mediatype[:len(mediatype)-1] } inBase64 = true i = j } else if c != ',' { mediatype = append(append(mediatype, TrimWhitespace(dataURI[i:j])...), c) i = j + 1 } else { mediatype = append(mediatype, TrimWhitespace(dataURI[i:j])...) } if c == ',' { if len(mediatype) == 0 || mediatype[0] == ';' { mediatype = []byte("text/plain") } data := dataURI[j+1:] if inBase64 { decoded := make([]byte, base64.StdEncoding.DecodedLen(len(data))) n, err := base64.StdEncoding.Decode(decoded, data) if err != nil { return nil, nil, err } data = decoded[:n] } else if unescaped, err := url.QueryUnescape(string(data)); err == nil { data = []byte(unescaped) } return mediatype, data, nil } } } } return nil, nil, ErrBadDataURI }
[ "func", "DataURI", "(", "dataURI", "[", "]", "byte", ")", "(", "[", "]", "byte", ",", "[", "]", "byte", ",", "error", ")", "{", "if", "len", "(", "dataURI", ")", ">", "5", "&&", "bytes", ".", "Equal", "(", "dataURI", "[", ":", "5", "]", ",", "[", "]", "byte", "(", "\"", "\"", ")", ")", "{", "dataURI", "=", "dataURI", "[", "5", ":", "]", "\n", "inBase64", ":=", "false", "\n", "var", "mediatype", "[", "]", "byte", "\n", "i", ":=", "0", "\n", "for", "j", ":=", "0", ";", "j", "<", "len", "(", "dataURI", ")", ";", "j", "++", "{", "c", ":=", "dataURI", "[", "j", "]", "\n", "if", "c", "==", "'='", "||", "c", "==", "';'", "||", "c", "==", "','", "{", "if", "c", "!=", "'='", "&&", "bytes", ".", "Equal", "(", "TrimWhitespace", "(", "dataURI", "[", "i", ":", "j", "]", ")", ",", "[", "]", "byte", "(", "\"", "\"", ")", ")", "{", "if", "len", "(", "mediatype", ")", ">", "0", "{", "mediatype", "=", "mediatype", "[", ":", "len", "(", "mediatype", ")", "-", "1", "]", "\n", "}", "\n", "inBase64", "=", "true", "\n", "i", "=", "j", "\n", "}", "else", "if", "c", "!=", "','", "{", "mediatype", "=", "append", "(", "append", "(", "mediatype", ",", "TrimWhitespace", "(", "dataURI", "[", "i", ":", "j", "]", ")", "...", ")", ",", "c", ")", "\n", "i", "=", "j", "+", "1", "\n", "}", "else", "{", "mediatype", "=", "append", "(", "mediatype", ",", "TrimWhitespace", "(", "dataURI", "[", "i", ":", "j", "]", ")", "...", ")", "\n", "}", "\n", "if", "c", "==", "','", "{", "if", "len", "(", "mediatype", ")", "==", "0", "||", "mediatype", "[", "0", "]", "==", "';'", "{", "mediatype", "=", "[", "]", "byte", "(", "\"", "\"", ")", "\n", "}", "\n", "data", ":=", "dataURI", "[", "j", "+", "1", ":", "]", "\n", "if", "inBase64", "{", "decoded", ":=", "make", "(", "[", "]", "byte", ",", "base64", ".", "StdEncoding", ".", "DecodedLen", "(", "len", "(", "data", ")", ")", ")", "\n", "n", ",", "err", ":=", "base64", ".", "StdEncoding", ".", "Decode", "(", "decoded", ",", "data", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "nil", ",", "err", "\n", "}", "\n", "data", "=", "decoded", "[", ":", "n", "]", "\n", "}", "else", "if", "unescaped", ",", "err", ":=", "url", ".", "QueryUnescape", "(", "string", "(", "data", ")", ")", ";", "err", "==", "nil", "{", "data", "=", "[", "]", "byte", "(", "unescaped", ")", "\n", "}", "\n", "return", "mediatype", ",", "data", ",", "nil", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "nil", ",", "nil", ",", "ErrBadDataURI", "\n", "}" ]
// DataURI parses the given data URI and returns the mediatype, data and ok.
[ "DataURI", "parses", "the", "given", "data", "URI", "and", "returns", "the", "mediatype", "data", "and", "ok", "." ]
b8d8be7d83bf428ee370587d439137776d18362c
https://github.com/tdewolff/parse/blob/b8d8be7d83bf428ee370587d439137776d18362c/common.go#L148-L190
12,243
tdewolff/parse
css/parse.go
NewParser
func NewParser(r io.Reader, isInline bool) *Parser { l := NewLexer(r) p := &Parser{ l: l, state: make([]State, 0, 4), } if isInline { p.state = append(p.state, (*Parser).parseDeclarationList) } else { p.state = append(p.state, (*Parser).parseStylesheet) } return p }
go
func NewParser(r io.Reader, isInline bool) *Parser { l := NewLexer(r) p := &Parser{ l: l, state: make([]State, 0, 4), } if isInline { p.state = append(p.state, (*Parser).parseDeclarationList) } else { p.state = append(p.state, (*Parser).parseStylesheet) } return p }
[ "func", "NewParser", "(", "r", "io", ".", "Reader", ",", "isInline", "bool", ")", "*", "Parser", "{", "l", ":=", "NewLexer", "(", "r", ")", "\n", "p", ":=", "&", "Parser", "{", "l", ":", "l", ",", "state", ":", "make", "(", "[", "]", "State", ",", "0", ",", "4", ")", ",", "}", "\n\n", "if", "isInline", "{", "p", ".", "state", "=", "append", "(", "p", ".", "state", ",", "(", "*", "Parser", ")", ".", "parseDeclarationList", ")", "\n", "}", "else", "{", "p", ".", "state", "=", "append", "(", "p", ".", "state", ",", "(", "*", "Parser", ")", ".", "parseStylesheet", ")", "\n", "}", "\n", "return", "p", "\n", "}" ]
// NewParser returns a new CSS parser from an io.Reader. isInline specifies whether this is an inline style attribute.
[ "NewParser", "returns", "a", "new", "CSS", "parser", "from", "an", "io", ".", "Reader", ".", "isInline", "specifies", "whether", "this", "is", "an", "inline", "style", "attribute", "." ]
b8d8be7d83bf428ee370587d439137776d18362c
https://github.com/tdewolff/parse/blob/b8d8be7d83bf428ee370587d439137776d18362c/css/parse.go#L94-L107
12,244
tdewolff/parse
css/parse.go
Err
func (p *Parser) Err() error { if p.err != nil { return p.err } return p.l.Err() }
go
func (p *Parser) Err() error { if p.err != nil { return p.err } return p.l.Err() }
[ "func", "(", "p", "*", "Parser", ")", "Err", "(", ")", "error", "{", "if", "p", ".", "err", "!=", "nil", "{", "return", "p", ".", "err", "\n", "}", "\n", "return", "p", ".", "l", ".", "Err", "(", ")", "\n", "}" ]
// Err returns the error encountered during parsing, this is often io.EOF but also other errors can be returned.
[ "Err", "returns", "the", "error", "encountered", "during", "parsing", "this", "is", "often", "io", ".", "EOF", "but", "also", "other", "errors", "can", "be", "returned", "." ]
b8d8be7d83bf428ee370587d439137776d18362c
https://github.com/tdewolff/parse/blob/b8d8be7d83bf428ee370587d439137776d18362c/css/parse.go#L110-L115
12,245
tdewolff/parse
buffer/writer.go
Write
func (w *Writer) Write(b []byte) (int, error) { n := len(b) end := len(w.buf) if end+n > cap(w.buf) { buf := make([]byte, end, 2*cap(w.buf)+n) copy(buf, w.buf) w.buf = buf } w.buf = w.buf[:end+n] return copy(w.buf[end:], b), nil }
go
func (w *Writer) Write(b []byte) (int, error) { n := len(b) end := len(w.buf) if end+n > cap(w.buf) { buf := make([]byte, end, 2*cap(w.buf)+n) copy(buf, w.buf) w.buf = buf } w.buf = w.buf[:end+n] return copy(w.buf[end:], b), nil }
[ "func", "(", "w", "*", "Writer", ")", "Write", "(", "b", "[", "]", "byte", ")", "(", "int", ",", "error", ")", "{", "n", ":=", "len", "(", "b", ")", "\n", "end", ":=", "len", "(", "w", ".", "buf", ")", "\n", "if", "end", "+", "n", ">", "cap", "(", "w", ".", "buf", ")", "{", "buf", ":=", "make", "(", "[", "]", "byte", ",", "end", ",", "2", "*", "cap", "(", "w", ".", "buf", ")", "+", "n", ")", "\n", "copy", "(", "buf", ",", "w", ".", "buf", ")", "\n", "w", ".", "buf", "=", "buf", "\n", "}", "\n", "w", ".", "buf", "=", "w", ".", "buf", "[", ":", "end", "+", "n", "]", "\n", "return", "copy", "(", "w", ".", "buf", "[", "end", ":", "]", ",", "b", ")", ",", "nil", "\n", "}" ]
// Write writes bytes from the given byte slice and returns the number of bytes written and an error if occurred. When err != nil, n == 0.
[ "Write", "writes", "bytes", "from", "the", "given", "byte", "slice", "and", "returns", "the", "number", "of", "bytes", "written", "and", "an", "error", "if", "occurred", ".", "When", "err", "!", "=", "nil", "n", "==", "0", "." ]
b8d8be7d83bf428ee370587d439137776d18362c
https://github.com/tdewolff/parse/blob/b8d8be7d83bf428ee370587d439137776d18362c/buffer/writer.go#L16-L26
12,246
tdewolff/parse
css/util.go
IsIdent
func IsIdent(b []byte) bool { l := NewLexer(buffer.NewReader(b)) l.consumeIdentToken() l.r.Restore() return l.r.Pos() == len(b) }
go
func IsIdent(b []byte) bool { l := NewLexer(buffer.NewReader(b)) l.consumeIdentToken() l.r.Restore() return l.r.Pos() == len(b) }
[ "func", "IsIdent", "(", "b", "[", "]", "byte", ")", "bool", "{", "l", ":=", "NewLexer", "(", "buffer", ".", "NewReader", "(", "b", ")", ")", "\n", "l", ".", "consumeIdentToken", "(", ")", "\n", "l", ".", "r", ".", "Restore", "(", ")", "\n", "return", "l", ".", "r", ".", "Pos", "(", ")", "==", "len", "(", "b", ")", "\n", "}" ]
// IsIdent returns true if the bytes are a valid identifier.
[ "IsIdent", "returns", "true", "if", "the", "bytes", "are", "a", "valid", "identifier", "." ]
b8d8be7d83bf428ee370587d439137776d18362c
https://github.com/tdewolff/parse/blob/b8d8be7d83bf428ee370587d439137776d18362c/css/util.go#L6-L11
12,247
tdewolff/parse
css/util.go
IsURLUnquoted
func IsURLUnquoted(b []byte) bool { l := NewLexer(buffer.NewReader(b)) l.consumeUnquotedURL() l.r.Restore() return l.r.Pos() == len(b) }
go
func IsURLUnquoted(b []byte) bool { l := NewLexer(buffer.NewReader(b)) l.consumeUnquotedURL() l.r.Restore() return l.r.Pos() == len(b) }
[ "func", "IsURLUnquoted", "(", "b", "[", "]", "byte", ")", "bool", "{", "l", ":=", "NewLexer", "(", "buffer", ".", "NewReader", "(", "b", ")", ")", "\n", "l", ".", "consumeUnquotedURL", "(", ")", "\n", "l", ".", "r", ".", "Restore", "(", ")", "\n", "return", "l", ".", "r", ".", "Pos", "(", ")", "==", "len", "(", "b", ")", "\n", "}" ]
// IsURLUnquoted returns true if the bytes are a valid unquoted URL.
[ "IsURLUnquoted", "returns", "true", "if", "the", "bytes", "are", "a", "valid", "unquoted", "URL", "." ]
b8d8be7d83bf428ee370587d439137776d18362c
https://github.com/tdewolff/parse/blob/b8d8be7d83bf428ee370587d439137776d18362c/css/util.go#L14-L19
12,248
tdewolff/parse
xml/util.go
EscapeAttrVal
func EscapeAttrVal(buf *[]byte, b []byte) []byte { singles := 0 doubles := 0 for i, c := range b { if c == '&' { if quote, n := parse.QuoteEntity(b[i:]); n > 0 { if quote == '"' { doubles++ } else { singles++ } } } else if c == '"' { doubles++ } else if c == '\'' { singles++ } } n := len(b) + 2 var quote byte var escapedQuote []byte if doubles > singles { n += singles * 4 quote = '\'' escapedQuote = singleQuoteEntityBytes } else { n += doubles * 4 quote = '"' escapedQuote = doubleQuoteEntityBytes } if n > cap(*buf) { *buf = make([]byte, 0, n) // maximum size, not actual size } t := (*buf)[:n] // maximum size, not actual size t[0] = quote j := 1 start := 0 for i, c := range b { if c == '&' { if entityQuote, n := parse.QuoteEntity(b[i:]); n > 0 { j += copy(t[j:], b[start:i]) if entityQuote != quote { t[j] = entityQuote j++ } else { j += copy(t[j:], escapedQuote) } start = i + n } } else if c == quote { j += copy(t[j:], b[start:i]) j += copy(t[j:], escapedQuote) start = i + 1 } } j += copy(t[j:], b[start:]) t[j] = quote return t[:j+1] }
go
func EscapeAttrVal(buf *[]byte, b []byte) []byte { singles := 0 doubles := 0 for i, c := range b { if c == '&' { if quote, n := parse.QuoteEntity(b[i:]); n > 0 { if quote == '"' { doubles++ } else { singles++ } } } else if c == '"' { doubles++ } else if c == '\'' { singles++ } } n := len(b) + 2 var quote byte var escapedQuote []byte if doubles > singles { n += singles * 4 quote = '\'' escapedQuote = singleQuoteEntityBytes } else { n += doubles * 4 quote = '"' escapedQuote = doubleQuoteEntityBytes } if n > cap(*buf) { *buf = make([]byte, 0, n) // maximum size, not actual size } t := (*buf)[:n] // maximum size, not actual size t[0] = quote j := 1 start := 0 for i, c := range b { if c == '&' { if entityQuote, n := parse.QuoteEntity(b[i:]); n > 0 { j += copy(t[j:], b[start:i]) if entityQuote != quote { t[j] = entityQuote j++ } else { j += copy(t[j:], escapedQuote) } start = i + n } } else if c == quote { j += copy(t[j:], b[start:i]) j += copy(t[j:], escapedQuote) start = i + 1 } } j += copy(t[j:], b[start:]) t[j] = quote return t[:j+1] }
[ "func", "EscapeAttrVal", "(", "buf", "*", "[", "]", "byte", ",", "b", "[", "]", "byte", ")", "[", "]", "byte", "{", "singles", ":=", "0", "\n", "doubles", ":=", "0", "\n", "for", "i", ",", "c", ":=", "range", "b", "{", "if", "c", "==", "'&'", "{", "if", "quote", ",", "n", ":=", "parse", ".", "QuoteEntity", "(", "b", "[", "i", ":", "]", ")", ";", "n", ">", "0", "{", "if", "quote", "==", "'\"'", "{", "doubles", "++", "\n", "}", "else", "{", "singles", "++", "\n", "}", "\n", "}", "\n", "}", "else", "if", "c", "==", "'\"'", "{", "doubles", "++", "\n", "}", "else", "if", "c", "==", "'\\''", "{", "singles", "++", "\n", "}", "\n", "}", "\n\n", "n", ":=", "len", "(", "b", ")", "+", "2", "\n", "var", "quote", "byte", "\n", "var", "escapedQuote", "[", "]", "byte", "\n", "if", "doubles", ">", "singles", "{", "n", "+=", "singles", "*", "4", "\n", "quote", "=", "'\\''", "\n", "escapedQuote", "=", "singleQuoteEntityBytes", "\n", "}", "else", "{", "n", "+=", "doubles", "*", "4", "\n", "quote", "=", "'\"'", "\n", "escapedQuote", "=", "doubleQuoteEntityBytes", "\n", "}", "\n", "if", "n", ">", "cap", "(", "*", "buf", ")", "{", "*", "buf", "=", "make", "(", "[", "]", "byte", ",", "0", ",", "n", ")", "// maximum size, not actual size", "\n", "}", "\n", "t", ":=", "(", "*", "buf", ")", "[", ":", "n", "]", "// maximum size, not actual size", "\n", "t", "[", "0", "]", "=", "quote", "\n", "j", ":=", "1", "\n", "start", ":=", "0", "\n", "for", "i", ",", "c", ":=", "range", "b", "{", "if", "c", "==", "'&'", "{", "if", "entityQuote", ",", "n", ":=", "parse", ".", "QuoteEntity", "(", "b", "[", "i", ":", "]", ")", ";", "n", ">", "0", "{", "j", "+=", "copy", "(", "t", "[", "j", ":", "]", ",", "b", "[", "start", ":", "i", "]", ")", "\n", "if", "entityQuote", "!=", "quote", "{", "t", "[", "j", "]", "=", "entityQuote", "\n", "j", "++", "\n", "}", "else", "{", "j", "+=", "copy", "(", "t", "[", "j", ":", "]", ",", "escapedQuote", ")", "\n", "}", "\n", "start", "=", "i", "+", "n", "\n", "}", "\n", "}", "else", "if", "c", "==", "quote", "{", "j", "+=", "copy", "(", "t", "[", "j", ":", "]", ",", "b", "[", "start", ":", "i", "]", ")", "\n", "j", "+=", "copy", "(", "t", "[", "j", ":", "]", ",", "escapedQuote", ")", "\n", "start", "=", "i", "+", "1", "\n", "}", "\n", "}", "\n", "j", "+=", "copy", "(", "t", "[", "j", ":", "]", ",", "b", "[", "start", ":", "]", ")", "\n", "t", "[", "j", "]", "=", "quote", "\n", "return", "t", "[", ":", "j", "+", "1", "]", "\n", "}" ]
// EscapeAttrVal returns the escape attribute value bytes without quotes.
[ "EscapeAttrVal", "returns", "the", "escape", "attribute", "value", "bytes", "without", "quotes", "." ]
b8d8be7d83bf428ee370587d439137776d18362c
https://github.com/tdewolff/parse/blob/b8d8be7d83bf428ee370587d439137776d18362c/xml/util.go#L13-L72
12,249
tdewolff/parse
xml/util.go
EscapeCDATAVal
func EscapeCDATAVal(buf *[]byte, b []byte) ([]byte, bool) { n := 0 for _, c := range b { if c == '<' || c == '&' { if c == '<' { n += 3 // &lt; } else { n += 4 // &amp; } if n > len("<![CDATA[]]>") { return b, false } } } if len(b)+n > cap(*buf) { *buf = make([]byte, 0, len(b)+n) } t := (*buf)[:len(b)+n] j := 0 start := 0 for i, c := range b { if c == '<' { j += copy(t[j:], b[start:i]) j += copy(t[j:], ltEntityBytes) start = i + 1 } else if c == '&' { j += copy(t[j:], b[start:i]) j += copy(t[j:], ampEntityBytes) start = i + 1 } } j += copy(t[j:], b[start:]) return t[:j], true }
go
func EscapeCDATAVal(buf *[]byte, b []byte) ([]byte, bool) { n := 0 for _, c := range b { if c == '<' || c == '&' { if c == '<' { n += 3 // &lt; } else { n += 4 // &amp; } if n > len("<![CDATA[]]>") { return b, false } } } if len(b)+n > cap(*buf) { *buf = make([]byte, 0, len(b)+n) } t := (*buf)[:len(b)+n] j := 0 start := 0 for i, c := range b { if c == '<' { j += copy(t[j:], b[start:i]) j += copy(t[j:], ltEntityBytes) start = i + 1 } else if c == '&' { j += copy(t[j:], b[start:i]) j += copy(t[j:], ampEntityBytes) start = i + 1 } } j += copy(t[j:], b[start:]) return t[:j], true }
[ "func", "EscapeCDATAVal", "(", "buf", "*", "[", "]", "byte", ",", "b", "[", "]", "byte", ")", "(", "[", "]", "byte", ",", "bool", ")", "{", "n", ":=", "0", "\n", "for", "_", ",", "c", ":=", "range", "b", "{", "if", "c", "==", "'<'", "||", "c", "==", "'&'", "{", "if", "c", "==", "'<'", "{", "n", "+=", "3", "// &lt;", "\n", "}", "else", "{", "n", "+=", "4", "// &amp;", "\n", "}", "\n", "if", "n", ">", "len", "(", "\"", "\"", ")", "{", "return", "b", ",", "false", "\n", "}", "\n", "}", "\n", "}", "\n", "if", "len", "(", "b", ")", "+", "n", ">", "cap", "(", "*", "buf", ")", "{", "*", "buf", "=", "make", "(", "[", "]", "byte", ",", "0", ",", "len", "(", "b", ")", "+", "n", ")", "\n", "}", "\n", "t", ":=", "(", "*", "buf", ")", "[", ":", "len", "(", "b", ")", "+", "n", "]", "\n", "j", ":=", "0", "\n", "start", ":=", "0", "\n", "for", "i", ",", "c", ":=", "range", "b", "{", "if", "c", "==", "'<'", "{", "j", "+=", "copy", "(", "t", "[", "j", ":", "]", ",", "b", "[", "start", ":", "i", "]", ")", "\n", "j", "+=", "copy", "(", "t", "[", "j", ":", "]", ",", "ltEntityBytes", ")", "\n", "start", "=", "i", "+", "1", "\n", "}", "else", "if", "c", "==", "'&'", "{", "j", "+=", "copy", "(", "t", "[", "j", ":", "]", ",", "b", "[", "start", ":", "i", "]", ")", "\n", "j", "+=", "copy", "(", "t", "[", "j", ":", "]", ",", "ampEntityBytes", ")", "\n", "start", "=", "i", "+", "1", "\n", "}", "\n", "}", "\n", "j", "+=", "copy", "(", "t", "[", "j", ":", "]", ",", "b", "[", "start", ":", "]", ")", "\n", "return", "t", "[", ":", "j", "]", ",", "true", "\n", "}" ]
// EscapeCDATAVal returns the escaped text bytes.
[ "EscapeCDATAVal", "returns", "the", "escaped", "text", "bytes", "." ]
b8d8be7d83bf428ee370587d439137776d18362c
https://github.com/tdewolff/parse/blob/b8d8be7d83bf428ee370587d439137776d18362c/xml/util.go#L75-L108
12,250
tdewolff/parse
util.go
Copy
func Copy(src []byte) (dst []byte) { dst = make([]byte, len(src)) copy(dst, src) return }
go
func Copy(src []byte) (dst []byte) { dst = make([]byte, len(src)) copy(dst, src) return }
[ "func", "Copy", "(", "src", "[", "]", "byte", ")", "(", "dst", "[", "]", "byte", ")", "{", "dst", "=", "make", "(", "[", "]", "byte", ",", "len", "(", "src", ")", ")", "\n", "copy", "(", "dst", ",", "src", ")", "\n", "return", "\n", "}" ]
// Copy returns a copy of the given byte slice.
[ "Copy", "returns", "a", "copy", "of", "the", "given", "byte", "slice", "." ]
b8d8be7d83bf428ee370587d439137776d18362c
https://github.com/tdewolff/parse/blob/b8d8be7d83bf428ee370587d439137776d18362c/util.go#L4-L8
12,251
tdewolff/parse
util.go
ToLower
func ToLower(src []byte) []byte { for i, c := range src { if c >= 'A' && c <= 'Z' { src[i] = c + ('a' - 'A') } } return src }
go
func ToLower(src []byte) []byte { for i, c := range src { if c >= 'A' && c <= 'Z' { src[i] = c + ('a' - 'A') } } return src }
[ "func", "ToLower", "(", "src", "[", "]", "byte", ")", "[", "]", "byte", "{", "for", "i", ",", "c", ":=", "range", "src", "{", "if", "c", ">=", "'A'", "&&", "c", "<=", "'Z'", "{", "src", "[", "i", "]", "=", "c", "+", "(", "'a'", "-", "'A'", ")", "\n", "}", "\n", "}", "\n", "return", "src", "\n", "}" ]
// ToLower converts all characters in the byte slice from A-Z to a-z.
[ "ToLower", "converts", "all", "characters", "in", "the", "byte", "slice", "from", "A", "-", "Z", "to", "a", "-", "z", "." ]
b8d8be7d83bf428ee370587d439137776d18362c
https://github.com/tdewolff/parse/blob/b8d8be7d83bf428ee370587d439137776d18362c/util.go#L11-L18
12,252
tdewolff/parse
util.go
IsAllWhitespace
func IsAllWhitespace(b []byte) bool { for _, c := range b { if !IsWhitespace(c) { return false } } return true }
go
func IsAllWhitespace(b []byte) bool { for _, c := range b { if !IsWhitespace(c) { return false } } return true }
[ "func", "IsAllWhitespace", "(", "b", "[", "]", "byte", ")", "bool", "{", "for", "_", ",", "c", ":=", "range", "b", "{", "if", "!", "IsWhitespace", "(", "c", ")", "{", "return", "false", "\n", "}", "\n", "}", "\n", "return", "true", "\n", "}" ]
// IsAllWhitespace returns true when the entire byte slice consists of space, \n, \r, \t, \f.
[ "IsAllWhitespace", "returns", "true", "when", "the", "entire", "byte", "slice", "consists", "of", "space", "\\", "n", "\\", "r", "\\", "t", "\\", "f", "." ]
b8d8be7d83bf428ee370587d439137776d18362c
https://github.com/tdewolff/parse/blob/b8d8be7d83bf428ee370587d439137776d18362c/util.go#L133-L140
12,253
tdewolff/parse
util.go
TrimWhitespace
func TrimWhitespace(b []byte) []byte { n := len(b) start := n for i := 0; i < n; i++ { if !IsWhitespace(b[i]) { start = i break } } end := n for i := n - 1; i >= start; i-- { if !IsWhitespace(b[i]) { end = i + 1 break } } return b[start:end] }
go
func TrimWhitespace(b []byte) []byte { n := len(b) start := n for i := 0; i < n; i++ { if !IsWhitespace(b[i]) { start = i break } } end := n for i := n - 1; i >= start; i-- { if !IsWhitespace(b[i]) { end = i + 1 break } } return b[start:end] }
[ "func", "TrimWhitespace", "(", "b", "[", "]", "byte", ")", "[", "]", "byte", "{", "n", ":=", "len", "(", "b", ")", "\n", "start", ":=", "n", "\n", "for", "i", ":=", "0", ";", "i", "<", "n", ";", "i", "++", "{", "if", "!", "IsWhitespace", "(", "b", "[", "i", "]", ")", "{", "start", "=", "i", "\n", "break", "\n", "}", "\n", "}", "\n", "end", ":=", "n", "\n", "for", "i", ":=", "n", "-", "1", ";", "i", ">=", "start", ";", "i", "--", "{", "if", "!", "IsWhitespace", "(", "b", "[", "i", "]", ")", "{", "end", "=", "i", "+", "1", "\n", "break", "\n", "}", "\n", "}", "\n", "return", "b", "[", "start", ":", "end", "]", "\n", "}" ]
// TrimWhitespace removes any leading and trailing whitespace characters.
[ "TrimWhitespace", "removes", "any", "leading", "and", "trailing", "whitespace", "characters", "." ]
b8d8be7d83bf428ee370587d439137776d18362c
https://github.com/tdewolff/parse/blob/b8d8be7d83bf428ee370587d439137776d18362c/util.go#L143-L160
12,254
tdewolff/parse
strconv/price.go
AppendPrice
func AppendPrice(b []byte, price int64, dec bool, milSeparator byte, decSeparator byte) []byte { if price < 0 { if price == -9223372036854775808 { x := []byte("92 233 720 368 547 758 08") x[2] = milSeparator x[6] = milSeparator x[10] = milSeparator x[14] = milSeparator x[18] = milSeparator x[22] = decSeparator return append(b, x...) } price = -price } // rounding if !dec { firstDec := (price / 10) % 10 if firstDec >= 5 { price += 100 } } // calculate size n := LenInt(price) - 2 if n > 0 { n += (n - 1) / 3 // mil separator } else { n = 1 } if dec { n += 2 + 1 // decimals + dec separator } // resize byte slice i := len(b) if i+n > cap(b) { b = append(b, make([]byte, n)...) } else { b = b[:i+n] } // print fractional-part i += n - 1 if dec { for j := 0; j < 2; j++ { c := byte(price%10) + '0' price /= 10 b[i] = c i-- } b[i] = decSeparator i-- } else { price /= 100 } if price == 0 { b[i] = '0' return b } // print integer-part j := 0 for price > 0 { if j == 3 { b[i] = milSeparator i-- j = 0 } c := byte(price%10) + '0' price /= 10 b[i] = c i-- j++ } return b }
go
func AppendPrice(b []byte, price int64, dec bool, milSeparator byte, decSeparator byte) []byte { if price < 0 { if price == -9223372036854775808 { x := []byte("92 233 720 368 547 758 08") x[2] = milSeparator x[6] = milSeparator x[10] = milSeparator x[14] = milSeparator x[18] = milSeparator x[22] = decSeparator return append(b, x...) } price = -price } // rounding if !dec { firstDec := (price / 10) % 10 if firstDec >= 5 { price += 100 } } // calculate size n := LenInt(price) - 2 if n > 0 { n += (n - 1) / 3 // mil separator } else { n = 1 } if dec { n += 2 + 1 // decimals + dec separator } // resize byte slice i := len(b) if i+n > cap(b) { b = append(b, make([]byte, n)...) } else { b = b[:i+n] } // print fractional-part i += n - 1 if dec { for j := 0; j < 2; j++ { c := byte(price%10) + '0' price /= 10 b[i] = c i-- } b[i] = decSeparator i-- } else { price /= 100 } if price == 0 { b[i] = '0' return b } // print integer-part j := 0 for price > 0 { if j == 3 { b[i] = milSeparator i-- j = 0 } c := byte(price%10) + '0' price /= 10 b[i] = c i-- j++ } return b }
[ "func", "AppendPrice", "(", "b", "[", "]", "byte", ",", "price", "int64", ",", "dec", "bool", ",", "milSeparator", "byte", ",", "decSeparator", "byte", ")", "[", "]", "byte", "{", "if", "price", "<", "0", "{", "if", "price", "==", "-", "9223372036854775808", "{", "x", ":=", "[", "]", "byte", "(", "\"", "\"", ")", "\n", "x", "[", "2", "]", "=", "milSeparator", "\n", "x", "[", "6", "]", "=", "milSeparator", "\n", "x", "[", "10", "]", "=", "milSeparator", "\n", "x", "[", "14", "]", "=", "milSeparator", "\n", "x", "[", "18", "]", "=", "milSeparator", "\n", "x", "[", "22", "]", "=", "decSeparator", "\n", "return", "append", "(", "b", ",", "x", "...", ")", "\n", "}", "\n", "price", "=", "-", "price", "\n", "}", "\n\n", "// rounding", "if", "!", "dec", "{", "firstDec", ":=", "(", "price", "/", "10", ")", "%", "10", "\n", "if", "firstDec", ">=", "5", "{", "price", "+=", "100", "\n", "}", "\n", "}", "\n\n", "// calculate size", "n", ":=", "LenInt", "(", "price", ")", "-", "2", "\n", "if", "n", ">", "0", "{", "n", "+=", "(", "n", "-", "1", ")", "/", "3", "// mil separator", "\n", "}", "else", "{", "n", "=", "1", "\n", "}", "\n", "if", "dec", "{", "n", "+=", "2", "+", "1", "// decimals + dec separator", "\n", "}", "\n\n", "// resize byte slice", "i", ":=", "len", "(", "b", ")", "\n", "if", "i", "+", "n", ">", "cap", "(", "b", ")", "{", "b", "=", "append", "(", "b", ",", "make", "(", "[", "]", "byte", ",", "n", ")", "...", ")", "\n", "}", "else", "{", "b", "=", "b", "[", ":", "i", "+", "n", "]", "\n", "}", "\n\n", "// print fractional-part", "i", "+=", "n", "-", "1", "\n", "if", "dec", "{", "for", "j", ":=", "0", ";", "j", "<", "2", ";", "j", "++", "{", "c", ":=", "byte", "(", "price", "%", "10", ")", "+", "'0'", "\n", "price", "/=", "10", "\n", "b", "[", "i", "]", "=", "c", "\n", "i", "--", "\n", "}", "\n", "b", "[", "i", "]", "=", "decSeparator", "\n", "i", "--", "\n", "}", "else", "{", "price", "/=", "100", "\n", "}", "\n\n", "if", "price", "==", "0", "{", "b", "[", "i", "]", "=", "'0'", "\n", "return", "b", "\n", "}", "\n\n", "// print integer-part", "j", ":=", "0", "\n", "for", "price", ">", "0", "{", "if", "j", "==", "3", "{", "b", "[", "i", "]", "=", "milSeparator", "\n", "i", "--", "\n", "j", "=", "0", "\n", "}", "\n\n", "c", ":=", "byte", "(", "price", "%", "10", ")", "+", "'0'", "\n", "price", "/=", "10", "\n", "b", "[", "i", "]", "=", "c", "\n", "i", "--", "\n", "j", "++", "\n", "}", "\n", "return", "b", "\n", "}" ]
// AppendPrice will append an int64 formatted as a price, where the int64 is the price in cents. // It does not display whether a price is negative or not.
[ "AppendPrice", "will", "append", "an", "int64", "formatted", "as", "a", "price", "where", "the", "int64", "is", "the", "price", "in", "cents", ".", "It", "does", "not", "display", "whether", "a", "price", "is", "negative", "or", "not", "." ]
b8d8be7d83bf428ee370587d439137776d18362c
https://github.com/tdewolff/parse/blob/b8d8be7d83bf428ee370587d439137776d18362c/strconv/price.go#L5-L83
12,255
tdewolff/parse
html/lex.go
Err
func (l *Lexer) Err() error { if l.err != nil { return l.err } return l.r.Err() }
go
func (l *Lexer) Err() error { if l.err != nil { return l.err } return l.r.Err() }
[ "func", "(", "l", "*", "Lexer", ")", "Err", "(", ")", "error", "{", "if", "l", ".", "err", "!=", "nil", "{", "return", "l", ".", "err", "\n", "}", "\n", "return", "l", ".", "r", ".", "Err", "(", ")", "\n", "}" ]
// Err returns the error encountered during lexing, this is often io.EOF but also other errors can be returned.
[ "Err", "returns", "the", "error", "encountered", "during", "lexing", "this", "is", "often", "io", ".", "EOF", "but", "also", "other", "errors", "can", "be", "returned", "." ]
b8d8be7d83bf428ee370587d439137776d18362c
https://github.com/tdewolff/parse/blob/b8d8be7d83bf428ee370587d439137776d18362c/html/lex.go#L81-L86
12,256
tdewolff/parse
html/lex.go
shiftXml
func (l *Lexer) shiftXml(rawTag Hash) []byte { inQuote := false for { c := l.r.Peek(0) if c == '"' { inQuote = !inQuote l.r.Move(1) } else if c == '<' && !inQuote && l.r.Peek(1) == '/' { mark := l.r.Pos() l.r.Move(2) for { if c = l.r.Peek(0); !('a' <= c && c <= 'z' || 'A' <= c && c <= 'Z') { break } l.r.Move(1) } if h := ToHash(parse.ToLower(parse.Copy(l.r.Lexeme()[mark+2:]))); h == rawTag { // copy so that ToLower doesn't change the case of the underlying slice break } } else if c == 0 { if l.r.Err() == nil { l.err = parse.NewErrorLexer("unexpected null character", l.r) } return l.r.Shift() } else { l.r.Move(1) } } for { c := l.r.Peek(0) if c == '>' { l.r.Move(1) break } else if c == 0 { if l.r.Err() == nil { l.err = parse.NewErrorLexer("unexpected null character", l.r) } return l.r.Shift() } l.r.Move(1) } return l.r.Shift() }
go
func (l *Lexer) shiftXml(rawTag Hash) []byte { inQuote := false for { c := l.r.Peek(0) if c == '"' { inQuote = !inQuote l.r.Move(1) } else if c == '<' && !inQuote && l.r.Peek(1) == '/' { mark := l.r.Pos() l.r.Move(2) for { if c = l.r.Peek(0); !('a' <= c && c <= 'z' || 'A' <= c && c <= 'Z') { break } l.r.Move(1) } if h := ToHash(parse.ToLower(parse.Copy(l.r.Lexeme()[mark+2:]))); h == rawTag { // copy so that ToLower doesn't change the case of the underlying slice break } } else if c == 0 { if l.r.Err() == nil { l.err = parse.NewErrorLexer("unexpected null character", l.r) } return l.r.Shift() } else { l.r.Move(1) } } for { c := l.r.Peek(0) if c == '>' { l.r.Move(1) break } else if c == 0 { if l.r.Err() == nil { l.err = parse.NewErrorLexer("unexpected null character", l.r) } return l.r.Shift() } l.r.Move(1) } return l.r.Shift() }
[ "func", "(", "l", "*", "Lexer", ")", "shiftXml", "(", "rawTag", "Hash", ")", "[", "]", "byte", "{", "inQuote", ":=", "false", "\n", "for", "{", "c", ":=", "l", ".", "r", ".", "Peek", "(", "0", ")", "\n", "if", "c", "==", "'\"'", "{", "inQuote", "=", "!", "inQuote", "\n", "l", ".", "r", ".", "Move", "(", "1", ")", "\n", "}", "else", "if", "c", "==", "'<'", "&&", "!", "inQuote", "&&", "l", ".", "r", ".", "Peek", "(", "1", ")", "==", "'/'", "{", "mark", ":=", "l", ".", "r", ".", "Pos", "(", ")", "\n", "l", ".", "r", ".", "Move", "(", "2", ")", "\n", "for", "{", "if", "c", "=", "l", ".", "r", ".", "Peek", "(", "0", ")", ";", "!", "(", "'a'", "<=", "c", "&&", "c", "<=", "'z'", "||", "'A'", "<=", "c", "&&", "c", "<=", "'Z'", ")", "{", "break", "\n", "}", "\n", "l", ".", "r", ".", "Move", "(", "1", ")", "\n", "}", "\n", "if", "h", ":=", "ToHash", "(", "parse", ".", "ToLower", "(", "parse", ".", "Copy", "(", "l", ".", "r", ".", "Lexeme", "(", ")", "[", "mark", "+", "2", ":", "]", ")", ")", ")", ";", "h", "==", "rawTag", "{", "// copy so that ToLower doesn't change the case of the underlying slice", "break", "\n", "}", "\n", "}", "else", "if", "c", "==", "0", "{", "if", "l", ".", "r", ".", "Err", "(", ")", "==", "nil", "{", "l", ".", "err", "=", "parse", ".", "NewErrorLexer", "(", "\"", "\"", ",", "l", ".", "r", ")", "\n", "}", "\n", "return", "l", ".", "r", ".", "Shift", "(", ")", "\n", "}", "else", "{", "l", ".", "r", ".", "Move", "(", "1", ")", "\n", "}", "\n", "}", "\n\n", "for", "{", "c", ":=", "l", ".", "r", ".", "Peek", "(", "0", ")", "\n", "if", "c", "==", "'>'", "{", "l", ".", "r", ".", "Move", "(", "1", ")", "\n", "break", "\n", "}", "else", "if", "c", "==", "0", "{", "if", "l", ".", "r", ".", "Err", "(", ")", "==", "nil", "{", "l", ".", "err", "=", "parse", ".", "NewErrorLexer", "(", "\"", "\"", ",", "l", ".", "r", ")", "\n", "}", "\n", "return", "l", ".", "r", ".", "Shift", "(", ")", "\n", "}", "\n", "l", ".", "r", ".", "Move", "(", "1", ")", "\n", "}", "\n", "return", "l", ".", "r", ".", "Shift", "(", ")", "\n", "}" ]
// shiftXml parses the content of a svg or math tag according to the XML 1.1 specifications, including the tag itself. // So far we have already parsed `<svg` or `<math`.
[ "shiftXml", "parses", "the", "content", "of", "a", "svg", "or", "math", "tag", "according", "to", "the", "XML", "1", ".", "1", "specifications", "including", "the", "tag", "itself", ".", "So", "far", "we", "have", "already", "parsed", "<svg", "or", "<math", "." ]
b8d8be7d83bf428ee370587d439137776d18362c
https://github.com/tdewolff/parse/blob/b8d8be7d83bf428ee370587d439137776d18362c/html/lex.go#L435-L478
12,257
tdewolff/parse
position.go
Position
func Position(r io.Reader, offset int) (line, col int, context string) { l := buffer.NewLexer(r) line = 1 for { c := l.Peek(0) if c == 0 && l.Err() != nil || offset == l.Pos() { col = l.Pos() + 1 context = positionContext(l, line, col) return } nNewline := 0 if c == '\n' { nNewline = 1 } else if c == '\r' { if l.Peek(1) == '\n' { nNewline = 2 } else { nNewline = 1 } } else if c >= 0xC0 { if r, n := l.PeekRune(0); r == '\u2028' || r == '\u2029' { nNewline = n } } else { l.Move(1) } if nNewline > 0 { if offset < l.Pos()+nNewline { // move onto offset position, let next iteration handle it l.Move(offset - l.Pos()) continue } l.Move(nNewline) line++ offset -= l.Pos() l.Skip() } } }
go
func Position(r io.Reader, offset int) (line, col int, context string) { l := buffer.NewLexer(r) line = 1 for { c := l.Peek(0) if c == 0 && l.Err() != nil || offset == l.Pos() { col = l.Pos() + 1 context = positionContext(l, line, col) return } nNewline := 0 if c == '\n' { nNewline = 1 } else if c == '\r' { if l.Peek(1) == '\n' { nNewline = 2 } else { nNewline = 1 } } else if c >= 0xC0 { if r, n := l.PeekRune(0); r == '\u2028' || r == '\u2029' { nNewline = n } } else { l.Move(1) } if nNewline > 0 { if offset < l.Pos()+nNewline { // move onto offset position, let next iteration handle it l.Move(offset - l.Pos()) continue } l.Move(nNewline) line++ offset -= l.Pos() l.Skip() } } }
[ "func", "Position", "(", "r", "io", ".", "Reader", ",", "offset", "int", ")", "(", "line", ",", "col", "int", ",", "context", "string", ")", "{", "l", ":=", "buffer", ".", "NewLexer", "(", "r", ")", "\n\n", "line", "=", "1", "\n", "for", "{", "c", ":=", "l", ".", "Peek", "(", "0", ")", "\n", "if", "c", "==", "0", "&&", "l", ".", "Err", "(", ")", "!=", "nil", "||", "offset", "==", "l", ".", "Pos", "(", ")", "{", "col", "=", "l", ".", "Pos", "(", ")", "+", "1", "\n", "context", "=", "positionContext", "(", "l", ",", "line", ",", "col", ")", "\n", "return", "\n", "}", "\n\n", "nNewline", ":=", "0", "\n", "if", "c", "==", "'\\n'", "{", "nNewline", "=", "1", "\n", "}", "else", "if", "c", "==", "'\\r'", "{", "if", "l", ".", "Peek", "(", "1", ")", "==", "'\\n'", "{", "nNewline", "=", "2", "\n", "}", "else", "{", "nNewline", "=", "1", "\n", "}", "\n", "}", "else", "if", "c", ">=", "0xC0", "{", "if", "r", ",", "n", ":=", "l", ".", "PeekRune", "(", "0", ")", ";", "r", "==", "'\\u2028'", "||", "r", "==", "'\\u2029'", "{", "nNewline", "=", "n", "\n", "}", "\n", "}", "else", "{", "l", ".", "Move", "(", "1", ")", "\n", "}", "\n\n", "if", "nNewline", ">", "0", "{", "if", "offset", "<", "l", ".", "Pos", "(", ")", "+", "nNewline", "{", "// move onto offset position, let next iteration handle it", "l", ".", "Move", "(", "offset", "-", "l", ".", "Pos", "(", ")", ")", "\n", "continue", "\n", "}", "\n", "l", ".", "Move", "(", "nNewline", ")", "\n", "line", "++", "\n", "offset", "-=", "l", ".", "Pos", "(", ")", "\n", "l", ".", "Skip", "(", ")", "\n", "}", "\n", "}", "\n", "}" ]
// Position returns the line and column number for a certain position in a file. It is useful for recovering the position in a file that caused an error. // It only treates \n, \r, and \r\n as newlines, which might be different from some languages also recognizing \f, \u2028, and \u2029 to be newlines.
[ "Position", "returns", "the", "line", "and", "column", "number", "for", "a", "certain", "position", "in", "a", "file", ".", "It", "is", "useful", "for", "recovering", "the", "position", "in", "a", "file", "that", "caused", "an", "error", ".", "It", "only", "treates", "\\", "n", "\\", "r", "and", "\\", "r", "\\", "n", "as", "newlines", "which", "might", "be", "different", "from", "some", "languages", "also", "recognizing", "\\", "f", "\\", "u2028", "and", "\\", "u2029", "to", "be", "newlines", "." ]
b8d8be7d83bf428ee370587d439137776d18362c
https://github.com/tdewolff/parse/blob/b8d8be7d83bf428ee370587d439137776d18362c/position.go#L13-L54
12,258
tdewolff/parse
buffer/reader.go
Read
func (r *Reader) Read(b []byte) (n int, err error) { if len(b) == 0 { return 0, nil } if r.pos >= len(r.buf) { return 0, io.EOF } n = copy(b, r.buf[r.pos:]) r.pos += n return }
go
func (r *Reader) Read(b []byte) (n int, err error) { if len(b) == 0 { return 0, nil } if r.pos >= len(r.buf) { return 0, io.EOF } n = copy(b, r.buf[r.pos:]) r.pos += n return }
[ "func", "(", "r", "*", "Reader", ")", "Read", "(", "b", "[", "]", "byte", ")", "(", "n", "int", ",", "err", "error", ")", "{", "if", "len", "(", "b", ")", "==", "0", "{", "return", "0", ",", "nil", "\n", "}", "\n", "if", "r", ".", "pos", ">=", "len", "(", "r", ".", "buf", ")", "{", "return", "0", ",", "io", ".", "EOF", "\n", "}", "\n", "n", "=", "copy", "(", "b", ",", "r", ".", "buf", "[", "r", ".", "pos", ":", "]", ")", "\n", "r", ".", "pos", "+=", "n", "\n", "return", "\n", "}" ]
// Read reads bytes into the given byte slice and returns the number of bytes read and an error if occurred.
[ "Read", "reads", "bytes", "into", "the", "given", "byte", "slice", "and", "returns", "the", "number", "of", "bytes", "read", "and", "an", "error", "if", "occurred", "." ]
b8d8be7d83bf428ee370587d439137776d18362c
https://github.com/tdewolff/parse/blob/b8d8be7d83bf428ee370587d439137776d18362c/buffer/reader.go#L19-L29
12,259
tdewolff/parse
strconv/int.go
ParseInt
func ParseInt(b []byte) (int64, int) { i := 0 neg := false if len(b) > 0 && (b[0] == '+' || b[0] == '-') { neg = b[0] == '-' i++ } n := uint64(0) for i < len(b) { c := b[i] if n > math.MaxUint64/10 { return 0, 0 } else if c >= '0' && c <= '9' { n *= 10 n += uint64(c - '0') } else { break } i++ } if !neg && n > uint64(math.MaxInt64) || n > uint64(math.MaxInt64)+1 { return 0, 0 } else if neg { return -int64(n), i } return int64(n), i }
go
func ParseInt(b []byte) (int64, int) { i := 0 neg := false if len(b) > 0 && (b[0] == '+' || b[0] == '-') { neg = b[0] == '-' i++ } n := uint64(0) for i < len(b) { c := b[i] if n > math.MaxUint64/10 { return 0, 0 } else if c >= '0' && c <= '9' { n *= 10 n += uint64(c - '0') } else { break } i++ } if !neg && n > uint64(math.MaxInt64) || n > uint64(math.MaxInt64)+1 { return 0, 0 } else if neg { return -int64(n), i } return int64(n), i }
[ "func", "ParseInt", "(", "b", "[", "]", "byte", ")", "(", "int64", ",", "int", ")", "{", "i", ":=", "0", "\n", "neg", ":=", "false", "\n", "if", "len", "(", "b", ")", ">", "0", "&&", "(", "b", "[", "0", "]", "==", "'+'", "||", "b", "[", "0", "]", "==", "'-'", ")", "{", "neg", "=", "b", "[", "0", "]", "==", "'-'", "\n", "i", "++", "\n", "}", "\n", "n", ":=", "uint64", "(", "0", ")", "\n", "for", "i", "<", "len", "(", "b", ")", "{", "c", ":=", "b", "[", "i", "]", "\n", "if", "n", ">", "math", ".", "MaxUint64", "/", "10", "{", "return", "0", ",", "0", "\n", "}", "else", "if", "c", ">=", "'0'", "&&", "c", "<=", "'9'", "{", "n", "*=", "10", "\n", "n", "+=", "uint64", "(", "c", "-", "'0'", ")", "\n", "}", "else", "{", "break", "\n", "}", "\n", "i", "++", "\n", "}", "\n", "if", "!", "neg", "&&", "n", ">", "uint64", "(", "math", ".", "MaxInt64", ")", "||", "n", ">", "uint64", "(", "math", ".", "MaxInt64", ")", "+", "1", "{", "return", "0", ",", "0", "\n", "}", "else", "if", "neg", "{", "return", "-", "int64", "(", "n", ")", ",", "i", "\n", "}", "\n", "return", "int64", "(", "n", ")", ",", "i", "\n", "}" ]
// Int parses a byte-slice and returns the integer it represents. // If an invalid character is encountered, it will stop there.
[ "Int", "parses", "a", "byte", "-", "slice", "and", "returns", "the", "integer", "it", "represents", ".", "If", "an", "invalid", "character", "is", "encountered", "it", "will", "stop", "there", "." ]
b8d8be7d83bf428ee370587d439137776d18362c
https://github.com/tdewolff/parse/blob/b8d8be7d83bf428ee370587d439137776d18362c/strconv/int.go#L9-L35
12,260
tdewolff/parse
strconv/float.go
ParseFloat
func ParseFloat(b []byte) (float64, int) { i := 0 neg := false if i < len(b) && (b[i] == '+' || b[i] == '-') { neg = b[i] == '-' i++ } dot := -1 trunk := -1 n := uint64(0) for ; i < len(b); i++ { c := b[i] if c >= '0' && c <= '9' { if trunk == -1 { if n > math.MaxUint64/10 { trunk = i } else { n *= 10 n += uint64(c - '0') } } } else if dot == -1 && c == '.' { dot = i } else { break } } f := float64(n) if neg { f = -f } mantExp := int64(0) if dot != -1 { if trunk == -1 { trunk = i } mantExp = int64(trunk - dot - 1) } else if trunk != -1 { mantExp = int64(trunk - i) } expExp := int64(0) if i < len(b) && (b[i] == 'e' || b[i] == 'E') { i++ if e, expLen := ParseInt(b[i:]); expLen > 0 { expExp = e i += expLen } } exp := expExp - mantExp // copied from strconv/atof.go if exp == 0 { return f, i } else if exp > 0 && exp <= 15+22 { // int * 10^k // If exponent is big but number of digits is not, // can move a few zeros into the integer part. if exp > 22 { f *= float64pow10[exp-22] exp = 22 } if f <= 1e15 && f >= -1e15 { return f * float64pow10[exp], i } } else if exp < 0 && exp >= -22 { // int / 10^k return f / float64pow10[-exp], i } f *= math.Pow10(int(-mantExp)) return f * math.Pow10(int(expExp)), i }
go
func ParseFloat(b []byte) (float64, int) { i := 0 neg := false if i < len(b) && (b[i] == '+' || b[i] == '-') { neg = b[i] == '-' i++ } dot := -1 trunk := -1 n := uint64(0) for ; i < len(b); i++ { c := b[i] if c >= '0' && c <= '9' { if trunk == -1 { if n > math.MaxUint64/10 { trunk = i } else { n *= 10 n += uint64(c - '0') } } } else if dot == -1 && c == '.' { dot = i } else { break } } f := float64(n) if neg { f = -f } mantExp := int64(0) if dot != -1 { if trunk == -1 { trunk = i } mantExp = int64(trunk - dot - 1) } else if trunk != -1 { mantExp = int64(trunk - i) } expExp := int64(0) if i < len(b) && (b[i] == 'e' || b[i] == 'E') { i++ if e, expLen := ParseInt(b[i:]); expLen > 0 { expExp = e i += expLen } } exp := expExp - mantExp // copied from strconv/atof.go if exp == 0 { return f, i } else if exp > 0 && exp <= 15+22 { // int * 10^k // If exponent is big but number of digits is not, // can move a few zeros into the integer part. if exp > 22 { f *= float64pow10[exp-22] exp = 22 } if f <= 1e15 && f >= -1e15 { return f * float64pow10[exp], i } } else if exp < 0 && exp >= -22 { // int / 10^k return f / float64pow10[-exp], i } f *= math.Pow10(int(-mantExp)) return f * math.Pow10(int(expExp)), i }
[ "func", "ParseFloat", "(", "b", "[", "]", "byte", ")", "(", "float64", ",", "int", ")", "{", "i", ":=", "0", "\n", "neg", ":=", "false", "\n", "if", "i", "<", "len", "(", "b", ")", "&&", "(", "b", "[", "i", "]", "==", "'+'", "||", "b", "[", "i", "]", "==", "'-'", ")", "{", "neg", "=", "b", "[", "i", "]", "==", "'-'", "\n", "i", "++", "\n", "}", "\n\n", "dot", ":=", "-", "1", "\n", "trunk", ":=", "-", "1", "\n", "n", ":=", "uint64", "(", "0", ")", "\n", "for", ";", "i", "<", "len", "(", "b", ")", ";", "i", "++", "{", "c", ":=", "b", "[", "i", "]", "\n", "if", "c", ">=", "'0'", "&&", "c", "<=", "'9'", "{", "if", "trunk", "==", "-", "1", "{", "if", "n", ">", "math", ".", "MaxUint64", "/", "10", "{", "trunk", "=", "i", "\n", "}", "else", "{", "n", "*=", "10", "\n", "n", "+=", "uint64", "(", "c", "-", "'0'", ")", "\n", "}", "\n", "}", "\n", "}", "else", "if", "dot", "==", "-", "1", "&&", "c", "==", "'.'", "{", "dot", "=", "i", "\n", "}", "else", "{", "break", "\n", "}", "\n", "}", "\n\n", "f", ":=", "float64", "(", "n", ")", "\n", "if", "neg", "{", "f", "=", "-", "f", "\n", "}", "\n\n", "mantExp", ":=", "int64", "(", "0", ")", "\n", "if", "dot", "!=", "-", "1", "{", "if", "trunk", "==", "-", "1", "{", "trunk", "=", "i", "\n", "}", "\n", "mantExp", "=", "int64", "(", "trunk", "-", "dot", "-", "1", ")", "\n", "}", "else", "if", "trunk", "!=", "-", "1", "{", "mantExp", "=", "int64", "(", "trunk", "-", "i", ")", "\n", "}", "\n", "expExp", ":=", "int64", "(", "0", ")", "\n", "if", "i", "<", "len", "(", "b", ")", "&&", "(", "b", "[", "i", "]", "==", "'e'", "||", "b", "[", "i", "]", "==", "'E'", ")", "{", "i", "++", "\n", "if", "e", ",", "expLen", ":=", "ParseInt", "(", "b", "[", "i", ":", "]", ")", ";", "expLen", ">", "0", "{", "expExp", "=", "e", "\n", "i", "+=", "expLen", "\n", "}", "\n", "}", "\n", "exp", ":=", "expExp", "-", "mantExp", "\n\n", "// copied from strconv/atof.go", "if", "exp", "==", "0", "{", "return", "f", ",", "i", "\n", "}", "else", "if", "exp", ">", "0", "&&", "exp", "<=", "15", "+", "22", "{", "// int * 10^k", "// If exponent is big but number of digits is not,", "// can move a few zeros into the integer part.", "if", "exp", ">", "22", "{", "f", "*=", "float64pow10", "[", "exp", "-", "22", "]", "\n", "exp", "=", "22", "\n", "}", "\n", "if", "f", "<=", "1e15", "&&", "f", ">=", "-", "1e15", "{", "return", "f", "*", "float64pow10", "[", "exp", "]", ",", "i", "\n", "}", "\n", "}", "else", "if", "exp", "<", "0", "&&", "exp", ">=", "-", "22", "{", "// int / 10^k", "return", "f", "/", "float64pow10", "[", "-", "exp", "]", ",", "i", "\n", "}", "\n", "f", "*=", "math", ".", "Pow10", "(", "int", "(", "-", "mantExp", ")", ")", "\n", "return", "f", "*", "math", ".", "Pow10", "(", "int", "(", "expExp", ")", ")", ",", "i", "\n", "}" ]
// Float parses a byte-slice and returns the float it represents. // If an invalid character is encountered, it will stop there.
[ "Float", "parses", "a", "byte", "-", "slice", "and", "returns", "the", "float", "it", "represents", ".", "If", "an", "invalid", "character", "is", "encountered", "it", "will", "stop", "there", "." ]
b8d8be7d83bf428ee370587d439137776d18362c
https://github.com/tdewolff/parse/blob/b8d8be7d83bf428ee370587d439137776d18362c/strconv/float.go#L13-L84
12,261
tdewolff/parse
error.go
NewError
func NewError(msg string, r io.Reader, offset int) *Error { return &Error{ Message: msg, r: r, Offset: offset, } }
go
func NewError(msg string, r io.Reader, offset int) *Error { return &Error{ Message: msg, r: r, Offset: offset, } }
[ "func", "NewError", "(", "msg", "string", ",", "r", "io", ".", "Reader", ",", "offset", "int", ")", "*", "Error", "{", "return", "&", "Error", "{", "Message", ":", "msg", ",", "r", ":", "r", ",", "Offset", ":", "offset", ",", "}", "\n", "}" ]
// NewError creates a new error
[ "NewError", "creates", "a", "new", "error" ]
b8d8be7d83bf428ee370587d439137776d18362c
https://github.com/tdewolff/parse/blob/b8d8be7d83bf428ee370587d439137776d18362c/error.go#L21-L27
12,262
tdewolff/parse
error.go
NewErrorLexer
func NewErrorLexer(msg string, l *buffer.Lexer) *Error { r := buffer.NewReader(l.Bytes()) offset := l.Offset() return NewError(msg, r, offset) }
go
func NewErrorLexer(msg string, l *buffer.Lexer) *Error { r := buffer.NewReader(l.Bytes()) offset := l.Offset() return NewError(msg, r, offset) }
[ "func", "NewErrorLexer", "(", "msg", "string", ",", "l", "*", "buffer", ".", "Lexer", ")", "*", "Error", "{", "r", ":=", "buffer", ".", "NewReader", "(", "l", ".", "Bytes", "(", ")", ")", "\n", "offset", ":=", "l", ".", "Offset", "(", ")", "\n", "return", "NewError", "(", "msg", ",", "r", ",", "offset", ")", "\n", "}" ]
// NewErrorLexer creates a new error from an active Lexer.
[ "NewErrorLexer", "creates", "a", "new", "error", "from", "an", "active", "Lexer", "." ]
b8d8be7d83bf428ee370587d439137776d18362c
https://github.com/tdewolff/parse/blob/b8d8be7d83bf428ee370587d439137776d18362c/error.go#L30-L34
12,263
tdewolff/parse
error.go
Position
func (e *Error) Position() (int, int, string) { if e.line == 0 { e.line, e.column, e.context = Position(e.r, e.Offset) } return e.line, e.column, e.context }
go
func (e *Error) Position() (int, int, string) { if e.line == 0 { e.line, e.column, e.context = Position(e.r, e.Offset) } return e.line, e.column, e.context }
[ "func", "(", "e", "*", "Error", ")", "Position", "(", ")", "(", "int", ",", "int", ",", "string", ")", "{", "if", "e", ".", "line", "==", "0", "{", "e", ".", "line", ",", "e", ".", "column", ",", "e", ".", "context", "=", "Position", "(", "e", ".", "r", ",", "e", ".", "Offset", ")", "\n", "}", "\n", "return", "e", ".", "line", ",", "e", ".", "column", ",", "e", ".", "context", "\n", "}" ]
// Positions re-parses the file to determine the line, column, and context of the error. // Context is the entire line at which the error occurred.
[ "Positions", "re", "-", "parses", "the", "file", "to", "determine", "the", "line", "column", "and", "context", "of", "the", "error", ".", "Context", "is", "the", "entire", "line", "at", "which", "the", "error", "occurred", "." ]
b8d8be7d83bf428ee370587d439137776d18362c
https://github.com/tdewolff/parse/blob/b8d8be7d83bf428ee370587d439137776d18362c/error.go#L38-L43
12,264
tdewolff/parse
error.go
Error
func (e *Error) Error() string { line, column, context := e.Position() return fmt.Sprintf("parse error:%d:%d: %s\n%s", line, column, e.Message, context) }
go
func (e *Error) Error() string { line, column, context := e.Position() return fmt.Sprintf("parse error:%d:%d: %s\n%s", line, column, e.Message, context) }
[ "func", "(", "e", "*", "Error", ")", "Error", "(", ")", "string", "{", "line", ",", "column", ",", "context", ":=", "e", ".", "Position", "(", ")", "\n", "return", "fmt", ".", "Sprintf", "(", "\"", "\\n", "\"", ",", "line", ",", "column", ",", "e", ".", "Message", ",", "context", ")", "\n", "}" ]
// Error returns the error string, containing the context and line + column number.
[ "Error", "returns", "the", "error", "string", "containing", "the", "context", "and", "line", "+", "column", "number", "." ]
b8d8be7d83bf428ee370587d439137776d18362c
https://github.com/tdewolff/parse/blob/b8d8be7d83bf428ee370587d439137776d18362c/error.go#L46-L49
12,265
tdewolff/parse
css/lex.go
consumeBracket
func (l *Lexer) consumeBracket() TokenType { switch l.r.Peek(0) { case '(': l.r.Move(1) return LeftParenthesisToken case ')': l.r.Move(1) return RightParenthesisToken case '[': l.r.Move(1) return LeftBracketToken case ']': l.r.Move(1) return RightBracketToken case '{': l.r.Move(1) return LeftBraceToken case '}': l.r.Move(1) return RightBraceToken } return ErrorToken }
go
func (l *Lexer) consumeBracket() TokenType { switch l.r.Peek(0) { case '(': l.r.Move(1) return LeftParenthesisToken case ')': l.r.Move(1) return RightParenthesisToken case '[': l.r.Move(1) return LeftBracketToken case ']': l.r.Move(1) return RightBracketToken case '{': l.r.Move(1) return LeftBraceToken case '}': l.r.Move(1) return RightBraceToken } return ErrorToken }
[ "func", "(", "l", "*", "Lexer", ")", "consumeBracket", "(", ")", "TokenType", "{", "switch", "l", ".", "r", ".", "Peek", "(", "0", ")", "{", "case", "'('", ":", "l", ".", "r", ".", "Move", "(", "1", ")", "\n", "return", "LeftParenthesisToken", "\n", "case", "')'", ":", "l", ".", "r", ".", "Move", "(", "1", ")", "\n", "return", "RightParenthesisToken", "\n", "case", "'['", ":", "l", ".", "r", ".", "Move", "(", "1", ")", "\n", "return", "LeftBracketToken", "\n", "case", "']'", ":", "l", ".", "r", ".", "Move", "(", "1", ")", "\n", "return", "RightBracketToken", "\n", "case", "'{'", ":", "l", ".", "r", ".", "Move", "(", "1", ")", "\n", "return", "LeftBraceToken", "\n", "case", "'}'", ":", "l", ".", "r", ".", "Move", "(", "1", ")", "\n", "return", "RightBraceToken", "\n", "}", "\n", "return", "ErrorToken", "\n", "}" ]
// consumeBracket consumes any bracket token.
[ "consumeBracket", "consumes", "any", "bracket", "token", "." ]
b8d8be7d83bf428ee370587d439137776d18362c
https://github.com/tdewolff/parse/blob/b8d8be7d83bf428ee370587d439137776d18362c/css/lex.go#L587-L609
12,266
tdewolff/parse
css/lex.go
consumeNumeric
func (l *Lexer) consumeNumeric() TokenType { if l.consumeNumberToken() { if l.consumeByte('%') { return PercentageToken } else if l.consumeIdentToken() { return DimensionToken } return NumberToken } return ErrorToken }
go
func (l *Lexer) consumeNumeric() TokenType { if l.consumeNumberToken() { if l.consumeByte('%') { return PercentageToken } else if l.consumeIdentToken() { return DimensionToken } return NumberToken } return ErrorToken }
[ "func", "(", "l", "*", "Lexer", ")", "consumeNumeric", "(", ")", "TokenType", "{", "if", "l", ".", "consumeNumberToken", "(", ")", "{", "if", "l", ".", "consumeByte", "(", "'%'", ")", "{", "return", "PercentageToken", "\n", "}", "else", "if", "l", ".", "consumeIdentToken", "(", ")", "{", "return", "DimensionToken", "\n", "}", "\n", "return", "NumberToken", "\n", "}", "\n", "return", "ErrorToken", "\n", "}" ]
// consumeNumeric consumes NumberToken, PercentageToken or DimensionToken.
[ "consumeNumeric", "consumes", "NumberToken", "PercentageToken", "or", "DimensionToken", "." ]
b8d8be7d83bf428ee370587d439137776d18362c
https://github.com/tdewolff/parse/blob/b8d8be7d83bf428ee370587d439137776d18362c/css/lex.go#L612-L622
12,267
tdewolff/parse
css/lex.go
consumeString
func (l *Lexer) consumeString() TokenType { // assume to be on " or ' delim := l.r.Peek(0) l.r.Move(1) for { c := l.r.Peek(0) if c == 0 && l.r.Err() != nil { break } else if c == '\n' || c == '\r' || c == '\f' { l.r.Move(1) return BadStringToken } else if c == delim { l.r.Move(1) break } else if c == '\\' { if !l.consumeEscape() { l.r.Move(1) l.consumeNewline() } } else { l.r.Move(1) } } return StringToken }
go
func (l *Lexer) consumeString() TokenType { // assume to be on " or ' delim := l.r.Peek(0) l.r.Move(1) for { c := l.r.Peek(0) if c == 0 && l.r.Err() != nil { break } else if c == '\n' || c == '\r' || c == '\f' { l.r.Move(1) return BadStringToken } else if c == delim { l.r.Move(1) break } else if c == '\\' { if !l.consumeEscape() { l.r.Move(1) l.consumeNewline() } } else { l.r.Move(1) } } return StringToken }
[ "func", "(", "l", "*", "Lexer", ")", "consumeString", "(", ")", "TokenType", "{", "// assume to be on \" or '", "delim", ":=", "l", ".", "r", ".", "Peek", "(", "0", ")", "\n", "l", ".", "r", ".", "Move", "(", "1", ")", "\n", "for", "{", "c", ":=", "l", ".", "r", ".", "Peek", "(", "0", ")", "\n", "if", "c", "==", "0", "&&", "l", ".", "r", ".", "Err", "(", ")", "!=", "nil", "{", "break", "\n", "}", "else", "if", "c", "==", "'\\n'", "||", "c", "==", "'\\r'", "||", "c", "==", "'\\f'", "{", "l", ".", "r", ".", "Move", "(", "1", ")", "\n", "return", "BadStringToken", "\n", "}", "else", "if", "c", "==", "delim", "{", "l", ".", "r", ".", "Move", "(", "1", ")", "\n", "break", "\n", "}", "else", "if", "c", "==", "'\\\\'", "{", "if", "!", "l", ".", "consumeEscape", "(", ")", "{", "l", ".", "r", ".", "Move", "(", "1", ")", "\n", "l", ".", "consumeNewline", "(", ")", "\n", "}", "\n", "}", "else", "{", "l", ".", "r", ".", "Move", "(", "1", ")", "\n", "}", "\n", "}", "\n", "return", "StringToken", "\n", "}" ]
// consumeString consumes a string and may return BadStringToken when a newline is encountered.
[ "consumeString", "consumes", "a", "string", "and", "may", "return", "BadStringToken", "when", "a", "newline", "is", "encountered", "." ]
b8d8be7d83bf428ee370587d439137776d18362c
https://github.com/tdewolff/parse/blob/b8d8be7d83bf428ee370587d439137776d18362c/css/lex.go#L625-L649
12,268
tdewolff/parse
css/lex.go
consumeRemnantsBadURL
func (l *Lexer) consumeRemnantsBadURL() { for { if l.consumeByte(')') || l.r.Err() != nil { break } else if !l.consumeEscape() { l.r.Move(1) } } }
go
func (l *Lexer) consumeRemnantsBadURL() { for { if l.consumeByte(')') || l.r.Err() != nil { break } else if !l.consumeEscape() { l.r.Move(1) } } }
[ "func", "(", "l", "*", "Lexer", ")", "consumeRemnantsBadURL", "(", ")", "{", "for", "{", "if", "l", ".", "consumeByte", "(", "')'", ")", "||", "l", ".", "r", ".", "Err", "(", ")", "!=", "nil", "{", "break", "\n", "}", "else", "if", "!", "l", ".", "consumeEscape", "(", ")", "{", "l", ".", "r", ".", "Move", "(", "1", ")", "\n", "}", "\n", "}", "\n", "}" ]
// consumeRemnantsBadUrl consumes bytes of a BadUrlToken so that normal tokenization may continue.
[ "consumeRemnantsBadUrl", "consumes", "bytes", "of", "a", "BadUrlToken", "so", "that", "normal", "tokenization", "may", "continue", "." ]
b8d8be7d83bf428ee370587d439137776d18362c
https://github.com/tdewolff/parse/blob/b8d8be7d83bf428ee370587d439137776d18362c/css/lex.go#L668-L676
12,269
tdewolff/parse
css/lex.go
consumeIdentlike
func (l *Lexer) consumeIdentlike() TokenType { if l.consumeIdentToken() { if l.r.Peek(0) != '(' { return IdentToken } else if !parse.EqualFold(bytes.Replace(l.r.Lexeme(), []byte{'\\'}, nil, -1), []byte{'u', 'r', 'l'}) { l.r.Move(1) return FunctionToken } l.r.Move(1) // consume url for l.consumeWhitespace() { } if c := l.r.Peek(0); c == '"' || c == '\'' { if l.consumeString() == BadStringToken { l.consumeRemnantsBadURL() return BadURLToken } } else if !l.consumeUnquotedURL() && !l.consumeWhitespace() { // if unquoted URL fails due to encountering whitespace, continue l.consumeRemnantsBadURL() return BadURLToken } for l.consumeWhitespace() { } if !l.consumeByte(')') && l.r.Err() != io.EOF { l.consumeRemnantsBadURL() return BadURLToken } return URLToken } return ErrorToken }
go
func (l *Lexer) consumeIdentlike() TokenType { if l.consumeIdentToken() { if l.r.Peek(0) != '(' { return IdentToken } else if !parse.EqualFold(bytes.Replace(l.r.Lexeme(), []byte{'\\'}, nil, -1), []byte{'u', 'r', 'l'}) { l.r.Move(1) return FunctionToken } l.r.Move(1) // consume url for l.consumeWhitespace() { } if c := l.r.Peek(0); c == '"' || c == '\'' { if l.consumeString() == BadStringToken { l.consumeRemnantsBadURL() return BadURLToken } } else if !l.consumeUnquotedURL() && !l.consumeWhitespace() { // if unquoted URL fails due to encountering whitespace, continue l.consumeRemnantsBadURL() return BadURLToken } for l.consumeWhitespace() { } if !l.consumeByte(')') && l.r.Err() != io.EOF { l.consumeRemnantsBadURL() return BadURLToken } return URLToken } return ErrorToken }
[ "func", "(", "l", "*", "Lexer", ")", "consumeIdentlike", "(", ")", "TokenType", "{", "if", "l", ".", "consumeIdentToken", "(", ")", "{", "if", "l", ".", "r", ".", "Peek", "(", "0", ")", "!=", "'('", "{", "return", "IdentToken", "\n", "}", "else", "if", "!", "parse", ".", "EqualFold", "(", "bytes", ".", "Replace", "(", "l", ".", "r", ".", "Lexeme", "(", ")", ",", "[", "]", "byte", "{", "'\\\\'", "}", ",", "nil", ",", "-", "1", ")", ",", "[", "]", "byte", "{", "'u'", ",", "'r'", ",", "'l'", "}", ")", "{", "l", ".", "r", ".", "Move", "(", "1", ")", "\n", "return", "FunctionToken", "\n", "}", "\n", "l", ".", "r", ".", "Move", "(", "1", ")", "\n\n", "// consume url", "for", "l", ".", "consumeWhitespace", "(", ")", "{", "}", "\n", "if", "c", ":=", "l", ".", "r", ".", "Peek", "(", "0", ")", ";", "c", "==", "'\"'", "||", "c", "==", "'\\''", "{", "if", "l", ".", "consumeString", "(", ")", "==", "BadStringToken", "{", "l", ".", "consumeRemnantsBadURL", "(", ")", "\n", "return", "BadURLToken", "\n", "}", "\n", "}", "else", "if", "!", "l", ".", "consumeUnquotedURL", "(", ")", "&&", "!", "l", ".", "consumeWhitespace", "(", ")", "{", "// if unquoted URL fails due to encountering whitespace, continue", "l", ".", "consumeRemnantsBadURL", "(", ")", "\n", "return", "BadURLToken", "\n", "}", "\n", "for", "l", ".", "consumeWhitespace", "(", ")", "{", "}", "\n", "if", "!", "l", ".", "consumeByte", "(", "')'", ")", "&&", "l", ".", "r", ".", "Err", "(", ")", "!=", "io", ".", "EOF", "{", "l", ".", "consumeRemnantsBadURL", "(", ")", "\n", "return", "BadURLToken", "\n", "}", "\n", "return", "URLToken", "\n", "}", "\n", "return", "ErrorToken", "\n", "}" ]
// consumeIdentlike consumes IdentToken, FunctionToken or UrlToken.
[ "consumeIdentlike", "consumes", "IdentToken", "FunctionToken", "or", "UrlToken", "." ]
b8d8be7d83bf428ee370587d439137776d18362c
https://github.com/tdewolff/parse/blob/b8d8be7d83bf428ee370587d439137776d18362c/css/lex.go#L679-L710
12,270
tdewolff/parse
json/parse.go
String
func (state State) String() string { switch state { case ValueState: return "Value" case ObjectKeyState: return "ObjectKey" case ObjectValueState: return "ObjectValue" case ArrayState: return "Array" } return "Invalid(" + strconv.Itoa(int(state)) + ")" }
go
func (state State) String() string { switch state { case ValueState: return "Value" case ObjectKeyState: return "ObjectKey" case ObjectValueState: return "ObjectValue" case ArrayState: return "Array" } return "Invalid(" + strconv.Itoa(int(state)) + ")" }
[ "func", "(", "state", "State", ")", "String", "(", ")", "string", "{", "switch", "state", "{", "case", "ValueState", ":", "return", "\"", "\"", "\n", "case", "ObjectKeyState", ":", "return", "\"", "\"", "\n", "case", "ObjectValueState", ":", "return", "\"", "\"", "\n", "case", "ArrayState", ":", "return", "\"", "\"", "\n", "}", "\n", "return", "\"", "\"", "+", "strconv", ".", "Itoa", "(", "int", "(", "state", ")", ")", "+", "\"", "\"", "\n", "}" ]
// String returns the string representation of a State.
[ "String", "returns", "the", "string", "representation", "of", "a", "State", "." ]
b8d8be7d83bf428ee370587d439137776d18362c
https://github.com/tdewolff/parse/blob/b8d8be7d83bf428ee370587d439137776d18362c/json/parse.go#L67-L79
12,271
tdewolff/parse
json/parse.go
NewParser
func NewParser(r io.Reader) *Parser { return &Parser{ r: buffer.NewLexer(r), state: []State{ValueState}, } }
go
func NewParser(r io.Reader) *Parser { return &Parser{ r: buffer.NewLexer(r), state: []State{ValueState}, } }
[ "func", "NewParser", "(", "r", "io", ".", "Reader", ")", "*", "Parser", "{", "return", "&", "Parser", "{", "r", ":", "buffer", ".", "NewLexer", "(", "r", ")", ",", "state", ":", "[", "]", "State", "{", "ValueState", "}", ",", "}", "\n", "}" ]
// NewParser returns a new Parser for a given io.Reader.
[ "NewParser", "returns", "a", "new", "Parser", "for", "a", "given", "io", ".", "Reader", "." ]
b8d8be7d83bf428ee370587d439137776d18362c
https://github.com/tdewolff/parse/blob/b8d8be7d83bf428ee370587d439137776d18362c/json/parse.go#L93-L98
12,272
tdewolff/parse
json/parse.go
Err
func (p *Parser) Err() error { if p.err != nil { return p.err } return p.r.Err() }
go
func (p *Parser) Err() error { if p.err != nil { return p.err } return p.r.Err() }
[ "func", "(", "p", "*", "Parser", ")", "Err", "(", ")", "error", "{", "if", "p", ".", "err", "!=", "nil", "{", "return", "p", ".", "err", "\n", "}", "\n", "return", "p", ".", "r", ".", "Err", "(", ")", "\n", "}" ]
// Err returns the error encountered during tokenization, this is often io.EOF but also other errors can be returned.
[ "Err", "returns", "the", "error", "encountered", "during", "tokenization", "this", "is", "often", "io", ".", "EOF", "but", "also", "other", "errors", "can", "be", "returned", "." ]
b8d8be7d83bf428ee370587d439137776d18362c
https://github.com/tdewolff/parse/blob/b8d8be7d83bf428ee370587d439137776d18362c/json/parse.go#L101-L106
12,273
tdewolff/parse
html/util.go
EscapeAttrVal
func EscapeAttrVal(buf *[]byte, orig, b []byte, isXML bool) []byte { singles := 0 doubles := 0 unquoted := true entities := false for i, c := range b { if charTable[c] { if c == '&' { entities = true if quote, n := parse.QuoteEntity(b[i:]); n > 0 { if quote == '"' { unquoted = false doubles++ } else { unquoted = false singles++ } } } else { unquoted = false if c == '"' { doubles++ } else if c == '\'' { singles++ } } } } if unquoted && !isXML { return b } else if !entities && len(orig) == len(b)+2 && (singles == 0 && orig[0] == '\'' || doubles == 0 && orig[0] == '"') { return orig } n := len(b) + 2 var quote byte var escapedQuote []byte if singles >= doubles || isXML { n += doubles * 4 quote = '"' escapedQuote = doubleQuoteEntityBytes } else { n += singles * 4 quote = '\'' escapedQuote = singleQuoteEntityBytes } if n > cap(*buf) { *buf = make([]byte, 0, n) // maximum size, not actual size } t := (*buf)[:n] // maximum size, not actual size t[0] = quote j := 1 start := 0 for i, c := range b { if c == '&' { if entityQuote, n := parse.QuoteEntity(b[i:]); n > 0 { j += copy(t[j:], b[start:i]) if entityQuote != quote { t[j] = entityQuote j++ } else { j += copy(t[j:], escapedQuote) } start = i + n } } else if c == quote { j += copy(t[j:], b[start:i]) j += copy(t[j:], escapedQuote) start = i + 1 } } j += copy(t[j:], b[start:]) t[j] = quote return t[:j+1] }
go
func EscapeAttrVal(buf *[]byte, orig, b []byte, isXML bool) []byte { singles := 0 doubles := 0 unquoted := true entities := false for i, c := range b { if charTable[c] { if c == '&' { entities = true if quote, n := parse.QuoteEntity(b[i:]); n > 0 { if quote == '"' { unquoted = false doubles++ } else { unquoted = false singles++ } } } else { unquoted = false if c == '"' { doubles++ } else if c == '\'' { singles++ } } } } if unquoted && !isXML { return b } else if !entities && len(orig) == len(b)+2 && (singles == 0 && orig[0] == '\'' || doubles == 0 && orig[0] == '"') { return orig } n := len(b) + 2 var quote byte var escapedQuote []byte if singles >= doubles || isXML { n += doubles * 4 quote = '"' escapedQuote = doubleQuoteEntityBytes } else { n += singles * 4 quote = '\'' escapedQuote = singleQuoteEntityBytes } if n > cap(*buf) { *buf = make([]byte, 0, n) // maximum size, not actual size } t := (*buf)[:n] // maximum size, not actual size t[0] = quote j := 1 start := 0 for i, c := range b { if c == '&' { if entityQuote, n := parse.QuoteEntity(b[i:]); n > 0 { j += copy(t[j:], b[start:i]) if entityQuote != quote { t[j] = entityQuote j++ } else { j += copy(t[j:], escapedQuote) } start = i + n } } else if c == quote { j += copy(t[j:], b[start:i]) j += copy(t[j:], escapedQuote) start = i + 1 } } j += copy(t[j:], b[start:]) t[j] = quote return t[:j+1] }
[ "func", "EscapeAttrVal", "(", "buf", "*", "[", "]", "byte", ",", "orig", ",", "b", "[", "]", "byte", ",", "isXML", "bool", ")", "[", "]", "byte", "{", "singles", ":=", "0", "\n", "doubles", ":=", "0", "\n", "unquoted", ":=", "true", "\n", "entities", ":=", "false", "\n", "for", "i", ",", "c", ":=", "range", "b", "{", "if", "charTable", "[", "c", "]", "{", "if", "c", "==", "'&'", "{", "entities", "=", "true", "\n", "if", "quote", ",", "n", ":=", "parse", ".", "QuoteEntity", "(", "b", "[", "i", ":", "]", ")", ";", "n", ">", "0", "{", "if", "quote", "==", "'\"'", "{", "unquoted", "=", "false", "\n", "doubles", "++", "\n", "}", "else", "{", "unquoted", "=", "false", "\n", "singles", "++", "\n", "}", "\n", "}", "\n", "}", "else", "{", "unquoted", "=", "false", "\n", "if", "c", "==", "'\"'", "{", "doubles", "++", "\n", "}", "else", "if", "c", "==", "'\\''", "{", "singles", "++", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "if", "unquoted", "&&", "!", "isXML", "{", "return", "b", "\n", "}", "else", "if", "!", "entities", "&&", "len", "(", "orig", ")", "==", "len", "(", "b", ")", "+", "2", "&&", "(", "singles", "==", "0", "&&", "orig", "[", "0", "]", "==", "'\\''", "||", "doubles", "==", "0", "&&", "orig", "[", "0", "]", "==", "'\"'", ")", "{", "return", "orig", "\n", "}", "\n\n", "n", ":=", "len", "(", "b", ")", "+", "2", "\n", "var", "quote", "byte", "\n", "var", "escapedQuote", "[", "]", "byte", "\n", "if", "singles", ">=", "doubles", "||", "isXML", "{", "n", "+=", "doubles", "*", "4", "\n", "quote", "=", "'\"'", "\n", "escapedQuote", "=", "doubleQuoteEntityBytes", "\n", "}", "else", "{", "n", "+=", "singles", "*", "4", "\n", "quote", "=", "'\\''", "\n", "escapedQuote", "=", "singleQuoteEntityBytes", "\n", "}", "\n", "if", "n", ">", "cap", "(", "*", "buf", ")", "{", "*", "buf", "=", "make", "(", "[", "]", "byte", ",", "0", ",", "n", ")", "// maximum size, not actual size", "\n", "}", "\n", "t", ":=", "(", "*", "buf", ")", "[", ":", "n", "]", "// maximum size, not actual size", "\n", "t", "[", "0", "]", "=", "quote", "\n", "j", ":=", "1", "\n", "start", ":=", "0", "\n", "for", "i", ",", "c", ":=", "range", "b", "{", "if", "c", "==", "'&'", "{", "if", "entityQuote", ",", "n", ":=", "parse", ".", "QuoteEntity", "(", "b", "[", "i", ":", "]", ")", ";", "n", ">", "0", "{", "j", "+=", "copy", "(", "t", "[", "j", ":", "]", ",", "b", "[", "start", ":", "i", "]", ")", "\n", "if", "entityQuote", "!=", "quote", "{", "t", "[", "j", "]", "=", "entityQuote", "\n", "j", "++", "\n", "}", "else", "{", "j", "+=", "copy", "(", "t", "[", "j", ":", "]", ",", "escapedQuote", ")", "\n", "}", "\n", "start", "=", "i", "+", "n", "\n", "}", "\n", "}", "else", "if", "c", "==", "quote", "{", "j", "+=", "copy", "(", "t", "[", "j", ":", "]", ",", "b", "[", "start", ":", "i", "]", ")", "\n", "j", "+=", "copy", "(", "t", "[", "j", ":", "]", ",", "escapedQuote", ")", "\n", "start", "=", "i", "+", "1", "\n", "}", "\n", "}", "\n", "j", "+=", "copy", "(", "t", "[", "j", ":", "]", ",", "b", "[", "start", ":", "]", ")", "\n", "t", "[", "j", "]", "=", "quote", "\n", "return", "t", "[", ":", "j", "+", "1", "]", "\n", "}" ]
// EscapeAttrVal returns the escaped attribute value bytes without quotes.
[ "EscapeAttrVal", "returns", "the", "escaped", "attribute", "value", "bytes", "without", "quotes", "." ]
b8d8be7d83bf428ee370587d439137776d18362c
https://github.com/tdewolff/parse/blob/b8d8be7d83bf428ee370587d439137776d18362c/html/util.go#L55-L129
12,274
peco/peco
keymap.go
NewKeymap
func NewKeymap(config map[string]string, actions map[string][]string) Keymap { return Keymap{ Config: config, Action: actions, seq: keyseq.New(), } }
go
func NewKeymap(config map[string]string, actions map[string][]string) Keymap { return Keymap{ Config: config, Action: actions, seq: keyseq.New(), } }
[ "func", "NewKeymap", "(", "config", "map", "[", "string", "]", "string", ",", "actions", "map", "[", "string", "]", "[", "]", "string", ")", "Keymap", "{", "return", "Keymap", "{", "Config", ":", "config", ",", "Action", ":", "actions", ",", "seq", ":", "keyseq", ".", "New", "(", ")", ",", "}", "\n", "}" ]
// NewKeymap creates a new Keymap struct
[ "NewKeymap", "creates", "a", "new", "Keymap", "struct" ]
967233e25328cb5d7065a5abb23cc8ed650a09b6
https://github.com/peco/peco/blob/967233e25328cb5d7065a5abb23cc8ed650a09b6/keymap.go#L15-L21
12,275
peco/peco
keymap.go
LookupAction
func (km Keymap) LookupAction(ev termbox.Event) Action { modifier := keyseq.ModNone if (ev.Mod & termbox.ModAlt) != 0 { modifier = keyseq.ModAlt } key := keyseq.Key{ Modifier: modifier, Key: ev.Key, Ch: ev.Ch, } action, err := km.seq.AcceptKey(key) switch err { case nil: // Found an action! if pdebug.Enabled { pdebug.Printf("Keymap.Handler: Fetched action") } return wrapClearSequence(action.(Action)) case keyseq.ErrInSequence: if pdebug.Enabled { pdebug.Printf("Keymap.Handler: Waiting for more commands...") } return wrapRememberSequence(ActionFunc(doNothing)) default: if pdebug.Enabled { pdebug.Printf("Keymap.Handler: Defaulting to doAcceptChar") } return wrapClearSequence(ActionFunc(doAcceptChar)) } }
go
func (km Keymap) LookupAction(ev termbox.Event) Action { modifier := keyseq.ModNone if (ev.Mod & termbox.ModAlt) != 0 { modifier = keyseq.ModAlt } key := keyseq.Key{ Modifier: modifier, Key: ev.Key, Ch: ev.Ch, } action, err := km.seq.AcceptKey(key) switch err { case nil: // Found an action! if pdebug.Enabled { pdebug.Printf("Keymap.Handler: Fetched action") } return wrapClearSequence(action.(Action)) case keyseq.ErrInSequence: if pdebug.Enabled { pdebug.Printf("Keymap.Handler: Waiting for more commands...") } return wrapRememberSequence(ActionFunc(doNothing)) default: if pdebug.Enabled { pdebug.Printf("Keymap.Handler: Defaulting to doAcceptChar") } return wrapClearSequence(ActionFunc(doAcceptChar)) } }
[ "func", "(", "km", "Keymap", ")", "LookupAction", "(", "ev", "termbox", ".", "Event", ")", "Action", "{", "modifier", ":=", "keyseq", ".", "ModNone", "\n", "if", "(", "ev", ".", "Mod", "&", "termbox", ".", "ModAlt", ")", "!=", "0", "{", "modifier", "=", "keyseq", ".", "ModAlt", "\n", "}", "\n\n", "key", ":=", "keyseq", ".", "Key", "{", "Modifier", ":", "modifier", ",", "Key", ":", "ev", ".", "Key", ",", "Ch", ":", "ev", ".", "Ch", ",", "}", "\n", "action", ",", "err", ":=", "km", ".", "seq", ".", "AcceptKey", "(", "key", ")", "\n\n", "switch", "err", "{", "case", "nil", ":", "// Found an action!", "if", "pdebug", ".", "Enabled", "{", "pdebug", ".", "Printf", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "wrapClearSequence", "(", "action", ".", "(", "Action", ")", ")", "\n", "case", "keyseq", ".", "ErrInSequence", ":", "if", "pdebug", ".", "Enabled", "{", "pdebug", ".", "Printf", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "wrapRememberSequence", "(", "ActionFunc", "(", "doNothing", ")", ")", "\n", "default", ":", "if", "pdebug", ".", "Enabled", "{", "pdebug", ".", "Printf", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "wrapClearSequence", "(", "ActionFunc", "(", "doAcceptChar", ")", ")", "\n", "}", "\n", "}" ]
// LookupAction returns the appropriate action for the given termbox event
[ "LookupAction", "returns", "the", "appropriate", "action", "for", "the", "given", "termbox", "event" ]
967233e25328cb5d7065a5abb23cc8ed650a09b6
https://github.com/peco/peco/blob/967233e25328cb5d7065a5abb23cc8ed650a09b6/keymap.go#L46-L77
12,276
peco/peco
keymap.go
ApplyKeybinding
func (km *Keymap) ApplyKeybinding() error { k := km.seq k.Clear() // Copy the map kb := map[string]Action{} for s, a := range defaultKeyBinding { kb[s] = a } // munge the map using config for s, as := range km.Config { if as == "-" { delete(kb, s) continue } v, err := km.resolveActionName(as, 0) if err != nil { return errors.Wrapf(err, "failed to resolve action name %s", as) } kb[s] = v } // now compile using kb // there's no need to do this, but we sort keys here just to make // debugging easier keys := make([]string, 0, len(kb)) for s := range kb { keys = append(keys, s) } sort.Strings(keys) for _, s := range keys { a := kb[s] list, err := keyseq.ToKeyList(s) if err != nil { return errors.Wrapf(err, "urnknown key %s: %s", s, err) } k.Add(list, a) } return errors.Wrap(k.Compile(), "failed to compile key binding patterns") }
go
func (km *Keymap) ApplyKeybinding() error { k := km.seq k.Clear() // Copy the map kb := map[string]Action{} for s, a := range defaultKeyBinding { kb[s] = a } // munge the map using config for s, as := range km.Config { if as == "-" { delete(kb, s) continue } v, err := km.resolveActionName(as, 0) if err != nil { return errors.Wrapf(err, "failed to resolve action name %s", as) } kb[s] = v } // now compile using kb // there's no need to do this, but we sort keys here just to make // debugging easier keys := make([]string, 0, len(kb)) for s := range kb { keys = append(keys, s) } sort.Strings(keys) for _, s := range keys { a := kb[s] list, err := keyseq.ToKeyList(s) if err != nil { return errors.Wrapf(err, "urnknown key %s: %s", s, err) } k.Add(list, a) } return errors.Wrap(k.Compile(), "failed to compile key binding patterns") }
[ "func", "(", "km", "*", "Keymap", ")", "ApplyKeybinding", "(", ")", "error", "{", "k", ":=", "km", ".", "seq", "\n", "k", ".", "Clear", "(", ")", "\n\n", "// Copy the map", "kb", ":=", "map", "[", "string", "]", "Action", "{", "}", "\n", "for", "s", ",", "a", ":=", "range", "defaultKeyBinding", "{", "kb", "[", "s", "]", "=", "a", "\n", "}", "\n\n", "// munge the map using config", "for", "s", ",", "as", ":=", "range", "km", ".", "Config", "{", "if", "as", "==", "\"", "\"", "{", "delete", "(", "kb", ",", "s", ")", "\n", "continue", "\n", "}", "\n\n", "v", ",", "err", ":=", "km", ".", "resolveActionName", "(", "as", ",", "0", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "as", ")", "\n", "}", "\n", "kb", "[", "s", "]", "=", "v", "\n", "}", "\n\n", "// now compile using kb", "// there's no need to do this, but we sort keys here just to make", "// debugging easier", "keys", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "kb", ")", ")", "\n", "for", "s", ":=", "range", "kb", "{", "keys", "=", "append", "(", "keys", ",", "s", ")", "\n", "}", "\n", "sort", ".", "Strings", "(", "keys", ")", "\n\n", "for", "_", ",", "s", ":=", "range", "keys", "{", "a", ":=", "kb", "[", "s", "]", "\n", "list", ",", "err", ":=", "keyseq", ".", "ToKeyList", "(", "s", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errors", ".", "Wrapf", "(", "err", ",", "\"", "\"", ",", "s", ",", "err", ")", "\n", "}", "\n\n", "k", ".", "Add", "(", "list", ",", "a", ")", "\n", "}", "\n\n", "return", "errors", ".", "Wrap", "(", "k", ".", "Compile", "(", ")", ",", "\"", "\"", ")", "\n", "}" ]
// ApplyKeybinding applies all of the custom key bindings on top of // the default key bindings
[ "ApplyKeybinding", "applies", "all", "of", "the", "custom", "key", "bindings", "on", "top", "of", "the", "default", "key", "bindings" ]
967233e25328cb5d7065a5abb23cc8ed650a09b6
https://github.com/peco/peco/blob/967233e25328cb5d7065a5abb23cc8ed650a09b6/keymap.go#L141-L185
12,277
peco/peco
buffer.go
LineAt
func (flb FilteredBuffer) LineAt(i int) (line.Line, error) { if i >= len(flb.selection) { return nil, errors.Errorf("specified index %d is out of range", len(flb.selection)) } return flb.src.LineAt(flb.selection[i]) }
go
func (flb FilteredBuffer) LineAt(i int) (line.Line, error) { if i >= len(flb.selection) { return nil, errors.Errorf("specified index %d is out of range", len(flb.selection)) } return flb.src.LineAt(flb.selection[i]) }
[ "func", "(", "flb", "FilteredBuffer", ")", "LineAt", "(", "i", "int", ")", "(", "line", ".", "Line", ",", "error", ")", "{", "if", "i", ">=", "len", "(", "flb", ".", "selection", ")", "{", "return", "nil", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "len", "(", "flb", ".", "selection", ")", ")", "\n", "}", "\n", "return", "flb", ".", "src", ".", "LineAt", "(", "flb", ".", "selection", "[", "i", "]", ")", "\n", "}" ]
// LineAt returns the line at index `i`. Note that the i-th element // in this filtered buffer may actually correspond to a totally // different line number in the source buffer.
[ "LineAt", "returns", "the", "line", "at", "index", "i", ".", "Note", "that", "the", "i", "-", "th", "element", "in", "this", "filtered", "buffer", "may", "actually", "correspond", "to", "a", "totally", "different", "line", "number", "in", "the", "source", "buffer", "." ]
967233e25328cb5d7065a5abb23cc8ed650a09b6
https://github.com/peco/peco/blob/967233e25328cb5d7065a5abb23cc8ed650a09b6/buffer.go#L60-L65
12,278
peco/peco
internal/keyseq/keys.go
EventToString
func EventToString(ev termbox.Event) (string, error) { s := "" if ev.Key == 0 { s = string([]rune{ev.Ch}) } else { var ok bool s, ok = keyToString[ev.Key] if !ok { return "", errors.Errorf("no such key %#v", ev) } // Special case for ArrowUp/Down/Left/Right switch s { case "ArrowUp": s = "^" case "ArrowDown": s = "v" case "ArrowLeft": s = "<" case "ArrowRight": s = ">" } } if ev.Mod&termbox.ModAlt == 1 { return "M-" + s, nil } return s, nil }
go
func EventToString(ev termbox.Event) (string, error) { s := "" if ev.Key == 0 { s = string([]rune{ev.Ch}) } else { var ok bool s, ok = keyToString[ev.Key] if !ok { return "", errors.Errorf("no such key %#v", ev) } // Special case for ArrowUp/Down/Left/Right switch s { case "ArrowUp": s = "^" case "ArrowDown": s = "v" case "ArrowLeft": s = "<" case "ArrowRight": s = ">" } } if ev.Mod&termbox.ModAlt == 1 { return "M-" + s, nil } return s, nil }
[ "func", "EventToString", "(", "ev", "termbox", ".", "Event", ")", "(", "string", ",", "error", ")", "{", "s", ":=", "\"", "\"", "\n", "if", "ev", ".", "Key", "==", "0", "{", "s", "=", "string", "(", "[", "]", "rune", "{", "ev", ".", "Ch", "}", ")", "\n", "}", "else", "{", "var", "ok", "bool", "\n", "s", ",", "ok", "=", "keyToString", "[", "ev", ".", "Key", "]", "\n", "if", "!", "ok", "{", "return", "\"", "\"", ",", "errors", ".", "Errorf", "(", "\"", "\"", ",", "ev", ")", "\n", "}", "\n\n", "// Special case for ArrowUp/Down/Left/Right", "switch", "s", "{", "case", "\"", "\"", ":", "s", "=", "\"", "\"", "\n", "case", "\"", "\"", ":", "s", "=", "\"", "\"", "\n", "case", "\"", "\"", ":", "s", "=", "\"", "\"", "\n", "case", "\"", "\"", ":", "s", "=", "\"", "\"", "\n", "}", "\n", "}", "\n\n", "if", "ev", ".", "Mod", "&", "termbox", ".", "ModAlt", "==", "1", "{", "return", "\"", "\"", "+", "s", ",", "nil", "\n", "}", "\n\n", "return", "s", ",", "nil", "\n", "}" ]
// EventToString returns human readable name for a given termbox.Event
[ "EventToString", "returns", "human", "readable", "name", "for", "a", "given", "termbox", ".", "Event" ]
967233e25328cb5d7065a5abb23cc8ed650a09b6
https://github.com/peco/peco/blob/967233e25328cb5d7065a5abb23cc8ed650a09b6/internal/keyseq/keys.go#L125-L154
12,279
peco/peco
filter/external.go
NewExternalCmd
func NewExternalCmd(name string, cmd string, args []string, threshold int, idgen line.IDGenerator, enableSep bool) *ExternalCmd { if len(args) == 0 { args = []string{"$QUERY"} } if threshold <= 0 { threshold = DefaultCustomFilterBufferThreshold } return &ExternalCmd{ args: args, cmd: cmd, enableSep: enableSep, idgen: idgen, name: name, outCh: pipeline.ChanOutput(make(chan interface{})), thresholdBufsiz: threshold, } }
go
func NewExternalCmd(name string, cmd string, args []string, threshold int, idgen line.IDGenerator, enableSep bool) *ExternalCmd { if len(args) == 0 { args = []string{"$QUERY"} } if threshold <= 0 { threshold = DefaultCustomFilterBufferThreshold } return &ExternalCmd{ args: args, cmd: cmd, enableSep: enableSep, idgen: idgen, name: name, outCh: pipeline.ChanOutput(make(chan interface{})), thresholdBufsiz: threshold, } }
[ "func", "NewExternalCmd", "(", "name", "string", ",", "cmd", "string", ",", "args", "[", "]", "string", ",", "threshold", "int", ",", "idgen", "line", ".", "IDGenerator", ",", "enableSep", "bool", ")", "*", "ExternalCmd", "{", "if", "len", "(", "args", ")", "==", "0", "{", "args", "=", "[", "]", "string", "{", "\"", "\"", "}", "\n", "}", "\n\n", "if", "threshold", "<=", "0", "{", "threshold", "=", "DefaultCustomFilterBufferThreshold", "\n", "}", "\n\n", "return", "&", "ExternalCmd", "{", "args", ":", "args", ",", "cmd", ":", "cmd", ",", "enableSep", ":", "enableSep", ",", "idgen", ":", "idgen", ",", "name", ":", "name", ",", "outCh", ":", "pipeline", ".", "ChanOutput", "(", "make", "(", "chan", "interface", "{", "}", ")", ")", ",", "thresholdBufsiz", ":", "threshold", ",", "}", "\n", "}" ]
// NewExternalCmd creates a new filter that uses an external // command to filter the input
[ "NewExternalCmd", "creates", "a", "new", "filter", "that", "uses", "an", "external", "command", "to", "filter", "the", "input" ]
967233e25328cb5d7065a5abb23cc8ed650a09b6
https://github.com/peco/peco/blob/967233e25328cb5d7065a5abb23cc8ed650a09b6/filter/external.go#L17-L35
12,280
peco/peco
hub/hub.go
New
func New(bufsiz int) *Hub { return &Hub{ isSync: false, queryCh: make(chan Payload, bufsiz), drawCh: make(chan Payload, bufsiz), statusMsgCh: make(chan Payload, bufsiz), pagingCh: make(chan Payload, bufsiz), } }
go
func New(bufsiz int) *Hub { return &Hub{ isSync: false, queryCh: make(chan Payload, bufsiz), drawCh: make(chan Payload, bufsiz), statusMsgCh: make(chan Payload, bufsiz), pagingCh: make(chan Payload, bufsiz), } }
[ "func", "New", "(", "bufsiz", "int", ")", "*", "Hub", "{", "return", "&", "Hub", "{", "isSync", ":", "false", ",", "queryCh", ":", "make", "(", "chan", "Payload", ",", "bufsiz", ")", ",", "drawCh", ":", "make", "(", "chan", "Payload", ",", "bufsiz", ")", ",", "statusMsgCh", ":", "make", "(", "chan", "Payload", ",", "bufsiz", ")", ",", "pagingCh", ":", "make", "(", "chan", "Payload", ",", "bufsiz", ")", ",", "}", "\n", "}" ]
// NewHub creates a new Hub struct
[ "NewHub", "creates", "a", "new", "Hub", "struct" ]
967233e25328cb5d7065a5abb23cc8ed650a09b6
https://github.com/peco/peco/blob/967233e25328cb5d7065a5abb23cc8ed650a09b6/hub/hub.go#L30-L38
12,281
peco/peco
hub/hub.go
send
func send(ch chan Payload, r *payload, needReply bool) { if needReply { r.done = make(chan struct{}) defer func() { <-r.done }() } ch <- r }
go
func send(ch chan Payload, r *payload, needReply bool) { if needReply { r.done = make(chan struct{}) defer func() { <-r.done }() } ch <- r }
[ "func", "send", "(", "ch", "chan", "Payload", ",", "r", "*", "payload", ",", "needReply", "bool", ")", "{", "if", "needReply", "{", "r", ".", "done", "=", "make", "(", "chan", "struct", "{", "}", ")", "\n", "defer", "func", "(", ")", "{", "<-", "r", ".", "done", "}", "(", ")", "\n", "}", "\n\n", "ch", "<-", "r", "\n", "}" ]
// low-level utility
[ "low", "-", "level", "utility" ]
967233e25328cb5d7065a5abb23cc8ed650a09b6
https://github.com/peco/peco/blob/967233e25328cb5d7065a5abb23cc8ed650a09b6/hub/hub.go#L65-L72
12,282
peco/peco
hub/hub.go
SendQuery
func (h *Hub) SendQuery(q string) { send(h.QueryCh(), NewPayload(q), h.isSync) }
go
func (h *Hub) SendQuery(q string) { send(h.QueryCh(), NewPayload(q), h.isSync) }
[ "func", "(", "h", "*", "Hub", ")", "SendQuery", "(", "q", "string", ")", "{", "send", "(", "h", ".", "QueryCh", "(", ")", ",", "NewPayload", "(", "q", ")", ",", "h", ".", "isSync", ")", "\n", "}" ]
// SendQuery sends the query string to be processed by the Filter
[ "SendQuery", "sends", "the", "query", "string", "to", "be", "processed", "by", "the", "Filter" ]
967233e25328cb5d7065a5abb23cc8ed650a09b6
https://github.com/peco/peco/blob/967233e25328cb5d7065a5abb23cc8ed650a09b6/hub/hub.go#L80-L82
12,283
peco/peco
hub/hub.go
SendDraw
func (h *Hub) SendDraw(options interface{}) { pdebug.Printf("START Hub.SendDraw %v", options) defer pdebug.Printf("END Hub.SendDraw %v", options) send(h.DrawCh(), NewPayload(options), h.isSync) }
go
func (h *Hub) SendDraw(options interface{}) { pdebug.Printf("START Hub.SendDraw %v", options) defer pdebug.Printf("END Hub.SendDraw %v", options) send(h.DrawCh(), NewPayload(options), h.isSync) }
[ "func", "(", "h", "*", "Hub", ")", "SendDraw", "(", "options", "interface", "{", "}", ")", "{", "pdebug", ".", "Printf", "(", "\"", "\"", ",", "options", ")", "\n", "defer", "pdebug", ".", "Printf", "(", "\"", "\"", ",", "options", ")", "\n", "send", "(", "h", ".", "DrawCh", "(", ")", ",", "NewPayload", "(", "options", ")", ",", "h", ".", "isSync", ")", "\n", "}" ]
// SendDraw sends a request to redraw the terminal display
[ "SendDraw", "sends", "a", "request", "to", "redraw", "the", "terminal", "display" ]
967233e25328cb5d7065a5abb23cc8ed650a09b6
https://github.com/peco/peco/blob/967233e25328cb5d7065a5abb23cc8ed650a09b6/hub/hub.go#L95-L99
12,284
peco/peco
hub/hub.go
SendStatusMsgAndClear
func (h *Hub) SendStatusMsgAndClear(q string, clearDelay time.Duration) { msg := newStatusMsgReq(q, clearDelay) send(h.StatusMsgCh(), NewPayload(msg), h.isSync) }
go
func (h *Hub) SendStatusMsgAndClear(q string, clearDelay time.Duration) { msg := newStatusMsgReq(q, clearDelay) send(h.StatusMsgCh(), NewPayload(msg), h.isSync) }
[ "func", "(", "h", "*", "Hub", ")", "SendStatusMsgAndClear", "(", "q", "string", ",", "clearDelay", "time", ".", "Duration", ")", "{", "msg", ":=", "newStatusMsgReq", "(", "q", ",", "clearDelay", ")", "\n", "send", "(", "h", ".", "StatusMsgCh", "(", ")", ",", "NewPayload", "(", "msg", ")", ",", "h", ".", "isSync", ")", "\n", "}" ]
// SendStatusMsgAndClear sends a string to be displayed in the status message, // as well as a delay until the message should be cleared
[ "SendStatusMsgAndClear", "sends", "a", "string", "to", "be", "displayed", "in", "the", "status", "message", "as", "well", "as", "a", "delay", "until", "the", "message", "should", "be", "cleared" ]
967233e25328cb5d7065a5abb23cc8ed650a09b6
https://github.com/peco/peco/blob/967233e25328cb5d7065a5abb23cc8ed650a09b6/hub/hub.go#L133-L136
12,285
peco/peco
hub/hub.go
SendPaging
func (h *Hub) SendPaging(x interface{}) { send(h.PagingCh(), NewPayload(x), h.isSync) }
go
func (h *Hub) SendPaging(x interface{}) { send(h.PagingCh(), NewPayload(x), h.isSync) }
[ "func", "(", "h", "*", "Hub", ")", "SendPaging", "(", "x", "interface", "{", "}", ")", "{", "send", "(", "h", ".", "PagingCh", "(", ")", ",", "NewPayload", "(", "x", ")", ",", "h", ".", "isSync", ")", "\n", "}" ]
// SendPaging sends a request to move the cursor around
[ "SendPaging", "sends", "a", "request", "to", "move", "the", "cursor", "around" ]
967233e25328cb5d7065a5abb23cc8ed650a09b6
https://github.com/peco/peco/blob/967233e25328cb5d7065a5abb23cc8ed650a09b6/hub/hub.go#L148-L150
12,286
peco/peco
screen.go
Flush
func (t *Termbox) Flush() error { t.mutex.Lock() defer t.mutex.Unlock() return errors.Wrap(termbox.Flush(), "failed to flush termbox") }
go
func (t *Termbox) Flush() error { t.mutex.Lock() defer t.mutex.Unlock() return errors.Wrap(termbox.Flush(), "failed to flush termbox") }
[ "func", "(", "t", "*", "Termbox", ")", "Flush", "(", ")", "error", "{", "t", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "t", ".", "mutex", ".", "Unlock", "(", ")", "\n", "return", "errors", ".", "Wrap", "(", "termbox", ".", "Flush", "(", ")", ",", "\"", "\"", ")", "\n", "}" ]
// Flush calls termbox.Flush
[ "Flush", "calls", "termbox", ".", "Flush" ]
967233e25328cb5d7065a5abb23cc8ed650a09b6
https://github.com/peco/peco/blob/967233e25328cb5d7065a5abb23cc8ed650a09b6/screen.go#L49-L53
12,287
peco/peco
screen.go
PollEvent
func (t *Termbox) PollEvent(ctx context.Context) chan termbox.Event { // XXX termbox.PollEvent() can get stuck on unexpected signal // handling cases. We still would like to wait until the user // (termbox) has some event for us to process, but we don't // want to allow termbox to control/block our input loop. // // Solution: put termbox polling in a separate goroutine, // and we just watch for a channel. The loop can now // safely be implemented in terms of select {} which is // safe from being stuck. evCh := make(chan termbox.Event) go func() { // keep listening to suspend requests here for { select { case <-ctx.Done(): return case <-t.suspendCh: if pdebug.Enabled { pdebug.Printf("poll event suspended!") } t.Close() } } }() go func() { defer func() { recover() }() defer func() { close(evCh) }() for { ev := termbox.PollEvent() if ev.Type != termbox.EventInterrupt { evCh <- ev continue } select { case <-ctx.Done(): return case replyCh := <-t.resumeCh: t.Init() close(replyCh) } } }() return evCh }
go
func (t *Termbox) PollEvent(ctx context.Context) chan termbox.Event { // XXX termbox.PollEvent() can get stuck on unexpected signal // handling cases. We still would like to wait until the user // (termbox) has some event for us to process, but we don't // want to allow termbox to control/block our input loop. // // Solution: put termbox polling in a separate goroutine, // and we just watch for a channel. The loop can now // safely be implemented in terms of select {} which is // safe from being stuck. evCh := make(chan termbox.Event) go func() { // keep listening to suspend requests here for { select { case <-ctx.Done(): return case <-t.suspendCh: if pdebug.Enabled { pdebug.Printf("poll event suspended!") } t.Close() } } }() go func() { defer func() { recover() }() defer func() { close(evCh) }() for { ev := termbox.PollEvent() if ev.Type != termbox.EventInterrupt { evCh <- ev continue } select { case <-ctx.Done(): return case replyCh := <-t.resumeCh: t.Init() close(replyCh) } } }() return evCh }
[ "func", "(", "t", "*", "Termbox", ")", "PollEvent", "(", "ctx", "context", ".", "Context", ")", "chan", "termbox", ".", "Event", "{", "// XXX termbox.PollEvent() can get stuck on unexpected signal", "// handling cases. We still would like to wait until the user", "// (termbox) has some event for us to process, but we don't", "// want to allow termbox to control/block our input loop.", "//", "// Solution: put termbox polling in a separate goroutine,", "// and we just watch for a channel. The loop can now", "// safely be implemented in terms of select {} which is", "// safe from being stuck.", "evCh", ":=", "make", "(", "chan", "termbox", ".", "Event", ")", "\n\n", "go", "func", "(", ")", "{", "// keep listening to suspend requests here", "for", "{", "select", "{", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "return", "\n", "case", "<-", "t", ".", "suspendCh", ":", "if", "pdebug", ".", "Enabled", "{", "pdebug", ".", "Printf", "(", "\"", "\"", ")", "\n", "}", "\n", "t", ".", "Close", "(", ")", "\n", "}", "\n", "}", "\n", "}", "(", ")", "\n\n", "go", "func", "(", ")", "{", "defer", "func", "(", ")", "{", "recover", "(", ")", "}", "(", ")", "\n", "defer", "func", "(", ")", "{", "close", "(", "evCh", ")", "}", "(", ")", "\n\n", "for", "{", "ev", ":=", "termbox", ".", "PollEvent", "(", ")", "\n", "if", "ev", ".", "Type", "!=", "termbox", ".", "EventInterrupt", "{", "evCh", "<-", "ev", "\n", "continue", "\n", "}", "\n\n", "select", "{", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "return", "\n", "case", "replyCh", ":=", "<-", "t", ".", "resumeCh", ":", "t", ".", "Init", "(", ")", "\n", "close", "(", "replyCh", ")", "\n", "}", "\n", "}", "\n", "}", "(", ")", "\n", "return", "evCh", "\n\n", "}" ]
// PollEvent returns a channel that you can listen to for // termbox's events. The actual polling is done in a // separate gouroutine
[ "PollEvent", "returns", "a", "channel", "that", "you", "can", "listen", "to", "for", "termbox", "s", "events", ".", "The", "actual", "polling", "is", "done", "in", "a", "separate", "gouroutine" ]
967233e25328cb5d7065a5abb23cc8ed650a09b6
https://github.com/peco/peco/blob/967233e25328cb5d7065a5abb23cc8ed650a09b6/screen.go#L58-L107
12,288
peco/peco
screen.go
SetCell
func (t *Termbox) SetCell(x, y int, ch rune, fg, bg termbox.Attribute) { t.mutex.Lock() defer t.mutex.Unlock() termbox.SetCell(x, y, ch, fg, bg) }
go
func (t *Termbox) SetCell(x, y int, ch rune, fg, bg termbox.Attribute) { t.mutex.Lock() defer t.mutex.Unlock() termbox.SetCell(x, y, ch, fg, bg) }
[ "func", "(", "t", "*", "Termbox", ")", "SetCell", "(", "x", ",", "y", "int", ",", "ch", "rune", ",", "fg", ",", "bg", "termbox", ".", "Attribute", ")", "{", "t", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "t", ".", "mutex", ".", "Unlock", "(", ")", "\n", "termbox", ".", "SetCell", "(", "x", ",", "y", ",", "ch", ",", "fg", ",", "bg", ")", "\n", "}" ]
// SetCell writes to the terminal
[ "SetCell", "writes", "to", "the", "terminal" ]
967233e25328cb5d7065a5abb23cc8ed650a09b6
https://github.com/peco/peco/blob/967233e25328cb5d7065a5abb23cc8ed650a09b6/screen.go#L130-L134
12,289
peco/peco
screen.go
Size
func (t *Termbox) Size() (int, int) { t.mutex.Lock() defer t.mutex.Unlock() return termbox.Size() }
go
func (t *Termbox) Size() (int, int) { t.mutex.Lock() defer t.mutex.Unlock() return termbox.Size() }
[ "func", "(", "t", "*", "Termbox", ")", "Size", "(", ")", "(", "int", ",", "int", ")", "{", "t", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "t", ".", "mutex", ".", "Unlock", "(", ")", "\n", "return", "termbox", ".", "Size", "(", ")", "\n", "}" ]
// Size returns the dimensions of the current terminal
[ "Size", "returns", "the", "dimensions", "of", "the", "current", "terminal" ]
967233e25328cb5d7065a5abb23cc8ed650a09b6
https://github.com/peco/peco/blob/967233e25328cb5d7065a5abb23cc8ed650a09b6/screen.go#L137-L141
12,290
peco/peco
query.go
Runes
func (q *Query) Runes() <-chan rune { q.mutex.Lock() defer q.mutex.Unlock() c := make(chan rune, len(q.query)) go func() { defer close(c) q.mutex.Lock() defer q.mutex.Unlock() for _, r := range q.query { c <- r } }() return c }
go
func (q *Query) Runes() <-chan rune { q.mutex.Lock() defer q.mutex.Unlock() c := make(chan rune, len(q.query)) go func() { defer close(c) q.mutex.Lock() defer q.mutex.Unlock() for _, r := range q.query { c <- r } }() return c }
[ "func", "(", "q", "*", "Query", ")", "Runes", "(", ")", "<-", "chan", "rune", "{", "q", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "q", ".", "mutex", ".", "Unlock", "(", ")", "\n", "c", ":=", "make", "(", "chan", "rune", ",", "len", "(", "q", ".", "query", ")", ")", "\n\n", "go", "func", "(", ")", "{", "defer", "close", "(", "c", ")", "\n", "q", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "q", ".", "mutex", ".", "Unlock", "(", ")", "\n\n", "for", "_", ",", "r", ":=", "range", "q", ".", "query", "{", "c", "<-", "r", "\n", "}", "\n", "}", "(", ")", "\n\n", "return", "c", "\n", "}" ]
// Runes returns a channel that gives you the list of runes in the query
[ "Runes", "returns", "a", "channel", "that", "gives", "you", "the", "list", "of", "runes", "in", "the", "query" ]
967233e25328cb5d7065a5abb23cc8ed650a09b6
https://github.com/peco/peco/blob/967233e25328cb5d7065a5abb23cc8ed650a09b6/query.go#L66-L82
12,291
peco/peco
action.go
Execute
func (a ActionFunc) Execute(ctx context.Context, state *Peco, e termbox.Event) { a(ctx, state, e) }
go
func (a ActionFunc) Execute(ctx context.Context, state *Peco, e termbox.Event) { a(ctx, state, e) }
[ "func", "(", "a", "ActionFunc", ")", "Execute", "(", "ctx", "context", ".", "Context", ",", "state", "*", "Peco", ",", "e", "termbox", ".", "Event", ")", "{", "a", "(", "ctx", ",", "state", ",", "e", ")", "\n", "}" ]
// Execute fulfills the Action interface for AfterFunc
[ "Execute", "fulfills", "the", "Action", "interface", "for", "AfterFunc" ]
967233e25328cb5d7065a5abb23cc8ed650a09b6
https://github.com/peco/peco/blob/967233e25328cb5d7065a5abb23cc8ed650a09b6/action.go#L29-L31
12,292
peco/peco
action.go
Register
func (a ActionFunc) Register(name string, defaultKeys ...termbox.Key) { nameToActions["peco."+name] = a for _, k := range defaultKeys { a.registerKeySequence(keyseq.KeyList{keyseq.NewKeyFromKey(k)}) } }
go
func (a ActionFunc) Register(name string, defaultKeys ...termbox.Key) { nameToActions["peco."+name] = a for _, k := range defaultKeys { a.registerKeySequence(keyseq.KeyList{keyseq.NewKeyFromKey(k)}) } }
[ "func", "(", "a", "ActionFunc", ")", "Register", "(", "name", "string", ",", "defaultKeys", "...", "termbox", ".", "Key", ")", "{", "nameToActions", "[", "\"", "\"", "+", "name", "]", "=", "a", "\n", "for", "_", ",", "k", ":=", "range", "defaultKeys", "{", "a", ".", "registerKeySequence", "(", "keyseq", ".", "KeyList", "{", "keyseq", ".", "NewKeyFromKey", "(", "k", ")", "}", ")", "\n", "}", "\n", "}" ]
// Register fulfills the Action interface for AfterFunc. Registers `a` // into the global action registry by the name `name`, and maps to // default keys via `defaultKeys`
[ "Register", "fulfills", "the", "Action", "interface", "for", "AfterFunc", ".", "Registers", "a", "into", "the", "global", "action", "registry", "by", "the", "name", "name", "and", "maps", "to", "default", "keys", "via", "defaultKeys" ]
967233e25328cb5d7065a5abb23cc8ed650a09b6
https://github.com/peco/peco/blob/967233e25328cb5d7065a5abb23cc8ed650a09b6/action.go#L40-L45
12,293
peco/peco
action.go
RegisterKeySequence
func (a ActionFunc) RegisterKeySequence(name string, k keyseq.KeyList) { nameToActions["peco."+name] = a a.registerKeySequence(k) }
go
func (a ActionFunc) RegisterKeySequence(name string, k keyseq.KeyList) { nameToActions["peco."+name] = a a.registerKeySequence(k) }
[ "func", "(", "a", "ActionFunc", ")", "RegisterKeySequence", "(", "name", "string", ",", "k", "keyseq", ".", "KeyList", ")", "{", "nameToActions", "[", "\"", "\"", "+", "name", "]", "=", "a", "\n", "a", ".", "registerKeySequence", "(", "k", ")", "\n", "}" ]
// RegisterKeySequence satisfies the Action interface for AfterFunc. // Registers the action to be mapped against a key sequence
[ "RegisterKeySequence", "satisfies", "the", "Action", "interface", "for", "AfterFunc", ".", "Registers", "the", "action", "to", "be", "mapped", "against", "a", "key", "sequence" ]
967233e25328cb5d7065a5abb23cc8ed650a09b6
https://github.com/peco/peco/blob/967233e25328cb5d7065a5abb23cc8ed650a09b6/action.go#L49-L52
12,294
peco/peco
action.go
doAcceptChar
func doAcceptChar(ctx context.Context, state *Peco, e termbox.Event) { if e.Key == termbox.KeySpace { e.Ch = ' ' } ch := e.Ch if ch <= 0 { return } if state.SingleKeyJumpMode() { doSingleKeyJump(ctx, state, e) return } q := state.Query() c := state.Caret() q.InsertAt(ch, c.Pos()) c.Move(1) h := state.Hub() h.SendDrawPrompt() // Update prompt before running query state.ExecQuery() }
go
func doAcceptChar(ctx context.Context, state *Peco, e termbox.Event) { if e.Key == termbox.KeySpace { e.Ch = ' ' } ch := e.Ch if ch <= 0 { return } if state.SingleKeyJumpMode() { doSingleKeyJump(ctx, state, e) return } q := state.Query() c := state.Caret() q.InsertAt(ch, c.Pos()) c.Move(1) h := state.Hub() h.SendDrawPrompt() // Update prompt before running query state.ExecQuery() }
[ "func", "doAcceptChar", "(", "ctx", "context", ".", "Context", ",", "state", "*", "Peco", ",", "e", "termbox", ".", "Event", ")", "{", "if", "e", ".", "Key", "==", "termbox", ".", "KeySpace", "{", "e", ".", "Ch", "=", "' '", "\n", "}", "\n\n", "ch", ":=", "e", ".", "Ch", "\n", "if", "ch", "<=", "0", "{", "return", "\n", "}", "\n\n", "if", "state", ".", "SingleKeyJumpMode", "(", ")", "{", "doSingleKeyJump", "(", "ctx", ",", "state", ",", "e", ")", "\n", "return", "\n", "}", "\n\n", "q", ":=", "state", ".", "Query", "(", ")", "\n", "c", ":=", "state", ".", "Caret", "(", ")", "\n\n", "q", ".", "InsertAt", "(", "ch", ",", "c", ".", "Pos", "(", ")", ")", "\n", "c", ".", "Move", "(", "1", ")", "\n\n", "h", ":=", "state", ".", "Hub", "(", ")", "\n", "h", ".", "SendDrawPrompt", "(", ")", "// Update prompt before running query", "\n\n", "state", ".", "ExecQuery", "(", ")", "\n", "}" ]
// This is an exception to the rule. This does not get registered // anywhere. You just call it directly
[ "This", "is", "an", "exception", "to", "the", "rule", ".", "This", "does", "not", "get", "registered", "anywhere", ".", "You", "just", "call", "it", "directly" ]
967233e25328cb5d7065a5abb23cc8ed650a09b6
https://github.com/peco/peco/blob/967233e25328cb5d7065a5abb23cc8ed650a09b6/action.go#L159-L184
12,295
peco/peco
pipeline/pipeline.go
IsEndMark
func IsEndMark(err error) bool { if em, ok := errors.Cause(err).(EndMarker); ok { return em.EndMark() } return false }
go
func IsEndMark(err error) bool { if em, ok := errors.Cause(err).(EndMarker); ok { return em.EndMark() } return false }
[ "func", "IsEndMark", "(", "err", "error", ")", "bool", "{", "if", "em", ",", "ok", ":=", "errors", ".", "Cause", "(", "err", ")", ".", "(", "EndMarker", ")", ";", "ok", "{", "return", "em", ".", "EndMark", "(", ")", "\n", "}", "\n", "return", "false", "\n", "}" ]
// IsEndMark is an utility function that checks if the given error // object is an EndMark
[ "IsEndMark", "is", "an", "utility", "function", "that", "checks", "if", "the", "given", "error", "object", "is", "an", "EndMark" ]
967233e25328cb5d7065a5abb23cc8ed650a09b6
https://github.com/peco/peco/blob/967233e25328cb5d7065a5abb23cc8ed650a09b6/pipeline/pipeline.go#L25-L30
12,296
peco/peco
pipeline/pipeline.go
Send
func (oc ChanOutput) Send(v interface{}) (err error) { if oc == nil { return errors.New("nil channel") } // We allow ourselves a timeout of 1 second. t := time.NewTimer(time.Second) defer t.Stop() select { case oc <- v: case <-t.C: return errors.New("failed to send (not listening)") } return nil }
go
func (oc ChanOutput) Send(v interface{}) (err error) { if oc == nil { return errors.New("nil channel") } // We allow ourselves a timeout of 1 second. t := time.NewTimer(time.Second) defer t.Stop() select { case oc <- v: case <-t.C: return errors.New("failed to send (not listening)") } return nil }
[ "func", "(", "oc", "ChanOutput", ")", "Send", "(", "v", "interface", "{", "}", ")", "(", "err", "error", ")", "{", "if", "oc", "==", "nil", "{", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// We allow ourselves a timeout of 1 second.", "t", ":=", "time", ".", "NewTimer", "(", "time", ".", "Second", ")", "\n", "defer", "t", ".", "Stop", "(", ")", "\n\n", "select", "{", "case", "oc", "<-", "v", ":", "case", "<-", "t", ".", "C", ":", "return", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Send sends the data `v` through this channel
[ "Send", "sends", "the", "data", "v", "through", "this", "channel" ]
967233e25328cb5d7065a5abb23cc8ed650a09b6
https://github.com/peco/peco/blob/967233e25328cb5d7065a5abb23cc8ed650a09b6/pipeline/pipeline.go#L53-L68
12,297
peco/peco
pipeline/pipeline.go
SendEndMark
func (oc ChanOutput) SendEndMark(s string) error { return errors.Wrap(oc.Send(errors.Wrap(EndMark{}, s)), "failed to send end mark") }
go
func (oc ChanOutput) SendEndMark(s string) error { return errors.Wrap(oc.Send(errors.Wrap(EndMark{}, s)), "failed to send end mark") }
[ "func", "(", "oc", "ChanOutput", ")", "SendEndMark", "(", "s", "string", ")", "error", "{", "return", "errors", ".", "Wrap", "(", "oc", ".", "Send", "(", "errors", ".", "Wrap", "(", "EndMark", "{", "}", ",", "s", ")", ")", ",", "\"", "\"", ")", "\n", "}" ]
// SendEndMark sends an end mark
[ "SendEndMark", "sends", "an", "end", "mark" ]
967233e25328cb5d7065a5abb23cc8ed650a09b6
https://github.com/peco/peco/blob/967233e25328cb5d7065a5abb23cc8ed650a09b6/pipeline/pipeline.go#L71-L73
12,298
peco/peco
pipeline/pipeline.go
SetSource
func (p *Pipeline) SetSource(s Source) { p.mutex.Lock() defer p.mutex.Unlock() p.src = s }
go
func (p *Pipeline) SetSource(s Source) { p.mutex.Lock() defer p.mutex.Unlock() p.src = s }
[ "func", "(", "p", "*", "Pipeline", ")", "SetSource", "(", "s", "Source", ")", "{", "p", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "p", ".", "mutex", ".", "Unlock", "(", ")", "\n\n", "p", ".", "src", "=", "s", "\n", "}" ]
// SetSource sets the source. // If called during `Run`, this method will block.
[ "SetSource", "sets", "the", "source", ".", "If", "called", "during", "Run", "this", "method", "will", "block", "." ]
967233e25328cb5d7065a5abb23cc8ed650a09b6
https://github.com/peco/peco/blob/967233e25328cb5d7065a5abb23cc8ed650a09b6/pipeline/pipeline.go#L84-L89
12,299
peco/peco
pipeline/pipeline.go
Add
func (p *Pipeline) Add(n Acceptor) { p.mutex.Lock() defer p.mutex.Unlock() p.nodes = append(p.nodes, n) }
go
func (p *Pipeline) Add(n Acceptor) { p.mutex.Lock() defer p.mutex.Unlock() p.nodes = append(p.nodes, n) }
[ "func", "(", "p", "*", "Pipeline", ")", "Add", "(", "n", "Acceptor", ")", "{", "p", ".", "mutex", ".", "Lock", "(", ")", "\n", "defer", "p", ".", "mutex", ".", "Unlock", "(", ")", "\n\n", "p", ".", "nodes", "=", "append", "(", "p", ".", "nodes", ",", "n", ")", "\n", "}" ]
// Add adds new Acceptor that work on data that goes through the Pipeline. // If called during `Run`, this method will block.
[ "Add", "adds", "new", "Acceptor", "that", "work", "on", "data", "that", "goes", "through", "the", "Pipeline", ".", "If", "called", "during", "Run", "this", "method", "will", "block", "." ]
967233e25328cb5d7065a5abb23cc8ed650a09b6
https://github.com/peco/peco/blob/967233e25328cb5d7065a5abb23cc8ed650a09b6/pipeline/pipeline.go#L93-L98